mirror of
https://github.com/davidkaya/aryx.git
synced 2026-07-30 08:28:48 +02:00
Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0eac1da70c | ||
|
|
b8553c6593 | ||
|
|
26847cf00d | ||
|
|
fce0430091 | ||
|
|
fa355197cb | ||
|
|
5f263002f0 | ||
|
|
1376de4148 | ||
|
|
5ce6bb4b0a | ||
|
|
47d3fb0a29 | ||
|
|
4da31cbdd6 | ||
|
|
f15323e37e | ||
|
|
f8fe9d866e | ||
|
|
6c24754749 | ||
|
|
2a7c627008 | ||
|
|
3a3e1d5eab | ||
|
|
9a9332369b | ||
|
|
67fb950e61 | ||
|
|
f7d376fc41 | ||
|
|
59ea028a24 | ||
|
|
c7910e6e4b | ||
|
|
418946b854 | ||
|
|
10fcaf2b92 | ||
|
|
34fb5420a4 | ||
|
|
05b3771544 | ||
|
|
9243ec10a2 | ||
|
|
1f49436d8a | ||
|
|
61b5788e78 | ||
|
|
875c6a3706 | ||
|
|
b4aaf62179 | ||
|
|
4ffd6ad8d4 | ||
|
|
c22bd32f97 | ||
|
|
dad9769fa1 | ||
|
|
56e2f8669c | ||
|
|
d6008da0af | ||
|
|
575aca360a | ||
|
|
649eeddff3 | ||
|
|
521be0de3c | ||
|
|
fdfa6f3046 | ||
|
|
0e9d77c745 | ||
|
|
bed6427dfc | ||
|
|
6068ee42e1 | ||
|
|
41d19e007d | ||
|
|
cc626a3152 | ||
|
|
8d08a1df1a | ||
|
|
08886f9078 | ||
|
|
1fdb1c27d5 | ||
|
|
4e34d2abfc | ||
|
|
7b9c4d140c | ||
|
|
fde82bef4d | ||
|
|
6ef44c6689 | ||
|
|
872476b2e3 | ||
|
|
b02a90a15f | ||
|
|
d3fb0a64c5 | ||
|
|
efcee8a621 | ||
|
|
543cf677ab | ||
|
|
952e69da9f | ||
|
|
fb5970cfa7 | ||
|
|
6714b93bed | ||
|
|
b038019954 |
+29
-9
@@ -37,6 +37,7 @@ flowchart LR
|
|||||||
Git[Local git repositories]
|
Git[Local git repositories]
|
||||||
Sidecar[.NET sidecar]
|
Sidecar[.NET sidecar]
|
||||||
Copilot[GitHub Copilot CLI<br/>+ agent runtime]
|
Copilot[GitHub Copilot CLI<br/>+ agent runtime]
|
||||||
|
Telemetry[OTLP collector<br/>Aspire Dashboard]
|
||||||
OS[Native windowing<br/>and desktop integration]
|
OS[Native windowing<br/>and desktop integration]
|
||||||
|
|
||||||
User --> Renderer
|
User --> Renderer
|
||||||
@@ -46,6 +47,7 @@ flowchart LR
|
|||||||
Main <--> Git
|
Main <--> Git
|
||||||
Main <--> Sidecar
|
Main <--> Sidecar
|
||||||
Sidecar <--> Copilot
|
Sidecar <--> Copilot
|
||||||
|
Sidecar --> Telemetry
|
||||||
Main <--> OS
|
Main <--> OS
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -55,9 +57,9 @@ flowchart LR
|
|||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Renderer | Screens, interaction, local view composition, theme application | Filesystem, process spawning, raw Electron access, Copilot runtime | Typed preload API and pushed events |
|
| 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` |
|
| Preload | Narrow bridge between browser context and Electron IPC | Business logic, persistence, orchestration | `ipcRenderer` / `ipcMain` |
|
||||||
| Main process | Workspace mutation, persistence, git inspection/write operations, run change attribution, commit workflow orchestration, session lifecycle, native window state, sidecar lifecycle, PTY-backed terminal lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar, native child processes |
|
| Main process | Workspace mutation, persistence, git inspection/write operations, run change attribution, commit workflow orchestration, session lifecycle, native window state, global hotkey registration, sidecar lifecycle, PTY-backed terminal lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar, native child processes |
|
||||||
| Sidecar | Capability discovery, workflow validation, run execution, streaming deltas and activity | UI, workspace persistence, Electron APIs | Line-delimited JSON over stdio |
|
| Sidecar | Capability discovery, workflow validation, run execution, provider event normalization, optional OTLP trace export, streaming deltas and activity, streamed text assembly | UI, workspace persistence, Electron APIs | Line-delimited JSON over stdio, OTLP to external collectors |
|
||||||
| External systems | Git data, Copilot account/model access, OS window chrome | Application state and UI behavior | Controlled adapters owned by main or sidecar |
|
| External systems | Git data, Copilot account/model access, telemetry collectors, OS window chrome | Application state and UI behavior | Controlled adapters owned by main or sidecar |
|
||||||
|
|
||||||
This split is the most important architectural feature in the app. It is what keeps the system understandable as more capabilities are added.
|
This split is the most important architectural feature in the app. It is what keeps the system understandable as more capabilities are added.
|
||||||
|
|
||||||
@@ -68,7 +70,7 @@ Aryx runs as a multi-process desktop application:
|
|||||||
1. The **renderer** displays the workspace and captures user intent.
|
1. The **renderer** displays the workspace and captures user intent.
|
||||||
2. The **preload bridge** exposes a small, typed API into the browser context.
|
2. The **preload bridge** exposes a small, typed API into the browser context.
|
||||||
3. The **main process** validates and mutates application state, persists it, and manages native integrations.
|
3. The **main process** validates and mutates application state, persists it, and manages native integrations.
|
||||||
4. The **sidecar** executes Copilot-backed turns and streams structured execution events back.
|
4. The **sidecar** executes Copilot-backed turns, can export OpenTelemetry traces to an external collector, and streams structured execution events back.
|
||||||
|
|
||||||
The sidecar is intentionally separate from the Electron main process so that AI runtime concerns stay isolated from UI and persistence concerns.
|
The sidecar is intentionally separate from the Electron main process so that AI runtime concerns stay isolated from UI and persistence concerns.
|
||||||
|
|
||||||
@@ -143,7 +145,9 @@ Their runtime semantics follow the Agent Framework orchestration model: sequenti
|
|||||||
|
|
||||||
For Copilot-backed agents, Aryx uses a repo-local provider module around the Copilot SDK session layer so workflow agent 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.
|
For Copilot-backed agents, Aryx uses a repo-local provider module around the Copilot SDK session layer so workflow agent 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.
|
||||||
|
|
||||||
The sidecar now keeps that Copilot-specific behavior behind provider seams. Core execution uses shared `IAgentProvider`, `IProviderTurnSupport`, `ProviderSessionEvent`, `ProviderAgentBundle`, `TurnExecutionState`, and `AgentWorkflowTurnRunner` abstractions, while `Services/Providers/Copilot/` owns SDK-specific bundle creation, transcript projection, approvals, user input, MCP OAuth, exit-plan-mode handling, CLI/session management, and event adaptation.
|
The sidecar now keeps that Copilot-specific behavior behind provider seams. Core execution uses shared `IAgentProvider`, `IProviderTurnSupport`, `ProviderSessionEvent`, `ProviderAgentBundle`, `TurnExecutionState`, and `AgentWorkflowTurnRunner` abstractions, while `Services/Providers/Copilot/` owns SDK-specific bundle creation, transcript projection, approvals, user input, MCP OAuth, exit-plan-mode handling, CLI/session management, and event adaptation. Provider adapters implement `IProviderEventAdapter.TryAdapt()` to translate provider-native session events into the normalized `ProviderSessionEvent` records that `TurnExecutionState` consumes. The Copilot adapter is the first concrete implementation; adding a second provider means writing a new adapter without changing the turn-state machine or the main-process contract.
|
||||||
|
|
||||||
|
Streamed text assembly is a single-owner responsibility. The sidecar's `StreamingTranscriptBuffer` resolves content deltas and snapshot-mode content from provider events, producing authoritative `content` fields on every message-delta event. The main process forwards that resolved content to the renderer, which trusts it directly without re-running merge logic. This eliminates the duplicate text-assembly that previously caused glitches when the sidecar, main process, and renderer each independently merged streaming text.
|
||||||
|
|
||||||
Workflows are shared application data, not renderer-only configuration. The same workflow definition now drives validation, persistence, session execution, and sidecar orchestration.
|
Workflows are shared application data, not renderer-only configuration. The same workflow definition now drives validation, persistence, session execution, and sidecar orchestration.
|
||||||
|
|
||||||
@@ -216,7 +220,7 @@ This is a structured stdio protocol used for:
|
|||||||
- streaming partial output
|
- streaming partial output
|
||||||
- streaming agent activity
|
- streaming agent activity
|
||||||
|
|
||||||
This protocol boundary keeps the AI execution runtime replaceable and prevents the Electron main process from becoming overloaded with workflow-specific behavior. On the sidecar side, raw provider events are first normalized into sidecar-owned provider event records before they become streamed run activity, so future providers can plug into the same transport without reshaping the main-process contract.
|
This protocol boundary keeps the AI execution runtime replaceable and prevents the Electron main process from becoming overloaded with workflow-specific behavior. On the sidecar side, raw provider events are first normalized into sidecar-owned provider event records (via `IProviderEventAdapter`) before they become streamed run activity, so future providers can plug into the same transport without reshaping the main-process contract. Each event carries capability metadata so the main process and renderer can degrade gracefully when a provider does not support intent, reasoning, or fine-grained tool progress.
|
||||||
|
|
||||||
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:
|
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:
|
||||||
|
|
||||||
@@ -225,7 +229,7 @@ The protocol also carries **turn-scoped lifecycle events** alongside output delt
|
|||||||
- **Sub-agent events**: started, completed, failed, selected, deselected — surfaced when custom agents are defined
|
- **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
|
- **Skill invocation events**: emitted when an agent-side skill is triggered
|
||||||
- **Message reclassification events**: let the sidecar retroactively mark a streamed assistant message as `thinking` once the SDK confirms that message requested tool work, so the UI can separate intermediate planning chatter from the final response without sacrificing live streaming
|
- **Message reclassification events**: let the sidecar retroactively mark a streamed assistant message as `thinking` once the SDK confirms that message requested tool work, so the UI can separate intermediate planning chatter from the final response without sacrificing live streaming
|
||||||
- **Assistant intent and reasoning-delta events**: optional Copilot SDK metadata that exposes short "what I'm doing" labels plus incremental reasoning text for richer thinking-process surfaces
|
- **Assistant intent and reasoning-delta events**: optional provider metadata that exposes short "what I'm doing" labels plus incremental reasoning text for richer thinking-process surfaces; normalized through the provider adapter layer so the UI consumes them uniformly regardless of provider origin
|
||||||
- **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
|
- **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
|
- **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 compaction events**: start and complete, with token-reduction metrics when infinite sessions trigger context trimming
|
||||||
@@ -350,7 +354,8 @@ That gives the system:
|
|||||||
|
|
||||||
The main process owns desktop concerns such as:
|
The main process owns desktop concerns such as:
|
||||||
|
|
||||||
- native window creation
|
- native window creation (main window and quick prompt overlay)
|
||||||
|
- global hotkey registration
|
||||||
- title bar behavior
|
- title bar behavior
|
||||||
- background process management
|
- background process management
|
||||||
- filesystem access
|
- filesystem access
|
||||||
@@ -358,13 +363,28 @@ The main process owns desktop concerns such as:
|
|||||||
|
|
||||||
This keeps those concerns out of the renderer while still letting the UI feel native.
|
This keeps those concerns out of the renderer while still letting the UI feel native.
|
||||||
|
|
||||||
|
### Multi-window setup and Quick Prompt
|
||||||
|
|
||||||
|
Aryx runs two `BrowserWindow` instances:
|
||||||
|
|
||||||
|
- the **main window** — the full workspace UI
|
||||||
|
- the **quick prompt window** — a frameless, transparent, always-on-top overlay for one-off AI questions
|
||||||
|
|
||||||
|
The quick prompt window loads a separate, lightweight renderer entry (`quickprompt.html` / `quickprompt.tsx`) with its own preload script (`preload/quickprompt.ts`). This keeps its bundle small and avoids loading the full workspace renderer. It communicates with the main process through dedicated IPC channels prefixed with `quick-prompt:`.
|
||||||
|
|
||||||
|
A **global hotkey service** (`src/main/services/globalHotkey.ts`) registers a system-wide keyboard shortcut (default `Super+Shift+A`, configurable in settings) using Electron's `globalShortcut` API. Pressing the hotkey toggles the quick prompt window. The service re-registers the shortcut when the configured hotkey changes and unregisters on app quit.
|
||||||
|
|
||||||
|
Quick prompt sessions are real `SessionRecord` instances created on the scratchpad project. The main process routes matching session events from the sidecar to the quick prompt window's `webContents`. After a response completes, the user can discard the session, close the window (preserving the session for later access in the main UI), or continue the conversation in the main window.
|
||||||
|
|
||||||
|
The `window-all-closed` handler excludes the quick prompt window so the app does not stay alive solely because the hidden popup exists.
|
||||||
|
|
||||||
## Build and release architecture
|
## Build and release architecture
|
||||||
|
|
||||||
Aryx ships as an Electron application bundled together with a self-contained .NET sidecar.
|
Aryx ships as an Electron application bundled together with a self-contained .NET sidecar.
|
||||||
|
|
||||||
The build pipeline is organized around three layers:
|
The build pipeline is organized around three layers:
|
||||||
|
|
||||||
- building the Electron renderer and main process assets
|
- building the Electron renderer entries (main workspace and quick prompt) and main process assets
|
||||||
- publishing the sidecar for the target runtime
|
- publishing the sidecar for the target runtime
|
||||||
- packaging platform artifacts with electron-builder
|
- packaging platform artifacts with electron-builder
|
||||||
|
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ Aryx is a desktop app that turns GitHub Copilot into a full workspace. Connect r
|
|||||||
| Message actions | Copy, pin, edit-and-resend, and regenerate individual messages |
|
| Message actions | Copy, pin, edit-and-resend, and regenerate individual messages |
|
||||||
| Bookmarks | Browse all pinned messages across sessions in one panel (`Ctrl+Shift+B`) |
|
| Bookmarks | Browse all pinned messages across sessions in one panel (`Ctrl+Shift+B`) |
|
||||||
| System tray | Minimize to tray, quick-launch scratchpads, and see running session count |
|
| System tray | Minimize to tray, quick-launch scratchpads, and see running session count |
|
||||||
|
| Quick Prompt | System-wide hotkey (`Win+Shift+A` / `Cmd+Shift+A`) summons a floating popup for instant AI questions from any app |
|
||||||
| Desktop notifications | Native OS alerts when runs complete, fail, or need approval |
|
| Desktop notifications | Native OS alerts when runs complete, fail, or need approval |
|
||||||
| Onboarding | First-launch walkthrough, interactive tooltips, and a "try it" quickstart |
|
| Onboarding | First-launch walkthrough, interactive tooltips, and a "try it" quickstart |
|
||||||
|
|
||||||
@@ -91,12 +92,21 @@ bun run test # typecheck + unit tests
|
|||||||
bun run sidecar:test # backend tests
|
bun run sidecar:test # backend tests
|
||||||
bun run build # full build (electron + sidecar)
|
bun run build # full build (electron + sidecar)
|
||||||
|
|
||||||
|
bun run aspire # start the standalone Aspire Dashboard in Docker
|
||||||
|
bun run dev:otel # start Aspire + Aryx dev with OTLP export enabled
|
||||||
bun run package # package for current platform → release/
|
bun run package # package for current platform → release/
|
||||||
bun run installer # create installable artifact
|
bun run installer # create installable artifact
|
||||||
bun run publish-release # publish to GitHub Releases
|
bun run publish-release # publish to GitHub Releases
|
||||||
|
bun run release # bump patch version, commit, tag, and push
|
||||||
|
bun run release minor # bump minor version instead (use major for breaking releases)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
For local observability, `bun run dev:otel` starts the Aspire Dashboard UI at `http://localhost:18888`
|
||||||
|
and configures the sidecar to export OpenTelemetry traces to `http://localhost:4317` over OTLP/gRPC.
|
||||||
|
This dev workflow requires Docker.
|
||||||
|
|
||||||
Tagged releases use GitHub Actions to build and publish Windows (NSIS), macOS (DMG, signed + notarized), and Linux (AppImage) artifacts. The app uses `electron-updater` for in-app updates.
|
Tagged releases use GitHub Actions to build and publish Windows (NSIS), macOS (DMG, signed + notarized), and Linux (AppImage) artifacts. The app uses `electron-updater` for in-app updates.
|
||||||
|
The release helper expects a clean git worktree, an upstream branch configured for the current branch, and permission to push commits and tags.
|
||||||
|
|
||||||
## Trademarks
|
## Trademarks
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,12 @@ export default defineConfig({
|
|||||||
preload: {
|
preload: {
|
||||||
build: {
|
build: {
|
||||||
outDir: 'dist-electron/preload',
|
outDir: 'dist-electron/preload',
|
||||||
|
rollupOptions: {
|
||||||
|
input: {
|
||||||
|
index: resolve(__dirname, 'src/preload/index.ts'),
|
||||||
|
quickprompt: resolve(__dirname, 'src/preload/quickprompt.ts'),
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
plugins: [externalizeDepsPlugin()],
|
plugins: [externalizeDepsPlugin()],
|
||||||
resolve: {
|
resolve: {
|
||||||
@@ -32,6 +38,12 @@ export default defineConfig({
|
|||||||
root: 'src/renderer',
|
root: 'src/renderer',
|
||||||
build: {
|
build: {
|
||||||
outDir: 'dist/renderer',
|
outDir: 'dist/renderer',
|
||||||
|
rollupOptions: {
|
||||||
|
input: {
|
||||||
|
index: resolve(__dirname, 'src/renderer/index.html'),
|
||||||
|
quickprompt: resolve(__dirname, 'src/renderer/quickprompt.html'),
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
plugins: [react(), tailwindcss()],
|
plugins: [react(), tailwindcss()],
|
||||||
resolve: {
|
resolve: {
|
||||||
|
|||||||
+4
-1
@@ -1,16 +1,19 @@
|
|||||||
{
|
{
|
||||||
"name": "aryx",
|
"name": "aryx",
|
||||||
"version": "0.0.24",
|
"version": "0.0.30",
|
||||||
"description": "Orchestrator for Copilot-powered agent workflows across multiple projects.",
|
"description": "Orchestrator for Copilot-powered agent workflows across multiple projects.",
|
||||||
"private": true,
|
"private": true,
|
||||||
"main": "dist-electron/main/index.js",
|
"main": "dist-electron/main/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "electron-vite dev",
|
"dev": "electron-vite dev",
|
||||||
|
"dev:otel": "bun run scripts/dev-with-otel.ts",
|
||||||
|
"aspire": "bun run scripts/launch-aspire-dashboard.ts",
|
||||||
"build:electron": "electron-vite build",
|
"build:electron": "electron-vite build",
|
||||||
"build": "bun run build:electron && bun run sidecar:build",
|
"build": "bun run build:electron && bun run sidecar:build",
|
||||||
"package": "bun run scripts/clean-release.ts && bun run build:electron && bun run sidecar:publish && electron-builder --dir --publish never",
|
"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",
|
"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",
|
"publish-release": "bun run scripts/clean-release.ts && bun run build:electron && bun run sidecar:publish && electron-builder --publish always",
|
||||||
|
"release": "bun run scripts/release.ts",
|
||||||
"preview": "electron-vite preview",
|
"preview": "electron-vite preview",
|
||||||
"lsp:typescript": "typescript-language-server --stdio",
|
"lsp:typescript": "typescript-language-server --stdio",
|
||||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||||
|
|||||||
@@ -0,0 +1,233 @@
|
|||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import net from 'node:net';
|
||||||
|
import { setTimeout as delay } from 'node:timers/promises';
|
||||||
|
|
||||||
|
export const aspireDashboardContainerName = 'aryx-aspire-dashboard';
|
||||||
|
export const aspireDashboardImage = 'mcr.microsoft.com/dotnet/aspire-dashboard:latest';
|
||||||
|
export const aspireDashboardUrls = {
|
||||||
|
dashboard: 'http://localhost:18888',
|
||||||
|
otlpGrpc: 'http://localhost:4317',
|
||||||
|
otlpHttp: 'http://localhost:4318',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
type ContainerState = 'missing' | 'running' | 'stopped';
|
||||||
|
|
||||||
|
export interface AspireDashboardHandle {
|
||||||
|
readonly dashboardUrl: string;
|
||||||
|
readonly otlpGrpcEndpoint: string;
|
||||||
|
readonly otlpHttpEndpoint: string;
|
||||||
|
readonly startedByScript: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAspireDashboardRunArgs(
|
||||||
|
containerName = aspireDashboardContainerName,
|
||||||
|
image = aspireDashboardImage,
|
||||||
|
): string[] {
|
||||||
|
return [
|
||||||
|
'run',
|
||||||
|
'--rm',
|
||||||
|
'-d',
|
||||||
|
'--name',
|
||||||
|
containerName,
|
||||||
|
'-p',
|
||||||
|
'18888:18888',
|
||||||
|
'-p',
|
||||||
|
'4317:18889',
|
||||||
|
'-p',
|
||||||
|
'4318:18890',
|
||||||
|
'-e',
|
||||||
|
'ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS=true',
|
||||||
|
image,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createOpenTelemetryEnvironment(
|
||||||
|
baseEnvironment: NodeJS.ProcessEnv,
|
||||||
|
endpoint: string = aspireDashboardUrls.otlpGrpc,
|
||||||
|
): NodeJS.ProcessEnv {
|
||||||
|
return {
|
||||||
|
...baseEnvironment,
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: endpoint,
|
||||||
|
OTEL_EXPORTER_OTLP_PROTOCOL: 'grpc',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function startAspireDashboard(): Promise<AspireDashboardHandle> {
|
||||||
|
await ensureDockerAvailable();
|
||||||
|
|
||||||
|
let startedByScript = false;
|
||||||
|
const containerState = await getContainerState(aspireDashboardContainerName);
|
||||||
|
if (containerState !== 'running') {
|
||||||
|
if (containerState === 'stopped') {
|
||||||
|
await runCommand('docker', ['rm', '-f', aspireDashboardContainerName], 'pipe');
|
||||||
|
}
|
||||||
|
|
||||||
|
await runCommand('docker', createAspireDashboardRunArgs(), 'pipe');
|
||||||
|
startedByScript = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
await waitForTcpPort(18888);
|
||||||
|
await waitForTcpPort(4317);
|
||||||
|
|
||||||
|
return {
|
||||||
|
dashboardUrl: aspireDashboardUrls.dashboard,
|
||||||
|
otlpGrpcEndpoint: aspireDashboardUrls.otlpGrpc,
|
||||||
|
otlpHttpEndpoint: aspireDashboardUrls.otlpHttp,
|
||||||
|
startedByScript,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function stopAspireDashboard(): Promise<void> {
|
||||||
|
const containerState = await getContainerState(aspireDashboardContainerName);
|
||||||
|
if (containerState === 'missing') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await runCommand('docker', ['rm', '-f', aspireDashboardContainerName], 'pipe');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureDockerAvailable(): Promise<void> {
|
||||||
|
const cliVersion = await runCommandCapture('docker', ['--version']);
|
||||||
|
if (cliVersion.exitCode !== 0) {
|
||||||
|
throw new Error(
|
||||||
|
'Docker is required to run the standalone Aspire Dashboard. Install Docker Desktop and ensure `docker` is available on PATH.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await isDockerDaemonAvailable()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await hasDockerDesktopCli()) {
|
||||||
|
console.log('Docker Desktop is not running. Starting it now...');
|
||||||
|
await runCommand('docker', ['desktop', 'start', '--detach'], 'pipe');
|
||||||
|
await waitForDockerDaemon();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(
|
||||||
|
'Docker is installed but the daemon is not running. Start Docker Desktop and rerun the Aspire command.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getContainerState(containerName: string): Promise<ContainerState> {
|
||||||
|
const result = await runCommandCapture('docker', [
|
||||||
|
'container',
|
||||||
|
'inspect',
|
||||||
|
'--format',
|
||||||
|
'{{.State.Status}}',
|
||||||
|
containerName,
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (result.exitCode !== 0) {
|
||||||
|
return 'missing';
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.stdout.trim() === 'running' ? 'running' : 'stopped';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForTcpPort(port: number, timeoutMs = 30_000): Promise<void> {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (await canConnect(port)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await delay(250);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Timed out waiting for localhost:${port} to accept connections.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function isDockerDaemonAvailable(): Promise<boolean> {
|
||||||
|
const result = await runCommandCapture('docker', ['info', '--format', '{{.ServerVersion}}']);
|
||||||
|
return result.exitCode === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function hasDockerDesktopCli(): Promise<boolean> {
|
||||||
|
const result = await runCommandCapture('docker', ['desktop', 'version']);
|
||||||
|
return result.exitCode === 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitForDockerDaemon(timeoutMs = 120_000): Promise<void> {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (await isDockerDaemonAvailable()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await delay(1_000);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Timed out waiting for Docker Desktop to start and accept API connections.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function canConnect(port: number): Promise<boolean> {
|
||||||
|
return new Promise<boolean>((resolve) => {
|
||||||
|
const socket = net.createConnection({ host: '127.0.0.1', port });
|
||||||
|
const finalize = (connected: boolean) => {
|
||||||
|
socket.removeAllListeners();
|
||||||
|
socket.destroy();
|
||||||
|
resolve(connected);
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.once('connect', () => finalize(true));
|
||||||
|
socket.once('error', () => finalize(false));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runCommand(command: string, args: string[], stdio: 'inherit' | 'pipe'): Promise<void> {
|
||||||
|
const result = await spawnProcess(command, args, stdio);
|
||||||
|
if (result.exitCode === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.stderr.trim().length > 0) {
|
||||||
|
throw new Error(result.stderr.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`${command} exited with code ${result.exitCode}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runCommandCapture(command: string, args: string[]): Promise<{ exitCode: number; stdout: string; stderr: string }> {
|
||||||
|
return spawnProcess(command, args, 'pipe');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function spawnProcess(
|
||||||
|
command: string,
|
||||||
|
args: string[],
|
||||||
|
stdio: 'inherit' | 'pipe',
|
||||||
|
): Promise<{ exitCode: number; stdout: string; stderr: string }> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const child = spawn(command, args, {
|
||||||
|
stdio: stdio === 'inherit' ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
||||||
|
windowsHide: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
let stderr = '';
|
||||||
|
|
||||||
|
if (stdio === 'pipe') {
|
||||||
|
child.stdout?.on('data', (chunk: Buffer | string) => {
|
||||||
|
stdout += chunk.toString();
|
||||||
|
});
|
||||||
|
child.stderr?.on('data', (chunk: Buffer | string) => {
|
||||||
|
stderr += chunk.toString();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
child.on('error', reject);
|
||||||
|
child.on('exit', (code, signal) => {
|
||||||
|
if (signal) {
|
||||||
|
reject(new Error(`${command} exited because of signal ${signal}.`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve({
|
||||||
|
exitCode: code ?? 1,
|
||||||
|
stdout,
|
||||||
|
stderr,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { dirname, resolve } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
import {
|
||||||
|
createOpenTelemetryEnvironment,
|
||||||
|
startAspireDashboard,
|
||||||
|
stopAspireDashboard,
|
||||||
|
} from './aspireDashboard';
|
||||||
|
|
||||||
|
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const repositoryRoot = resolve(scriptDirectory, '..');
|
||||||
|
const signalExitCodes: Partial<Record<NodeJS.Signals, number>> = {
|
||||||
|
SIGINT: 130,
|
||||||
|
SIGTERM: 143,
|
||||||
|
};
|
||||||
|
|
||||||
|
const dashboard = await startAspireDashboard();
|
||||||
|
|
||||||
|
console.log(`Aspire Dashboard: ${dashboard.dashboardUrl}`);
|
||||||
|
console.log(`Aryx sidecar OTLP endpoint: ${dashboard.otlpGrpcEndpoint}`);
|
||||||
|
|
||||||
|
const child = spawn(process.execPath, ['run', 'dev'], {
|
||||||
|
cwd: repositoryRoot,
|
||||||
|
env: createOpenTelemetryEnvironment(process.env, dashboard.otlpGrpcEndpoint),
|
||||||
|
stdio: 'inherit',
|
||||||
|
windowsHide: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||||
|
process.on(signal, () => {
|
||||||
|
if (child.exitCode === null && child.signalCode === null) {
|
||||||
|
child.kill(signal);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let exitResult: { code: number | null; signal: NodeJS.Signals | null };
|
||||||
|
|
||||||
|
try {
|
||||||
|
exitResult = await new Promise((resolve, reject) => {
|
||||||
|
child.on('error', reject);
|
||||||
|
child.on('exit', (code, signal) => {
|
||||||
|
resolve({ code, signal });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
if (dashboard.startedByScript) {
|
||||||
|
await stopAspireDashboard();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exitResult.signal) {
|
||||||
|
process.exitCode = signalExitCodes[exitResult.signal] ?? 1;
|
||||||
|
} else {
|
||||||
|
process.exitCode = exitResult.code ?? 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { startAspireDashboard } from './aspireDashboard';
|
||||||
|
|
||||||
|
const dashboard = await startAspireDashboard();
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`${dashboard.startedByScript ? 'Started' : 'Reusing'} Aspire Dashboard at ${dashboard.dashboardUrl}`,
|
||||||
|
);
|
||||||
|
console.log(`OTLP/gRPC receiver: ${dashboard.otlpGrpcEndpoint}`);
|
||||||
|
console.log(`OTLP/HTTP receiver: ${dashboard.otlpHttpEndpoint}`);
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { readFile, writeFile } from 'node:fs/promises';
|
||||||
|
import { dirname, relative, resolve } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const repositoryRoot = resolve(scriptDirectory, '..');
|
||||||
|
const packageJsonPath = resolve(repositoryRoot, 'package.json');
|
||||||
|
|
||||||
|
export type ReleaseBump = 'patch' | 'minor' | 'major';
|
||||||
|
|
||||||
|
interface PackageJsonShape {
|
||||||
|
version?: unknown;
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitCommandResult {
|
||||||
|
exitCode: number;
|
||||||
|
stdout: string;
|
||||||
|
stderr: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type GitRunner = (args: string[]) => Promise<GitCommandResult>;
|
||||||
|
|
||||||
|
export interface ReleaseDependencies {
|
||||||
|
readText(path: string): Promise<string>;
|
||||||
|
writeText(path: string, content: string): Promise<void>;
|
||||||
|
runGit: GitRunner;
|
||||||
|
log(message: string): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReleaseWorkflowOptions {
|
||||||
|
repositoryRoot: string;
|
||||||
|
packageJsonPath: string;
|
||||||
|
bumpArg?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReleaseResult {
|
||||||
|
bump: ReleaseBump;
|
||||||
|
currentVersion: string;
|
||||||
|
nextVersion: string;
|
||||||
|
tagName: string;
|
||||||
|
localBranch: string;
|
||||||
|
remote: string;
|
||||||
|
upstreamBranch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UpstreamTarget {
|
||||||
|
remote: string;
|
||||||
|
branch: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createGitRunner(cwd: string): GitRunner {
|
||||||
|
return async (args) =>
|
||||||
|
new Promise((resolvePromise, rejectPromise) => {
|
||||||
|
const child = spawn('git', args, {
|
||||||
|
cwd,
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
});
|
||||||
|
|
||||||
|
let stdout = '';
|
||||||
|
let stderr = '';
|
||||||
|
|
||||||
|
child.stdout?.on('data', (chunk: Buffer | string) => {
|
||||||
|
stdout += chunk.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
child.stderr?.on('data', (chunk: Buffer | string) => {
|
||||||
|
stderr += chunk.toString();
|
||||||
|
});
|
||||||
|
|
||||||
|
child.on('error', rejectPromise);
|
||||||
|
child.on('close', (code, signal) => {
|
||||||
|
if (signal) {
|
||||||
|
rejectPromise(new Error(`git ${args.join(' ')} exited because of signal ${signal}.`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolvePromise({
|
||||||
|
exitCode: code ?? 1,
|
||||||
|
stdout,
|
||||||
|
stderr,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createReleaseDependencies(cwd: string): ReleaseDependencies {
|
||||||
|
return {
|
||||||
|
readText: (path) => readFile(path, 'utf8'),
|
||||||
|
writeText: (path, content) => writeFile(path, content, 'utf8'),
|
||||||
|
runGit: createGitRunner(cwd),
|
||||||
|
log: console.log,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function parsePackageJson(packageJsonText: string): PackageJsonShape {
|
||||||
|
try {
|
||||||
|
return JSON.parse(packageJsonText) as PackageJsonShape;
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
throw new Error(`Could not parse package.json: ${message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseReleaseBump(value?: string): ReleaseBump {
|
||||||
|
if (value === undefined) {
|
||||||
|
return 'patch';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value === 'patch' || value === 'minor' || value === 'major') {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unsupported release bump "${value}". Use patch, minor, or major.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readPackageVersion(packageJsonText: string): string {
|
||||||
|
const packageJson = parsePackageJson(packageJsonText);
|
||||||
|
|
||||||
|
if (typeof packageJson.version !== 'string') {
|
||||||
|
throw new Error('package.json is missing a string version field.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return packageJson.version;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseSemver(version: string): [number, number, number] {
|
||||||
|
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(version);
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
throw new Error(`Unsupported version "${version}". Expected a simple x.y.z semantic version.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function incrementVersion(version: string, bump: ReleaseBump): string {
|
||||||
|
const [major, minor, patch] = parseSemver(version);
|
||||||
|
|
||||||
|
switch (bump) {
|
||||||
|
case 'major':
|
||||||
|
return `${major + 1}.0.0`;
|
||||||
|
case 'minor':
|
||||||
|
return `${major}.${minor + 1}.0`;
|
||||||
|
case 'patch':
|
||||||
|
return `${major}.${minor}.${patch + 1}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectNewline(packageJsonText: string): '\r\n' | '\n' {
|
||||||
|
return packageJsonText.includes('\r\n') ? '\r\n' : '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updatePackageJsonVersion(packageJsonText: string, nextVersion: string): string {
|
||||||
|
const newline = detectNewline(packageJsonText);
|
||||||
|
const packageJson = parsePackageJson(packageJsonText);
|
||||||
|
|
||||||
|
if (typeof packageJson.version !== 'string') {
|
||||||
|
throw new Error('package.json is missing a string version field.');
|
||||||
|
}
|
||||||
|
|
||||||
|
packageJson.version = nextVersion;
|
||||||
|
|
||||||
|
return `${JSON.stringify(packageJson, null, 2).replace(/\n/g, newline)}${newline}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatGitFailure(args: string[], result: GitCommandResult): string {
|
||||||
|
const detail = result.stderr.trim() || result.stdout.trim();
|
||||||
|
|
||||||
|
if (detail.length > 0) {
|
||||||
|
return `git ${args.join(' ')} failed: ${detail}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `git ${args.join(' ')} failed with exit code ${result.exitCode}.`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runGitOrThrow(runGit: GitRunner, args: string[], context: string): Promise<GitCommandResult> {
|
||||||
|
const result = await runGit(args);
|
||||||
|
|
||||||
|
if (result.exitCode !== 0) {
|
||||||
|
throw new Error(`${context} ${formatGitFailure(args, result)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureCleanWorktree(runGit: GitRunner): Promise<void> {
|
||||||
|
const result = await runGitOrThrow(runGit, ['status', '--porcelain'], 'Could not inspect the current git worktree.');
|
||||||
|
|
||||||
|
if (result.stdout.trim().length > 0) {
|
||||||
|
throw new Error('Release requires a clean git worktree. Commit, stash, or discard changes first.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveLocalBranch(runGit: GitRunner): Promise<string> {
|
||||||
|
const result = await runGit(['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
||||||
|
|
||||||
|
if (result.exitCode !== 0) {
|
||||||
|
throw new Error('Release requires a checked-out branch. Detached HEAD is not supported.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const branch = result.stdout.trim();
|
||||||
|
|
||||||
|
if (branch.length === 0) {
|
||||||
|
throw new Error('Release could not determine the current branch name.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return branch;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeUpstreamBranch(mergeRef: string): string {
|
||||||
|
const prefix = 'refs/heads/';
|
||||||
|
|
||||||
|
if (!mergeRef.startsWith(prefix)) {
|
||||||
|
throw new Error(`Release expected an upstream branch ref, received "${mergeRef}".`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return mergeRef.slice(prefix.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resolveUpstreamTarget(runGit: GitRunner, localBranch: string): Promise<UpstreamTarget> {
|
||||||
|
const remoteResult = await runGit(['config', '--get', `branch.${localBranch}.remote`]);
|
||||||
|
const mergeResult = await runGit(['config', '--get', `branch.${localBranch}.merge`]);
|
||||||
|
|
||||||
|
if (remoteResult.exitCode !== 0 || mergeResult.exitCode !== 0) {
|
||||||
|
throw new Error(`Release requires an upstream branch for ${localBranch}. Configure tracking before running the release helper.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const remote = remoteResult.stdout.trim();
|
||||||
|
const mergeRef = mergeResult.stdout.trim();
|
||||||
|
|
||||||
|
if (remote.length === 0 || mergeRef.length === 0) {
|
||||||
|
throw new Error(`Release requires an upstream branch for ${localBranch}. Configure tracking before running the release helper.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
remote,
|
||||||
|
branch: normalizeUpstreamBranch(mergeRef),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureTagDoesNotExist(runGit: GitRunner, tagName: string): Promise<void> {
|
||||||
|
const result = await runGitOrThrow(runGit, ['tag', '--list', tagName], 'Could not inspect existing git tags.');
|
||||||
|
|
||||||
|
if (result.stdout.trim().length > 0) {
|
||||||
|
throw new Error(`Tag ${tagName} already exists. Choose a different release version.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runReleaseWorkflow(
|
||||||
|
options: ReleaseWorkflowOptions,
|
||||||
|
dependencies: ReleaseDependencies,
|
||||||
|
): Promise<ReleaseResult> {
|
||||||
|
const bump = parseReleaseBump(options.bumpArg);
|
||||||
|
const packageJsonText = await dependencies.readText(options.packageJsonPath);
|
||||||
|
const currentVersion = readPackageVersion(packageJsonText);
|
||||||
|
const nextVersion = incrementVersion(currentVersion, bump);
|
||||||
|
const tagName = `v${nextVersion}`;
|
||||||
|
const packageJsonFile = relative(options.repositoryRoot, options.packageJsonPath);
|
||||||
|
|
||||||
|
await ensureCleanWorktree(dependencies.runGit);
|
||||||
|
|
||||||
|
const localBranch = await resolveLocalBranch(dependencies.runGit);
|
||||||
|
const upstreamTarget = await resolveUpstreamTarget(dependencies.runGit, localBranch);
|
||||||
|
|
||||||
|
await ensureTagDoesNotExist(dependencies.runGit, tagName);
|
||||||
|
|
||||||
|
const updatedPackageJson = updatePackageJsonVersion(packageJsonText, nextVersion);
|
||||||
|
const commitMessage = `chore: release ${tagName}`;
|
||||||
|
const tagMessage = `Release ${tagName}`;
|
||||||
|
|
||||||
|
await dependencies.writeText(options.packageJsonPath, updatedPackageJson);
|
||||||
|
await runGitOrThrow(dependencies.runGit, ['add', packageJsonFile], `Could not stage ${packageJsonFile}.`);
|
||||||
|
await runGitOrThrow(dependencies.runGit, ['commit', '-m', commitMessage], 'Could not create the release commit.');
|
||||||
|
await runGitOrThrow(dependencies.runGit, ['tag', '-a', tagName, '-m', tagMessage], 'Could not create the annotated release tag.');
|
||||||
|
await runGitOrThrow(
|
||||||
|
dependencies.runGit,
|
||||||
|
['push', '--follow-tags', upstreamTarget.remote, `HEAD:${upstreamTarget.branch}`],
|
||||||
|
'Could not push the release commit and tag.',
|
||||||
|
);
|
||||||
|
|
||||||
|
dependencies.log(`Released ${tagName} from ${localBranch} to ${upstreamTarget.remote}/${upstreamTarget.branch}.`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
bump,
|
||||||
|
currentVersion,
|
||||||
|
nextVersion,
|
||||||
|
tagName,
|
||||||
|
localBranch,
|
||||||
|
remote: upstreamTarget.remote,
|
||||||
|
upstreamBranch: upstreamTarget.branch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function main(argv: string[]): Promise<void> {
|
||||||
|
await runReleaseWorkflow(
|
||||||
|
{
|
||||||
|
repositoryRoot,
|
||||||
|
packageJsonPath,
|
||||||
|
bumpArg: argv[0],
|
||||||
|
},
|
||||||
|
createReleaseDependencies(repositoryRoot),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (import.meta.main) {
|
||||||
|
await main(process.argv.slice(2)).catch((error: unknown) => {
|
||||||
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
console.error(message);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -10,9 +10,11 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="GitHub.Copilot.SDK" Version="0.2.1" />
|
<PackageReference Include="GitHub.Copilot.SDK" Version="0.2.1" />
|
||||||
<PackageReference Include="Microsoft.Agents.AI" Version="1.0.0" />
|
<PackageReference Include="Microsoft.Agents.AI" Version="1.1.0" />
|
||||||
<PackageReference Include="Microsoft.Agents.AI.GitHub.Copilot" Version="1.0.0-preview.260402.1" />
|
<PackageReference Include="Microsoft.Agents.AI.GitHub.Copilot" Version="1.1.0-preview.260410.1" />
|
||||||
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.0.0" />
|
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.1.0" />
|
||||||
|
<PackageReference Include="OpenTelemetry" Version="1.13.1" />
|
||||||
|
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.13.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -678,6 +678,7 @@ public sealed class ApprovalRequestedEventDto : SidecarEventDto
|
|||||||
public string? AgentName { get; init; }
|
public string? AgentName { get; init; }
|
||||||
public string? ToolName { get; init; }
|
public string? ToolName { get; init; }
|
||||||
public string? PermissionKind { get; init; }
|
public string? PermissionKind { get; init; }
|
||||||
|
public string? ApprovalToolKey { get; init; }
|
||||||
public string Title { get; init; } = string.Empty;
|
public string Title { get; init; } = string.Empty;
|
||||||
public string? Detail { get; init; }
|
public string? Detail { get; init; }
|
||||||
public PermissionDetailDto? PermissionDetail { get; init; }
|
public PermissionDetailDto? PermissionDetail { get; init; }
|
||||||
|
|||||||
@@ -2,10 +2,13 @@ namespace Aryx.AgentHost.Contracts;
|
|||||||
|
|
||||||
internal abstract record ProviderSessionEvent;
|
internal abstract record ProviderSessionEvent;
|
||||||
|
|
||||||
internal sealed record ProviderAssistantMessageDeltaEvent(string MessageId) : ProviderSessionEvent;
|
internal sealed record ProviderAssistantMessageDeltaEvent(
|
||||||
|
string MessageId,
|
||||||
|
string? DeltaContent) : ProviderSessionEvent;
|
||||||
|
|
||||||
internal sealed record ProviderAssistantMessageEvent(
|
internal sealed record ProviderAssistantMessageEvent(
|
||||||
string MessageId,
|
string MessageId,
|
||||||
|
string? Content,
|
||||||
bool HasToolRequests) : ProviderSessionEvent;
|
bool HasToolRequests) : ProviderSessionEvent;
|
||||||
|
|
||||||
internal sealed record ProviderToolExecutionStartEvent(
|
internal sealed record ProviderToolExecutionStartEvent(
|
||||||
@@ -13,12 +16,35 @@ internal sealed record ProviderToolExecutionStartEvent(
|
|||||||
string ToolName,
|
string ToolName,
|
||||||
IReadOnlyDictionary<string, object?>? ToolArguments) : ProviderSessionEvent;
|
IReadOnlyDictionary<string, object?>? ToolArguments) : ProviderSessionEvent;
|
||||||
|
|
||||||
|
internal sealed record ProviderToolExecutionProgressEvent(
|
||||||
|
string ToolCallId,
|
||||||
|
string? ProgressMessage) : ProviderSessionEvent;
|
||||||
|
|
||||||
|
internal sealed record ProviderToolExecutionPartialResultEvent(
|
||||||
|
string ToolCallId,
|
||||||
|
string? PartialOutput) : ProviderSessionEvent;
|
||||||
|
|
||||||
|
internal sealed record ProviderToolExecutionCompleteEvent(
|
||||||
|
string ToolCallId,
|
||||||
|
bool Success,
|
||||||
|
string? ResultContent,
|
||||||
|
string? DetailedResultContent,
|
||||||
|
string? Error) : ProviderSessionEvent;
|
||||||
|
|
||||||
internal sealed record ProviderAssistantIntentEvent(string? Intent) : ProviderSessionEvent;
|
internal sealed record ProviderAssistantIntentEvent(string? Intent) : ProviderSessionEvent;
|
||||||
|
|
||||||
internal sealed record ProviderAssistantReasoningDeltaEvent(
|
internal sealed record ProviderAssistantReasoningDeltaEvent(
|
||||||
string? ReasoningId,
|
string? ReasoningId,
|
||||||
string? DeltaContent) : ProviderSessionEvent;
|
string? DeltaContent) : ProviderSessionEvent;
|
||||||
|
|
||||||
|
internal sealed record ProviderAssistantReasoningEvent(
|
||||||
|
string? ReasoningId,
|
||||||
|
string? Content) : ProviderSessionEvent;
|
||||||
|
|
||||||
|
internal sealed record ProviderAssistantTurnStartEvent(string? TurnId) : ProviderSessionEvent;
|
||||||
|
|
||||||
|
internal sealed record ProviderAssistantTurnEndEvent(string? TurnId) : ProviderSessionEvent;
|
||||||
|
|
||||||
internal sealed record ProviderSubagentStartedEvent(
|
internal sealed record ProviderSubagentStartedEvent(
|
||||||
string? ToolCallId,
|
string? ToolCallId,
|
||||||
string? AgentName,
|
string? AgentName,
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
namespace Aryx.AgentHost.Contracts;
|
||||||
|
|
||||||
|
internal sealed record ProviderTurnStreamCapabilities
|
||||||
|
{
|
||||||
|
public static ProviderTurnStreamCapabilities None { get; } = new();
|
||||||
|
|
||||||
|
public bool SupportsIntent { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsReasoningDelta { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsReasoningBlock { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsToolExecutionProgress { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsToolExecutionPartialResult { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsToolExecutionCompletion { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsSubagentLifecycle { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsHookLifecycle { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsSessionCompaction { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsPendingMessagesMutation { get; init; }
|
||||||
|
|
||||||
|
public bool SupportsSessionTurnBoundaries { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
namespace Aryx.AgentHost.Contracts;
|
||||||
|
|
||||||
|
internal enum ProviderToolExecutionStatus
|
||||||
|
{
|
||||||
|
Running,
|
||||||
|
Completed,
|
||||||
|
Failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record ProviderToolExecutionSnapshot
|
||||||
|
{
|
||||||
|
public string ToolCallId { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public string? ToolName { get; init; }
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, object?>? ToolArguments { get; init; }
|
||||||
|
|
||||||
|
public ProviderToolExecutionStatus Status { get; init; }
|
||||||
|
|
||||||
|
public string? LatestProgressMessage { get; init; }
|
||||||
|
|
||||||
|
public string PartialOutput { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public string? ResultContent { get; init; }
|
||||||
|
|
||||||
|
public string? DetailedResultContent { get; init; }
|
||||||
|
|
||||||
|
public string? Error { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record ProviderReasoningSnapshot
|
||||||
|
{
|
||||||
|
public string ReasoningId { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public string Content { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public bool IsComplete { get; init; }
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using Aryx.AgentHost.Services;
|
using Aryx.AgentHost.Services;
|
||||||
|
using OpenTelemetry.Trace;
|
||||||
|
|
||||||
if (!args.Contains("--stdio", StringComparer.Ordinal))
|
if (!args.Contains("--stdio", StringComparer.Ordinal))
|
||||||
{
|
{
|
||||||
@@ -6,5 +7,7 @@ if (!args.Contains("--stdio", StringComparer.Ordinal))
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
using TracerProvider? tracerProvider = OpenTelemetrySetup.CreateTracerProviderFromEnvironment();
|
||||||
|
|
||||||
SidecarProtocolHost host = new();
|
SidecarProtocolHost host = new();
|
||||||
await host.RunAsync(Console.In, Console.Out, CancellationToken.None);
|
await host.RunAsync(Console.In, Console.Out, CancellationToken.None);
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ public class AgentWorkflowTurnRunner : ITurnWorkflowRunner
|
|||||||
onDelta,
|
onDelta,
|
||||||
onEvent)
|
onEvent)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
|
await EmitPendingEventsAsync(state, onDelta, onEvent).ConfigureAwait(false);
|
||||||
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
||||||
if (shouldEndTurn)
|
if (shouldEndTurn)
|
||||||
{
|
{
|
||||||
@@ -108,13 +108,13 @@ public class AgentWorkflowTurnRunner : ITurnWorkflowRunner
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
|
await EmitPendingEventsAsync(state, onDelta, onEvent).ConfigureAwait(false);
|
||||||
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
||||||
return state.FinalizeCompletedMessages(transcriptProjector);
|
return state.FinalizeCompletedMessages(transcriptProjector);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (runCancellation.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
|
catch (OperationCanceledException) when (runCancellation.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
|
await EmitPendingEventsAsync(state, onDelta, onEvent).ConfigureAwait(false);
|
||||||
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
|
||||||
ExitPlanModeRequestedEventDto? exitPlanModeEvent =
|
ExitPlanModeRequestedEventDto? exitPlanModeEvent =
|
||||||
_providerTurnSupport.ConsumePendingExitPlanModeRequest(command.RequestId);
|
_providerTurnSupport.ConsumePendingExitPlanModeRequest(command.RequestId);
|
||||||
@@ -230,10 +230,17 @@ public class AgentWorkflowTurnRunner : ITurnWorkflowRunner
|
|||||||
|
|
||||||
private static async Task EmitPendingEventsAsync(
|
private static async Task EmitPendingEventsAsync(
|
||||||
TurnExecutionState state,
|
TurnExecutionState state,
|
||||||
|
Func<TurnDeltaEventDto, Task> onDelta,
|
||||||
Func<SidecarEventDto, Task> onEvent)
|
Func<SidecarEventDto, Task> onEvent)
|
||||||
{
|
{
|
||||||
foreach (SidecarEventDto pendingEvent in state.DrainPendingEvents())
|
foreach (SidecarEventDto pendingEvent in state.DrainPendingEvents())
|
||||||
{
|
{
|
||||||
|
if (pendingEvent is TurnDeltaEventDto delta)
|
||||||
|
{
|
||||||
|
await onDelta(delta).ConfigureAwait(false);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
await onEvent(pendingEvent).ConfigureAwait(false);
|
await onEvent(pendingEvent).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -326,8 +333,7 @@ public class AgentWorkflowTurnRunner : ITurnWorkflowRunner
|
|||||||
command,
|
command,
|
||||||
requestInfo,
|
requestInfo,
|
||||||
state.ActiveAgent,
|
state.ActiveAgent,
|
||||||
state.ToolNamesByCallId,
|
state.ToolCalls);
|
||||||
state.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
if (activity is null)
|
if (activity is null)
|
||||||
{
|
{
|
||||||
@@ -524,10 +530,14 @@ public class AgentWorkflowTurnRunner : ITurnWorkflowRunner
|
|||||||
}
|
}
|
||||||
|
|
||||||
string messageId = state.CreateMessageId(update.Update.MessageId);
|
string messageId = state.CreateMessageId(update.Update.MessageId);
|
||||||
(string _, string currentAuthorName, string currentContent) = state.AppendDelta(
|
if (!state.TryAppendDelta(
|
||||||
messageId,
|
messageId,
|
||||||
authorName,
|
authorName,
|
||||||
update.Update.Text);
|
update.Update.Text,
|
||||||
|
out TranscriptSegment currentSegment))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
await onDelta(new TurnDeltaEventDto
|
await onDelta(new TurnDeltaEventDto
|
||||||
{
|
{
|
||||||
@@ -535,9 +545,9 @@ public class AgentWorkflowTurnRunner : ITurnWorkflowRunner
|
|||||||
RequestId = command.RequestId,
|
RequestId = command.RequestId,
|
||||||
SessionId = command.SessionId,
|
SessionId = command.SessionId,
|
||||||
MessageId = messageId,
|
MessageId = messageId,
|
||||||
AuthorName = currentAuthorName,
|
AuthorName = currentSegment.AuthorName,
|
||||||
ContentDelta = update.Update.Text,
|
ContentDelta = update.Update.Text,
|
||||||
Content = currentContent,
|
Content = currentSegment.Content,
|
||||||
}).ConfigureAwait(false);
|
}).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,5 +4,7 @@ namespace Aryx.AgentHost.Services;
|
|||||||
|
|
||||||
internal interface IProviderEventAdapter
|
internal interface IProviderEventAdapter
|
||||||
{
|
{
|
||||||
|
ProviderTurnStreamCapabilities Capabilities { get; }
|
||||||
|
|
||||||
ProviderSessionEvent? TryAdapt(object rawEvent);
|
ProviderSessionEvent? TryAdapt(object rawEvent);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using OpenTelemetry;
|
||||||
|
using OpenTelemetry.Exporter;
|
||||||
|
using OpenTelemetry.Resources;
|
||||||
|
using OpenTelemetry.Trace;
|
||||||
|
|
||||||
|
namespace Aryx.AgentHost.Services;
|
||||||
|
|
||||||
|
internal static class OpenTelemetrySetup
|
||||||
|
{
|
||||||
|
private const string ServiceName = "Aryx.AgentHost";
|
||||||
|
private const string EndpointEnvironmentVariableName = "OTEL_EXPORTER_OTLP_ENDPOINT";
|
||||||
|
private const string ProtocolEnvironmentVariableName = "OTEL_EXPORTER_OTLP_PROTOCOL";
|
||||||
|
|
||||||
|
private static readonly string[] ActivitySourceNames =
|
||||||
|
[
|
||||||
|
"Experimental.Microsoft.Agents.AI",
|
||||||
|
"Microsoft.Agents.AI.Workflows",
|
||||||
|
];
|
||||||
|
|
||||||
|
public static TracerProvider? CreateTracerProviderFromEnvironment(TextWriter? diagnosticsWriter = null)
|
||||||
|
{
|
||||||
|
return CreateTracerProvider(ReadEnvironmentVariables(), diagnosticsWriter ?? Console.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static TracerProvider? CreateTracerProvider(
|
||||||
|
IEnumerable<KeyValuePair<string, string?>> environmentVariables,
|
||||||
|
TextWriter diagnosticsWriter)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(environmentVariables);
|
||||||
|
ArgumentNullException.ThrowIfNull(diagnosticsWriter);
|
||||||
|
|
||||||
|
OpenTelemetryTracingConfiguration? configuration = ResolveTracingConfiguration(environmentVariables);
|
||||||
|
if (configuration is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
diagnosticsWriter.WriteLine(
|
||||||
|
$"Aryx.AgentHost OpenTelemetry tracing enabled ({configuration.ProtocolLabel}) -> {configuration.Endpoint}.");
|
||||||
|
|
||||||
|
return Sdk.CreateTracerProviderBuilder()
|
||||||
|
.SetResourceBuilder(
|
||||||
|
ResourceBuilder.CreateDefault()
|
||||||
|
.AddService(ServiceName, serviceVersion: ResolveServiceVersion()))
|
||||||
|
.AddSource(configuration.ActivitySourceNames.ToArray())
|
||||||
|
.AddOtlpExporter(options =>
|
||||||
|
{
|
||||||
|
options.Endpoint = configuration.Endpoint;
|
||||||
|
options.Protocol = configuration.Protocol;
|
||||||
|
})
|
||||||
|
.Build();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static OpenTelemetryTracingConfiguration? ResolveTracingConfiguration(
|
||||||
|
IEnumerable<KeyValuePair<string, string?>> environmentVariables)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(environmentVariables);
|
||||||
|
|
||||||
|
string? endpointValue = ReadSetting(environmentVariables, EndpointEnvironmentVariableName);
|
||||||
|
if (string.IsNullOrWhiteSpace(endpointValue))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Uri.TryCreate(endpointValue, UriKind.Absolute, out Uri? endpoint)
|
||||||
|
|| (endpoint.Scheme != Uri.UriSchemeHttp && endpoint.Scheme != Uri.UriSchemeHttps))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"{EndpointEnvironmentVariableName} must be an absolute http or https URL. Received '{endpointValue}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
OtlpExportProtocol protocol = ResolveProtocol(ReadSetting(environmentVariables, ProtocolEnvironmentVariableName));
|
||||||
|
return new OpenTelemetryTracingConfiguration(endpoint, protocol, ActivitySourceNames);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? ResolveServiceVersion()
|
||||||
|
{
|
||||||
|
return typeof(OpenTelemetrySetup).Assembly.GetName().Version?.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<KeyValuePair<string, string?>> ReadEnvironmentVariables()
|
||||||
|
{
|
||||||
|
return Environment.GetEnvironmentVariables()
|
||||||
|
.Cast<DictionaryEntry>()
|
||||||
|
.Select(entry => new KeyValuePair<string, string?>(
|
||||||
|
entry.Key?.ToString() ?? string.Empty,
|
||||||
|
entry.Value?.ToString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? ReadSetting(
|
||||||
|
IEnumerable<KeyValuePair<string, string?>> environmentVariables,
|
||||||
|
string name)
|
||||||
|
{
|
||||||
|
foreach (KeyValuePair<string, string?> entry in environmentVariables)
|
||||||
|
{
|
||||||
|
if (!string.Equals(entry.Key, name, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return string.IsNullOrWhiteSpace(entry.Value)
|
||||||
|
? null
|
||||||
|
: entry.Value.Trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static OtlpExportProtocol ResolveProtocol(string? protocolValue)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(protocolValue))
|
||||||
|
{
|
||||||
|
return OtlpExportProtocol.Grpc;
|
||||||
|
}
|
||||||
|
|
||||||
|
return protocolValue.Trim().ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"grpc" => OtlpExportProtocol.Grpc,
|
||||||
|
"http/protobuf" => OtlpExportProtocol.HttpProtobuf,
|
||||||
|
_ => throw new InvalidOperationException(
|
||||||
|
$"{ProtocolEnvironmentVariableName} must be 'grpc' or 'http/protobuf'. Received '{protocolValue}'."),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed record OpenTelemetryTracingConfiguration(
|
||||||
|
Uri Endpoint,
|
||||||
|
OtlpExportProtocol Protocol,
|
||||||
|
IReadOnlyList<string> ActivitySourceNames)
|
||||||
|
{
|
||||||
|
public string ProtocolLabel => Protocol switch
|
||||||
|
{
|
||||||
|
OtlpExportProtocol.HttpProtobuf => "http/protobuf",
|
||||||
|
_ => "grpc",
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -87,8 +87,13 @@ internal sealed class CopilotAgentBundle : ProviderAgentBundle
|
|||||||
name: definition.GetAgentName(),
|
name: definition.GetAgentName(),
|
||||||
description: NormalizeOptionalString(definition.Config.Description));
|
description: NormalizeOptionalString(definition.Config.Description));
|
||||||
|
|
||||||
agents.Add(agent);
|
AIAgent instrumentedAgent = new AIAgentBuilder(agent).UseOpenTelemetry().Build();
|
||||||
|
agents.Add(instrumentedAgent);
|
||||||
disposables.Add(agent);
|
disposables.Add(agent);
|
||||||
|
if (instrumentedAgent is IDisposable instrumentedDisposable)
|
||||||
|
{
|
||||||
|
disposables.Add(new SyncDisposableAdapter(instrumentedDisposable));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The bundle owns the shared client — disposed after all agents.
|
// The bundle owns the shared client — disposed after all agents.
|
||||||
@@ -328,4 +333,17 @@ internal sealed class CopilotAgentBundle : ProviderAgentBundle
|
|||||||
{
|
{
|
||||||
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adapts a synchronous <see cref="IDisposable"/> to <see cref="IAsyncDisposable"/>
|
||||||
|
/// so it can be tracked in the async disposal pipeline.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class SyncDisposableAdapter(IDisposable inner) : IAsyncDisposable
|
||||||
|
{
|
||||||
|
public ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
inner.Dispose();
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+182
-70
@@ -21,22 +21,33 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
private const string HookPermissionKind = "hook";
|
private const string HookPermissionKind = "hook";
|
||||||
private const string ToolCallingActivityType = "tool-calling";
|
private const string ToolCallingActivityType = "tool-calling";
|
||||||
|
|
||||||
private static readonly Dictionary<string, string> HookToolCategories = new(StringComparer.OrdinalIgnoreCase)
|
private static readonly Dictionary<string, HookToolApprovalMapping> HookToolApprovals = new(StringComparer.OrdinalIgnoreCase)
|
||||||
{
|
{
|
||||||
["view"] = ReadPermissionKind,
|
["view"] = new(ReadPermissionKind, ReadPermissionKind),
|
||||||
["glob"] = ReadPermissionKind,
|
["show_file"] = new(ReadPermissionKind, ReadPermissionKind),
|
||||||
["grep"] = ReadPermissionKind,
|
["read_file"] = new(ReadPermissionKind, ReadPermissionKind),
|
||||||
["lsp"] = ReadPermissionKind,
|
["glob"] = new(ReadPermissionKind, ReadPermissionKind),
|
||||||
["edit"] = WritePermissionKind,
|
["grep"] = new(ReadPermissionKind, ReadPermissionKind),
|
||||||
["create"] = WritePermissionKind,
|
["rg"] = new(ReadPermissionKind, ReadPermissionKind),
|
||||||
["powershell"] = ShellPermissionKind,
|
["lsp"] = new(ReadPermissionKind, ReadPermissionKind),
|
||||||
["read_powershell"] = ShellPermissionKind,
|
["edit"] = new(WritePermissionKind, WritePermissionKind),
|
||||||
["write_powershell"] = ShellPermissionKind,
|
["create"] = new(WritePermissionKind, WritePermissionKind),
|
||||||
["stop_powershell"] = ShellPermissionKind,
|
["write_file"] = new(WritePermissionKind, WritePermissionKind),
|
||||||
["list_powershell"] = ShellPermissionKind,
|
["apply_patch"] = new(WritePermissionKind, WritePermissionKind),
|
||||||
["web_fetch"] = UrlPermissionKind,
|
["bash"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
["web_search"] = UrlPermissionKind,
|
["read_bash"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
["store_memory"] = MemoryPermissionKind,
|
["write_bash"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
|
["stop_bash"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
|
["list_bash"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
|
["powershell"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
|
["read_powershell"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
|
["write_powershell"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
|
["stop_powershell"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
|
["list_powershell"] = new(ShellPermissionKind, ShellPermissionKind),
|
||||||
|
["web_fetch"] = new(UrlPermissionKind, WebFetchToolName),
|
||||||
|
["web_search"] = new(UrlPermissionKind, WebFetchToolName),
|
||||||
|
["store_memory"] = new(MemoryPermissionKind, StoreMemoryToolName),
|
||||||
|
["remember_fact"] = new(MemoryPermissionKind, StoreMemoryToolName),
|
||||||
};
|
};
|
||||||
|
|
||||||
private readonly ConcurrentDictionary<string, PendingApprovalRequest> _pendingApprovals = new(StringComparer.Ordinal);
|
private readonly ConcurrentDictionary<string, PendingApprovalRequest> _pendingApprovals = new(StringComparer.Ordinal);
|
||||||
@@ -70,7 +81,7 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
WorkflowNodeDto agent,
|
WorkflowNodeDto agent,
|
||||||
PermissionRequest request,
|
PermissionRequest request,
|
||||||
PermissionInvocation invocation,
|
PermissionInvocation invocation,
|
||||||
IReadOnlyDictionary<string, string> toolNamesByCallId,
|
ToolCallRegistry toolCalls,
|
||||||
Func<ApprovalRequestedEventDto, Task> onApproval,
|
Func<ApprovalRequestedEventDto, Task> onApproval,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
@@ -79,7 +90,7 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
agent,
|
agent,
|
||||||
request,
|
request,
|
||||||
invocation,
|
invocation,
|
||||||
toolNamesByCallId,
|
toolCalls,
|
||||||
onActivity: null,
|
onActivity: null,
|
||||||
onApproval,
|
onApproval,
|
||||||
cancellationToken)
|
cancellationToken)
|
||||||
@@ -91,24 +102,27 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
WorkflowNodeDto agent,
|
WorkflowNodeDto agent,
|
||||||
PermissionRequest request,
|
PermissionRequest request,
|
||||||
PermissionInvocation invocation,
|
PermissionInvocation invocation,
|
||||||
IReadOnlyDictionary<string, string> toolNamesByCallId,
|
ToolCallRegistry toolCalls,
|
||||||
Func<AgentActivityEventDto, Task>? onActivity,
|
Func<AgentActivityEventDto, Task>? onActivity,
|
||||||
Func<ApprovalRequestedEventDto, Task> onApproval,
|
Func<ApprovalRequestedEventDto, Task> onApproval,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
string? toolName = ResolveApprovalToolName(request, toolNamesByCallId);
|
ResolvedApprovalContext approval = ResolveApprovalContext(request, toolCalls, command.Tooling?.McpServers);
|
||||||
string? autoApprovedToolName = ResolveAutoApprovedToolName(request);
|
string? approvalCacheKey = ResolveApprovalCacheKey(approval.ToolName, approval.ApprovalToolKey);
|
||||||
string? mcpServerApprovalKey = ResolveMcpServerApprovalKey(request, command.Tooling?.McpServers);
|
|
||||||
string? approvalCacheKey = ResolveApprovalCacheKey(toolName, autoApprovedToolName);
|
|
||||||
|
|
||||||
AgentActivityEventDto? fileChangeActivity = BuildToolCallFileChangeActivity(command, agent, request, toolName);
|
AgentActivityEventDto? fileChangeActivity = BuildToolCallFileChangeActivity(command, agent, request, approval.ToolName);
|
||||||
if (fileChangeActivity is not null && onActivity is not null)
|
if (fileChangeActivity is not null && onActivity is not null)
|
||||||
{
|
{
|
||||||
await onActivity(fileChangeActivity).ConfigureAwait(false);
|
await onActivity(fileChangeActivity).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (IsToolApprovedForRequest(command.RequestId, approvalCacheKey)
|
if (IsToolApprovedForRequest(command.RequestId, approvalCacheKey)
|
||||||
|| !RequiresToolCallApproval(command.Workflow.Settings.ApprovalPolicy, agent.GetAgentId(), toolName, autoApprovedToolName, mcpServerApprovalKey))
|
|| !RequiresToolCallApproval(
|
||||||
|
command.Workflow.Settings.ApprovalPolicy,
|
||||||
|
agent.GetAgentId(),
|
||||||
|
approval.ToolName,
|
||||||
|
approval.ApprovalToolKey,
|
||||||
|
approval.McpServerApprovalKey))
|
||||||
{
|
{
|
||||||
return CreateApprovalResult(PermissionRequestResultKind.Approved);
|
return CreateApprovalResult(PermissionRequestResultKind.Approved);
|
||||||
}
|
}
|
||||||
@@ -127,7 +141,7 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
request,
|
request,
|
||||||
invocation,
|
invocation,
|
||||||
pending.ApprovalId,
|
pending.ApprovalId,
|
||||||
toolName))
|
approval.ToolName))
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
using CancellationTokenRegistration registration = cancellationToken.Register(
|
using CancellationTokenRegistration registration = cancellationToken.Register(
|
||||||
@@ -155,21 +169,22 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
string approvalId,
|
string approvalId,
|
||||||
string? toolName)
|
string? toolName)
|
||||||
{
|
{
|
||||||
string permissionKind = ResolvePermissionKind(request, command.Tooling?.McpServers);
|
ResolvedApprovalContext approval = ResolveApprovalContext(request, toolName, command.Tooling?.McpServers);
|
||||||
|
|
||||||
string agentId = agent.GetAgentId();
|
string agentId = agent.GetAgentId();
|
||||||
string agentName = agent.GetAgentName();
|
string agentName = agent.GetAgentName();
|
||||||
string? sessionId = NormalizeOptionalString(invocation.SessionId);
|
string? sessionId = NormalizeOptionalString(invocation.SessionId);
|
||||||
string? normalizedToolName = NormalizeOptionalString(toolName);
|
string? normalizedToolName = approval.ToolName;
|
||||||
|
string? displayToolName = normalizedToolName ?? NormalizeOptionalString(approval.ApprovalToolKey);
|
||||||
string? requestedUrl = request is PermissionRequestUrl urlRequest
|
string? requestedUrl = request is PermissionRequestUrl urlRequest
|
||||||
? NormalizeOptionalString(urlRequest.Url)
|
? NormalizeOptionalString(urlRequest.Url)
|
||||||
: null;
|
: null;
|
||||||
string title = normalizedToolName is null
|
string title = displayToolName is null
|
||||||
? $"Approve {permissionKind}"
|
? $"Approve {approval.PermissionKind}"
|
||||||
: $"Approve {normalizedToolName}";
|
: $"Approve {displayToolName}";
|
||||||
string detail = normalizedToolName is null
|
string detail = displayToolName is null
|
||||||
? $"{agentName} requested {permissionKind} permission"
|
? $"{agentName} requested {approval.PermissionKind} permission"
|
||||||
: $"{agentName} requested {permissionKind} permission for tool \"{normalizedToolName}\"";
|
: $"{agentName} requested {approval.PermissionKind} permission for tool \"{displayToolName}\"";
|
||||||
|
|
||||||
if (requestedUrl is not null)
|
if (requestedUrl is not null)
|
||||||
{
|
{
|
||||||
@@ -195,7 +210,8 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
AgentId = NormalizeOptionalString(agentId),
|
AgentId = NormalizeOptionalString(agentId),
|
||||||
AgentName = NormalizeOptionalString(agentName),
|
AgentName = NormalizeOptionalString(agentName),
|
||||||
ToolName = normalizedToolName,
|
ToolName = normalizedToolName,
|
||||||
PermissionKind = permissionKind,
|
PermissionKind = approval.PermissionKind,
|
||||||
|
ApprovalToolKey = NormalizeOptionalString(approval.ApprovalToolKey),
|
||||||
Title = title,
|
Title = title,
|
||||||
Detail = detail,
|
Detail = detail,
|
||||||
PermissionDetail = BuildPermissionDetail(request, command.Tooling?.McpServers),
|
PermissionDetail = BuildPermissionDetail(request, command.Tooling?.McpServers),
|
||||||
@@ -314,7 +330,7 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
ApprovalPolicyDto? approvalPolicy,
|
ApprovalPolicyDto? approvalPolicy,
|
||||||
string agentId,
|
string agentId,
|
||||||
string? toolName,
|
string? toolName,
|
||||||
string? autoApprovedToolName = null,
|
string? approvalToolKey = null,
|
||||||
string? mcpServerApprovalKey = null)
|
string? mcpServerApprovalKey = null)
|
||||||
{
|
{
|
||||||
if (approvalPolicy?.Rules is null || approvalPolicy.Rules.Count == 0)
|
if (approvalPolicy?.Rules is null || approvalPolicy.Rules.Count == 0)
|
||||||
@@ -333,21 +349,21 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return !MatchesAutoApprovedTool(autoApprovedToolNames, toolName, autoApprovedToolName)
|
return !MatchesAutoApprovedTool(autoApprovedToolNames, toolName, approvalToolKey)
|
||||||
&& !MatchesAutoApprovedToolName(autoApprovedToolNames, mcpServerApprovalKey);
|
&& !MatchesAutoApprovedToolName(autoApprovedToolNames, mcpServerApprovalKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static bool TryGetApprovalToolName(
|
internal static bool TryGetApprovalToolName(
|
||||||
PermissionRequest request,
|
PermissionRequest request,
|
||||||
IReadOnlyDictionary<string, string>? toolNamesByCallId,
|
ToolCallRegistry? toolCalls,
|
||||||
out string? toolName)
|
out string? toolName)
|
||||||
{
|
{
|
||||||
toolName = ResolveApprovalToolName(request, toolNamesByCallId);
|
toolName = ResolveApprovalToolName(request, toolCalls);
|
||||||
return toolName is not null;
|
return toolName is not null;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static bool TryGetApprovalToolName(PermissionRequest request, out string? toolName)
|
internal static bool TryGetApprovalToolName(PermissionRequest request, out string? toolName)
|
||||||
=> TryGetApprovalToolName(request, toolNamesByCallId: null, out toolName);
|
=> TryGetApprovalToolName(request, toolCalls: null, out toolName);
|
||||||
|
|
||||||
internal void ClearRequestApprovals(string requestId)
|
internal void ClearRequestApprovals(string requestId)
|
||||||
{
|
{
|
||||||
@@ -404,16 +420,74 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
|
|
||||||
private static string? ResolveApprovalToolName(
|
private static string? ResolveApprovalToolName(
|
||||||
PermissionRequest request,
|
PermissionRequest request,
|
||||||
IReadOnlyDictionary<string, string>? toolNamesByCallId)
|
ToolCallRegistry? toolCalls)
|
||||||
{
|
{
|
||||||
return GetDirectToolName(request)
|
return GetDirectToolName(request)
|
||||||
?? ResolveToolNameFromLookup(request, toolNamesByCallId)
|
?? ResolveToolNameFromLookup(request, toolCalls)
|
||||||
?? GetFallbackToolName(request);
|
?? GetFallbackToolName(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string? ResolveAutoApprovedToolName(PermissionRequest request)
|
private static ResolvedApprovalContext ResolveApprovalContext(
|
||||||
|
PermissionRequest request,
|
||||||
|
ToolCallRegistry? toolCalls,
|
||||||
|
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
|
||||||
{
|
{
|
||||||
return GetFallbackToolName(request);
|
return ResolveApprovalContext(
|
||||||
|
request,
|
||||||
|
ResolveApprovalToolName(request, toolCalls),
|
||||||
|
configuredMcpServers);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ResolvedApprovalContext ResolveApprovalContext(
|
||||||
|
PermissionRequest request,
|
||||||
|
string? toolName,
|
||||||
|
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
|
||||||
|
{
|
||||||
|
string? normalizedToolName = NormalizeOptionalString(toolName);
|
||||||
|
return request switch
|
||||||
|
{
|
||||||
|
PermissionRequestShell => new(
|
||||||
|
normalizedToolName,
|
||||||
|
ShellPermissionKind,
|
||||||
|
ShellPermissionKind,
|
||||||
|
null),
|
||||||
|
PermissionRequestWrite => new(
|
||||||
|
normalizedToolName,
|
||||||
|
WritePermissionKind,
|
||||||
|
WritePermissionKind,
|
||||||
|
null),
|
||||||
|
PermissionRequestRead => new(
|
||||||
|
normalizedToolName,
|
||||||
|
ReadPermissionKind,
|
||||||
|
ReadPermissionKind,
|
||||||
|
null),
|
||||||
|
PermissionRequestUrl => new(
|
||||||
|
normalizedToolName,
|
||||||
|
UrlPermissionKind,
|
||||||
|
WebFetchToolName,
|
||||||
|
null),
|
||||||
|
PermissionRequestMemory => new(
|
||||||
|
normalizedToolName,
|
||||||
|
MemoryPermissionKind,
|
||||||
|
StoreMemoryToolName,
|
||||||
|
null),
|
||||||
|
PermissionRequestMcp => new(
|
||||||
|
normalizedToolName,
|
||||||
|
McpPermissionKind,
|
||||||
|
normalizedToolName,
|
||||||
|
ResolveMcpServerApprovalKey(request, configuredMcpServers)),
|
||||||
|
PermissionRequestCustomTool => new(
|
||||||
|
normalizedToolName,
|
||||||
|
CustomToolPermissionKind,
|
||||||
|
normalizedToolName,
|
||||||
|
null),
|
||||||
|
PermissionRequestHook => ResolveHookApprovalContext(normalizedToolName, configuredMcpServers),
|
||||||
|
_ => new(
|
||||||
|
normalizedToolName,
|
||||||
|
NormalizeOptionalString(request.Kind) ?? "tool access",
|
||||||
|
normalizedToolName,
|
||||||
|
ResolveMcpServerApprovalKey(request, configuredMcpServers)),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private const string McpServerApprovalPrefix = "mcp_server:";
|
private const string McpServerApprovalPrefix = "mcp_server:";
|
||||||
@@ -480,16 +554,16 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
|
|
||||||
private static string? ResolveToolNameFromLookup(
|
private static string? ResolveToolNameFromLookup(
|
||||||
PermissionRequest request,
|
PermissionRequest request,
|
||||||
IReadOnlyDictionary<string, string>? toolNamesByCallId)
|
ToolCallRegistry? toolCalls)
|
||||||
{
|
{
|
||||||
if (toolNamesByCallId is null)
|
if (toolCalls is null)
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
string? toolCallId = GetToolCallId(request);
|
string? toolCallId = GetToolCallId(request);
|
||||||
if (toolCallId is null
|
if (toolCallId is null
|
||||||
|| !toolNamesByCallId.TryGetValue(toolCallId, out string? resolvedToolName))
|
|| !toolCalls.TryGetToolName(toolCallId, out string? resolvedToolName))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -522,44 +596,56 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
PermissionRequestWrite => WritePermissionKind,
|
PermissionRequestWrite => WritePermissionKind,
|
||||||
PermissionRequestRead => ReadPermissionKind,
|
PermissionRequestRead => ReadPermissionKind,
|
||||||
PermissionRequestMemory => StoreMemoryToolName,
|
PermissionRequestMemory => StoreMemoryToolName,
|
||||||
PermissionRequestHook hook => ResolveHookToolCategory(hook.ToolName),
|
PermissionRequestHook hook => ResolveHookApprovalToolKey(hook.ToolName),
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static string? ResolveHookToolCategory(string? toolName)
|
internal static string? ResolveHookToolCategory(string? toolName)
|
||||||
{
|
{
|
||||||
string? normalized = NormalizeOptionalString(toolName);
|
return TryResolveHookToolApproval(toolName, out HookToolApprovalMapping? mapping) && mapping is not null
|
||||||
if (normalized is null)
|
? mapping.PermissionKind
|
||||||
{
|
: null;
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return HookToolCategories.TryGetValue(normalized, out string? category) ? category : null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string ResolvePermissionKind(
|
internal static string? ResolveHookApprovalToolKey(string? toolName)
|
||||||
PermissionRequest request,
|
{
|
||||||
|
return TryResolveHookToolApproval(toolName, out HookToolApprovalMapping? mapping) && mapping is not null
|
||||||
|
? mapping.ApprovalToolKey
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static ResolvedApprovalContext ResolveHookApprovalContext(
|
||||||
|
string? toolName,
|
||||||
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
|
IReadOnlyList<RunTurnMcpServerConfigDto>? configuredMcpServers)
|
||||||
{
|
{
|
||||||
string permissionKind = string.IsNullOrWhiteSpace(request.Kind)
|
string? normalizedToolName = NormalizeOptionalString(toolName);
|
||||||
? "tool access"
|
if (normalizedToolName is null)
|
||||||
: request.Kind.Trim();
|
|
||||||
|
|
||||||
if (request is not PermissionRequestHook hook)
|
|
||||||
{
|
{
|
||||||
return permissionKind;
|
return new ResolvedApprovalContext(null, HookPermissionKind, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
string? resolvedCategory = ResolveHookToolCategory(hook.ToolName);
|
if (TryResolveHookToolApproval(normalizedToolName, out HookToolApprovalMapping? mapping) && mapping is not null)
|
||||||
if (resolvedCategory is not null)
|
|
||||||
{
|
{
|
||||||
return resolvedCategory;
|
return new ResolvedApprovalContext(
|
||||||
|
normalizedToolName,
|
||||||
|
mapping.PermissionKind,
|
||||||
|
mapping.ApprovalToolKey,
|
||||||
|
null);
|
||||||
}
|
}
|
||||||
|
|
||||||
return ResolveHookMcpServerName(hook.ToolName, configuredMcpServers) is not null
|
string? mcpServerApprovalKey = ResolveHookMcpServerApprovalKey(normalizedToolName, configuredMcpServers);
|
||||||
? McpPermissionKind
|
return mcpServerApprovalKey is not null
|
||||||
: permissionKind;
|
? new ResolvedApprovalContext(
|
||||||
|
normalizedToolName,
|
||||||
|
McpPermissionKind,
|
||||||
|
normalizedToolName,
|
||||||
|
mcpServerApprovalKey)
|
||||||
|
: new ResolvedApprovalContext(
|
||||||
|
normalizedToolName,
|
||||||
|
HookPermissionKind,
|
||||||
|
normalizedToolName,
|
||||||
|
null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static PermissionDetailDto BuildHookPermissionDetail(
|
private static PermissionDetailDto BuildHookPermissionDetail(
|
||||||
@@ -619,13 +705,29 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
: strippedToolName;
|
: strippedToolName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static bool TryResolveHookToolApproval(
|
||||||
|
string? toolName,
|
||||||
|
out HookToolApprovalMapping? mapping)
|
||||||
|
{
|
||||||
|
string? normalizedToolName = NormalizeOptionalString(toolName);
|
||||||
|
if (normalizedToolName is not null
|
||||||
|
&& HookToolApprovals.TryGetValue(normalizedToolName, out HookToolApprovalMapping? resolvedMapping))
|
||||||
|
{
|
||||||
|
mapping = resolvedMapping;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
mapping = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
private static bool MatchesAutoApprovedTool(
|
private static bool MatchesAutoApprovedTool(
|
||||||
IReadOnlyList<string> autoApprovedToolNames,
|
IReadOnlyList<string> autoApprovedToolNames,
|
||||||
string? toolName,
|
string? toolName,
|
||||||
string? autoApprovedToolName)
|
string? approvalToolKey)
|
||||||
{
|
{
|
||||||
return MatchesAutoApprovedToolName(autoApprovedToolNames, toolName)
|
return MatchesAutoApprovedToolName(autoApprovedToolNames, toolName)
|
||||||
|| MatchesAutoApprovedToolName(autoApprovedToolNames, autoApprovedToolName);
|
|| MatchesAutoApprovedToolName(autoApprovedToolNames, approvalToolKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool MatchesAutoApprovedToolName(
|
private static bool MatchesAutoApprovedToolName(
|
||||||
@@ -720,6 +822,16 @@ internal sealed class CopilotApprovalCoordinator
|
|||||||
return normalized.Count > 0 ? normalized : null;
|
return normalized.Count > 0 ? normalized : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal sealed record ResolvedApprovalContext(
|
||||||
|
string? ToolName,
|
||||||
|
string PermissionKind,
|
||||||
|
string? ApprovalToolKey,
|
||||||
|
string? McpServerApprovalKey);
|
||||||
|
|
||||||
|
private sealed record HookToolApprovalMapping(
|
||||||
|
string PermissionKind,
|
||||||
|
string ApprovalToolKey);
|
||||||
|
|
||||||
private sealed record PendingApprovalRequest(
|
private sealed record PendingApprovalRequest(
|
||||||
string RequestId,
|
string RequestId,
|
||||||
string SessionId,
|
string SessionId,
|
||||||
|
|||||||
@@ -5,18 +5,34 @@ namespace Aryx.AgentHost.Services;
|
|||||||
|
|
||||||
internal sealed class CopilotEventAdapter : IProviderEventAdapter
|
internal sealed class CopilotEventAdapter : IProviderEventAdapter
|
||||||
{
|
{
|
||||||
|
public ProviderTurnStreamCapabilities Capabilities { get; } = new()
|
||||||
|
{
|
||||||
|
SupportsIntent = true,
|
||||||
|
SupportsReasoningDelta = true,
|
||||||
|
SupportsReasoningBlock = true,
|
||||||
|
SupportsToolExecutionProgress = true,
|
||||||
|
SupportsToolExecutionPartialResult = true,
|
||||||
|
SupportsToolExecutionCompletion = true,
|
||||||
|
SupportsSubagentLifecycle = true,
|
||||||
|
SupportsHookLifecycle = true,
|
||||||
|
SupportsSessionCompaction = true,
|
||||||
|
SupportsPendingMessagesMutation = true,
|
||||||
|
SupportsSessionTurnBoundaries = true,
|
||||||
|
};
|
||||||
|
|
||||||
public ProviderSessionEvent? TryAdapt(object rawEvent)
|
public ProviderSessionEvent? TryAdapt(object rawEvent)
|
||||||
{
|
{
|
||||||
return rawEvent switch
|
return rawEvent switch
|
||||||
{
|
{
|
||||||
AssistantMessageDeltaEvent messageDelta
|
AssistantMessageDeltaEvent messageDelta
|
||||||
when NormalizeRequiredString(messageDelta.Data?.MessageId) is { } messageId =>
|
when NormalizeRequiredString(messageDelta.Data?.MessageId) is { } messageId =>
|
||||||
new ProviderAssistantMessageDeltaEvent(messageId),
|
new ProviderAssistantMessageDeltaEvent(messageId, messageDelta.Data?.DeltaContent),
|
||||||
|
|
||||||
AssistantMessageEvent assistantMessage
|
AssistantMessageEvent assistantMessage
|
||||||
when NormalizeRequiredString(assistantMessage.Data?.MessageId) is { } messageId =>
|
when NormalizeRequiredString(assistantMessage.Data?.MessageId) is { } messageId =>
|
||||||
new ProviderAssistantMessageEvent(
|
new ProviderAssistantMessageEvent(
|
||||||
messageId,
|
messageId,
|
||||||
|
assistantMessage.Data?.Content,
|
||||||
assistantMessage.Data?.ToolRequests is { Length: > 0 }),
|
assistantMessage.Data?.ToolRequests is { Length: > 0 }),
|
||||||
|
|
||||||
ToolExecutionStartEvent toolExecutionStart
|
ToolExecutionStartEvent toolExecutionStart
|
||||||
@@ -27,6 +43,27 @@ internal sealed class CopilotEventAdapter : IProviderEventAdapter
|
|||||||
toolName,
|
toolName,
|
||||||
WorkflowRequestInfoInterpreter.NormalizeRawToolArguments(toolExecutionStart.Data?.Arguments)),
|
WorkflowRequestInfoInterpreter.NormalizeRawToolArguments(toolExecutionStart.Data?.Arguments)),
|
||||||
|
|
||||||
|
ToolExecutionProgressEvent toolExecutionProgress
|
||||||
|
when NormalizeRequiredString(toolExecutionProgress.Data?.ToolCallId) is { } toolCallId =>
|
||||||
|
new ProviderToolExecutionProgressEvent(
|
||||||
|
toolCallId,
|
||||||
|
NormalizeOptionalString(toolExecutionProgress.Data?.ProgressMessage)),
|
||||||
|
|
||||||
|
ToolExecutionPartialResultEvent toolExecutionPartialResult
|
||||||
|
when NormalizeRequiredString(toolExecutionPartialResult.Data?.ToolCallId) is { } toolCallId =>
|
||||||
|
new ProviderToolExecutionPartialResultEvent(
|
||||||
|
toolCallId,
|
||||||
|
toolExecutionPartialResult.Data?.PartialOutput),
|
||||||
|
|
||||||
|
ToolExecutionCompleteEvent toolExecutionComplete
|
||||||
|
when NormalizeRequiredString(toolExecutionComplete.Data?.ToolCallId) is { } toolCallId =>
|
||||||
|
new ProviderToolExecutionCompleteEvent(
|
||||||
|
toolCallId,
|
||||||
|
toolExecutionComplete.Data?.Success ?? false,
|
||||||
|
NormalizeOptionalString(toolExecutionComplete.Data?.Result?.Content),
|
||||||
|
NormalizeOptionalString(toolExecutionComplete.Data?.Result?.DetailedContent),
|
||||||
|
NormalizeOptionalString(toolExecutionComplete.Data?.Error?.Message)),
|
||||||
|
|
||||||
AssistantIntentEvent intentEvent =>
|
AssistantIntentEvent intentEvent =>
|
||||||
new ProviderAssistantIntentEvent(NormalizeOptionalString(intentEvent.Data?.Intent)),
|
new ProviderAssistantIntentEvent(NormalizeOptionalString(intentEvent.Data?.Intent)),
|
||||||
|
|
||||||
@@ -35,6 +72,17 @@ internal sealed class CopilotEventAdapter : IProviderEventAdapter
|
|||||||
NormalizeOptionalString(reasoningDelta.Data?.ReasoningId),
|
NormalizeOptionalString(reasoningDelta.Data?.ReasoningId),
|
||||||
reasoningDelta.Data?.DeltaContent),
|
reasoningDelta.Data?.DeltaContent),
|
||||||
|
|
||||||
|
AssistantReasoningEvent reasoning =>
|
||||||
|
new ProviderAssistantReasoningEvent(
|
||||||
|
NormalizeOptionalString(reasoning.Data?.ReasoningId),
|
||||||
|
reasoning.Data?.Content),
|
||||||
|
|
||||||
|
AssistantTurnStartEvent turnStart =>
|
||||||
|
new ProviderAssistantTurnStartEvent(NormalizeOptionalString(turnStart.Data?.TurnId)),
|
||||||
|
|
||||||
|
AssistantTurnEndEvent turnEnd =>
|
||||||
|
new ProviderAssistantTurnEndEvent(NormalizeOptionalString(turnEnd.Data?.TurnId)),
|
||||||
|
|
||||||
SubagentStartedEvent started =>
|
SubagentStartedEvent started =>
|
||||||
new ProviderSubagentStartedEvent(
|
new ProviderSubagentStartedEvent(
|
||||||
started.Data?.ToolCallId,
|
started.Data?.ToolCallId,
|
||||||
|
|||||||
@@ -248,17 +248,16 @@ internal static class CopilotSessionHooks
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
string? autoApprovedToolName = CopilotApprovalCoordinator.ResolveHookToolCategory(toolName) ?? toolName;
|
CopilotApprovalCoordinator.ResolvedApprovalContext approval = CopilotApprovalCoordinator.ResolveHookApprovalContext(
|
||||||
string? mcpServerApprovalKey = CopilotApprovalCoordinator.ResolveHookMcpServerApprovalKey(
|
|
||||||
toolName,
|
toolName,
|
||||||
command.Tooling?.McpServers);
|
command.Tooling?.McpServers);
|
||||||
|
|
||||||
bool requiresApproval = CopilotApprovalCoordinator.RequiresToolCallApproval(
|
bool requiresApproval = CopilotApprovalCoordinator.RequiresToolCallApproval(
|
||||||
command.Workflow.Settings.ApprovalPolicy,
|
command.Workflow.Settings.ApprovalPolicy,
|
||||||
agentDefinition.GetAgentId(),
|
agentDefinition.GetAgentId(),
|
||||||
toolName,
|
approval.ToolName,
|
||||||
autoApprovedToolName,
|
approval.ApprovalToolKey,
|
||||||
mcpServerApprovalKey);
|
approval.McpServerApprovalKey);
|
||||||
|
|
||||||
return new PreToolUseHookOutput
|
return new PreToolUseHookOutput
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ internal sealed class CopilotTurnRunnerSupport : IProviderTurnSupport
|
|||||||
CancellationTokenSource runCancellation,
|
CancellationTokenSource runCancellation,
|
||||||
CancellationToken cancellationToken)
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
state.SetStreamCapabilities(_providerEventAdapter.Capabilities);
|
||||||
|
|
||||||
return await CopilotAgentBundle.CreateAsync(
|
return await CopilotAgentBundle.CreateAsync(
|
||||||
command,
|
command,
|
||||||
(agent, request, invocation) => _approvalCoordinator.RequestApprovalAsync(
|
(agent, request, invocation) => _approvalCoordinator.RequestApprovalAsync(
|
||||||
@@ -27,7 +29,7 @@ internal sealed class CopilotTurnRunnerSupport : IProviderTurnSupport
|
|||||||
agent,
|
agent,
|
||||||
request,
|
request,
|
||||||
invocation,
|
invocation,
|
||||||
state.ToolNamesByCallId,
|
state.ToolCalls,
|
||||||
activity => AgentWorkflowTurnRunner.EmitActivityAsync(command, state, activity, onEvent),
|
activity => AgentWorkflowTurnRunner.EmitActivityAsync(command, state, activity, onEvent),
|
||||||
onApproval,
|
onApproval,
|
||||||
runCancellation.Token),
|
runCancellation.Token),
|
||||||
|
|||||||
+18
-76
@@ -1,16 +1,9 @@
|
|||||||
using System.Text;
|
|
||||||
using Aryx.AgentHost.Contracts;
|
using Aryx.AgentHost.Contracts;
|
||||||
using GitHub.Copilot.SDK;
|
using GitHub.Copilot.SDK;
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
|
|
||||||
namespace Aryx.AgentHost.Services;
|
namespace Aryx.AgentHost.Services;
|
||||||
|
|
||||||
internal readonly record struct TranscriptSegment(string MessageId, string AuthorName, string Content)
|
|
||||||
{
|
|
||||||
public static TranscriptSegment FromTuple((string MessageId, string AuthorName, string Content) segment)
|
|
||||||
=> new(segment.MessageId, segment.AuthorName, segment.Content);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static class WorkflowTranscriptProjector
|
internal static class WorkflowTranscriptProjector
|
||||||
{
|
{
|
||||||
public static ChatMessage ToChatMessage(ChatMessageDto message)
|
public static ChatMessage ToChatMessage(ChatMessageDto message)
|
||||||
@@ -146,10 +139,16 @@ internal static class WorkflowTranscriptProjector
|
|||||||
ChatMessage message,
|
ChatMessage message,
|
||||||
TranscriptSegment? matchedSegment)
|
TranscriptSegment? matchedSegment)
|
||||||
{
|
{
|
||||||
|
if (matchedSegment is { IsFinalized: true } finalizedSegment
|
||||||
|
&& !string.IsNullOrWhiteSpace(finalizedSegment.Content))
|
||||||
|
{
|
||||||
|
return finalizedSegment.Content;
|
||||||
|
}
|
||||||
|
|
||||||
return FirstNonBlank(
|
return FirstNonBlank(
|
||||||
message.Text,
|
message.Text,
|
||||||
matchedSegment?.Content,
|
TryGetAssistantMessageContent(message),
|
||||||
TryGetAssistantMessageContent(message))
|
matchedSegment?.Content)
|
||||||
?? string.Empty;
|
?? string.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -227,6 +226,16 @@ internal static class WorkflowTranscriptProjector
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
string? messageId = FirstNonBlank(message.MessageId);
|
||||||
|
if (messageId is not null
|
||||||
|
&& TryFindSegment(
|
||||||
|
remainingSegments,
|
||||||
|
segment => string.Equals(segment.MessageId, messageId, StringComparison.Ordinal),
|
||||||
|
out TranscriptSegment messageIdMatchedSegment))
|
||||||
|
{
|
||||||
|
return messageIdMatchedSegment;
|
||||||
|
}
|
||||||
|
|
||||||
string? messageText = string.IsNullOrWhiteSpace(message.Text) ? null : message.Text;
|
string? messageText = string.IsNullOrWhiteSpace(message.Text) ? null : message.Text;
|
||||||
if (messageText is not null)
|
if (messageText is not null)
|
||||||
{
|
{
|
||||||
@@ -445,70 +454,3 @@ internal static class WorkflowTranscriptProjector
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal sealed class StreamingTranscriptBuffer
|
|
||||||
{
|
|
||||||
private readonly List<BufferedTranscriptSegment> _segments = [];
|
|
||||||
|
|
||||||
public int Count => _segments.Count;
|
|
||||||
|
|
||||||
public TranscriptSegment AppendDelta(
|
|
||||||
string messageId,
|
|
||||||
string authorName,
|
|
||||||
string delta)
|
|
||||||
{
|
|
||||||
BufferedTranscriptSegment segment = GetOrCreateSegment(messageId, authorName);
|
|
||||||
segment.SetContent(StreamingTextMerger.Merge(segment.Content.ToString(), delta));
|
|
||||||
segment.SetAuthorName(authorName);
|
|
||||||
return segment.ToSnapshot();
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<TranscriptSegment> Snapshot()
|
|
||||||
{
|
|
||||||
return _segments.Select(segment => segment.ToSnapshot()).ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private BufferedTranscriptSegment GetOrCreateSegment(string messageId, string authorName)
|
|
||||||
{
|
|
||||||
BufferedTranscriptSegment? existing = _segments.LastOrDefault(segment => segment.MessageId == messageId);
|
|
||||||
if (existing is not null)
|
|
||||||
{
|
|
||||||
return existing;
|
|
||||||
}
|
|
||||||
|
|
||||||
BufferedTranscriptSegment created = new(messageId, authorName);
|
|
||||||
_segments.Add(created);
|
|
||||||
return created;
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class BufferedTranscriptSegment
|
|
||||||
{
|
|
||||||
public BufferedTranscriptSegment(string messageId, string authorName)
|
|
||||||
{
|
|
||||||
MessageId = messageId;
|
|
||||||
AuthorName = authorName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public string MessageId { get; }
|
|
||||||
|
|
||||||
public string AuthorName { get; private set; }
|
|
||||||
|
|
||||||
public StringBuilder Content { get; } = new();
|
|
||||||
|
|
||||||
public void SetContent(string value)
|
|
||||||
{
|
|
||||||
Content.Clear();
|
|
||||||
Content.Append(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void SetAuthorName(string value)
|
|
||||||
{
|
|
||||||
AuthorName = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TranscriptSegment ToSnapshot()
|
|
||||||
{
|
|
||||||
return new TranscriptSegment(MessageId, AuthorName, Content.ToString());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
using System.Text.RegularExpressions;
|
|
||||||
|
|
||||||
namespace Aryx.AgentHost.Services;
|
namespace Aryx.AgentHost.Services;
|
||||||
|
|
||||||
internal static partial class StreamingTextMerger
|
internal static partial class StreamingTextMerger
|
||||||
@@ -7,7 +5,6 @@ internal static partial class StreamingTextMerger
|
|||||||
private const double SnapshotReplacementMinLengthRatio = 0.6;
|
private const double SnapshotReplacementMinLengthRatio = 0.6;
|
||||||
private const int SnapshotReplacementMinTokenCount = 3;
|
private const int SnapshotReplacementMinTokenCount = 3;
|
||||||
private const double SnapshotReplacementSharedTokenRatio = 0.5;
|
private const double SnapshotReplacementSharedTokenRatio = 0.5;
|
||||||
private const string CharactersThatDoNotNeedLeadingSpace = "([{/\"'`";
|
|
||||||
|
|
||||||
public static string Merge(string current, string incoming)
|
public static string Merge(string current, string incoming)
|
||||||
{
|
{
|
||||||
@@ -32,51 +29,7 @@ internal static partial class StreamingTextMerger
|
|||||||
return incoming;
|
return incoming;
|
||||||
}
|
}
|
||||||
|
|
||||||
return current + ResolveBoundarySeparator(current, incoming) + incoming;
|
return current + incoming;
|
||||||
}
|
|
||||||
|
|
||||||
private static bool TryMergeSnapshotVariants(string current, string incoming, out string merged)
|
|
||||||
{
|
|
||||||
if (incoming.StartsWith(current, StringComparison.Ordinal)
|
|
||||||
|| incoming.Contains(current, StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
merged = incoming;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (current.Contains(incoming, StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
merged = current;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
merged = string.Empty;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool TryMergeByOverlap(string current, string incoming, out string merged)
|
|
||||||
{
|
|
||||||
int overlapLength = ComputeSuffixPrefixOverlap(current, incoming);
|
|
||||||
if (overlapLength == 0)
|
|
||||||
{
|
|
||||||
merged = string.Empty;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
merged = current + incoming[overlapLength..];
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string ResolveBoundarySeparator(string current, string incoming)
|
|
||||||
{
|
|
||||||
if (ShouldInsertNewlineBoundary(current, incoming))
|
|
||||||
{
|
|
||||||
return "\n";
|
|
||||||
}
|
|
||||||
|
|
||||||
return ShouldInsertSpaceBoundary(current, incoming)
|
|
||||||
? " "
|
|
||||||
: string.Empty;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int ComputeSuffixPrefixOverlap(string current, string incoming)
|
private static int ComputeSuffixPrefixOverlap(string current, string incoming)
|
||||||
@@ -125,54 +78,6 @@ internal static partial class StreamingTextMerger
|
|||||||
&& incomingTokens.Count >= SnapshotReplacementMinTokenCount;
|
&& incomingTokens.Count >= SnapshotReplacementMinTokenCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool ShouldInsertNewlineBoundary(string current, string incoming)
|
|
||||||
{
|
|
||||||
return !current.EndsWith('\n')
|
|
||||||
&& MarkdownBlockPrefixRegex().IsMatch(incoming.TrimStart());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool ShouldInsertSpaceBoundary(string current, string incoming)
|
|
||||||
{
|
|
||||||
char lastCharacter = current[^1];
|
|
||||||
char firstCharacter = incoming[0];
|
|
||||||
if (HasExistingBoundary(lastCharacter, firstCharacter)
|
|
||||||
|| CharactersThatDoNotNeedLeadingSpace.Contains(lastCharacter))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ClosingPunctuationRegex().IsMatch(incoming))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return StartsLikeASeparatedInlineFragment(firstCharacter, incoming)
|
|
||||||
|| LooksLikeWordBoundary(current, incoming);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool HasExistingBoundary(char lastCharacter, char firstCharacter)
|
|
||||||
{
|
|
||||||
return char.IsWhiteSpace(lastCharacter) || char.IsWhiteSpace(firstCharacter);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool StartsLikeASeparatedInlineFragment(char firstCharacter, string incoming)
|
|
||||||
{
|
|
||||||
return MarkdownInlinePrefixRegex().IsMatch(incoming)
|
|
||||||
|| char.IsUpper(firstCharacter)
|
|
||||||
|| char.IsDigit(firstCharacter);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool LooksLikeWordBoundary(string current, string incoming)
|
|
||||||
{
|
|
||||||
string[] currentTokens = Tokenize(current).ToArray();
|
|
||||||
string[] incomingTokens = Tokenize(incoming).ToArray();
|
|
||||||
string firstIncomingToken = incomingTokens.FirstOrDefault() ?? string.Empty;
|
|
||||||
|
|
||||||
return currentTokens.Length >= 2
|
|
||||||
&& incomingTokens.Length >= 2
|
|
||||||
&& firstIncomingToken.Length >= 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IEnumerable<string> Tokenize(string value)
|
private static IEnumerable<string> Tokenize(string value)
|
||||||
{
|
{
|
||||||
return TokenRegex()
|
return TokenRegex()
|
||||||
@@ -181,15 +86,38 @@ internal static partial class StreamingTextMerger
|
|||||||
.Where(token => token.Length > 0);
|
.Where(token => token.Length > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
[GeneratedRegex("[a-z0-9]+", RegexOptions.IgnoreCase)]
|
private static bool TryMergeSnapshotVariants(string current, string incoming, out string merged)
|
||||||
private static partial Regex TokenRegex();
|
{
|
||||||
|
if (incoming.StartsWith(current, StringComparison.Ordinal)
|
||||||
|
|| incoming.Contains(current, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
merged = incoming;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
[GeneratedRegex(@"^[.,!?;:%)\]}]")]
|
if (current.Contains(incoming, StringComparison.Ordinal))
|
||||||
private static partial Regex ClosingPunctuationRegex();
|
{
|
||||||
|
merged = current;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
[GeneratedRegex(@"^[*_`~\[]")]
|
merged = string.Empty;
|
||||||
private static partial Regex MarkdownInlinePrefixRegex();
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
[GeneratedRegex(@"^(?:#{1,6}\s|[-*+]\s|\d+\.\s|>\s|```)", RegexOptions.Singleline)]
|
private static bool TryMergeByOverlap(string current, string incoming, out string merged)
|
||||||
private static partial Regex MarkdownBlockPrefixRegex();
|
{
|
||||||
|
int overlapLength = ComputeSuffixPrefixOverlap(current, incoming);
|
||||||
|
if (overlapLength == 0)
|
||||||
|
{
|
||||||
|
merged = string.Empty;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
merged = current + incoming[overlapLength..];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[System.Text.RegularExpressions.GeneratedRegex("[a-z0-9]+", System.Text.RegularExpressions.RegexOptions.IgnoreCase)]
|
||||||
|
private static partial System.Text.RegularExpressions.Regex TokenRegex();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Aryx.AgentHost.Services;
|
||||||
|
|
||||||
|
internal readonly record struct TranscriptSegment(
|
||||||
|
string MessageId,
|
||||||
|
string AuthorName,
|
||||||
|
string Content,
|
||||||
|
bool IsFinalized = false)
|
||||||
|
{
|
||||||
|
public static TranscriptSegment FromTuple((string MessageId, string AuthorName, string Content) segment)
|
||||||
|
=> new(segment.MessageId, segment.AuthorName, segment.Content);
|
||||||
|
|
||||||
|
public void Deconstruct(out string messageId, out string authorName, out string content)
|
||||||
|
{
|
||||||
|
messageId = MessageId;
|
||||||
|
authorName = AuthorName;
|
||||||
|
content = Content;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class StreamingTranscriptBuffer
|
||||||
|
{
|
||||||
|
private readonly List<BufferedTranscriptSegment> _segments = [];
|
||||||
|
|
||||||
|
public int Count => _segments.Count;
|
||||||
|
|
||||||
|
public TranscriptSegment AppendDelta(
|
||||||
|
string messageId,
|
||||||
|
string authorName,
|
||||||
|
string delta)
|
||||||
|
{
|
||||||
|
_ = TryAppendDelta(messageId, authorName, delta, out TranscriptSegment segment);
|
||||||
|
return segment;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryAppendDelta(
|
||||||
|
string messageId,
|
||||||
|
string authorName,
|
||||||
|
string delta,
|
||||||
|
out TranscriptSegment segment)
|
||||||
|
{
|
||||||
|
BufferedTranscriptSegment bufferedSegment = GetOrCreateSegment(messageId, authorName);
|
||||||
|
bool contentChanged = bufferedSegment.TryAppendDelta(authorName, delta);
|
||||||
|
segment = bufferedSegment.ToSnapshot();
|
||||||
|
return contentChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryApplySnapshot(
|
||||||
|
string messageId,
|
||||||
|
string authorName,
|
||||||
|
string content,
|
||||||
|
out TranscriptSegment segment)
|
||||||
|
{
|
||||||
|
BufferedTranscriptSegment bufferedSegment = GetOrCreateSegment(messageId, authorName);
|
||||||
|
bool visibleContentChanged = bufferedSegment.TryApplySnapshot(authorName, content);
|
||||||
|
segment = bufferedSegment.ToSnapshot();
|
||||||
|
return visibleContentChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<TranscriptSegment> Snapshot()
|
||||||
|
{
|
||||||
|
return _segments.Select(segment => segment.ToSnapshot()).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private BufferedTranscriptSegment GetOrCreateSegment(string messageId, string authorName)
|
||||||
|
{
|
||||||
|
BufferedTranscriptSegment? existing = _segments.LastOrDefault(segment => segment.MessageId == messageId);
|
||||||
|
if (existing is not null)
|
||||||
|
{
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
BufferedTranscriptSegment created = new(messageId, authorName);
|
||||||
|
_segments.Add(created);
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class BufferedTranscriptSegment
|
||||||
|
{
|
||||||
|
public BufferedTranscriptSegment(string messageId, string authorName)
|
||||||
|
{
|
||||||
|
MessageId = messageId;
|
||||||
|
AuthorName = authorName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string MessageId { get; }
|
||||||
|
|
||||||
|
public string AuthorName { get; private set; }
|
||||||
|
|
||||||
|
public bool IsFinalized { get; private set; }
|
||||||
|
|
||||||
|
public StringBuilder Content { get; } = new();
|
||||||
|
|
||||||
|
public bool TryAppendDelta(string authorName, string delta)
|
||||||
|
{
|
||||||
|
SetAuthorName(authorName);
|
||||||
|
if (IsFinalized || string.IsNullOrEmpty(delta))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
string currentContent = Content.ToString();
|
||||||
|
string mergedContent = StreamingTextMerger.Merge(currentContent, delta);
|
||||||
|
if (string.Equals(currentContent, mergedContent, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
SetContent(mergedContent);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryApplySnapshot(string authorName, string content)
|
||||||
|
{
|
||||||
|
SetAuthorName(authorName);
|
||||||
|
string normalizedContent = content ?? string.Empty;
|
||||||
|
string currentContent = Content.ToString();
|
||||||
|
bool visibleContentChanged = !string.Equals(currentContent, normalizedContent, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
SetContent(normalizedContent);
|
||||||
|
IsFinalized = true;
|
||||||
|
return visibleContentChanged;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetContent(string value)
|
||||||
|
{
|
||||||
|
Content.Clear();
|
||||||
|
Content.Append(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetAuthorName(string value)
|
||||||
|
{
|
||||||
|
AuthorName = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TranscriptSegment ToSnapshot()
|
||||||
|
{
|
||||||
|
return new TranscriptSegment(MessageId, AuthorName, Content.ToString(), IsFinalized);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using Aryx.AgentHost.Contracts;
|
||||||
|
|
||||||
|
namespace Aryx.AgentHost.Services;
|
||||||
|
|
||||||
|
internal sealed class ToolCallRegistry
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<string, ProviderToolExecutionSnapshot> _toolExecutionsByCallId = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
public bool TryGetExecution(string? toolCallId, [NotNullWhen(true)] out ProviderToolExecutionSnapshot? snapshot)
|
||||||
|
{
|
||||||
|
snapshot = null;
|
||||||
|
return !string.IsNullOrWhiteSpace(toolCallId)
|
||||||
|
&& _toolExecutionsByCallId.TryGetValue(toolCallId, out snapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetToolName(string? toolCallId, [NotNullWhen(true)] out string? toolName)
|
||||||
|
{
|
||||||
|
toolName = null;
|
||||||
|
return TryGetExecution(toolCallId, out ProviderToolExecutionSnapshot? snapshot)
|
||||||
|
&& !string.IsNullOrWhiteSpace(snapshot.ToolName)
|
||||||
|
&& (toolName = snapshot.ToolName) is not null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool HasTrackedArguments(string? toolCallId)
|
||||||
|
{
|
||||||
|
return TryGetExecution(toolCallId, out ProviderToolExecutionSnapshot? snapshot)
|
||||||
|
&& snapshot.ToolArguments is { Count: > 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RecordToolStart(
|
||||||
|
string toolCallId,
|
||||||
|
string toolName,
|
||||||
|
IReadOnlyDictionary<string, object?>? toolArguments)
|
||||||
|
{
|
||||||
|
_toolExecutionsByCallId.AddOrUpdate(
|
||||||
|
toolCallId,
|
||||||
|
static (id, state) => new ProviderToolExecutionSnapshot
|
||||||
|
{
|
||||||
|
ToolCallId = id,
|
||||||
|
ToolName = state.ToolName,
|
||||||
|
ToolArguments = state.ToolArguments,
|
||||||
|
Status = ProviderToolExecutionStatus.Running,
|
||||||
|
},
|
||||||
|
static (_, existing, state) => existing with
|
||||||
|
{
|
||||||
|
ToolName = state.ToolName,
|
||||||
|
ToolArguments = state.ToolArguments,
|
||||||
|
Status = ProviderToolExecutionStatus.Running,
|
||||||
|
},
|
||||||
|
(ToolName: toolName, ToolArguments: toolArguments));
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryRecordToolRequest(
|
||||||
|
string? toolCallId,
|
||||||
|
string toolName,
|
||||||
|
IReadOnlyDictionary<string, object?>? toolArguments)
|
||||||
|
{
|
||||||
|
bool hasToolArguments = toolArguments is { Count: > 0 };
|
||||||
|
string? normalizedToolCallId = NormalizeOptionalString(toolCallId);
|
||||||
|
if (normalizedToolCallId is null)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_toolExecutionsByCallId.TryGetValue(normalizedToolCallId, out ProviderToolExecutionSnapshot? existing))
|
||||||
|
{
|
||||||
|
bool trackedHasArguments = existing.ToolArguments is { Count: > 0 };
|
||||||
|
if (trackedHasArguments || !hasToolArguments)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_toolExecutionsByCallId.AddOrUpdate(
|
||||||
|
normalizedToolCallId,
|
||||||
|
id => new ProviderToolExecutionSnapshot
|
||||||
|
{
|
||||||
|
ToolCallId = id,
|
||||||
|
ToolName = toolName,
|
||||||
|
ToolArguments = toolArguments,
|
||||||
|
Status = ProviderToolExecutionStatus.Running,
|
||||||
|
},
|
||||||
|
(_, existing) => existing with
|
||||||
|
{
|
||||||
|
ToolName = toolName,
|
||||||
|
ToolArguments = toolArguments,
|
||||||
|
Status = existing.Status is ProviderToolExecutionStatus.Completed or ProviderToolExecutionStatus.Failed
|
||||||
|
? existing.Status
|
||||||
|
: ProviderToolExecutionStatus.Running,
|
||||||
|
});
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RecordProgress(string toolCallId, string? progressMessage)
|
||||||
|
{
|
||||||
|
string? normalizedProgress = NormalizeOptionalString(progressMessage);
|
||||||
|
_toolExecutionsByCallId.AddOrUpdate(
|
||||||
|
toolCallId,
|
||||||
|
id => new ProviderToolExecutionSnapshot
|
||||||
|
{
|
||||||
|
ToolCallId = id,
|
||||||
|
Status = ProviderToolExecutionStatus.Running,
|
||||||
|
LatestProgressMessage = normalizedProgress,
|
||||||
|
},
|
||||||
|
(_, existing) => existing with
|
||||||
|
{
|
||||||
|
Status = existing.Status is ProviderToolExecutionStatus.Completed or ProviderToolExecutionStatus.Failed
|
||||||
|
? existing.Status
|
||||||
|
: ProviderToolExecutionStatus.Running,
|
||||||
|
LatestProgressMessage = normalizedProgress ?? existing.LatestProgressMessage,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RecordPartialResult(string toolCallId, string? partialOutput)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(partialOutput))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_toolExecutionsByCallId.AddOrUpdate(
|
||||||
|
toolCallId,
|
||||||
|
id => new ProviderToolExecutionSnapshot
|
||||||
|
{
|
||||||
|
ToolCallId = id,
|
||||||
|
Status = ProviderToolExecutionStatus.Running,
|
||||||
|
PartialOutput = partialOutput,
|
||||||
|
},
|
||||||
|
(_, existing) => existing with
|
||||||
|
{
|
||||||
|
Status = existing.Status is ProviderToolExecutionStatus.Completed or ProviderToolExecutionStatus.Failed
|
||||||
|
? existing.Status
|
||||||
|
: ProviderToolExecutionStatus.Running,
|
||||||
|
PartialOutput = string.Concat(existing.PartialOutput, partialOutput),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RecordCompletion(ProviderToolExecutionCompleteEvent toolExecution)
|
||||||
|
{
|
||||||
|
_toolExecutionsByCallId.AddOrUpdate(
|
||||||
|
toolExecution.ToolCallId,
|
||||||
|
id => new ProviderToolExecutionSnapshot
|
||||||
|
{
|
||||||
|
ToolCallId = id,
|
||||||
|
Status = toolExecution.Success ? ProviderToolExecutionStatus.Completed : ProviderToolExecutionStatus.Failed,
|
||||||
|
ResultContent = toolExecution.ResultContent,
|
||||||
|
DetailedResultContent = toolExecution.DetailedResultContent,
|
||||||
|
Error = toolExecution.Error,
|
||||||
|
},
|
||||||
|
(_, existing) => existing with
|
||||||
|
{
|
||||||
|
Status = toolExecution.Success ? ProviderToolExecutionStatus.Completed : ProviderToolExecutionStatus.Failed,
|
||||||
|
ResultContent = toolExecution.ResultContent ?? existing.ResultContent,
|
||||||
|
DetailedResultContent = toolExecution.DetailedResultContent ?? existing.DetailedResultContent,
|
||||||
|
Error = toolExecution.Error ?? existing.Error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? NormalizeOptionalString(string? value)
|
||||||
|
{
|
||||||
|
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using Aryx.AgentHost.Contracts;
|
using Aryx.AgentHost.Contracts;
|
||||||
using Microsoft.Extensions.AI;
|
using Microsoft.Extensions.AI;
|
||||||
|
|
||||||
@@ -14,6 +15,8 @@ internal class TurnExecutionState
|
|||||||
private readonly ConcurrentQueue<SidecarEventDto> _pendingEvents = new();
|
private readonly ConcurrentQueue<SidecarEventDto> _pendingEvents = new();
|
||||||
private readonly ConcurrentQueue<McpOauthRequiredEventDto> _pendingMcpOauthRequests = new();
|
private readonly ConcurrentQueue<McpOauthRequiredEventDto> _pendingMcpOauthRequests = new();
|
||||||
private readonly ConcurrentDictionary<string, AgentIdentity> _observedAgentsByMessageId = new(StringComparer.Ordinal);
|
private readonly ConcurrentDictionary<string, AgentIdentity> _observedAgentsByMessageId = new(StringComparer.Ordinal);
|
||||||
|
private readonly ConcurrentDictionary<string, ProviderReasoningSnapshot> _reasoningById = new(StringComparer.Ordinal);
|
||||||
|
private readonly ConcurrentDictionary<string, string> _latestIntentByAgentId = new(StringComparer.Ordinal);
|
||||||
private readonly StreamingTranscriptBuffer _transcriptBuffer = new();
|
private readonly StreamingTranscriptBuffer _transcriptBuffer = new();
|
||||||
private int _fallbackMessageIndex;
|
private int _fallbackMessageIndex;
|
||||||
private string? _lastObservedMessageId;
|
private string? _lastObservedMessageId;
|
||||||
@@ -25,9 +28,7 @@ internal class TurnExecutionState
|
|||||||
_agentSubworkflowIndex = AgentIdentityResolver.BuildAgentSubworkflowIndex(command.Workflow, _workflowLibrary);
|
_agentSubworkflowIndex = AgentIdentityResolver.BuildAgentSubworkflowIndex(command.Workflow, _workflowLibrary);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ConcurrentDictionary<string, string> ToolNamesByCallId { get; } = new(StringComparer.Ordinal);
|
public ToolCallRegistry ToolCalls { get; } = new();
|
||||||
|
|
||||||
public ConcurrentDictionary<string, bool> ToolCallHasArgumentsById { get; } = new(StringComparer.Ordinal);
|
|
||||||
|
|
||||||
public AgentIdentity? ActiveAgent { get; private set; }
|
public AgentIdentity? ActiveAgent { get; private set; }
|
||||||
|
|
||||||
@@ -35,8 +36,19 @@ internal class TurnExecutionState
|
|||||||
|
|
||||||
public bool HasPendingExitPlanModeRequest { get; private set; }
|
public bool HasPendingExitPlanModeRequest { get; private set; }
|
||||||
|
|
||||||
|
public ProviderTurnStreamCapabilities StreamCapabilities { get; private set; } = ProviderTurnStreamCapabilities.None;
|
||||||
|
|
||||||
|
public string? CurrentProviderTurnId { get; private set; }
|
||||||
|
|
||||||
|
public string? LatestCompletedProviderTurnId { get; private set; }
|
||||||
|
|
||||||
public bool SuppressHookLifecycleEvents { get; set; }
|
public bool SuppressHookLifecycleEvents { get; set; }
|
||||||
|
|
||||||
|
public void SetStreamCapabilities(ProviderTurnStreamCapabilities capabilities)
|
||||||
|
{
|
||||||
|
StreamCapabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities));
|
||||||
|
}
|
||||||
|
|
||||||
public AgentIdentity ResolveAgentIdentity(string? agentId, string? agentName)
|
public AgentIdentity ResolveAgentIdentity(string? agentId, string? agentName)
|
||||||
{
|
{
|
||||||
return AgentIdentityResolver.ResolveAgentIdentity(
|
return AgentIdentityResolver.ResolveAgentIdentity(
|
||||||
@@ -143,6 +155,20 @@ internal class TurnExecutionState
|
|||||||
case ProviderAssistantMessageEvent assistantMessage:
|
case ProviderAssistantMessageEvent assistantMessage:
|
||||||
RecordObservedAgentForMessage(agent, assistantMessage.MessageId);
|
RecordObservedAgentForMessage(agent, assistantMessage.MessageId);
|
||||||
QueueThinkingIfNeeded(agent);
|
QueueThinkingIfNeeded(agent);
|
||||||
|
if (!string.IsNullOrWhiteSpace(assistantMessage.Content)
|
||||||
|
&& TryFinalizeTranscriptMessage(
|
||||||
|
assistantMessage.MessageId,
|
||||||
|
agent.AgentName,
|
||||||
|
assistantMessage.Content,
|
||||||
|
out TranscriptSegment finalizedSegment))
|
||||||
|
{
|
||||||
|
_pendingEvents.Enqueue(CreateTurnDeltaEvent(
|
||||||
|
finalizedSegment.MessageId,
|
||||||
|
finalizedSegment.AuthorName,
|
||||||
|
string.Empty,
|
||||||
|
finalizedSegment.Content));
|
||||||
|
}
|
||||||
|
|
||||||
if (assistantMessage.HasToolRequests)
|
if (assistantMessage.HasToolRequests)
|
||||||
{
|
{
|
||||||
QueueMessageReclassifiedIfNeeded(assistantMessage.MessageId);
|
QueueMessageReclassifiedIfNeeded(assistantMessage.MessageId);
|
||||||
@@ -151,20 +177,36 @@ internal class TurnExecutionState
|
|||||||
case ProviderToolExecutionStartEvent toolExecutionStart:
|
case ProviderToolExecutionStartEvent toolExecutionStart:
|
||||||
string toolCallId = toolExecutionStart.ToolCallId;
|
string toolCallId = toolExecutionStart.ToolCallId;
|
||||||
string toolName = toolExecutionStart.ToolName;
|
string toolName = toolExecutionStart.ToolName;
|
||||||
TrackToolCall(toolCallId, toolName, toolExecutionStart.ToolArguments);
|
bool shouldQueueToolActivity = TrackToolCall(toolCallId, toolName, toolExecutionStart.ToolArguments);
|
||||||
ActiveAgent = agent;
|
ActiveAgent = agent;
|
||||||
AgentActivityEventDto? toolActivity = CreateToolCallingActivity(
|
if (shouldQueueToolActivity)
|
||||||
agent, toolName, toolCallId, toolExecutionStart.ToolArguments);
|
|
||||||
if (toolActivity is not null)
|
|
||||||
{
|
{
|
||||||
_pendingEvents.Enqueue(toolActivity);
|
AgentActivityEventDto? toolActivity = CreateToolCallingActivity(
|
||||||
|
agent, toolName, toolCallId, toolExecutionStart.ToolArguments);
|
||||||
|
if (toolActivity is not null)
|
||||||
|
{
|
||||||
|
_pendingEvents.Enqueue(toolActivity);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
QueueMessageReclassifiedIfNeeded(_lastObservedMessageId);
|
QueueMessageReclassifiedIfNeeded(_lastObservedMessageId);
|
||||||
break;
|
break;
|
||||||
|
case ProviderToolExecutionProgressEvent toolExecutionProgress:
|
||||||
|
ActiveAgent = agent;
|
||||||
|
TrackToolExecutionProgress(toolExecutionProgress.ToolCallId, toolExecutionProgress.ProgressMessage);
|
||||||
|
break;
|
||||||
|
case ProviderToolExecutionPartialResultEvent toolExecutionPartialResult:
|
||||||
|
ActiveAgent = agent;
|
||||||
|
TrackToolExecutionPartialResult(toolExecutionPartialResult.ToolCallId, toolExecutionPartialResult.PartialOutput);
|
||||||
|
break;
|
||||||
|
case ProviderToolExecutionCompleteEvent toolExecutionComplete:
|
||||||
|
ActiveAgent = agent;
|
||||||
|
TrackToolExecutionComplete(toolExecutionComplete);
|
||||||
|
break;
|
||||||
case ProviderAssistantIntentEvent intentEvent:
|
case ProviderAssistantIntentEvent intentEvent:
|
||||||
ActiveAgent = agent;
|
ActiveAgent = agent;
|
||||||
QueueThinkingIfNeeded(agent);
|
QueueThinkingIfNeeded(agent);
|
||||||
|
TrackLatestIntent(agent.AgentId, intentEvent.Intent);
|
||||||
AssistantIntentEventDto? assistantIntent = CreateAssistantIntentEvent(agent, intentEvent.Intent);
|
AssistantIntentEventDto? assistantIntent = CreateAssistantIntentEvent(agent, intentEvent.Intent);
|
||||||
if (assistantIntent is not null)
|
if (assistantIntent is not null)
|
||||||
{
|
{
|
||||||
@@ -174,6 +216,7 @@ internal class TurnExecutionState
|
|||||||
case ProviderAssistantReasoningDeltaEvent reasoningDelta:
|
case ProviderAssistantReasoningDeltaEvent reasoningDelta:
|
||||||
ActiveAgent = agent;
|
ActiveAgent = agent;
|
||||||
QueueThinkingIfNeeded(agent);
|
QueueThinkingIfNeeded(agent);
|
||||||
|
TrackReasoningContent(reasoningDelta.ReasoningId, reasoningDelta.DeltaContent, isComplete: false);
|
||||||
ReasoningDeltaEventDto? reasoningDeltaEvent = CreateReasoningDeltaEvent(
|
ReasoningDeltaEventDto? reasoningDeltaEvent = CreateReasoningDeltaEvent(
|
||||||
agent,
|
agent,
|
||||||
reasoningDelta.ReasoningId,
|
reasoningDelta.ReasoningId,
|
||||||
@@ -183,6 +226,22 @@ internal class TurnExecutionState
|
|||||||
_pendingEvents.Enqueue(reasoningDeltaEvent);
|
_pendingEvents.Enqueue(reasoningDeltaEvent);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
case ProviderAssistantReasoningEvent reasoning:
|
||||||
|
ActiveAgent = agent;
|
||||||
|
TrackReasoningContent(reasoning.ReasoningId, reasoning.Content, isComplete: true);
|
||||||
|
break;
|
||||||
|
case ProviderAssistantTurnStartEvent turnStart:
|
||||||
|
ActiveAgent = agent;
|
||||||
|
CurrentProviderTurnId = turnStart.TurnId;
|
||||||
|
break;
|
||||||
|
case ProviderAssistantTurnEndEvent turnEnd:
|
||||||
|
ActiveAgent = agent;
|
||||||
|
LatestCompletedProviderTurnId = turnEnd.TurnId;
|
||||||
|
if (string.Equals(CurrentProviderTurnId, turnEnd.TurnId, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
CurrentProviderTurnId = null;
|
||||||
|
}
|
||||||
|
break;
|
||||||
case ProviderSubagentStartedEvent started:
|
case ProviderSubagentStartedEvent started:
|
||||||
ActiveAgent = agent;
|
ActiveAgent = agent;
|
||||||
_pendingEvents.Enqueue(CreateSubagentStartedEvent(agent, started));
|
_pendingEvents.Enqueue(CreateSubagentStartedEvent(agent, started));
|
||||||
@@ -291,6 +350,25 @@ internal class TurnExecutionState
|
|||||||
return pending;
|
return pending;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public bool TryGetToolExecution(string? toolCallId, [NotNullWhen(true)] out ProviderToolExecutionSnapshot? snapshot)
|
||||||
|
{
|
||||||
|
return ToolCalls.TryGetExecution(toolCallId, out snapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetReasoning(string? reasoningId, [NotNullWhen(true)] out ProviderReasoningSnapshot? snapshot)
|
||||||
|
{
|
||||||
|
snapshot = null;
|
||||||
|
return !string.IsNullOrWhiteSpace(reasoningId)
|
||||||
|
&& _reasoningById.TryGetValue(reasoningId, out snapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryGetLatestIntent(string? agentId, [NotNullWhen(true)] out string? intent)
|
||||||
|
{
|
||||||
|
intent = null;
|
||||||
|
return !string.IsNullOrWhiteSpace(agentId)
|
||||||
|
&& _latestIntentByAgentId.TryGetValue(agentId, out intent);
|
||||||
|
}
|
||||||
|
|
||||||
public bool TryResolveObservedAgentForMessage(string? messageId, out AgentIdentity agent)
|
public bool TryResolveObservedAgentForMessage(string? messageId, out AgentIdentity agent)
|
||||||
{
|
{
|
||||||
agent = default;
|
agent = default;
|
||||||
@@ -311,6 +389,24 @@ internal class TurnExecutionState
|
|||||||
return _transcriptBuffer.AppendDelta(messageId, authorName, delta);
|
return _transcriptBuffer.AppendDelta(messageId, authorName, delta);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public bool TryAppendDelta(
|
||||||
|
string messageId,
|
||||||
|
string authorName,
|
||||||
|
string delta,
|
||||||
|
out TranscriptSegment segment)
|
||||||
|
{
|
||||||
|
return _transcriptBuffer.TryAppendDelta(messageId, authorName, delta, out segment);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool TryFinalizeTranscriptMessage(
|
||||||
|
string messageId,
|
||||||
|
string authorName,
|
||||||
|
string content,
|
||||||
|
out TranscriptSegment segment)
|
||||||
|
{
|
||||||
|
return _transcriptBuffer.TryApplySnapshot(messageId, authorName, content, out segment);
|
||||||
|
}
|
||||||
|
|
||||||
public void ClearActiveAgentIfMatching(AgentIdentity completedAgent)
|
public void ClearActiveAgentIfMatching(AgentIdentity completedAgent)
|
||||||
{
|
{
|
||||||
if (ActiveAgent.HasValue
|
if (ActiveAgent.HasValue
|
||||||
@@ -327,13 +423,61 @@ internal class TurnExecutionState
|
|||||||
_lastObservedMessageId = messageId;
|
_lastObservedMessageId = messageId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void TrackToolCall(
|
private bool TrackToolCall(
|
||||||
string toolCallId,
|
string toolCallId,
|
||||||
string toolName,
|
string toolName,
|
||||||
IReadOnlyDictionary<string, object?>? toolArguments)
|
IReadOnlyDictionary<string, object?>? toolArguments)
|
||||||
{
|
{
|
||||||
ToolNamesByCallId[toolCallId] = toolName;
|
return ToolCalls.TryRecordToolRequest(toolCallId, toolName, toolArguments);
|
||||||
ToolCallHasArgumentsById[toolCallId] = toolArguments is { Count: > 0 };
|
}
|
||||||
|
|
||||||
|
private void TrackToolExecutionProgress(string toolCallId, string? progressMessage)
|
||||||
|
{
|
||||||
|
ToolCalls.RecordProgress(toolCallId, progressMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void TrackToolExecutionPartialResult(string toolCallId, string? partialOutput)
|
||||||
|
{
|
||||||
|
ToolCalls.RecordPartialResult(toolCallId, partialOutput);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void TrackToolExecutionComplete(ProviderToolExecutionCompleteEvent toolExecution)
|
||||||
|
{
|
||||||
|
ToolCalls.RecordCompletion(toolExecution);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void TrackLatestIntent(string agentId, string? intent)
|
||||||
|
{
|
||||||
|
string? normalizedIntent = NormalizeOptionalString(intent);
|
||||||
|
if (normalizedIntent is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_latestIntentByAgentId[agentId] = normalizedIntent;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void TrackReasoningContent(string? reasoningId, string? content, bool isComplete)
|
||||||
|
{
|
||||||
|
string? normalizedReasoningId = NormalizeOptionalString(reasoningId);
|
||||||
|
if (normalizedReasoningId is null || content is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_reasoningById.AddOrUpdate(
|
||||||
|
normalizedReasoningId,
|
||||||
|
id => new ProviderReasoningSnapshot
|
||||||
|
{
|
||||||
|
ReasoningId = id,
|
||||||
|
Content = content,
|
||||||
|
IsComplete = isComplete,
|
||||||
|
},
|
||||||
|
(_, existing) => existing with
|
||||||
|
{
|
||||||
|
Content = isComplete ? content : string.Concat(existing.Content, content),
|
||||||
|
IsComplete = isComplete || existing.IsComplete,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void QueueMessageReclassifiedIfNeeded(string? messageId)
|
private void QueueMessageReclassifiedIfNeeded(string? messageId)
|
||||||
@@ -613,6 +757,24 @@ internal class TurnExecutionState
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private TurnDeltaEventDto CreateTurnDeltaEvent(
|
||||||
|
string messageId,
|
||||||
|
string authorName,
|
||||||
|
string contentDelta,
|
||||||
|
string? content)
|
||||||
|
{
|
||||||
|
return new TurnDeltaEventDto
|
||||||
|
{
|
||||||
|
Type = "turn-delta",
|
||||||
|
RequestId = _command.RequestId,
|
||||||
|
SessionId = _command.SessionId,
|
||||||
|
MessageId = messageId,
|
||||||
|
AuthorName = authorName,
|
||||||
|
ContentDelta = contentDelta,
|
||||||
|
Content = content,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private SkillInvokedEventDto CreateSkillInvokedEvent(
|
private SkillInvokedEventDto CreateSkillInvokedEvent(
|
||||||
AgentIdentity agent,
|
AgentIdentity agent,
|
||||||
ProviderSkillInvokedEvent data)
|
ProviderSkillInvokedEvent data)
|
||||||
@@ -759,4 +921,9 @@ internal class TurnExecutionState
|
|||||||
AgentName = agent.AgentName,
|
AgentName = agent.AgentName,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string? NormalizeOptionalString(string? value)
|
||||||
|
{
|
||||||
|
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using System.Collections.Concurrent;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Aryx.AgentHost.Contracts;
|
using Aryx.AgentHost.Contracts;
|
||||||
using Microsoft.Agents.AI.Workflows;
|
using Microsoft.Agents.AI.Workflows;
|
||||||
@@ -20,8 +19,7 @@ internal static class WorkflowRequestInfoInterpreter
|
|||||||
RunTurnCommandDto command,
|
RunTurnCommandDto command,
|
||||||
RequestInfoEvent requestInfo,
|
RequestInfoEvent requestInfo,
|
||||||
AgentIdentity? activeAgent,
|
AgentIdentity? activeAgent,
|
||||||
ConcurrentDictionary<string, string> toolNamesByCallId,
|
ToolCallRegistry toolCalls)
|
||||||
ConcurrentDictionary<string, bool> toolCallHasArgumentsById)
|
|
||||||
{
|
{
|
||||||
RequestInterpretation interpretation = InterpretRequest(command, requestInfo);
|
RequestInterpretation interpretation = InterpretRequest(command, requestInfo);
|
||||||
return interpretation switch
|
return interpretation switch
|
||||||
@@ -29,7 +27,7 @@ internal static class WorkflowRequestInfoInterpreter
|
|||||||
HandoffRequestInterpretation handoff =>
|
HandoffRequestInterpretation handoff =>
|
||||||
CreateHandoffActivity(command, handoff.TargetAgent, activeAgent),
|
CreateHandoffActivity(command, handoff.TargetAgent, activeAgent),
|
||||||
ToolRequestInterpretation tool when activeAgent.HasValue =>
|
ToolRequestInterpretation tool when activeAgent.HasValue =>
|
||||||
CreateToolCallingActivity(command, activeAgent.Value, tool, toolNamesByCallId, toolCallHasArgumentsById),
|
CreateToolCallingActivity(command, activeAgent.Value, tool, toolCalls),
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -66,22 +64,13 @@ internal static class WorkflowRequestInfoInterpreter
|
|||||||
RunTurnCommandDto command,
|
RunTurnCommandDto command,
|
||||||
AgentIdentity activeAgent,
|
AgentIdentity activeAgent,
|
||||||
ToolRequestInterpretation tool,
|
ToolRequestInterpretation tool,
|
||||||
ConcurrentDictionary<string, string> toolNamesByCallId,
|
ToolCallRegistry toolCalls)
|
||||||
ConcurrentDictionary<string, bool> toolCallHasArgumentsById)
|
|
||||||
{
|
{
|
||||||
bool hasToolArguments = tool.ToolArguments is { Count: > 0 };
|
if (!toolCalls.TryRecordToolRequest(tool.ToolCallId, tool.ToolName, tool.ToolArguments))
|
||||||
if (tool.ToolCallId is not null && toolNamesByCallId.ContainsKey(tool.ToolCallId))
|
|
||||||
{
|
{
|
||||||
bool trackedHasArguments = toolCallHasArgumentsById.TryGetValue(tool.ToolCallId, out bool hasTrackedArguments)
|
return null;
|
||||||
&& hasTrackedArguments;
|
|
||||||
if (trackedHasArguments || !hasToolArguments)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
TrackToolCallId(toolNamesByCallId, toolCallHasArgumentsById, tool.ToolCallId, tool.ToolName, hasToolArguments);
|
|
||||||
|
|
||||||
return new AgentActivityEventDto
|
return new AgentActivityEventDto
|
||||||
{
|
{
|
||||||
Type = "agent-activity",
|
Type = "agent-activity",
|
||||||
@@ -98,20 +87,6 @@ internal static class WorkflowRequestInfoInterpreter
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void TrackToolCallId(
|
|
||||||
ConcurrentDictionary<string, string> toolNamesByCallId,
|
|
||||||
ConcurrentDictionary<string, bool> toolCallHasArgumentsById,
|
|
||||||
string? toolCallId,
|
|
||||||
string toolName,
|
|
||||||
bool hasToolArguments)
|
|
||||||
{
|
|
||||||
if (toolCallId is not null)
|
|
||||||
{
|
|
||||||
toolNamesByCallId[toolCallId] = toolName;
|
|
||||||
toolCallHasArgumentsById[toolCallId] = hasToolArguments;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static RequestInterpretation InterpretRequest(
|
private static RequestInterpretation InterpretRequest(
|
||||||
RunTurnCommandDto command,
|
RunTurnCommandDto command,
|
||||||
RequestInfoEvent requestInfo)
|
RequestInfoEvent requestInfo)
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ internal sealed class WorkflowRunner
|
|||||||
builder = builder.WithName(workflowDefinition.Name);
|
builder = builder.WithName(workflowDefinition.Name);
|
||||||
}
|
}
|
||||||
|
|
||||||
return builder.WithOutputFrom(routes[endNode.Id].Exit).Build();
|
return builder.WithOutputFrom(routes[endNode.Id].Exit).WithOpenTelemetry().Build();
|
||||||
}
|
}
|
||||||
|
|
||||||
private WorkflowNodeRoute CreateNodeRoute(
|
private WorkflowNodeRoute CreateNodeRoute(
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
using Aryx.AgentHost.Contracts;
|
||||||
|
using Aryx.AgentHost.Services;
|
||||||
|
using GitHub.Copilot.SDK;
|
||||||
|
|
||||||
|
namespace Aryx.AgentHost.Tests;
|
||||||
|
|
||||||
|
public sealed class CopilotEventAdapterTests
|
||||||
|
{
|
||||||
|
private static readonly CopilotEventAdapter Adapter = new();
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Capabilities_AdvertiseRichTurnStreamSupport()
|
||||||
|
{
|
||||||
|
ProviderTurnStreamCapabilities capabilities = Adapter.Capabilities;
|
||||||
|
|
||||||
|
Assert.True(capabilities.SupportsIntent);
|
||||||
|
Assert.True(capabilities.SupportsReasoningDelta);
|
||||||
|
Assert.True(capabilities.SupportsReasoningBlock);
|
||||||
|
Assert.True(capabilities.SupportsToolExecutionProgress);
|
||||||
|
Assert.True(capabilities.SupportsToolExecutionPartialResult);
|
||||||
|
Assert.True(capabilities.SupportsToolExecutionCompletion);
|
||||||
|
Assert.True(capabilities.SupportsSubagentLifecycle);
|
||||||
|
Assert.True(capabilities.SupportsHookLifecycle);
|
||||||
|
Assert.True(capabilities.SupportsSessionCompaction);
|
||||||
|
Assert.True(capabilities.SupportsPendingMessagesMutation);
|
||||||
|
Assert.True(capabilities.SupportsSessionTurnBoundaries);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryAdapt_ToolExecutionComplete_MapsNormalizedResult()
|
||||||
|
{
|
||||||
|
ProviderToolExecutionCompleteEvent evt = Assert.IsType<ProviderToolExecutionCompleteEvent>(
|
||||||
|
Adapter.TryAdapt(SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "tool.execution_complete",
|
||||||
|
"data": {
|
||||||
|
"toolCallId": "tool-call-1",
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"content": "summary",
|
||||||
|
"detailedContent": "summary\nfull"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": "11111111-2222-3333-4444-555555555555",
|
||||||
|
"timestamp": "2026-03-27T00:00:00Z"
|
||||||
|
}
|
||||||
|
""")));
|
||||||
|
|
||||||
|
Assert.Equal("tool-call-1", evt.ToolCallId);
|
||||||
|
Assert.True(evt.Success);
|
||||||
|
Assert.Equal("summary", evt.ResultContent);
|
||||||
|
Assert.Equal("summary\nfull", evt.DetailedResultContent);
|
||||||
|
Assert.Null(evt.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TryAdapt_AssistantReasoning_MapsCompletedReasoningBlock()
|
||||||
|
{
|
||||||
|
ProviderAssistantReasoningEvent evt = Assert.IsType<ProviderAssistantReasoningEvent>(
|
||||||
|
Adapter.TryAdapt(SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "assistant.reasoning",
|
||||||
|
"data": {
|
||||||
|
"reasoningId": "reasoning-1",
|
||||||
|
"content": "Planning the next step."
|
||||||
|
},
|
||||||
|
"id": "66666666-7777-8888-9999-aaaaaaaaaaaa",
|
||||||
|
"timestamp": "2026-03-27T00:00:00Z"
|
||||||
|
}
|
||||||
|
""")));
|
||||||
|
|
||||||
|
Assert.Equal("reasoning-1", evt.ReasoningId);
|
||||||
|
Assert.Equal("Planning the next step.", evt.Content);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -154,11 +154,15 @@ public sealed class CopilotSessionHooksTests
|
|||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("view", "read")]
|
[InlineData("view", "read")]
|
||||||
[InlineData("grep", "read")]
|
[InlineData("grep", "read")]
|
||||||
|
[InlineData("rg", "read")]
|
||||||
[InlineData("edit", "write")]
|
[InlineData("edit", "write")]
|
||||||
|
[InlineData("apply_patch", "write")]
|
||||||
[InlineData("powershell", "shell")]
|
[InlineData("powershell", "shell")]
|
||||||
public async Task Create_PreToolUseAutoAllowsWhenCategoryIsApproved(string toolName, string category)
|
[InlineData("web_search", "web_fetch")]
|
||||||
|
[InlineData("store_memory", "store_memory")]
|
||||||
|
public async Task Create_PreToolUseAutoAllowsWhenApprovalToolKeyIsApproved(string toolName, string approvalToolKey)
|
||||||
{
|
{
|
||||||
RunTurnCommandDto command = CreateCommandWithAutoApprovedCategory(category);
|
RunTurnCommandDto command = CreateCommandWithAutoApprovedCategory(approvalToolKey);
|
||||||
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner());
|
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Workflow.GetAgentNodes()[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner());
|
||||||
|
|
||||||
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
|
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
|
||||||
|
|||||||
@@ -110,10 +110,9 @@ public sealed class CopilotTurnExecutionStateTests
|
|||||||
Assert.Equal("tool-call-1", toolActivity.ToolCallId);
|
Assert.Equal("tool-call-1", toolActivity.ToolCallId);
|
||||||
Assert.NotNull(toolActivity.ToolArguments);
|
Assert.NotNull(toolActivity.ToolArguments);
|
||||||
Assert.Equal("/src/main.ts", toolActivity.ToolArguments["path"]);
|
Assert.Equal("/src/main.ts", toolActivity.ToolArguments["path"]);
|
||||||
Assert.True(state.ToolNamesByCallId.TryGetValue("tool-call-1", out string? toolName));
|
Assert.True(state.ToolCalls.TryGetToolName("tool-call-1", out string? toolName));
|
||||||
Assert.Equal("view", toolName);
|
Assert.Equal("view", toolName);
|
||||||
Assert.True(state.ToolCallHasArgumentsById.TryGetValue("tool-call-1", out bool hasArguments));
|
Assert.True(state.ToolCalls.HasTrackedArguments("tool-call-1"));
|
||||||
Assert.True(hasArguments);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -129,8 +128,115 @@ public sealed class CopilotTurnExecutionStateTests
|
|||||||
|
|
||||||
AgentActivityEventDto toolActivity = Assert.Single(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
|
AgentActivityEventDto toolActivity = Assert.Single(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
|
||||||
Assert.Null(toolActivity.ToolArguments);
|
Assert.Null(toolActivity.ToolArguments);
|
||||||
Assert.True(state.ToolCallHasArgumentsById.TryGetValue("tool-call-1", out bool hasArguments));
|
Assert.False(state.ToolCalls.HasTrackedArguments("tool-call-1"));
|
||||||
Assert.False(hasArguments);
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ObserveSessionEvent_ToolExecutionProgress_TracksLatestProgressMessage()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[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"}"""));
|
||||||
|
_ = state.DrainPendingEvents();
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""{"type":"tool.execution_progress","data":{"toolCallId":"tool-call-1","progressMessage":"Scanning repository"},"id":"43333333-3333-3333-3333-333333333333","timestamp":"2026-03-27T00:00:01Z"}"""));
|
||||||
|
|
||||||
|
Assert.True(state.TryGetToolExecution("tool-call-1", out ProviderToolExecutionSnapshot? toolExecution));
|
||||||
|
Assert.NotNull(toolExecution);
|
||||||
|
Assert.Equal(ProviderToolExecutionStatus.Running, toolExecution.Status);
|
||||||
|
Assert.Equal("view", toolExecution.ToolName);
|
||||||
|
Assert.Equal("Scanning repository", toolExecution.LatestProgressMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ObserveSessionEvent_ToolExecutionPartialResult_AppendsPartialOutput()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""{"type":"tool.execution_start","data":{"toolCallId":"tool-call-1","toolName":"bash"},"id":"53333333-3333-3333-3333-333333333333","timestamp":"2026-03-27T00:00:00Z"}"""));
|
||||||
|
_ = state.DrainPendingEvents();
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""{"type":"tool.execution_partial_result","data":{"toolCallId":"tool-call-1","partialOutput":"first line\n"},"id":"63333333-3333-3333-3333-333333333333","timestamp":"2026-03-27T00:00:01Z"}"""));
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""{"type":"tool.execution_partial_result","data":{"toolCallId":"tool-call-1","partialOutput":"second line"},"id":"73333333-3333-3333-3333-333333333333","timestamp":"2026-03-27T00:00:02Z"}"""));
|
||||||
|
|
||||||
|
Assert.True(state.TryGetToolExecution("tool-call-1", out ProviderToolExecutionSnapshot? toolExecution));
|
||||||
|
Assert.NotNull(toolExecution);
|
||||||
|
Assert.Equal("first line\nsecond line", toolExecution.PartialOutput);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ObserveSessionEvent_ToolExecutionComplete_TracksFinalToolState()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""{"type":"tool.execution_start","data":{"toolCallId":"tool-call-1","toolName":"view","arguments":{"path":"README.md"}},"id":"83333333-3333-3333-3333-333333333333","timestamp":"2026-03-27T00:00:00Z"}"""));
|
||||||
|
_ = state.DrainPendingEvents();
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "tool.execution_complete",
|
||||||
|
"data": {
|
||||||
|
"toolCallId": "tool-call-1",
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"content": "README excerpt",
|
||||||
|
"detailedContent": "README excerpt\nwith more detail"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": "93333333-3333-3333-3333-333333333333",
|
||||||
|
"timestamp": "2026-03-27T00:00:01Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
|
||||||
|
Assert.True(state.TryGetToolExecution("tool-call-1", out ProviderToolExecutionSnapshot? toolExecution));
|
||||||
|
Assert.NotNull(toolExecution);
|
||||||
|
Assert.Equal(ProviderToolExecutionStatus.Completed, toolExecution.Status);
|
||||||
|
Assert.Equal("view", toolExecution.ToolName);
|
||||||
|
Assert.NotNull(toolExecution.ToolArguments);
|
||||||
|
Assert.Equal("README excerpt", toolExecution.ResultContent);
|
||||||
|
Assert.Equal("README excerpt\nwith more detail", toolExecution.DetailedResultContent);
|
||||||
|
Assert.Null(toolExecution.Error);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ObserveSessionEvent_ToolExecutionCompleteFailure_TracksErrorState()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""{"type":"tool.execution_complete","data":{"toolCallId":"tool-call-err","success":false,"error":{"message":"permission denied"}},"id":"a3333333-3333-3333-3333-333333333333","timestamp":"2026-03-27T00:00:01Z"}"""));
|
||||||
|
|
||||||
|
Assert.True(state.TryGetToolExecution("tool-call-err", out ProviderToolExecutionSnapshot? toolExecution));
|
||||||
|
Assert.NotNull(toolExecution);
|
||||||
|
Assert.Equal(ProviderToolExecutionStatus.Failed, toolExecution.Status);
|
||||||
|
Assert.Equal("permission denied", toolExecution.Error);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -145,10 +251,9 @@ public sealed class CopilotTurnExecutionStateTests
|
|||||||
"""{"type":"tool.execution_start","data":{"toolCallId":"tool-call-1","toolName":"handoff_to_specialist"},"id":"1ce9d1dc-68f1-4df5-9728-f97017233279","timestamp":"2026-03-27T00:00:00Z"}"""));
|
"""{"type":"tool.execution_start","data":{"toolCallId":"tool-call-1","toolName":"handoff_to_specialist"},"id":"1ce9d1dc-68f1-4df5-9728-f97017233279","timestamp":"2026-03-27T00:00:00Z"}"""));
|
||||||
|
|
||||||
Assert.Empty(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
|
Assert.Empty(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
|
||||||
Assert.True(state.ToolNamesByCallId.TryGetValue("tool-call-1", out string? toolName));
|
Assert.True(state.ToolCalls.TryGetToolName("tool-call-1", out string? toolName));
|
||||||
Assert.Equal("handoff_to_specialist", toolName);
|
Assert.Equal("handoff_to_specialist", toolName);
|
||||||
Assert.True(state.ToolCallHasArgumentsById.TryGetValue("tool-call-1", out bool hasArguments));
|
Assert.False(state.ToolCalls.HasTrackedArguments("tool-call-1"));
|
||||||
Assert.False(hasArguments);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -267,14 +372,12 @@ public sealed class CopilotTurnExecutionStateTests
|
|||||||
Assert.Contains(toolActivities, activity => activity.ToolCallId == "tool-call-2" && activity.ToolName == "view");
|
Assert.Contains(toolActivities, activity => activity.ToolCallId == "tool-call-2" && activity.ToolName == "view");
|
||||||
MessageReclassifiedEventDto reclassified = Assert.Single(pending.OfType<MessageReclassifiedEventDto>());
|
MessageReclassifiedEventDto reclassified = Assert.Single(pending.OfType<MessageReclassifiedEventDto>());
|
||||||
Assert.Equal("msg-3", reclassified.MessageId);
|
Assert.Equal("msg-3", reclassified.MessageId);
|
||||||
Assert.True(state.ToolNamesByCallId.TryGetValue("tool-call-1", out string? firstToolName));
|
Assert.True(state.ToolCalls.TryGetToolName("tool-call-1", out string? firstToolName));
|
||||||
Assert.Equal("rg", firstToolName);
|
Assert.Equal("rg", firstToolName);
|
||||||
Assert.True(state.ToolNamesByCallId.TryGetValue("tool-call-2", out string? secondToolName));
|
Assert.True(state.ToolCalls.TryGetToolName("tool-call-2", out string? secondToolName));
|
||||||
Assert.Equal("view", secondToolName);
|
Assert.Equal("view", secondToolName);
|
||||||
Assert.True(state.ToolCallHasArgumentsById.TryGetValue("tool-call-1", out bool firstHasArguments));
|
Assert.False(state.ToolCalls.HasTrackedArguments("tool-call-1"));
|
||||||
Assert.False(firstHasArguments);
|
Assert.False(state.ToolCalls.HasTrackedArguments("tool-call-2"));
|
||||||
Assert.True(state.ToolCallHasArgumentsById.TryGetValue("tool-call-2", out bool secondHasArguments));
|
|
||||||
Assert.False(secondHasArguments);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -366,6 +469,9 @@ public sealed class CopilotTurnExecutionStateTests
|
|||||||
Assert.Equal("session-1", intent.SessionId);
|
Assert.Equal("session-1", intent.SessionId);
|
||||||
Assert.Equal("agent-1", intent.AgentId);
|
Assert.Equal("agent-1", intent.AgentId);
|
||||||
Assert.Equal("Searching incident playbooks", intent.Intent);
|
Assert.Equal("Searching incident playbooks", intent.Intent);
|
||||||
|
Assert.True(state.TryGetLatestIntent("agent-1", out string? latestIntent));
|
||||||
|
Assert.NotNull(latestIntent);
|
||||||
|
Assert.Equal("Searching incident playbooks", latestIntent);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -399,6 +505,93 @@ public sealed class CopilotTurnExecutionStateTests
|
|||||||
Assert.Equal("agent-1", reasoning.AgentId);
|
Assert.Equal("agent-1", reasoning.AgentId);
|
||||||
Assert.Equal("reasoning-2", reasoning.ReasoningId);
|
Assert.Equal("reasoning-2", reasoning.ReasoningId);
|
||||||
Assert.Equal("Searching logs.", reasoning.ContentDelta);
|
Assert.Equal("Searching logs.", reasoning.ContentDelta);
|
||||||
|
Assert.True(state.TryGetReasoning("reasoning-2", out ProviderReasoningSnapshot? reasoningState));
|
||||||
|
Assert.NotNull(reasoningState);
|
||||||
|
Assert.Equal("Searching logs.", reasoningState.Content);
|
||||||
|
Assert.False(reasoningState.IsComplete);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ObserveSessionEvent_AssistantReasoning_TracksCompletedReasoningBlock()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "assistant.reasoning_delta",
|
||||||
|
"data": {
|
||||||
|
"reasoningId": "reasoning-3",
|
||||||
|
"deltaContent": "Planning."
|
||||||
|
},
|
||||||
|
"id": "cd269258-5e5d-46b6-bf3f-bd8cba793b1a",
|
||||||
|
"timestamp": "2026-03-27T00:00:00Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
_ = state.DrainPendingEvents();
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "assistant.reasoning",
|
||||||
|
"data": {
|
||||||
|
"reasoningId": "reasoning-3",
|
||||||
|
"content": "Planning. Checking logs."
|
||||||
|
},
|
||||||
|
"id": "dd269258-5e5d-46b6-bf3f-bd8cba793b1a",
|
||||||
|
"timestamp": "2026-03-27T00:00:01Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
|
||||||
|
Assert.True(state.TryGetReasoning("reasoning-3", out ProviderReasoningSnapshot? reasoning));
|
||||||
|
Assert.NotNull(reasoning);
|
||||||
|
Assert.Equal("Planning. Checking logs.", reasoning.Content);
|
||||||
|
Assert.True(reasoning.IsComplete);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ObserveSessionEvent_AssistantTurnBoundaries_TrackProviderTurnIds()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "assistant.turn_start",
|
||||||
|
"data": {
|
||||||
|
"turnId": "turn-sdk-1"
|
||||||
|
},
|
||||||
|
"id": "ed269258-5e5d-46b6-bf3f-bd8cba793b1a",
|
||||||
|
"timestamp": "2026-03-27T00:00:00Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
|
||||||
|
Assert.Equal("turn-sdk-1", state.CurrentProviderTurnId);
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "assistant.turn_end",
|
||||||
|
"data": {
|
||||||
|
"turnId": "turn-sdk-1"
|
||||||
|
},
|
||||||
|
"id": "fd269258-5e5d-46b6-bf3f-bd8cba793b1a",
|
||||||
|
"timestamp": "2026-03-27T00:00:01Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
|
||||||
|
Assert.Null(state.CurrentProviderTurnId);
|
||||||
|
Assert.Equal("turn-sdk-1", state.LatestCompletedProviderTurnId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -654,6 +847,53 @@ public sealed class CopilotTurnExecutionStateTests
|
|||||||
Assert.Equal("agent-1", evt.AgentId);
|
Assert.Equal("agent-1", evt.AgentId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ObserveSessionEvent_AssistantMessage_FinalizesTranscriptAndSuppressesLateDeltas()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
|
||||||
|
Assert.True(state.TryAppendDelta("msg-final", "Primary", "Draft response", out TranscriptSegment streamed));
|
||||||
|
Assert.False(streamed.IsFinalized);
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
command.Workflow.GetAgentNodes()[0],
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "assistant.message",
|
||||||
|
"data": {
|
||||||
|
"messageId": "msg-final",
|
||||||
|
"content": "Provider final response"
|
||||||
|
},
|
||||||
|
"id": "12121212-1212-1212-1212-121212121212",
|
||||||
|
"timestamp": "2026-03-27T00:00:00Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
|
||||||
|
TurnDeltaEventDto correction = Assert.Single(state.DrainPendingEvents().OfType<TurnDeltaEventDto>());
|
||||||
|
Assert.Equal("msg-final", correction.MessageId);
|
||||||
|
Assert.Equal("Primary", correction.AuthorName);
|
||||||
|
Assert.Equal(string.Empty, correction.ContentDelta);
|
||||||
|
Assert.Equal("Provider final response", correction.Content);
|
||||||
|
|
||||||
|
Assert.False(state.TryAppendDelta("msg-final", "Primary", " late delta", out TranscriptSegment unchanged));
|
||||||
|
Assert.True(unchanged.IsFinalized);
|
||||||
|
Assert.Equal("Provider final response", unchanged.Content);
|
||||||
|
|
||||||
|
ChatMessage output = new(ChatRole.Assistant, "Workflow wording")
|
||||||
|
{
|
||||||
|
MessageId = "msg-final",
|
||||||
|
AuthorName = "assistant",
|
||||||
|
};
|
||||||
|
|
||||||
|
state.UpdateCompletedMessages([output], []);
|
||||||
|
ChatMessageDto completed = Assert.Single(state.FinalizeCompletedMessages());
|
||||||
|
Assert.Equal("msg-final", completed.Id);
|
||||||
|
Assert.Equal("Primary", completed.AuthorName);
|
||||||
|
Assert.Equal("Provider final response", completed.Content);
|
||||||
|
}
|
||||||
|
|
||||||
private static SessionEvent CreateHookStartEvent()
|
private static SessionEvent CreateHookStartEvent()
|
||||||
{
|
{
|
||||||
return SessionEvent.FromJson(
|
return SessionEvent.FromJson(
|
||||||
|
|||||||
@@ -451,6 +451,50 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ProjectCompletedMessages_UsesExactMessageIdMatchBeforeFallbackHeuristics()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand(
|
||||||
|
"group-chat",
|
||||||
|
CreateAgent(id: "agent-group-writer", name: "Writer"),
|
||||||
|
CreateAgent(id: "agent-group-reviewer", name: "Reviewer"));
|
||||||
|
|
||||||
|
IReadOnlyList<ChatMessageDto> messages = WorkflowTranscriptProjector.ProjectCompletedMessagesFromSegments(
|
||||||
|
command,
|
||||||
|
[
|
||||||
|
new ChatMessage(ChatRole.Assistant, "Revised draft with cleaner wording.")
|
||||||
|
{
|
||||||
|
AuthorName = "assistant",
|
||||||
|
MessageId = "msg-writer-2",
|
||||||
|
},
|
||||||
|
new ChatMessage(ChatRole.Assistant, "Review feedback with cleaner wording.")
|
||||||
|
{
|
||||||
|
AuthorName = "assistant",
|
||||||
|
MessageId = "msg-reviewer-1",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
new TranscriptSegment("msg-writer-1", "Writer", "Initial draft."),
|
||||||
|
new TranscriptSegment("msg-reviewer-1", "Reviewer", "Review feedback with draft wording."),
|
||||||
|
new TranscriptSegment("msg-writer-2", "Writer", "Revised draft with draft wording."),
|
||||||
|
]);
|
||||||
|
|
||||||
|
Assert.Collection(
|
||||||
|
messages,
|
||||||
|
writer =>
|
||||||
|
{
|
||||||
|
Assert.Equal("msg-writer-2", writer.Id);
|
||||||
|
Assert.Equal("Writer", writer.AuthorName);
|
||||||
|
Assert.Equal("Revised draft with cleaner wording.", writer.Content);
|
||||||
|
},
|
||||||
|
reviewer =>
|
||||||
|
{
|
||||||
|
Assert.Equal("msg-reviewer-1", reviewer.Id);
|
||||||
|
Assert.Equal("Reviewer", reviewer.AuthorName);
|
||||||
|
Assert.Equal("Review feedback with cleaner wording.", reviewer.Content);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ProjectCompletedMessages_UsesFallbackAgentForGenericAssistantOutput()
|
public void ProjectCompletedMessages_UsesFallbackAgentForGenericAssistantOutput()
|
||||||
{
|
{
|
||||||
@@ -531,6 +575,36 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Assert.Equal("Done — GoogleClient.cs now contains the requested class with cleaned formatting.", message.Content);
|
Assert.Equal("Done — GoogleClient.cs now contains the requested class with cleaned formatting.", message.Content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ProjectCompletedMessages_PrefersFinalizedSegmentContentOverWorkflowOutput()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateCommand(
|
||||||
|
"single",
|
||||||
|
CreateAgent(id: "agent-single-primary", name: "Primary Agent"));
|
||||||
|
|
||||||
|
IReadOnlyList<ChatMessageDto> messages = WorkflowTranscriptProjector.ProjectCompletedMessagesFromSegments(
|
||||||
|
command,
|
||||||
|
[
|
||||||
|
new ChatMessage(ChatRole.Assistant, "Workflow wording that arrived later.")
|
||||||
|
{
|
||||||
|
AuthorName = "assistant",
|
||||||
|
MessageId = "msg-1",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
new TranscriptSegment(
|
||||||
|
"msg-1",
|
||||||
|
"Primary Agent",
|
||||||
|
"Provider final wording that should win.",
|
||||||
|
IsFinalized: true),
|
||||||
|
]);
|
||||||
|
|
||||||
|
ChatMessageDto message = Assert.Single(messages);
|
||||||
|
Assert.Equal("msg-1", message.Id);
|
||||||
|
Assert.Equal("Primary Agent", message.AuthorName);
|
||||||
|
Assert.Equal("Provider final wording that should win.", message.Content);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ProjectCompletedMessages_DropsBlankAssistantOutputMessages()
|
public void ProjectCompletedMessages_DropsBlankAssistantOutputMessages()
|
||||||
{
|
{
|
||||||
@@ -602,7 +676,22 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Assert.Equal("msg-2", second.MessageId);
|
Assert.Equal("msg-2", second.MessageId);
|
||||||
Assert.Equal("Implementer", second.AuthorName);
|
Assert.Equal("Implementer", second.AuthorName);
|
||||||
Assert.Equal("B", second.Content);
|
Assert.Equal("B", second.Content);
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StreamingTranscriptBuffer_IgnoresLateDeltasAfterFinalSnapshot()
|
||||||
|
{
|
||||||
|
StreamingTranscriptBuffer buffer = new();
|
||||||
|
|
||||||
|
buffer.AppendDelta("msg-1", "Architect", "Draft");
|
||||||
|
Assert.True(buffer.TryApplySnapshot("msg-1", "Architect", "Final", out TranscriptSegment finalized));
|
||||||
|
Assert.True(finalized.IsFinalized);
|
||||||
|
Assert.Equal("Final", finalized.Content);
|
||||||
|
|
||||||
|
Assert.False(buffer.TryAppendDelta("msg-1", "Architect", " late delta", out TranscriptSegment unchanged));
|
||||||
|
Assert.True(unchanged.IsFinalized);
|
||||||
|
Assert.Equal("Final", unchanged.Content);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -776,8 +865,165 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Assert.Equal("tool-call-1", activity.ToolCallId);
|
Assert.Equal("tool-call-1", activity.ToolCallId);
|
||||||
Assert.NotNull(activity.ToolArguments);
|
Assert.NotNull(activity.ToolArguments);
|
||||||
Assert.Equal(@"C:\workspace\README.md", activity.ToolArguments["path"]);
|
Assert.Equal(@"C:\workspace\README.md", activity.ToolArguments["path"]);
|
||||||
Assert.True(state.ToolCallHasArgumentsById.TryGetValue("tool-call-1", out bool hasArguments));
|
Assert.True(state.ToolCalls.HasTrackedArguments("tool-call-1"));
|
||||||
Assert.True(hasArguments);
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ObserveSessionEvent_ToolExecutionStart_DoesNotDuplicateTrackedRequestInfoActivity()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateApprovalCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
WorkflowNodeDto agent = CreateAgent("agent-1", "Primary");
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
agent,
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "assistant.message_delta",
|
||||||
|
"data": {
|
||||||
|
"messageId": "msg-1",
|
||||||
|
"deltaContent": "Inspecting"
|
||||||
|
},
|
||||||
|
"id": "b61652d1-120e-4a9f-8f0e-1dbf04fb18da",
|
||||||
|
"timestamp": "2026-03-27T00:00:00Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
_ = state.DrainPendingEvents();
|
||||||
|
|
||||||
|
RequestInfoEvent requestInfo = CreateRequestInfoEvent(
|
||||||
|
new FunctionCallContent("tool-call-1", "view", new Dictionary<string, object?>
|
||||||
|
{
|
||||||
|
["path"] = @"C:\workspace\README.md",
|
||||||
|
}));
|
||||||
|
List<AgentActivityEventDto> requestActivities = [];
|
||||||
|
|
||||||
|
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 =>
|
||||||
|
{
|
||||||
|
requestActivities.Add(Assert.IsType<AgentActivityEventDto>(sidecarEvent));
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}),
|
||||||
|
])!;
|
||||||
|
|
||||||
|
bool shouldEndTurn = await handleTask;
|
||||||
|
|
||||||
|
Assert.False(shouldEndTurn);
|
||||||
|
AgentActivityEventDto requestActivity = Assert.Single(requestActivities);
|
||||||
|
Assert.Equal("tool-calling", requestActivity.ActivityType);
|
||||||
|
Assert.True(state.ToolCalls.HasTrackedArguments("tool-call-1"));
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
agent,
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "tool.execution_start",
|
||||||
|
"data": {
|
||||||
|
"toolCallId": "tool-call-1",
|
||||||
|
"toolName": "view",
|
||||||
|
"arguments": {
|
||||||
|
"path": "C:\\workspace\\README.md"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": "c61652d1-120e-4a9f-8f0e-1dbf04fb18da",
|
||||||
|
"timestamp": "2026-03-27T00:00:01Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
|
||||||
|
IReadOnlyList<SidecarEventDto> pending = state.DrainPendingEvents();
|
||||||
|
Assert.DoesNotContain(
|
||||||
|
pending.OfType<AgentActivityEventDto>(),
|
||||||
|
activity => activity.ActivityType == "tool-calling");
|
||||||
|
|
||||||
|
MessageReclassifiedEventDto reclassified = Assert.Single(pending.OfType<MessageReclassifiedEventDto>());
|
||||||
|
Assert.Equal("msg-1", reclassified.MessageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ObserveSessionEvent_ToolExecutionStart_EmitsEnrichmentWhenRequestInfoWasMissingArguments()
|
||||||
|
{
|
||||||
|
RunTurnCommandDto command = CreateApprovalCommand();
|
||||||
|
CopilotTurnExecutionState state = new(command);
|
||||||
|
WorkflowNodeDto agent = CreateAgent("agent-1", "Primary");
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
agent,
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "assistant.message_delta",
|
||||||
|
"data": {
|
||||||
|
"messageId": "msg-2",
|
||||||
|
"deltaContent": "Inspecting"
|
||||||
|
},
|
||||||
|
"id": "d61652d1-120e-4a9f-8f0e-1dbf04fb18da",
|
||||||
|
"timestamp": "2026-03-27T00:00:00Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
_ = state.DrainPendingEvents();
|
||||||
|
|
||||||
|
RequestInfoEvent requestInfo = CreateRequestInfoEvent(
|
||||||
|
new FunctionCallContent("tool-call-1", "view", new Dictionary<string, object?>()));
|
||||||
|
List<AgentActivityEventDto> requestActivities = [];
|
||||||
|
|
||||||
|
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 =>
|
||||||
|
{
|
||||||
|
requestActivities.Add(Assert.IsType<AgentActivityEventDto>(sidecarEvent));
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}),
|
||||||
|
])!;
|
||||||
|
|
||||||
|
bool shouldEndTurn = await handleTask;
|
||||||
|
|
||||||
|
Assert.False(shouldEndTurn);
|
||||||
|
AgentActivityEventDto requestActivity = Assert.Single(requestActivities);
|
||||||
|
Assert.Null(requestActivity.ToolArguments);
|
||||||
|
Assert.False(state.ToolCalls.HasTrackedArguments("tool-call-1"));
|
||||||
|
|
||||||
|
state.ObserveSessionEvent(
|
||||||
|
agent,
|
||||||
|
SessionEvent.FromJson(
|
||||||
|
"""
|
||||||
|
{
|
||||||
|
"type": "tool.execution_start",
|
||||||
|
"data": {
|
||||||
|
"toolCallId": "tool-call-1",
|
||||||
|
"toolName": "view",
|
||||||
|
"arguments": {
|
||||||
|
"path": "C:\\workspace\\README.md"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"id": "e61652d1-120e-4a9f-8f0e-1dbf04fb18da",
|
||||||
|
"timestamp": "2026-03-27T00:00:01Z"
|
||||||
|
}
|
||||||
|
"""));
|
||||||
|
|
||||||
|
AgentActivityEventDto enrichment = Assert.Single(
|
||||||
|
state.DrainPendingEvents().OfType<AgentActivityEventDto>(),
|
||||||
|
activity => activity.ActivityType == "tool-calling");
|
||||||
|
Assert.NotNull(enrichment.ToolArguments);
|
||||||
|
Assert.Equal(@"C:\workspace\README.md", enrichment.ToolArguments["path"]);
|
||||||
|
Assert.True(state.ToolCalls.HasTrackedArguments("tool-call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -1241,6 +1487,28 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "git.status"));
|
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "git.status"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RequiresToolCallApproval_HonorsCanonicalHookApprovalKeysForModernToolNames()
|
||||||
|
{
|
||||||
|
ApprovalPolicyDto policy = new()
|
||||||
|
{
|
||||||
|
Rules =
|
||||||
|
[
|
||||||
|
new ApprovalCheckpointRuleDto
|
||||||
|
{
|
||||||
|
Kind = "tool-call",
|
||||||
|
AgentIds = ["agent-1"],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
AutoApprovedToolNames = ["read", "write", "web_fetch"],
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "rg", "read"));
|
||||||
|
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "apply_patch", "write"));
|
||||||
|
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "web_search", "web_fetch"));
|
||||||
|
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "powershell", "shell"));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void RequiresToolCallApproval_HonorsMcpServerLevelApprovalKey()
|
public void RequiresToolCallApproval_HonorsMcpServerLevelApprovalKey()
|
||||||
{
|
{
|
||||||
@@ -1372,14 +1640,12 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void TryGetApprovalToolName_UsesToolCallLookupForPermissionCategoriesWithoutDirectToolNames()
|
public void TryGetApprovalToolName_UsesToolCallLookupForPermissionCategoriesWithoutDirectToolNames()
|
||||||
{
|
{
|
||||||
Dictionary<string, string> toolNamesByCallId = new(StringComparer.Ordinal)
|
ToolCallRegistry toolCalls = CreateToolCallRegistry(
|
||||||
{
|
("tool-call-url", "web_fetch"),
|
||||||
["tool-call-url"] = "web_fetch",
|
("tool-call-shell", "shell"),
|
||||||
["tool-call-shell"] = "shell",
|
("tool-call-read", "view"),
|
||||||
["tool-call-read"] = "view",
|
("tool-call-write", "write_file"),
|
||||||
["tool-call-write"] = "write_file",
|
("tool-call-memory", "store_memory"));
|
||||||
["tool-call-memory"] = "store_memory",
|
|
||||||
};
|
|
||||||
|
|
||||||
Assert.True(
|
Assert.True(
|
||||||
CopilotApprovalCoordinator.TryGetApprovalToolName(
|
CopilotApprovalCoordinator.TryGetApprovalToolName(
|
||||||
@@ -1390,7 +1656,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Intention = "Fetch the requested page",
|
Intention = "Fetch the requested page",
|
||||||
Url = "https://example.com/docs",
|
Url = "https://example.com/docs",
|
||||||
},
|
},
|
||||||
toolNamesByCallId,
|
toolCalls,
|
||||||
out string? urlToolName));
|
out string? urlToolName));
|
||||||
Assert.Equal("web_fetch", urlToolName);
|
Assert.Equal("web_fetch", urlToolName);
|
||||||
|
|
||||||
@@ -1408,7 +1674,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
HasWriteFileRedirection = false,
|
HasWriteFileRedirection = false,
|
||||||
CanOfferSessionApproval = false,
|
CanOfferSessionApproval = false,
|
||||||
},
|
},
|
||||||
toolNamesByCallId,
|
toolCalls,
|
||||||
out string? shellToolName));
|
out string? shellToolName));
|
||||||
Assert.Equal("shell", shellToolName);
|
Assert.Equal("shell", shellToolName);
|
||||||
|
|
||||||
@@ -1421,7 +1687,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Intention = "Inspect a file",
|
Intention = "Inspect a file",
|
||||||
Path = "README.md",
|
Path = "README.md",
|
||||||
},
|
},
|
||||||
toolNamesByCallId,
|
toolCalls,
|
||||||
out string? readToolName));
|
out string? readToolName));
|
||||||
Assert.Equal("view", readToolName);
|
Assert.Equal("view", readToolName);
|
||||||
|
|
||||||
@@ -1435,7 +1701,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
FileName = "README.md",
|
FileName = "README.md",
|
||||||
Diff = "@@ -1 +1 @@",
|
Diff = "@@ -1 +1 @@",
|
||||||
},
|
},
|
||||||
toolNamesByCallId,
|
toolCalls,
|
||||||
out string? writeToolName));
|
out string? writeToolName));
|
||||||
Assert.Equal("write_file", writeToolName);
|
Assert.Equal("write_file", writeToolName);
|
||||||
|
|
||||||
@@ -1449,7 +1715,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Fact = "Use Bun for script execution.",
|
Fact = "Use Bun for script execution.",
|
||||||
Citations = "package.json",
|
Citations = "package.json",
|
||||||
},
|
},
|
||||||
toolNamesByCallId,
|
toolCalls,
|
||||||
out string? memoryToolName));
|
out string? memoryToolName));
|
||||||
Assert.Equal("store_memory", memoryToolName);
|
Assert.Equal("store_memory", memoryToolName);
|
||||||
}
|
}
|
||||||
@@ -1494,6 +1760,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
"lsp_ts_hover");
|
"lsp_ts_hover");
|
||||||
|
|
||||||
Assert.Equal("lsp_ts_hover", approvalEvent.ToolName);
|
Assert.Equal("lsp_ts_hover", approvalEvent.ToolName);
|
||||||
|
Assert.Equal("lsp_ts_hover", approvalEvent.ApprovalToolKey);
|
||||||
Assert.Equal("Approve lsp_ts_hover", approvalEvent.Title);
|
Assert.Equal("Approve lsp_ts_hover", approvalEvent.Title);
|
||||||
Assert.Contains("tool \"lsp_ts_hover\"", approvalEvent.Detail);
|
Assert.Contains("tool \"lsp_ts_hover\"", approvalEvent.Detail);
|
||||||
Assert.NotNull(approvalEvent.PermissionDetail);
|
Assert.NotNull(approvalEvent.PermissionDetail);
|
||||||
@@ -1526,6 +1793,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
"web_fetch");
|
"web_fetch");
|
||||||
|
|
||||||
Assert.Equal("web_fetch", approvalEvent.ToolName);
|
Assert.Equal("web_fetch", approvalEvent.ToolName);
|
||||||
|
Assert.Equal("web_fetch", approvalEvent.ApprovalToolKey);
|
||||||
Assert.Equal("Approve web_fetch", approvalEvent.Title);
|
Assert.Equal("Approve web_fetch", approvalEvent.Title);
|
||||||
Assert.Contains("url permission", approvalEvent.Detail);
|
Assert.Contains("url permission", approvalEvent.Detail);
|
||||||
Assert.Contains("tool \"web_fetch\"", approvalEvent.Detail);
|
Assert.Contains("tool \"web_fetch\"", approvalEvent.Detail);
|
||||||
@@ -1748,11 +2016,21 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("view", "read")]
|
[InlineData("view", "read")]
|
||||||
|
[InlineData("show_file", "read")]
|
||||||
|
[InlineData("read_file", "read")]
|
||||||
[InlineData("glob", "read")]
|
[InlineData("glob", "read")]
|
||||||
[InlineData("grep", "read")]
|
[InlineData("grep", "read")]
|
||||||
|
[InlineData("rg", "read")]
|
||||||
[InlineData("lsp", "read")]
|
[InlineData("lsp", "read")]
|
||||||
[InlineData("edit", "write")]
|
[InlineData("edit", "write")]
|
||||||
[InlineData("create", "write")]
|
[InlineData("create", "write")]
|
||||||
|
[InlineData("write_file", "write")]
|
||||||
|
[InlineData("apply_patch", "write")]
|
||||||
|
[InlineData("bash", "shell")]
|
||||||
|
[InlineData("read_bash", "shell")]
|
||||||
|
[InlineData("write_bash", "shell")]
|
||||||
|
[InlineData("stop_bash", "shell")]
|
||||||
|
[InlineData("list_bash", "shell")]
|
||||||
[InlineData("powershell", "shell")]
|
[InlineData("powershell", "shell")]
|
||||||
[InlineData("read_powershell", "shell")]
|
[InlineData("read_powershell", "shell")]
|
||||||
[InlineData("write_powershell", "shell")]
|
[InlineData("write_powershell", "shell")]
|
||||||
@@ -1761,6 +2039,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
[InlineData("web_fetch", "url")]
|
[InlineData("web_fetch", "url")]
|
||||||
[InlineData("web_search", "url")]
|
[InlineData("web_search", "url")]
|
||||||
[InlineData("store_memory", "memory")]
|
[InlineData("store_memory", "memory")]
|
||||||
|
[InlineData("remember_fact", "memory")]
|
||||||
public void ResolveHookToolCategory_ReturnsExpectedCategoryForKnownTools(string toolName, string expectedCategory)
|
public void ResolveHookToolCategory_ReturnsExpectedCategoryForKnownTools(string toolName, string expectedCategory)
|
||||||
{
|
{
|
||||||
Assert.Equal(expectedCategory, CopilotApprovalCoordinator.ResolveHookToolCategory(toolName));
|
Assert.Equal(expectedCategory, CopilotApprovalCoordinator.ResolveHookToolCategory(toolName));
|
||||||
@@ -1783,6 +2062,29 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Assert.Null(CopilotApprovalCoordinator.ResolveHookToolCategory(" "));
|
Assert.Null(CopilotApprovalCoordinator.ResolveHookToolCategory(" "));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("view", "read")]
|
||||||
|
[InlineData("rg", "read")]
|
||||||
|
[InlineData("apply_patch", "write")]
|
||||||
|
[InlineData("bash", "shell")]
|
||||||
|
[InlineData("web_fetch", "web_fetch")]
|
||||||
|
[InlineData("web_search", "web_fetch")]
|
||||||
|
[InlineData("store_memory", "store_memory")]
|
||||||
|
[InlineData("remember_fact", "store_memory")]
|
||||||
|
public void ResolveHookApprovalToolKey_ReturnsExpectedKeyForKnownTools(string toolName, string expectedKey)
|
||||||
|
{
|
||||||
|
Assert.Equal(expectedKey, CopilotApprovalCoordinator.ResolveHookApprovalToolKey(toolName));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolveHookApprovalToolKey_ReturnsNullForUnknownTools()
|
||||||
|
{
|
||||||
|
Assert.Null(CopilotApprovalCoordinator.ResolveHookApprovalToolKey("custom_tool"));
|
||||||
|
Assert.Null(CopilotApprovalCoordinator.ResolveHookApprovalToolKey(null));
|
||||||
|
Assert.Null(CopilotApprovalCoordinator.ResolveHookApprovalToolKey(""));
|
||||||
|
Assert.Null(CopilotApprovalCoordinator.ResolveHookApprovalToolKey(" "));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ResolveHookMcpServerApprovalKey_PrefersLongestConfiguredServerName()
|
public void ResolveHookMcpServerApprovalKey_PrefersLongestConfiguredServerName()
|
||||||
{
|
{
|
||||||
@@ -1875,6 +2177,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
"view");
|
"view");
|
||||||
|
|
||||||
Assert.Equal("view", approvalEvent.ToolName);
|
Assert.Equal("view", approvalEvent.ToolName);
|
||||||
|
Assert.Equal("read", approvalEvent.ApprovalToolKey);
|
||||||
Assert.Equal("read", approvalEvent.PermissionKind);
|
Assert.Equal("read", approvalEvent.PermissionKind);
|
||||||
Assert.Contains("read permission", approvalEvent.Detail);
|
Assert.Contains("read permission", approvalEvent.Detail);
|
||||||
}
|
}
|
||||||
@@ -1907,6 +2210,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
"icm-mcp-get_schedule");
|
"icm-mcp-get_schedule");
|
||||||
|
|
||||||
Assert.Equal("mcp", approvalEvent.PermissionKind);
|
Assert.Equal("mcp", approvalEvent.PermissionKind);
|
||||||
|
Assert.Equal("icm-mcp-get_schedule", approvalEvent.ApprovalToolKey);
|
||||||
Assert.Contains("mcp permission", approvalEvent.Detail);
|
Assert.Contains("mcp permission", approvalEvent.Detail);
|
||||||
Assert.NotNull(approvalEvent.PermissionDetail);
|
Assert.NotNull(approvalEvent.PermissionDetail);
|
||||||
Assert.Equal("mcp", approvalEvent.PermissionDetail!.Kind);
|
Assert.Equal("mcp", approvalEvent.PermissionDetail!.Kind);
|
||||||
@@ -1938,6 +2242,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
"icm-mcp-get_schedule");
|
"icm-mcp-get_schedule");
|
||||||
|
|
||||||
Assert.Equal("hook", approvalEvent.PermissionKind);
|
Assert.Equal("hook", approvalEvent.PermissionKind);
|
||||||
|
Assert.Equal("icm-mcp-get_schedule", approvalEvent.ApprovalToolKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -1960,7 +2265,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
{
|
{
|
||||||
SessionId = "copilot-session-1",
|
SessionId = "copilot-session-1",
|
||||||
},
|
},
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal),
|
CreateToolCallRegistry(),
|
||||||
approval =>
|
approval =>
|
||||||
{
|
{
|
||||||
observedApproval = approval;
|
observedApproval = approval;
|
||||||
@@ -1970,6 +2275,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
|
|
||||||
Assert.False(pending.IsCompleted);
|
Assert.False(pending.IsCompleted);
|
||||||
Assert.NotNull(observedApproval);
|
Assert.NotNull(observedApproval);
|
||||||
|
Assert.Equal("lsp_ts_definition", observedApproval!.ApprovalToolKey);
|
||||||
|
|
||||||
await coordinator.ResolveApprovalAsync(
|
await coordinator.ResolveApprovalAsync(
|
||||||
new ResolveApprovalCommandDto
|
new ResolveApprovalCommandDto
|
||||||
@@ -2007,10 +2313,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
{
|
{
|
||||||
SessionId = "copilot-session-1",
|
SessionId = "copilot-session-1",
|
||||||
},
|
},
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
CreateToolCallRegistry(("tool-call-write-1", "apply_patch")),
|
||||||
{
|
|
||||||
["tool-call-write-1"] = "apply_patch",
|
|
||||||
},
|
|
||||||
activity =>
|
activity =>
|
||||||
{
|
{
|
||||||
observedActivity = activity;
|
observedActivity = activity;
|
||||||
@@ -2029,6 +2332,8 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
Assert.Equal("tool-calling", observedActivity!.ActivityType);
|
Assert.Equal("tool-calling", observedActivity!.ActivityType);
|
||||||
Assert.Equal("apply_patch", observedActivity.ToolName);
|
Assert.Equal("apply_patch", observedActivity.ToolName);
|
||||||
Assert.Equal("tool-call-write-1", observedActivity.ToolCallId);
|
Assert.Equal("tool-call-write-1", observedActivity.ToolCallId);
|
||||||
|
Assert.Equal("apply_patch", observedApproval!.ToolName);
|
||||||
|
Assert.Equal("write", observedApproval.ApprovalToolKey);
|
||||||
|
|
||||||
ToolCallFileChangeDto preview = Assert.Single(observedActivity.FileChanges!);
|
ToolCallFileChangeDto preview = Assert.Single(observedActivity.FileChanges!);
|
||||||
Assert.Equal("README.md", preview.Path);
|
Assert.Equal("README.md", preview.Path);
|
||||||
@@ -2067,7 +2372,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
{
|
{
|
||||||
SessionId = "copilot-session-1",
|
SessionId = "copilot-session-1",
|
||||||
},
|
},
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal),
|
CreateToolCallRegistry(),
|
||||||
approval =>
|
approval =>
|
||||||
{
|
{
|
||||||
sawApproval = true;
|
sawApproval = true;
|
||||||
@@ -2104,7 +2409,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
{
|
{
|
||||||
SessionId = "copilot-session-1",
|
SessionId = "copilot-session-1",
|
||||||
},
|
},
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal),
|
CreateToolCallRegistry(),
|
||||||
approval =>
|
approval =>
|
||||||
{
|
{
|
||||||
sawApproval = true;
|
sawApproval = true;
|
||||||
@@ -2137,10 +2442,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
{
|
{
|
||||||
SessionId = "copilot-session-1",
|
SessionId = "copilot-session-1",
|
||||||
},
|
},
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
CreateToolCallRegistry(("tool-call-read-1", "view")),
|
||||||
{
|
|
||||||
["tool-call-read-1"] = "view",
|
|
||||||
},
|
|
||||||
approval =>
|
approval =>
|
||||||
{
|
{
|
||||||
firstApproval = approval;
|
firstApproval = approval;
|
||||||
@@ -2150,6 +2452,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
|
|
||||||
Assert.False(firstPending.IsCompleted);
|
Assert.False(firstPending.IsCompleted);
|
||||||
Assert.NotNull(firstApproval);
|
Assert.NotNull(firstApproval);
|
||||||
|
Assert.Equal("read", firstApproval!.ApprovalToolKey);
|
||||||
|
|
||||||
await coordinator.ResolveApprovalAsync(
|
await coordinator.ResolveApprovalAsync(
|
||||||
new ResolveApprovalCommandDto
|
new ResolveApprovalCommandDto
|
||||||
@@ -2178,10 +2481,83 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
{
|
{
|
||||||
SessionId = "copilot-session-1",
|
SessionId = "copilot-session-1",
|
||||||
},
|
},
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
CreateToolCallRegistry(("tool-call-read-2", "grep")),
|
||||||
|
approval =>
|
||||||
{
|
{
|
||||||
["tool-call-read-2"] = "grep",
|
sawSecondApproval = true;
|
||||||
|
return Task.CompletedTask;
|
||||||
},
|
},
|
||||||
|
CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.False(sawSecondApproval);
|
||||||
|
Assert.Equal(PermissionRequestResultKind.Approved, secondResult.Kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RequestApprovalAsync_AlwaysApproveCachesCanonicalWriteApprovalForModernHookTools()
|
||||||
|
{
|
||||||
|
CopilotApprovalCoordinator coordinator = new();
|
||||||
|
ApprovalRequestedEventDto? firstApproval = null;
|
||||||
|
RunTurnCommandDto command = CreateApprovalCommand();
|
||||||
|
|
||||||
|
Task<PermissionRequestResult> firstPending = coordinator.RequestApprovalAsync(
|
||||||
|
command,
|
||||||
|
command.Workflow.GetAgentNodes()[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",
|
||||||
|
},
|
||||||
|
CreateToolCallRegistry(("tool-call-write-1", "apply_patch")),
|
||||||
|
approval =>
|
||||||
|
{
|
||||||
|
firstApproval = approval;
|
||||||
|
return Task.CompletedTask;
|
||||||
|
},
|
||||||
|
CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.False(firstPending.IsCompleted);
|
||||||
|
Assert.NotNull(firstApproval);
|
||||||
|
Assert.Equal("write", firstApproval!.ApprovalToolKey);
|
||||||
|
|
||||||
|
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.Workflow.GetAgentNodes()[0],
|
||||||
|
new PermissionRequestWrite
|
||||||
|
{
|
||||||
|
Kind = "write",
|
||||||
|
ToolCallId = "tool-call-write-2",
|
||||||
|
Intention = "Create docs draft",
|
||||||
|
FileName = "docs\\guide.md",
|
||||||
|
Diff = "@@ -0,0 +1 @@",
|
||||||
|
NewFileContents = "# Guide\n",
|
||||||
|
},
|
||||||
|
new PermissionInvocation
|
||||||
|
{
|
||||||
|
SessionId = "copilot-session-1",
|
||||||
|
},
|
||||||
|
CreateToolCallRegistry(("tool-call-write-2", "write_file")),
|
||||||
approval =>
|
approval =>
|
||||||
{
|
{
|
||||||
sawSecondApproval = true;
|
sawSecondApproval = true;
|
||||||
@@ -2214,10 +2590,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
{
|
{
|
||||||
SessionId = "copilot-session-1",
|
SessionId = "copilot-session-1",
|
||||||
},
|
},
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
CreateToolCallRegistry(("tool-call-read-1", "view")),
|
||||||
{
|
|
||||||
["tool-call-read-1"] = "view",
|
|
||||||
},
|
|
||||||
approval =>
|
approval =>
|
||||||
{
|
{
|
||||||
firstApproval = approval;
|
firstApproval = approval;
|
||||||
@@ -2254,10 +2627,7 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
{
|
{
|
||||||
SessionId = "copilot-session-1",
|
SessionId = "copilot-session-1",
|
||||||
},
|
},
|
||||||
new Dictionary<string, string>(StringComparer.Ordinal)
|
CreateToolCallRegistry(("tool-call-read-2", "grep")),
|
||||||
{
|
|
||||||
["tool-call-read-2"] = "grep",
|
|
||||||
},
|
|
||||||
approval =>
|
approval =>
|
||||||
{
|
{
|
||||||
secondApproval = approval;
|
secondApproval = approval;
|
||||||
@@ -2548,6 +2918,17 @@ public sealed class CopilotWorkflowRunnerTests
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static ToolCallRegistry CreateToolCallRegistry(params (string ToolCallId, string ToolName)[] toolCalls)
|
||||||
|
{
|
||||||
|
ToolCallRegistry registry = new();
|
||||||
|
foreach ((string toolCallId, string toolName) in toolCalls)
|
||||||
|
{
|
||||||
|
registry.RecordToolStart(toolCallId, toolName, toolArguments: null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return registry;
|
||||||
|
}
|
||||||
|
|
||||||
private static RunTurnCommandDto CreateRequestPortCommand()
|
private static RunTurnCommandDto CreateRequestPortCommand()
|
||||||
{
|
{
|
||||||
return new RunTurnCommandDto
|
return new RunTurnCommandDto
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
using Aryx.AgentHost.Services;
|
||||||
|
using OpenTelemetry.Exporter;
|
||||||
|
using OpenTelemetry.Trace;
|
||||||
|
|
||||||
|
namespace Aryx.AgentHost.Tests;
|
||||||
|
|
||||||
|
public sealed class OpenTelemetrySetupTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void ResolveTracingConfiguration_ReturnsNullWhenEndpointMissing()
|
||||||
|
{
|
||||||
|
OpenTelemetryTracingConfiguration? configuration = OpenTelemetrySetup.ResolveTracingConfiguration([]);
|
||||||
|
|
||||||
|
Assert.Null(configuration);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolveTracingConfiguration_UsesGrpcByDefault()
|
||||||
|
{
|
||||||
|
OpenTelemetryTracingConfiguration? configuration = OpenTelemetrySetup.ResolveTracingConfiguration(
|
||||||
|
[
|
||||||
|
new KeyValuePair<string, string?>("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
Assert.NotNull(configuration);
|
||||||
|
Assert.Equal(new Uri("http://localhost:4317"), configuration.Endpoint);
|
||||||
|
Assert.Equal(OtlpExportProtocol.Grpc, configuration.Protocol);
|
||||||
|
Assert.Collection(
|
||||||
|
configuration.ActivitySourceNames,
|
||||||
|
source => Assert.Equal("Experimental.Microsoft.Agents.AI", source),
|
||||||
|
source => Assert.Equal("Microsoft.Agents.AI.Workflows", source));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolveTracingConfiguration_UsesHttpProtobufWhenRequested()
|
||||||
|
{
|
||||||
|
OpenTelemetryTracingConfiguration? configuration = OpenTelemetrySetup.ResolveTracingConfiguration(
|
||||||
|
[
|
||||||
|
new KeyValuePair<string, string?>("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318"),
|
||||||
|
new KeyValuePair<string, string?>("OTEL_EXPORTER_OTLP_PROTOCOL", "http/protobuf"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
Assert.NotNull(configuration);
|
||||||
|
Assert.Equal(new Uri("http://localhost:4318"), configuration.Endpoint);
|
||||||
|
Assert.Equal(OtlpExportProtocol.HttpProtobuf, configuration.Protocol);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolveTracingConfiguration_ThrowsWhenEndpointInvalid()
|
||||||
|
{
|
||||||
|
InvalidOperationException error = Assert.Throws<InvalidOperationException>(() =>
|
||||||
|
OpenTelemetrySetup.ResolveTracingConfiguration(
|
||||||
|
[
|
||||||
|
new KeyValuePair<string, string?>("OTEL_EXPORTER_OTLP_ENDPOINT", "localhost:4317"),
|
||||||
|
]));
|
||||||
|
|
||||||
|
Assert.Contains("OTEL_EXPORTER_OTLP_ENDPOINT", error.Message, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResolveTracingConfiguration_ThrowsWhenProtocolUnsupported()
|
||||||
|
{
|
||||||
|
InvalidOperationException error = Assert.Throws<InvalidOperationException>(() =>
|
||||||
|
OpenTelemetrySetup.ResolveTracingConfiguration(
|
||||||
|
[
|
||||||
|
new KeyValuePair<string, string?>("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317"),
|
||||||
|
new KeyValuePair<string, string?>("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json"),
|
||||||
|
]));
|
||||||
|
|
||||||
|
Assert.Contains("OTEL_EXPORTER_OTLP_PROTOCOL", error.Message, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void CreateTracerProvider_CreatesProviderAndWritesDiagnosticsWhenConfigured()
|
||||||
|
{
|
||||||
|
StringWriter diagnosticsWriter = new();
|
||||||
|
|
||||||
|
using TracerProvider? tracerProvider = OpenTelemetrySetup.CreateTracerProvider(
|
||||||
|
[
|
||||||
|
new KeyValuePair<string, string?>("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317"),
|
||||||
|
],
|
||||||
|
diagnosticsWriter);
|
||||||
|
|
||||||
|
Assert.NotNull(tracerProvider);
|
||||||
|
Assert.Contains("Aryx.AgentHost OpenTelemetry tracing enabled", diagnosticsWriter.ToString(), StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -412,6 +412,7 @@ public sealed class SidecarProtocolHostTests
|
|||||||
AgentId = "agent-1",
|
AgentId = "agent-1",
|
||||||
AgentName = "Primary",
|
AgentName = "Primary",
|
||||||
PermissionKind = "tool access",
|
PermissionKind = "tool access",
|
||||||
|
ApprovalToolKey = "shell",
|
||||||
Title = "Approve tool access",
|
Title = "Approve tool access",
|
||||||
PermissionDetail = new PermissionDetailDto
|
PermissionDetail = new PermissionDetailDto
|
||||||
{
|
{
|
||||||
@@ -437,6 +438,7 @@ public sealed class SidecarProtocolHostTests
|
|||||||
Assert.Equal("turn-approval", approvalEvent.GetProperty("requestId").GetString());
|
Assert.Equal("turn-approval", approvalEvent.GetProperty("requestId").GetString());
|
||||||
Assert.Equal("approval-1", approvalEvent.GetProperty("approvalId").GetString());
|
Assert.Equal("approval-1", approvalEvent.GetProperty("approvalId").GetString());
|
||||||
Assert.Equal("tool-call", approvalEvent.GetProperty("approvalKind").GetString());
|
Assert.Equal("tool-call", approvalEvent.GetProperty("approvalKind").GetString());
|
||||||
|
Assert.Equal("shell", approvalEvent.GetProperty("approvalToolKey").GetString());
|
||||||
Assert.Equal("Approve tool access", approvalEvent.GetProperty("title").GetString());
|
Assert.Equal("Approve tool access", approvalEvent.GetProperty("title").GetString());
|
||||||
JsonElement permissionDetail = approvalEvent.GetProperty("permissionDetail");
|
JsonElement permissionDetail = approvalEvent.GetProperty("permissionDetail");
|
||||||
Assert.Equal("shell", permissionDetail.GetProperty("kind").GetString());
|
Assert.Equal("shell", permissionDetail.GetProperty("kind").GetString());
|
||||||
|
|||||||
@@ -37,22 +37,36 @@ public sealed class StreamingTextMergerTests
|
|||||||
Assert.Equal(incoming, StreamingTextMerger.Merge(current, incoming));
|
Assert.Equal(incoming, StreamingTextMerger.Merge(current, incoming));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void Merge_InsertsWhitespaceWhenSnapshotLikeUpdatesWouldOtherwiseGlueWordsTogether()
|
[InlineData("requires all wr", "itable fields", "requires all writable fields")]
|
||||||
|
[InlineData("becomes frag", "ile for clients", "becomes fragile for clients")]
|
||||||
|
[InlineData("Endpoint (domain) uniqu", "eness across tenants", "Endpoint (domain) uniqueness across tenants")]
|
||||||
|
[InlineData("The doc says \"wildc", "ards are allowed\"", "The doc says \"wildcards are allowed\"")]
|
||||||
|
[InlineData("What wildcard syntax supported (*.cont", "oso.com? contoso.* ?)", "What wildcard syntax supported (*.contoso.com? contoso.* ?)")]
|
||||||
|
[InlineData("How does Pur", "view match traffic", "How does Purview match traffic")]
|
||||||
|
[InlineData("more M", "DA properties", "more MDA properties")]
|
||||||
|
[InlineData("does UA", "G normalize them?", "does UAG normalize them?")]
|
||||||
|
public void Merge_DoesNotInjectSpacesIntoSplitWords(string current, string incoming, string expected)
|
||||||
{
|
{
|
||||||
Assert.Equal(
|
Assert.Equal(expected, StreamingTextMerger.Merge(current, incoming));
|
||||||
"How about The **Ashen Crown** feels",
|
|
||||||
StreamingTextMerger.Merge("How about", "The **Ashen Crown** feels"));
|
|
||||||
Assert.Equal(
|
|
||||||
"The **Ashen Crown** feels classic and timeless.",
|
|
||||||
StreamingTextMerger.Merge("The **Ashen Crown** feels", "classic and timeless."));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Merge_InsertsNewlineBeforeStreamedMarkdownBlockMarkers()
|
public void Merge_PreservesWhitespaceAlreadyPresentInDelta()
|
||||||
|
{
|
||||||
|
Assert.Equal(
|
||||||
|
"How about The **Ashen Crown** feels",
|
||||||
|
StreamingTextMerger.Merge("How about", " The **Ashen Crown** feels"));
|
||||||
|
Assert.Equal(
|
||||||
|
"The **Ashen Crown** feels classic and timeless.",
|
||||||
|
StreamingTextMerger.Merge("The **Ashen Crown** feels", " classic and timeless."));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Merge_PreservesNewlineAlreadyPresentInDelta()
|
||||||
{
|
{
|
||||||
Assert.Equal(
|
Assert.Equal(
|
||||||
"If you want, I can also give you\n- darker titles",
|
"If you want, I can also give you\n- darker titles",
|
||||||
StreamingTextMerger.Merge("If you want, I can also give you", "- darker titles"));
|
StreamingTextMerger.Merge("If you want, I can also give you", "\n- darker titles"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System.Collections.Concurrent;
|
|
||||||
using System.Runtime.CompilerServices;
|
using System.Runtime.CompilerServices;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Aryx.AgentHost.Contracts;
|
using Aryx.AgentHost.Contracts;
|
||||||
@@ -27,8 +26,7 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateSingleAgentCommand(),
|
CreateSingleAgentCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-1", "Primary"),
|
new AgentIdentity("agent-1", "Primary"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Equal("tool-calling", activity.ActivityType);
|
Assert.Equal("tool-calling", activity.ActivityType);
|
||||||
@@ -38,8 +36,9 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
Assert.NotNull(activity.ToolArguments);
|
Assert.NotNull(activity.ToolArguments);
|
||||||
Assert.Equal(@"C:\workspace\file.txt", activity.ToolArguments["path"]);
|
Assert.Equal(@"C:\workspace\file.txt", activity.ToolArguments["path"]);
|
||||||
Assert.Equal([10, 25], Assert.IsAssignableFrom<IReadOnlyList<object?>>(activity.ToolArguments["viewRange"]));
|
Assert.Equal([10, 25], Assert.IsAssignableFrom<IReadOnlyList<object?>>(activity.ToolArguments["viewRange"]));
|
||||||
Assert.Equal("view", tracking.ToolNamesByCallId["call-1"]);
|
Assert.True(tracking.TryGetToolName("call-1", out string? toolName));
|
||||||
Assert.True(tracking.ToolCallHasArgumentsById["call-1"]);
|
Assert.Equal("view", toolName);
|
||||||
|
Assert.True(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -61,8 +60,7 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateSingleAgentCommand(),
|
CreateSingleAgentCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-1", "Primary"),
|
new AgentIdentity("agent-1", "Primary"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Equal("tool-calling", activity.ActivityType);
|
Assert.Equal("tool-calling", activity.ActivityType);
|
||||||
@@ -70,8 +68,9 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
Assert.NotNull(activity.ToolArguments);
|
Assert.NotNull(activity.ToolArguments);
|
||||||
Assert.Equal(@"C:\workspace", activity.ToolArguments["path"]);
|
Assert.Equal(@"C:\workspace", activity.ToolArguments["path"]);
|
||||||
Assert.Equal(true, activity.ToolArguments["includeIgnored"]);
|
Assert.Equal(true, activity.ToolArguments["includeIgnored"]);
|
||||||
Assert.Equal("git.status", tracking.ToolNamesByCallId["call-1"]);
|
Assert.True(tracking.TryGetToolName("call-1", out string? toolName));
|
||||||
Assert.True(tracking.ToolCallHasArgumentsById["call-1"]);
|
Assert.Equal("git.status", toolName);
|
||||||
|
Assert.True(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -85,8 +84,7 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateSingleAgentCommand(),
|
CreateSingleAgentCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-1", "Primary"),
|
new AgentIdentity("agent-1", "Primary"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Equal("tool-calling", activity.ActivityType);
|
Assert.Equal("tool-calling", activity.ActivityType);
|
||||||
@@ -95,8 +93,9 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
Assert.Equal(
|
Assert.Equal(
|
||||||
["print('hello')"],
|
["print('hello')"],
|
||||||
Assert.IsAssignableFrom<IReadOnlyList<object?>>(activity.ToolArguments["inputs"]));
|
Assert.IsAssignableFrom<IReadOnlyList<object?>>(activity.ToolArguments["inputs"]));
|
||||||
Assert.Equal("code interpreter", tracking.ToolNamesByCallId["call-1"]);
|
Assert.True(tracking.TryGetToolName("call-1", out string? toolName));
|
||||||
Assert.True(tracking.ToolCallHasArgumentsById["call-1"]);
|
Assert.Equal("code interpreter", toolName);
|
||||||
|
Assert.True(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -109,15 +108,14 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateSingleAgentCommand(),
|
CreateSingleAgentCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-1", "Primary"),
|
new AgentIdentity("agent-1", "Primary"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Equal("tool-calling", activity.ActivityType);
|
Assert.Equal("tool-calling", activity.ActivityType);
|
||||||
Assert.Equal("image generation", activity.ToolName);
|
Assert.Equal("image generation", activity.ToolName);
|
||||||
Assert.Null(activity.ToolArguments);
|
Assert.Null(activity.ToolArguments);
|
||||||
Assert.Empty(tracking.ToolNamesByCallId);
|
Assert.False(tracking.TryGetToolName("call-1", out _));
|
||||||
Assert.Empty(tracking.ToolCallHasArgumentsById);
|
Assert.False(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -135,12 +133,11 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateSingleAgentCommand(),
|
CreateSingleAgentCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-1", "Primary"),
|
new AgentIdentity("agent-1", "Primary"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Null(activity.ToolArguments);
|
Assert.Null(activity.ToolArguments);
|
||||||
Assert.False(tracking.ToolCallHasArgumentsById["call-1"]);
|
Assert.False(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -160,21 +157,25 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateSingleAgentCommand(),
|
CreateSingleAgentCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-1", "Primary"),
|
new AgentIdentity("agent-1", "Primary"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.NotNull(activity.ToolArguments);
|
Assert.NotNull(activity.ToolArguments);
|
||||||
Assert.Equal("[truncated]", activity.ToolArguments["command"]);
|
Assert.Equal("[truncated]", activity.ToolArguments["command"]);
|
||||||
Assert.True(tracking.ToolCallHasArgumentsById["call-1"]);
|
Assert.True(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void TryCreateActivityFromRequest_SkipsDuplicateTrackedToolCallIdsThatAlreadyHaveArguments()
|
public void TryCreateActivityFromRequest_SkipsDuplicateTrackedToolCallIdsThatAlreadyHaveArguments()
|
||||||
{
|
{
|
||||||
var tracking = CreateToolTracking();
|
var tracking = CreateToolTracking();
|
||||||
tracking.ToolNamesByCallId["call-1"] = "view";
|
tracking.RecordToolStart(
|
||||||
tracking.ToolCallHasArgumentsById["call-1"] = true;
|
"call-1",
|
||||||
|
"view",
|
||||||
|
new Dictionary<string, object?>
|
||||||
|
{
|
||||||
|
["path"] = @"C:\workspace\seed.txt",
|
||||||
|
});
|
||||||
RequestInfoEvent requestInfo = CreateRequestInfoEvent(
|
RequestInfoEvent requestInfo = CreateRequestInfoEvent(
|
||||||
new FunctionCallContent("call-1", "view", new Dictionary<string, object?>
|
new FunctionCallContent("call-1", "view", new Dictionary<string, object?>
|
||||||
{
|
{
|
||||||
@@ -185,20 +186,19 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateSingleAgentCommand(),
|
CreateSingleAgentCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-1", "Primary"),
|
new AgentIdentity("agent-1", "Primary"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.Null(activity);
|
Assert.Null(activity);
|
||||||
Assert.Equal("view", tracking.ToolNamesByCallId["call-1"]);
|
Assert.True(tracking.TryGetToolName("call-1", out string? toolName));
|
||||||
Assert.True(tracking.ToolCallHasArgumentsById["call-1"]);
|
Assert.Equal("view", toolName);
|
||||||
|
Assert.True(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void TryCreateActivityFromRequest_EmitsEnrichmentWhenTrackedToolCallWasMissingArguments()
|
public void TryCreateActivityFromRequest_EmitsEnrichmentWhenTrackedToolCallWasMissingArguments()
|
||||||
{
|
{
|
||||||
var tracking = CreateToolTracking();
|
var tracking = CreateToolTracking();
|
||||||
tracking.ToolNamesByCallId["call-1"] = "view";
|
tracking.RecordToolStart("call-1", "view", toolArguments: null);
|
||||||
tracking.ToolCallHasArgumentsById["call-1"] = false;
|
|
||||||
RequestInfoEvent requestInfo = CreateRequestInfoEvent(
|
RequestInfoEvent requestInfo = CreateRequestInfoEvent(
|
||||||
new FunctionCallContent("call-1", "view", new Dictionary<string, object?>
|
new FunctionCallContent("call-1", "view", new Dictionary<string, object?>
|
||||||
{
|
{
|
||||||
@@ -209,16 +209,16 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateSingleAgentCommand(),
|
CreateSingleAgentCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-1", "Primary"),
|
new AgentIdentity("agent-1", "Primary"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Equal("tool-calling", activity.ActivityType);
|
Assert.Equal("tool-calling", activity.ActivityType);
|
||||||
Assert.Equal("call-1", activity.ToolCallId);
|
Assert.Equal("call-1", activity.ToolCallId);
|
||||||
Assert.NotNull(activity.ToolArguments);
|
Assert.NotNull(activity.ToolArguments);
|
||||||
Assert.Equal(@"C:\workspace\file.txt", activity.ToolArguments["path"]);
|
Assert.Equal(@"C:\workspace\file.txt", activity.ToolArguments["path"]);
|
||||||
Assert.Equal("view", tracking.ToolNamesByCallId["call-1"]);
|
Assert.True(tracking.TryGetToolName("call-1", out string? toolName));
|
||||||
Assert.True(tracking.ToolCallHasArgumentsById["call-1"]);
|
Assert.Equal("view", toolName);
|
||||||
|
Assert.True(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -232,8 +232,7 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateHandoffCommand(),
|
CreateHandoffCommand(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-handoff-triage", "Triage"),
|
new AgentIdentity("agent-handoff-triage", "Triage"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Equal("handoff", activity.ActivityType);
|
Assert.Equal("handoff", activity.ActivityType);
|
||||||
@@ -242,8 +241,8 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
Assert.Equal("agent-handoff-triage", activity.SourceAgentId);
|
Assert.Equal("agent-handoff-triage", activity.SourceAgentId);
|
||||||
Assert.Equal("Triage", activity.SourceAgentName);
|
Assert.Equal("Triage", activity.SourceAgentName);
|
||||||
Assert.Null(activity.ToolName);
|
Assert.Null(activity.ToolName);
|
||||||
Assert.Empty(tracking.ToolNamesByCallId);
|
Assert.False(tracking.TryGetToolName("call-1", out _));
|
||||||
Assert.Empty(tracking.ToolCallHasArgumentsById);
|
Assert.False(tracking.HasTrackedArguments("call-1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -263,8 +262,7 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
"agent-reviewer",
|
"agent-reviewer",
|
||||||
"Reviewer",
|
"Reviewer",
|
||||||
new SubworkflowContext("subworkflow-review", "Review Lane")),
|
new SubworkflowContext("subworkflow-review", "Review Lane")),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Equal("tool-calling", activity.ActivityType);
|
Assert.Equal("tool-calling", activity.ActivityType);
|
||||||
@@ -283,8 +281,7 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
CreateHandoffCommandWithReferencedSubworkflow(),
|
CreateHandoffCommandWithReferencedSubworkflow(),
|
||||||
requestInfo,
|
requestInfo,
|
||||||
new AgentIdentity("agent-handoff-triage", "Triage"),
|
new AgentIdentity("agent-handoff-triage", "Triage"),
|
||||||
tracking.ToolNamesByCallId,
|
tracking);
|
||||||
tracking.ToolCallHasArgumentsById);
|
|
||||||
|
|
||||||
Assert.NotNull(activity);
|
Assert.NotNull(activity);
|
||||||
Assert.Equal("handoff", activity.ActivityType);
|
Assert.Equal("handoff", activity.ActivityType);
|
||||||
@@ -417,10 +414,7 @@ public sealed class WorkflowRequestInfoInterpreterTests
|
|||||||
workflowLibrary: [nestedWorkflow]);
|
workflowLibrary: [nestedWorkflow]);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static (
|
private static ToolCallRegistry CreateToolTracking() => new();
|
||||||
ConcurrentDictionary<string, string> ToolNamesByCallId,
|
|
||||||
ConcurrentDictionary<string, bool> ToolCallHasArgumentsById) CreateToolTracking()
|
|
||||||
=> (new(StringComparer.Ordinal), new(StringComparer.Ordinal));
|
|
||||||
|
|
||||||
private static RunTurnCommandDto CreateCommand(
|
private static RunTurnCommandDto CreateCommand(
|
||||||
string orchestrationMode,
|
string orchestrationMode,
|
||||||
|
|||||||
+95
-154
@@ -117,7 +117,6 @@ import {
|
|||||||
} from '@shared/domain/session';
|
} from '@shared/domain/session';
|
||||||
import { prepareChatMessageContent } from '@shared/utils/chatMessage';
|
import { prepareChatMessageContent } from '@shared/utils/chatMessage';
|
||||||
import {
|
import {
|
||||||
appendRunActivityEvent,
|
|
||||||
cancelSessionRunRecord,
|
cancelSessionRunRecord,
|
||||||
completeSessionRunRecord,
|
completeSessionRunRecord,
|
||||||
createSessionRunRecord,
|
createSessionRunRecord,
|
||||||
@@ -132,6 +131,7 @@ import {
|
|||||||
} from '@shared/domain/runTimeline';
|
} from '@shared/domain/runTimeline';
|
||||||
import {
|
import {
|
||||||
createSessionToolingSelection,
|
createSessionToolingSelection,
|
||||||
|
createDefaultQuickPromptSettings,
|
||||||
listApprovalToolNames,
|
listApprovalToolNames,
|
||||||
normalizeTerminalHeight,
|
normalizeTerminalHeight,
|
||||||
normalizeTheme,
|
normalizeTheme,
|
||||||
@@ -140,6 +140,8 @@ import {
|
|||||||
type AppearanceTheme,
|
type AppearanceTheme,
|
||||||
type LspProfileDefinition,
|
type LspProfileDefinition,
|
||||||
type McpServerDefinition,
|
type McpServerDefinition,
|
||||||
|
type OpenTelemetrySettings,
|
||||||
|
type QuickPromptSettings,
|
||||||
type SessionToolingSelection,
|
type SessionToolingSelection,
|
||||||
type WorkspaceToolingSettings,
|
type WorkspaceToolingSettings,
|
||||||
normalizeLspProfileDefinition,
|
normalizeLspProfileDefinition,
|
||||||
@@ -150,7 +152,6 @@ import {
|
|||||||
} from '@shared/domain/tooling';
|
} from '@shared/domain/tooling';
|
||||||
import type { WorkspaceState } from '@shared/domain/workspace';
|
import type { WorkspaceState } from '@shared/domain/workspace';
|
||||||
import { createId, nowIso } from '@shared/utils/ids';
|
import { createId, nowIso } from '@shared/utils/ids';
|
||||||
import { mergeStreamingText } from '@shared/utils/streamingText';
|
|
||||||
|
|
||||||
import { WorkspaceRepository } from '@main/persistence/workspaceRepository';
|
import { WorkspaceRepository } from '@main/persistence/workspaceRepository';
|
||||||
import { getScratchpadSessionPath } from '@main/persistence/appPaths';
|
import { getScratchpadSessionPath } from '@main/persistence/appPaths';
|
||||||
@@ -469,6 +470,7 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
|
|||||||
async loadWorkspace(): Promise<WorkspaceState> {
|
async loadWorkspace(): Promise<WorkspaceState> {
|
||||||
if (!this.workspace) {
|
if (!this.workspace) {
|
||||||
this.workspace = await this.workspaceRepository.load();
|
this.workspace = await this.workspaceRepository.load();
|
||||||
|
this.sidecar.setOpenTelemetrySettings(this.workspace.settings.openTelemetry);
|
||||||
const selectedProjectId = this.workspace.selectedProjectId;
|
const selectedProjectId = this.workspace.selectedProjectId;
|
||||||
const selectedProject = selectedProjectId
|
const selectedProject = selectedProjectId
|
||||||
? this.workspace.projects.find((project) => project.id === selectedProjectId)
|
? this.workspace.projects.find((project) => project.id === selectedProjectId)
|
||||||
@@ -830,6 +832,28 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
|
|||||||
return this.persistAndBroadcast(workspace);
|
return this.persistAndBroadcast(workspace);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async setOpenTelemetry(settings: OpenTelemetrySettings): Promise<WorkspaceState> {
|
||||||
|
const workspace = await this.loadWorkspace();
|
||||||
|
workspace.settings.openTelemetry = settings;
|
||||||
|
this.sidecar.setOpenTelemetrySettings(settings);
|
||||||
|
return this.persistAndBroadcast(workspace);
|
||||||
|
}
|
||||||
|
|
||||||
|
getQuickPromptSettings(): QuickPromptSettings {
|
||||||
|
return this.workspace?.settings.quickPrompt ?? createDefaultQuickPromptSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
getCurrentTheme(): AppearanceTheme {
|
||||||
|
return this.workspace?.settings.theme ?? 'dark';
|
||||||
|
}
|
||||||
|
|
||||||
|
async setQuickPromptSettings(patch: Partial<QuickPromptSettings>): Promise<WorkspaceState> {
|
||||||
|
const workspace = await this.loadWorkspace();
|
||||||
|
const current = workspace.settings.quickPrompt ?? createDefaultQuickPromptSettings();
|
||||||
|
workspace.settings.quickPrompt = { ...current, ...patch };
|
||||||
|
return this.persistAndBroadcast(workspace);
|
||||||
|
}
|
||||||
|
|
||||||
async describeTerminal(): Promise<TerminalSnapshot | undefined> {
|
async describeTerminal(): Promise<TerminalSnapshot | undefined> {
|
||||||
return this.ptyManager.getSnapshot();
|
return this.ptyManager.getSnapshot();
|
||||||
}
|
}
|
||||||
@@ -1134,6 +1158,50 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
|
|||||||
return this.persistAndBroadcast(workspace);
|
return this.persistAndBroadcast(workspace);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async batchSetSessionsArchived(sessionIds: string[], isArchived: boolean): Promise<WorkspaceState> {
|
||||||
|
const workspace = await this.loadWorkspace();
|
||||||
|
const now = nowIso();
|
||||||
|
for (const sessionId of sessionIds) {
|
||||||
|
const session = workspace.sessions.find((s) => s.id === sessionId);
|
||||||
|
if (session) {
|
||||||
|
session.isArchived = isArchived;
|
||||||
|
session.updatedAt = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return this.persistAndBroadcast(workspace);
|
||||||
|
}
|
||||||
|
|
||||||
|
async batchDeleteSessions(sessionIds: string[]): Promise<WorkspaceState> {
|
||||||
|
const workspace = await this.loadWorkspace();
|
||||||
|
const idsToDelete = new Set(sessionIds);
|
||||||
|
|
||||||
|
// Run cleanup sequentially to avoid requestId collisions in sidecar dispatch
|
||||||
|
for (const session of workspace.sessions) {
|
||||||
|
if (!idsToDelete.has(session.id)) continue;
|
||||||
|
|
||||||
|
const scratchpadDirectory = this.resolveScratchpadSessionDirectory(session);
|
||||||
|
if (scratchpadDirectory) {
|
||||||
|
await rm(scratchpadDirectory, { recursive: true, force: true }).catch(() => {
|
||||||
|
// Best-effort — directory may not exist or be locked
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.sidecar.deleteSession(session.id);
|
||||||
|
} catch {
|
||||||
|
// Best-effort — don't fail the deletion if SDK cleanup fails
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
workspace.sessions = workspace.sessions.filter((s) => !idsToDelete.has(s.id));
|
||||||
|
|
||||||
|
if (workspace.selectedSessionId && idsToDelete.has(workspace.selectedSessionId)) {
|
||||||
|
workspace.selectedSessionId = workspace.sessions[0]?.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.persistAndBroadcast(workspace);
|
||||||
|
}
|
||||||
|
|
||||||
async regenerateSessionMessage(sessionId: string, messageId: string): Promise<void> {
|
async regenerateSessionMessage(sessionId: string, messageId: string): Promise<void> {
|
||||||
const workspace = await this.loadWorkspace();
|
const workspace = await this.loadWorkspace();
|
||||||
const session = this.requireSession(workspace, sessionId);
|
const session = this.requireSession(workspace, sessionId);
|
||||||
@@ -1907,158 +1975,6 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
|
|||||||
session.cwd = scratchpadDirectory;
|
session.cwd = scratchpadDirectory;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async applyTurnDelta(
|
|
||||||
workspace: WorkspaceState,
|
|
||||||
sessionId: string,
|
|
||||||
requestId: string,
|
|
||||||
event: TurnDeltaEvent,
|
|
||||||
): Promise<void> {
|
|
||||||
if (event.content === undefined && event.contentDelta === undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const occurredAt = nowIso();
|
|
||||||
const session = this.requireSession(workspace, sessionId);
|
|
||||||
const existing = session.messages.find((message) => message.id === event.messageId);
|
|
||||||
const content =
|
|
||||||
existing && event.content === undefined
|
|
||||||
? mergeStreamingText(existing.content, event.contentDelta)
|
|
||||||
: (event.content ?? event.contentDelta);
|
|
||||||
|
|
||||||
// When a new assistant message begins, auto-complete any previously pending
|
|
||||||
// assistant messages so only the latest one shows the "Thinking" indicator.
|
|
||||||
const completedMessages: ChatMessageRecord[] = [];
|
|
||||||
if (existing) {
|
|
||||||
existing.content = content;
|
|
||||||
existing.pending = true;
|
|
||||||
existing.authorName = event.authorName;
|
|
||||||
} else {
|
|
||||||
for (const message of session.messages) {
|
|
||||||
if (message.pending && message.role === 'assistant') {
|
|
||||||
message.pending = false;
|
|
||||||
completedMessages.push(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
session.messages.push({
|
|
||||||
id: event.messageId,
|
|
||||||
role: 'assistant',
|
|
||||||
authorName: event.authorName,
|
|
||||||
content,
|
|
||||||
createdAt: occurredAt,
|
|
||||||
pending: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextRun = this.updateSessionRun(session, requestId, (run) =>
|
|
||||||
upsertRunMessageEvent(run, {
|
|
||||||
messageId: event.messageId,
|
|
||||||
occurredAt,
|
|
||||||
authorName: event.authorName,
|
|
||||||
content,
|
|
||||||
status: 'running',
|
|
||||||
}));
|
|
||||||
|
|
||||||
session.updatedAt = occurredAt;
|
|
||||||
await this.workspaceRepository.save(workspace);
|
|
||||||
|
|
||||||
for (const completed of completedMessages) {
|
|
||||||
this.emitSessionEvent({
|
|
||||||
sessionId,
|
|
||||||
kind: 'message-complete',
|
|
||||||
occurredAt,
|
|
||||||
messageId: completed.id,
|
|
||||||
authorName: completed.authorName,
|
|
||||||
content: completed.content,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
this.emitSessionEvent({
|
|
||||||
sessionId,
|
|
||||||
kind: 'message-delta',
|
|
||||||
occurredAt,
|
|
||||||
messageId: event.messageId,
|
|
||||||
authorName: event.authorName,
|
|
||||||
contentDelta: event.contentDelta,
|
|
||||||
content: event.content,
|
|
||||||
});
|
|
||||||
if (nextRun) {
|
|
||||||
this.emitRunUpdated(sessionId, occurredAt, nextRun);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async applyMessageReclassified(
|
|
||||||
workspace: WorkspaceState,
|
|
||||||
sessionId: string,
|
|
||||||
event: MessageReclassifiedEvent,
|
|
||||||
): Promise<void> {
|
|
||||||
const session = this.requireSession(workspace, sessionId);
|
|
||||||
const message = session.messages.find((m) => m.id === event.messageId);
|
|
||||||
if (!message || message.messageKind === 'thinking') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
message.messageKind = 'thinking';
|
|
||||||
const occurredAt = nowIso();
|
|
||||||
session.updatedAt = occurredAt;
|
|
||||||
await this.workspaceRepository.save(workspace);
|
|
||||||
|
|
||||||
this.emitSessionEvent({
|
|
||||||
sessionId,
|
|
||||||
kind: 'message-reclassified',
|
|
||||||
occurredAt,
|
|
||||||
messageId: event.messageId,
|
|
||||||
messageKind: 'thinking',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private async applyAgentActivity(
|
|
||||||
workspace: WorkspaceState,
|
|
||||||
sessionId: string,
|
|
||||||
requestId: string,
|
|
||||||
event: AgentActivityEvent,
|
|
||||||
): Promise<void> {
|
|
||||||
const occurredAt = nowIso();
|
|
||||||
const session = this.requireSession(workspace, sessionId);
|
|
||||||
const activityType = event.activityType;
|
|
||||||
let nextRun: SessionRunRecord | undefined;
|
|
||||||
if (activityType === 'thinking' || activityType === 'tool-calling' || activityType === 'handoff') {
|
|
||||||
nextRun = this.updateSessionRun(session, requestId, (run) =>
|
|
||||||
appendRunActivityEvent(run, {
|
|
||||||
activityType,
|
|
||||||
occurredAt,
|
|
||||||
agentId: event.agentId,
|
|
||||||
agentName: event.agentName,
|
|
||||||
sourceAgentId: event.sourceAgentId,
|
|
||||||
sourceAgentName: event.sourceAgentName,
|
|
||||||
toolName: event.toolName,
|
|
||||||
toolCallId: event.toolCallId,
|
|
||||||
toolArguments: event.toolArguments,
|
|
||||||
fileChanges: event.fileChanges,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
if (nextRun) {
|
|
||||||
session.updatedAt = occurredAt;
|
|
||||||
await this.workspaceRepository.save(workspace);
|
|
||||||
this.emitRunUpdated(sessionId, occurredAt, nextRun);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.emitSessionEvent({
|
|
||||||
sessionId,
|
|
||||||
kind: 'agent-activity',
|
|
||||||
occurredAt,
|
|
||||||
activityType: event.activityType,
|
|
||||||
agentId: event.agentId,
|
|
||||||
agentName: event.agentName,
|
|
||||||
subworkflowNodeId: event.subworkflowNodeId,
|
|
||||||
subworkflowName: event.subworkflowName,
|
|
||||||
sourceAgentId: event.sourceAgentId,
|
|
||||||
sourceAgentName: event.sourceAgentName,
|
|
||||||
toolName: event.toolName,
|
|
||||||
toolCallId: event.toolCallId,
|
|
||||||
toolArguments: event.toolArguments,
|
|
||||||
fileChanges: event.fileChanges,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private emitCompletedActivity(
|
private emitCompletedActivity(
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
workflow: WorkflowDefinition,
|
workflow: WorkflowDefinition,
|
||||||
@@ -2384,6 +2300,31 @@ export class AryxAppService extends EventEmitter<AppServiceEvents> {
|
|||||||
usageQuotaSnapshots: event.quotaSnapshots,
|
usageQuotaSnapshots: event.quotaSnapshots,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
|
case 'assistant-intent': {
|
||||||
|
const session = this.requireSession(workspace, sessionId);
|
||||||
|
session.currentIntent = event.intent;
|
||||||
|
session.updatedAt = occurredAt;
|
||||||
|
this.emitSessionEvent({
|
||||||
|
sessionId,
|
||||||
|
kind: 'assistant-intent',
|
||||||
|
occurredAt,
|
||||||
|
agentId: event.agentId,
|
||||||
|
agentName: event.agentName,
|
||||||
|
intent: event.intent,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'reasoning-delta':
|
||||||
|
this.emitSessionEvent({
|
||||||
|
sessionId,
|
||||||
|
kind: 'reasoning-delta',
|
||||||
|
occurredAt,
|
||||||
|
agentId: event.agentId,
|
||||||
|
agentName: event.agentName,
|
||||||
|
reasoningId: event.reasoningId,
|
||||||
|
reasoningDelta: event.contentDelta,
|
||||||
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+66
-7
@@ -1,19 +1,53 @@
|
|||||||
import electron from 'electron';
|
import electron from 'electron';
|
||||||
import type { BrowserWindow as BrowserWindowType } from 'electron';
|
import type { BrowserWindow as BrowserWindowType } from 'electron';
|
||||||
|
|
||||||
import { registerIpcHandlers } from '@main/ipc/registerIpcHandlers';
|
import { registerIpcHandlers, registerQuickPromptIpcHandlers } from '@main/ipc/registerIpcHandlers';
|
||||||
import { AryxAppService } from '@main/AryxAppService';
|
import { AryxAppService } from '@main/AryxAppService';
|
||||||
import { AutoUpdateService } from '@main/services/autoUpdater';
|
import { AutoUpdateService } from '@main/services/autoUpdater';
|
||||||
|
import { GlobalHotkeyService } from '@main/services/globalHotkey';
|
||||||
import { createMainWindow } from '@main/windows/createMainWindow';
|
import { createMainWindow } from '@main/windows/createMainWindow';
|
||||||
|
import {
|
||||||
|
createQuickPromptWindow,
|
||||||
|
toggleQuickPromptWindow,
|
||||||
|
} from '@main/windows/createQuickPromptWindow';
|
||||||
import { applyTitleBarTheme } from '@main/windows/titleBarTheme';
|
import { applyTitleBarTheme } from '@main/windows/titleBarTheme';
|
||||||
import { SystemTray, setupCloseToTray, showAndFocusWindow } from '@main/services/systemTray';
|
import { SystemTray, setupCloseToTray, showAndFocusWindow } from '@main/services/systemTray';
|
||||||
|
import { createDefaultQuickPromptSettings } from '@shared/domain/tooling';
|
||||||
|
|
||||||
const { app, BrowserWindow } = electron;
|
const { app, BrowserWindow } = electron;
|
||||||
|
|
||||||
|
// Enforce single instance — quit immediately if another instance already holds the lock.
|
||||||
|
const gotTheLock = app.requestSingleInstanceLock();
|
||||||
|
if (!gotTheLock) {
|
||||||
|
app.quit();
|
||||||
|
}
|
||||||
|
|
||||||
let mainWindow: BrowserWindowType | undefined;
|
let mainWindow: BrowserWindowType | undefined;
|
||||||
|
let quickPromptWindow: BrowserWindowType | undefined;
|
||||||
let appService: AryxAppService | undefined;
|
let appService: AryxAppService | undefined;
|
||||||
let systemTray: SystemTray | undefined;
|
let systemTray: SystemTray | undefined;
|
||||||
let autoUpdateService: AutoUpdateService | undefined;
|
let autoUpdateService: AutoUpdateService | undefined;
|
||||||
|
let globalHotkeyService: GlobalHotkeyService | undefined;
|
||||||
|
|
||||||
|
let quickPromptInitialized = false;
|
||||||
|
|
||||||
|
/** Lazily creates the quick prompt window on first use. */
|
||||||
|
function ensureQuickPromptWindow(): BrowserWindowType | undefined {
|
||||||
|
if (quickPromptWindow && !quickPromptWindow.isDestroyed()) return quickPromptWindow;
|
||||||
|
if (quickPromptInitialized) return undefined;
|
||||||
|
if (!mainWindow || !appService) return undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
quickPromptWindow = createQuickPromptWindow();
|
||||||
|
registerQuickPromptIpcHandlers(mainWindow, appService, quickPromptWindow);
|
||||||
|
quickPromptInitialized = true;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[aryx] Failed to create quick prompt window:', err);
|
||||||
|
quickPromptInitialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return quickPromptWindow;
|
||||||
|
}
|
||||||
|
|
||||||
async function bootstrap(): Promise<void> {
|
async function bootstrap(): Promise<void> {
|
||||||
appService = new AryxAppService();
|
appService = new AryxAppService();
|
||||||
@@ -21,22 +55,23 @@ async function bootstrap(): Promise<void> {
|
|||||||
autoUpdateService = new AutoUpdateService({ isPackaged: app.isPackaged });
|
autoUpdateService = new AutoUpdateService({ isPackaged: app.isPackaged });
|
||||||
|
|
||||||
mainWindow = createMainWindow();
|
mainWindow = createMainWindow();
|
||||||
|
|
||||||
registerIpcHandlers(mainWindow, appService, autoUpdateService);
|
registerIpcHandlers(mainWindow, appService, autoUpdateService);
|
||||||
|
|
||||||
// Start workspace loading in parallel — don't block window from showing.
|
// Start workspace loading in parallel — don't block window from showing.
|
||||||
// The renderer fetches the workspace via its own IPC call after mount.
|
// The renderer fetches the workspace via its own IPC call after mount.
|
||||||
const workspaceReady = appService.loadWorkspace();
|
const workspaceReady = appService.loadWorkspace();
|
||||||
|
|
||||||
// Apply theme and set up tray once workspace is available
|
// Apply theme, set up tray, and register global hotkey once workspace is available
|
||||||
workspaceReady
|
workspaceReady
|
||||||
.then((workspace) => {
|
.then((workspace) => {
|
||||||
if (!mainWindow) return;
|
if (!mainWindow) return;
|
||||||
applyTitleBarTheme(mainWindow, workspace.settings.theme);
|
applyTitleBarTheme(mainWindow, workspace.settings.theme);
|
||||||
|
|
||||||
systemTray = new SystemTray({
|
systemTray = new SystemTray({
|
||||||
onShowWindow: showAndFocusWindow,
|
onShowWindow: () => showAndFocusWindow(mainWindow!),
|
||||||
onCreateScratchpad: () => {
|
onCreateScratchpad: () => {
|
||||||
showAndFocusWindow();
|
showAndFocusWindow(mainWindow!);
|
||||||
mainWindow?.webContents.send('tray:create-scratchpad');
|
mainWindow?.webContents.send('tray:create-scratchpad');
|
||||||
},
|
},
|
||||||
onQuit: () => app.quit(),
|
onQuit: () => app.quit(),
|
||||||
@@ -47,6 +82,21 @@ async function bootstrap(): Promise<void> {
|
|||||||
appService!.on('workspace-updated', (updatedWorkspace) => {
|
appService!.on('workspace-updated', (updatedWorkspace) => {
|
||||||
systemTray?.updateRunningCount(updatedWorkspace);
|
systemTray?.updateRunningCount(updatedWorkspace);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Register global hotkey — the quick prompt window is created lazily on
|
||||||
|
// first press so it cannot interfere with main window startup.
|
||||||
|
globalHotkeyService = new GlobalHotkeyService();
|
||||||
|
const hotkeySettings = workspace.settings.quickPrompt ?? createDefaultQuickPromptSettings();
|
||||||
|
globalHotkeyService.register(hotkeySettings, () => {
|
||||||
|
const win = ensureQuickPromptWindow();
|
||||||
|
if (win) void toggleQuickPromptWindow(win, appService!.getCurrentTheme());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Re-register hotkey when settings change
|
||||||
|
appService!.on('workspace-updated', (updatedWorkspace) => {
|
||||||
|
const updatedSettings = updatedWorkspace.settings.quickPrompt ?? createDefaultQuickPromptSettings();
|
||||||
|
globalHotkeyService?.update(updatedSettings);
|
||||||
|
});
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
console.error('[aryx bootstrap] workspace load failed', error);
|
console.error('[aryx bootstrap] workspace load failed', error);
|
||||||
@@ -65,6 +115,12 @@ async function bootstrap(): Promise<void> {
|
|||||||
autoUpdateService.start();
|
autoUpdateService.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
app.on('second-instance', () => {
|
||||||
|
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
|
showAndFocusWindow(mainWindow);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
app.whenReady().then(bootstrap);
|
app.whenReady().then(bootstrap);
|
||||||
|
|
||||||
app.on('window-all-closed', () => {
|
app.on('window-all-closed', () => {
|
||||||
@@ -72,7 +128,9 @@ app.on('window-all-closed', () => {
|
|||||||
if (process.platform === 'darwin') return;
|
if (process.platform === 'darwin') return;
|
||||||
|
|
||||||
const windows = BrowserWindow.getAllWindows();
|
const windows = BrowserWindow.getAllWindows();
|
||||||
const allHidden = windows.length > 0 && windows.every((w) => !w.isVisible());
|
// Ignore the quick prompt window (it's always hidden, never truly closed)
|
||||||
|
const visibleWindows = windows.filter((w) => w !== quickPromptWindow);
|
||||||
|
const allHidden = visibleWindows.length > 0 && visibleWindows.every((w) => !w.isVisible());
|
||||||
if (allHidden) return;
|
if (allHidden) return;
|
||||||
|
|
||||||
app.quit();
|
app.quit();
|
||||||
@@ -81,12 +139,13 @@ app.on('window-all-closed', () => {
|
|||||||
app.on('activate', async () => {
|
app.on('activate', async () => {
|
||||||
if (BrowserWindow.getAllWindows().length === 0) {
|
if (BrowserWindow.getAllWindows().length === 0) {
|
||||||
await bootstrap();
|
await bootstrap();
|
||||||
} else {
|
} else if (mainWindow && !mainWindow.isDestroyed()) {
|
||||||
showAndFocusWindow();
|
showAndFocusWindow(mainWindow);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
app.on('before-quit', async () => {
|
app.on('before-quit', async () => {
|
||||||
|
globalHotkeyService?.dispose();
|
||||||
autoUpdateService?.dispose();
|
autoUpdateService?.dispose();
|
||||||
autoUpdateService = undefined;
|
autoUpdateService = undefined;
|
||||||
systemTray?.dispose();
|
systemTray?.dispose();
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import type { BrowserWindow } from 'electron';
|
|||||||
import { ipcChannels } from '@shared/contracts/channels';
|
import { ipcChannels } from '@shared/contracts/channels';
|
||||||
import type {
|
import type {
|
||||||
BranchSessionInput,
|
BranchSessionInput,
|
||||||
|
BatchDeleteSessionsInput,
|
||||||
|
BatchSetSessionsArchivedInput,
|
||||||
CancelSessionTurnInput,
|
CancelSessionTurnInput,
|
||||||
CommitProjectGitChangesInput,
|
CommitProjectGitChangesInput,
|
||||||
CreateSessionInput,
|
CreateSessionInput,
|
||||||
@@ -51,14 +53,18 @@ import type {
|
|||||||
UpdateSessionModelConfigInput,
|
UpdateSessionModelConfigInput,
|
||||||
UpdateSessionApprovalSettingsInput,
|
UpdateSessionApprovalSettingsInput,
|
||||||
UpdateSessionToolingInput,
|
UpdateSessionToolingInput,
|
||||||
|
QuickPromptSendInput,
|
||||||
} from '@shared/contracts/ipc';
|
} from '@shared/contracts/ipc';
|
||||||
import type { QuerySessionsInput } from '@shared/domain/sessionLibrary';
|
import type { QuerySessionsInput } from '@shared/domain/sessionLibrary';
|
||||||
import type { AppearanceTheme } from '@shared/domain/tooling';
|
import type { AppearanceTheme, OpenTelemetrySettings, QuickPromptSettings } from '@shared/domain/tooling';
|
||||||
|
|
||||||
import { AryxAppService } from '@main/AryxAppService';
|
import { AryxAppService } from '@main/AryxAppService';
|
||||||
import { AutoUpdateService } from '@main/services/autoUpdater';
|
import { AutoUpdateService } from '@main/services/autoUpdater';
|
||||||
import { createDesktopNotificationHandler } from '@main/services/desktopNotifications';
|
import { createDesktopNotificationHandler } from '@main/services/desktopNotifications';
|
||||||
import { applyTitleBarTheme } from '@main/windows/titleBarTheme';
|
import { applyTitleBarTheme } from '@main/windows/titleBarTheme';
|
||||||
|
import { hideQuickPromptWindow } from '@main/windows/createQuickPromptWindow';
|
||||||
|
import { buildAvailableModelCatalog } from '@shared/domain/models';
|
||||||
|
import { SCRATCHPAD_PROJECT_ID } from '@shared/domain/project';
|
||||||
import type { UpdateStatus } from '@shared/contracts/ipc';
|
import type { UpdateStatus } from '@shared/contracts/ipc';
|
||||||
|
|
||||||
const { ipcMain } = electron;
|
const { ipcMain } = electron;
|
||||||
@@ -149,6 +155,10 @@ export function registerIpcHandlers(
|
|||||||
ipcChannels.setGitAutoRefreshEnabled,
|
ipcChannels.setGitAutoRefreshEnabled,
|
||||||
(_event, enabled: boolean) => service.setGitAutoRefreshEnabled(enabled),
|
(_event, enabled: boolean) => service.setGitAutoRefreshEnabled(enabled),
|
||||||
);
|
);
|
||||||
|
ipcMain.handle(
|
||||||
|
ipcChannels.setOpenTelemetry,
|
||||||
|
(_event, settings: OpenTelemetrySettings) => service.setOpenTelemetry(settings),
|
||||||
|
);
|
||||||
ipcMain.handle(ipcChannels.checkForUpdates, () => autoUpdateService.checkForUpdates());
|
ipcMain.handle(ipcChannels.checkForUpdates, () => autoUpdateService.checkForUpdates());
|
||||||
ipcMain.handle(ipcChannels.installUpdate, () => {
|
ipcMain.handle(ipcChannels.installUpdate, () => {
|
||||||
autoUpdateService.installUpdate();
|
autoUpdateService.installUpdate();
|
||||||
@@ -220,6 +230,12 @@ export function registerIpcHandlers(
|
|||||||
ipcMain.handle(ipcChannels.deleteSession, (_event, input: DeleteSessionInput) =>
|
ipcMain.handle(ipcChannels.deleteSession, (_event, input: DeleteSessionInput) =>
|
||||||
service.deleteSession(input.sessionId),
|
service.deleteSession(input.sessionId),
|
||||||
);
|
);
|
||||||
|
ipcMain.handle(ipcChannels.batchSetSessionsArchived, (_event, input: BatchSetSessionsArchivedInput) =>
|
||||||
|
service.batchSetSessionsArchived(input.sessionIds, input.isArchived),
|
||||||
|
);
|
||||||
|
ipcMain.handle(ipcChannels.batchDeleteSessions, (_event, input: BatchDeleteSessionsInput) =>
|
||||||
|
service.batchDeleteSessions(input.sessionIds),
|
||||||
|
);
|
||||||
ipcMain.handle(ipcChannels.regenerateSessionMessage, (_event, input: RegenerateSessionMessageInput) =>
|
ipcMain.handle(ipcChannels.regenerateSessionMessage, (_event, input: RegenerateSessionMessageInput) =>
|
||||||
service.regenerateSessionMessage(input.sessionId, input.messageId),
|
service.regenerateSessionMessage(input.sessionId, input.messageId),
|
||||||
);
|
);
|
||||||
@@ -348,4 +364,101 @@ export function registerIpcHandlers(
|
|||||||
service.on('terminal-exit', (info) => {
|
service.on('terminal-exit', (info) => {
|
||||||
window.webContents.send(ipcChannels.terminalExit, info);
|
window.webContents.send(ipcChannels.terminalExit, info);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- Quick Prompt IPC (window-independent) ---
|
||||||
|
|
||||||
|
ipcMain.handle(ipcChannels.quickPromptGetCapabilities, async () => {
|
||||||
|
const capabilities = await service.describeSidecarCapabilities();
|
||||||
|
const settings = service.getQuickPromptSettings();
|
||||||
|
const models = buildAvailableModelCatalog(capabilities.models);
|
||||||
|
return {
|
||||||
|
models,
|
||||||
|
defaultModel: settings.defaultModel,
|
||||||
|
defaultReasoningEffort: settings.defaultReasoningEffort,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(
|
||||||
|
ipcChannels.quickPromptSetSettings,
|
||||||
|
(_event, settings: Partial<QuickPromptSettings>) => service.setQuickPromptSettings(settings),
|
||||||
|
);
|
||||||
|
|
||||||
|
ipcMain.handle(
|
||||||
|
ipcChannels.quickPromptGetSettings,
|
||||||
|
() => service.getQuickPromptSettings(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register IPC handlers that depend on the quick prompt BrowserWindow.
|
||||||
|
* Called separately after the quick prompt window is created (deferred from bootstrap).
|
||||||
|
*/
|
||||||
|
export function registerQuickPromptIpcHandlers(
|
||||||
|
mainWindow: BrowserWindow,
|
||||||
|
service: AryxAppService,
|
||||||
|
quickPromptWindow: BrowserWindow,
|
||||||
|
): void {
|
||||||
|
let quickPromptSessionId: string | undefined;
|
||||||
|
|
||||||
|
ipcMain.handle(ipcChannels.quickPromptSend, async (_event, input: QuickPromptSendInput) => {
|
||||||
|
const workspace = await service.loadWorkspace();
|
||||||
|
const workflowId = workspace.selectedWorkflowId ?? workspace.workflows[0]?.id;
|
||||||
|
if (!workflowId) throw new Error('No workflow available');
|
||||||
|
|
||||||
|
const created = await service.createSession(SCRATCHPAD_PROJECT_ID, workflowId);
|
||||||
|
const session = created.sessions[0];
|
||||||
|
if (!session) throw new Error('Failed to create quick prompt session');
|
||||||
|
|
||||||
|
quickPromptSessionId = session.id;
|
||||||
|
|
||||||
|
// Apply model override if provided
|
||||||
|
if (input.model) {
|
||||||
|
await service.updateSessionModelConfig(session.id, input.model, input.reasoningEffort);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send the message (fire-and-forget — results arrive via session events)
|
||||||
|
void service.sendSessionMessage(session.id, input.content);
|
||||||
|
|
||||||
|
return { sessionId: session.id };
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(ipcChannels.quickPromptCancelTurn, async () => {
|
||||||
|
if (quickPromptSessionId) {
|
||||||
|
await service.cancelSessionTurn(quickPromptSessionId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(ipcChannels.quickPromptDiscard, async () => {
|
||||||
|
if (quickPromptSessionId) {
|
||||||
|
await service.deleteSession(quickPromptSessionId);
|
||||||
|
quickPromptSessionId = undefined;
|
||||||
|
}
|
||||||
|
hideQuickPromptWindow(quickPromptWindow);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(ipcChannels.quickPromptClose, async () => {
|
||||||
|
quickPromptSessionId = undefined;
|
||||||
|
hideQuickPromptWindow(quickPromptWindow);
|
||||||
|
});
|
||||||
|
|
||||||
|
ipcMain.handle(ipcChannels.quickPromptContinueInAryx, async () => {
|
||||||
|
if (quickPromptSessionId) {
|
||||||
|
await service.selectSession(quickPromptSessionId);
|
||||||
|
quickPromptSessionId = undefined;
|
||||||
|
}
|
||||||
|
hideQuickPromptWindow(quickPromptWindow);
|
||||||
|
// Show and focus the main window
|
||||||
|
if (!mainWindow.isDestroyed()) {
|
||||||
|
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||||
|
mainWindow.show();
|
||||||
|
mainWindow.focus();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Route session events to the quick prompt window
|
||||||
|
service.on('session-event', (event) => {
|
||||||
|
if (event.sessionId === quickPromptSessionId && !quickPromptWindow.isDestroyed()) {
|
||||||
|
quickPromptWindow.webContents.send(ipcChannels.quickPromptSessionEvent, event);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,9 +7,9 @@ import type {
|
|||||||
import {
|
import {
|
||||||
dequeuePendingApprovalState,
|
dequeuePendingApprovalState,
|
||||||
enqueuePendingApprovalState,
|
enqueuePendingApprovalState,
|
||||||
|
getPendingApprovalToolKey,
|
||||||
listPendingApprovals,
|
listPendingApprovals,
|
||||||
resolvePendingApproval,
|
resolvePendingApproval,
|
||||||
resolveApprovalToolKey,
|
|
||||||
type ApprovalDecision,
|
type ApprovalDecision,
|
||||||
type PendingApprovalRecord,
|
type PendingApprovalRecord,
|
||||||
} from '@shared/domain/approval';
|
} from '@shared/domain/approval';
|
||||||
@@ -109,7 +109,7 @@ export class ApprovalCoordinator {
|
|||||||
this.setSessionPendingApprovalState(session, dequeuePendingApprovalState(session, approvalId));
|
this.setSessionPendingApprovalState(session, dequeuePendingApprovalState(session, approvalId));
|
||||||
session.updatedAt = resolvedAt;
|
session.updatedAt = resolvedAt;
|
||||||
|
|
||||||
const approvalKey = resolveApprovalToolKey(approval.toolName, approval.permissionKind);
|
const approvalKey = getPendingApprovalToolKey(approval);
|
||||||
if (decision === 'approved' && alwaysApprove && approvalKey) {
|
if (decision === 'approved' && alwaysApprove && approvalKey) {
|
||||||
const existing = session.approvalSettings?.autoApprovedToolNames ?? [];
|
const existing = session.approvalSettings?.autoApprovedToolNames ?? [];
|
||||||
if (!existing.includes(approvalKey)) {
|
if (!existing.includes(approvalKey)) {
|
||||||
@@ -127,7 +127,7 @@ export class ApprovalCoordinator {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const queuedKey = resolveApprovalToolKey(queued.toolName, queued.permissionKind);
|
const queuedKey = getPendingApprovalToolKey(queued);
|
||||||
if (queuedKey !== approvalKey) {
|
if (queuedKey !== approvalKey) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -361,6 +361,7 @@ export class ApprovalCoordinator {
|
|||||||
agentName: event.agentName,
|
agentName: event.agentName,
|
||||||
toolName: event.toolName,
|
toolName: event.toolName,
|
||||||
permissionKind: event.permissionKind,
|
permissionKind: event.permissionKind,
|
||||||
|
approvalToolKey: event.approvalToolKey,
|
||||||
title: event.title,
|
title: event.title,
|
||||||
detail: event.detail,
|
detail: event.detail,
|
||||||
permissionDetail: event.permissionDetail,
|
permissionDetail: event.permissionDetail,
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import electron from 'electron';
|
||||||
|
|
||||||
|
import type { QuickPromptSettings } from '@shared/domain/tooling';
|
||||||
|
|
||||||
|
export class GlobalHotkeyService {
|
||||||
|
private currentAccelerator: string | undefined;
|
||||||
|
private lastFailedAccelerator: string | undefined;
|
||||||
|
private callback: (() => void) | undefined;
|
||||||
|
|
||||||
|
register(settings: QuickPromptSettings, callback: () => void): void {
|
||||||
|
this.callback = callback;
|
||||||
|
|
||||||
|
if (!settings.enabled) {
|
||||||
|
this.unregister();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const accelerator = toElectronAccelerator(settings.hotkey);
|
||||||
|
|
||||||
|
// Already registered this accelerator — nothing to do
|
||||||
|
if (accelerator === this.currentAccelerator) return;
|
||||||
|
|
||||||
|
// Don't retry an accelerator that already failed (avoids log spam on
|
||||||
|
// repeated workspace-updated events during startup)
|
||||||
|
if (accelerator === this.lastFailedAccelerator) return;
|
||||||
|
|
||||||
|
this.unregister();
|
||||||
|
|
||||||
|
// Access globalShortcut lazily to ensure electron is fully initialised
|
||||||
|
const { globalShortcut } = electron;
|
||||||
|
if (!globalShortcut) {
|
||||||
|
console.error('[globalHotkey] electron.globalShortcut is not available');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const registered = globalShortcut.register(accelerator, callback);
|
||||||
|
if (registered) {
|
||||||
|
console.info(`[globalHotkey] Registered: ${accelerator}`);
|
||||||
|
this.currentAccelerator = accelerator;
|
||||||
|
this.lastFailedAccelerator = undefined;
|
||||||
|
} else {
|
||||||
|
console.warn(
|
||||||
|
`[globalHotkey] Failed to register accelerator: ${accelerator}` +
|
||||||
|
' — it may be reserved by the OS or another application',
|
||||||
|
);
|
||||||
|
this.currentAccelerator = undefined;
|
||||||
|
this.lastFailedAccelerator = accelerator;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[globalHotkey] Error registering ${accelerator}:`, err);
|
||||||
|
this.currentAccelerator = undefined;
|
||||||
|
this.lastFailedAccelerator = accelerator;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-registers with updated settings (e.g. hotkey string changed). */
|
||||||
|
update(settings: QuickPromptSettings): void {
|
||||||
|
if (!this.callback) return;
|
||||||
|
this.register(settings, this.callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
unregister(): void {
|
||||||
|
if (this.currentAccelerator) {
|
||||||
|
try {
|
||||||
|
const { globalShortcut } = electron;
|
||||||
|
globalShortcut?.unregister(this.currentAccelerator);
|
||||||
|
} catch {
|
||||||
|
// best-effort
|
||||||
|
}
|
||||||
|
this.currentAccelerator = undefined;
|
||||||
|
}
|
||||||
|
this.lastFailedAccelerator = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
this.unregister();
|
||||||
|
this.callback = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a portable hotkey string to an Electron accelerator.
|
||||||
|
*
|
||||||
|
* - "Super" → "Meta" (Win key on Windows, Cmd on macOS)
|
||||||
|
* - Strings already using Electron-native names pass through unchanged.
|
||||||
|
*/
|
||||||
|
function toElectronAccelerator(hotkey: string): string {
|
||||||
|
return hotkey.replace(/\bSuper\b/gi, 'Meta');
|
||||||
|
}
|
||||||
@@ -633,7 +633,7 @@ export class SessionTurnExecutor {
|
|||||||
messageId: event.messageId,
|
messageId: event.messageId,
|
||||||
authorName: event.authorName,
|
authorName: event.authorName,
|
||||||
contentDelta: event.contentDelta,
|
contentDelta: event.contentDelta,
|
||||||
content: event.content,
|
content,
|
||||||
});
|
});
|
||||||
if (nextRun) {
|
if (nextRun) {
|
||||||
this.emitRunUpdated(sessionId, occurredAt, nextRun);
|
this.emitRunUpdated(sessionId, occurredAt, nextRun);
|
||||||
@@ -822,6 +822,7 @@ export class SessionTurnExecutor {
|
|||||||
const completedAt = nowIso();
|
const completedAt = nowIso();
|
||||||
session.status = 'idle';
|
session.status = 'idle';
|
||||||
session.lastError = undefined;
|
session.lastError = undefined;
|
||||||
|
session.currentIntent = undefined;
|
||||||
session.pendingUserInput = undefined;
|
session.pendingUserInput = undefined;
|
||||||
session.pendingPlanReview = undefined;
|
session.pendingPlanReview = undefined;
|
||||||
session.pendingMcpAuth = undefined;
|
session.pendingMcpAuth = undefined;
|
||||||
@@ -854,6 +855,7 @@ export class SessionTurnExecutor {
|
|||||||
const cancelledAt = nowIso();
|
const cancelledAt = nowIso();
|
||||||
session.status = 'idle';
|
session.status = 'idle';
|
||||||
session.lastError = undefined;
|
session.lastError = undefined;
|
||||||
|
session.currentIntent = undefined;
|
||||||
session.pendingUserInput = undefined;
|
session.pendingUserInput = undefined;
|
||||||
session.pendingPlanReview = undefined;
|
session.pendingPlanReview = undefined;
|
||||||
session.pendingMcpAuth = undefined;
|
session.pendingMcpAuth = undefined;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { join } from 'node:path';
|
|||||||
|
|
||||||
import type { WorkspaceState } from '@shared/domain/workspace';
|
import type { WorkspaceState } from '@shared/domain/workspace';
|
||||||
|
|
||||||
const { app, Menu, Tray, nativeImage, BrowserWindow } = electron;
|
const { app, Menu, Tray, nativeImage } = electron;
|
||||||
type TrayType = InstanceType<typeof Tray>;
|
type TrayType = InstanceType<typeof Tray>;
|
||||||
type NativeImageType = ReturnType<typeof nativeImage.createFromPath>;
|
type NativeImageType = ReturnType<typeof nativeImage.createFromPath>;
|
||||||
|
|
||||||
@@ -123,10 +123,8 @@ export function setupCloseToTray(
|
|||||||
/**
|
/**
|
||||||
* Show and focus the main window, restoring from tray if hidden.
|
* Show and focus the main window, restoring from tray if hidden.
|
||||||
*/
|
*/
|
||||||
export function showAndFocusWindow(): void {
|
export function showAndFocusWindow(mainWindow: Electron.BrowserWindow): void {
|
||||||
const windows = BrowserWindow.getAllWindows();
|
if (mainWindow.isDestroyed()) return;
|
||||||
const mainWindow = windows[0];
|
|
||||||
if (!mainWindow) return;
|
|
||||||
|
|
||||||
// On macOS, show the dock icon again
|
// On macOS, show the dock icon again
|
||||||
if (process.platform === 'darwin') {
|
if (process.platform === 'darwin') {
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
|
import type { OpenTelemetrySettings } from '@shared/domain/tooling';
|
||||||
|
|
||||||
const blockedEnvironmentPrefixes = ['BUN_', 'COPILOT_', 'ELECTRON_', 'NODE_', 'NPM_'];
|
const blockedEnvironmentPrefixes = ['BUN_', 'COPILOT_', 'ELECTRON_', 'NODE_', 'NPM_'];
|
||||||
|
|
||||||
export function createSidecarEnvironment(baseEnvironment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
export function createSidecarEnvironment(
|
||||||
|
baseEnvironment: NodeJS.ProcessEnv,
|
||||||
|
openTelemetry?: OpenTelemetrySettings,
|
||||||
|
): NodeJS.ProcessEnv {
|
||||||
const sanitizedEnvironment: NodeJS.ProcessEnv = {};
|
const sanitizedEnvironment: NodeJS.ProcessEnv = {};
|
||||||
|
|
||||||
for (const [name, value] of Object.entries(baseEnvironment)) {
|
for (const [name, value] of Object.entries(baseEnvironment)) {
|
||||||
@@ -13,5 +18,9 @@ export function createSidecarEnvironment(baseEnvironment: NodeJS.ProcessEnv): No
|
|||||||
sanitizedEnvironment[name] = value;
|
sanitizedEnvironment[name] = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (openTelemetry?.enabled && openTelemetry.endpoint) {
|
||||||
|
sanitizedEnvironment.OTEL_EXPORTER_OTLP_ENDPOINT = openTelemetry.endpoint;
|
||||||
|
}
|
||||||
|
|
||||||
return sanitizedEnvironment;
|
return sanitizedEnvironment;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import type {
|
|||||||
} from '@shared/contracts/sidecar';
|
} from '@shared/contracts/sidecar';
|
||||||
import type { ApprovalDecision } from '@shared/domain/approval';
|
import type { ApprovalDecision } from '@shared/domain/approval';
|
||||||
import type { ChatMessageRecord } from '@shared/domain/session';
|
import type { ChatMessageRecord } from '@shared/domain/session';
|
||||||
|
import type { OpenTelemetrySettings } from '@shared/domain/tooling';
|
||||||
import { createSidecarEnvironment } from '@main/sidecar/sidecarEnvironment';
|
import { createSidecarEnvironment } from '@main/sidecar/sidecarEnvironment';
|
||||||
import {
|
import {
|
||||||
markRunTurnPendingErrored,
|
markRunTurnPendingErrored,
|
||||||
@@ -109,6 +110,11 @@ export class SidecarClient {
|
|||||||
private processState?: ManagedSidecarProcess;
|
private processState?: ManagedSidecarProcess;
|
||||||
private nextProcessId = 0;
|
private nextProcessId = 0;
|
||||||
private readonly pending = new Map<string, PendingCommand>();
|
private readonly pending = new Map<string, PendingCommand>();
|
||||||
|
private openTelemetrySettings?: OpenTelemetrySettings;
|
||||||
|
|
||||||
|
setOpenTelemetrySettings(settings?: OpenTelemetrySettings): void {
|
||||||
|
this.openTelemetrySettings = settings;
|
||||||
|
}
|
||||||
|
|
||||||
async describeCapabilities(): Promise<SidecarCapabilities> {
|
async describeCapabilities(): Promise<SidecarCapabilities> {
|
||||||
const command = await this.dispatch<SidecarCapabilities>({
|
const command = await this.dispatch<SidecarCapabilities>({
|
||||||
@@ -240,7 +246,7 @@ export class SidecarClient {
|
|||||||
});
|
});
|
||||||
const childProcess = spawn(sidecar.command, sidecar.args, {
|
const childProcess = spawn(sidecar.command, sidecar.args, {
|
||||||
cwd: sidecar.cwd,
|
cwd: sidecar.cwd,
|
||||||
env: createSidecarEnvironment(process.env),
|
env: createSidecarEnvironment(process.env, this.openTelemetrySettings),
|
||||||
stdio: 'pipe',
|
stdio: 'pipe',
|
||||||
windowsHide: true,
|
windowsHide: true,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import electron from 'electron';
|
||||||
|
import type { BrowserWindow as BrowserWindowType } from 'electron';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
|
||||||
|
import { resolveWindowIconPath } from '@main/windows/appIcon';
|
||||||
|
|
||||||
|
const { app, BrowserWindow, screen } = electron;
|
||||||
|
|
||||||
|
export function createQuickPromptWindow(): BrowserWindowType {
|
||||||
|
const window = new BrowserWindow({
|
||||||
|
width: 680,
|
||||||
|
height: 520,
|
||||||
|
minHeight: 72,
|
||||||
|
show: false,
|
||||||
|
frame: false,
|
||||||
|
transparent: true,
|
||||||
|
resizable: false,
|
||||||
|
skipTaskbar: true,
|
||||||
|
alwaysOnTop: true,
|
||||||
|
maximizable: false,
|
||||||
|
minimizable: false,
|
||||||
|
fullscreenable: false,
|
||||||
|
focusable: true,
|
||||||
|
title: 'Aryx Quick Prompt',
|
||||||
|
icon: resolveWindowIconPath({
|
||||||
|
appPath: app.getAppPath(),
|
||||||
|
platform: process.platform,
|
||||||
|
}),
|
||||||
|
webPreferences: {
|
||||||
|
preload: join(__dirname, '../preload/quickprompt.js'),
|
||||||
|
contextIsolation: true,
|
||||||
|
nodeIntegration: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const rendererUrl = process.env.ELECTRON_RENDERER_URL;
|
||||||
|
|
||||||
|
if (rendererUrl) {
|
||||||
|
void window.loadURL(`${rendererUrl}/quickprompt.html`);
|
||||||
|
} else {
|
||||||
|
void window.loadFile(join(__dirname, '../../dist/renderer/quickprompt.html'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide on blur — but only if the window itself loses focus (not from
|
||||||
|
// devtools or transient focus changes during show/hide).
|
||||||
|
window.on('blur', () => {
|
||||||
|
// Longer delay: avoid hiding during transient focus shifts when
|
||||||
|
// interacting with model selector dropdown or other UI elements.
|
||||||
|
setTimeout(() => {
|
||||||
|
if (window.isVisible() && !window.isFocused()) {
|
||||||
|
window.webContents.send('quick-prompt:hide');
|
||||||
|
window.hide();
|
||||||
|
}
|
||||||
|
}, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
return window;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function toggleQuickPromptWindow(window: BrowserWindowType, theme?: string): Promise<void> {
|
||||||
|
if (window.isVisible()) {
|
||||||
|
window.webContents.send('quick-prompt:hide');
|
||||||
|
window.hide();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for the renderer to finish loading before showing — on the very
|
||||||
|
// first activation the page may still be loading from disk/dev-server.
|
||||||
|
if (window.webContents.isLoading()) {
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
window.webContents.once('did-finish-load', () => resolve());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
centerOnActiveDisplay(window);
|
||||||
|
window.webContents.send('quick-prompt:show', theme ?? 'dark');
|
||||||
|
window.show();
|
||||||
|
window.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showQuickPromptWindow(window: BrowserWindowType, theme?: string): void {
|
||||||
|
centerOnActiveDisplay(window);
|
||||||
|
window.webContents.send('quick-prompt:show', theme ?? 'dark');
|
||||||
|
window.show();
|
||||||
|
window.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hideQuickPromptWindow(window: BrowserWindowType): void {
|
||||||
|
if (!window.isVisible()) return;
|
||||||
|
window.webContents.send('quick-prompt:hide');
|
||||||
|
window.hide();
|
||||||
|
}
|
||||||
|
|
||||||
|
function centerOnActiveDisplay(window: BrowserWindowType): void {
|
||||||
|
const cursorPoint = screen.getCursorScreenPoint();
|
||||||
|
const activeDisplay = screen.getDisplayNearestPoint(cursorPoint);
|
||||||
|
const { x, y, width, height } = activeDisplay.workArea;
|
||||||
|
|
||||||
|
const [windowWidth] = window.getSize();
|
||||||
|
const windowX = Math.round(x + (width - windowWidth) / 2);
|
||||||
|
// Position in the upper-third of the screen for command-bar feel
|
||||||
|
const windowY = Math.round(y + height * 0.25);
|
||||||
|
|
||||||
|
window.setPosition(windowX, windowY);
|
||||||
|
}
|
||||||
@@ -36,6 +36,9 @@ const api: ElectronApi = {
|
|||||||
setNotificationsEnabled: (enabled) => ipcRenderer.invoke(ipcChannels.setNotificationsEnabled, enabled),
|
setNotificationsEnabled: (enabled) => ipcRenderer.invoke(ipcChannels.setNotificationsEnabled, enabled),
|
||||||
setMinimizeToTray: (enabled) => ipcRenderer.invoke(ipcChannels.setMinimizeToTray, enabled),
|
setMinimizeToTray: (enabled) => ipcRenderer.invoke(ipcChannels.setMinimizeToTray, enabled),
|
||||||
setGitAutoRefreshEnabled: (enabled) => ipcRenderer.invoke(ipcChannels.setGitAutoRefreshEnabled, enabled),
|
setGitAutoRefreshEnabled: (enabled) => ipcRenderer.invoke(ipcChannels.setGitAutoRefreshEnabled, enabled),
|
||||||
|
setOpenTelemetry: (settings) => ipcRenderer.invoke(ipcChannels.setOpenTelemetry, settings),
|
||||||
|
getQuickPromptSettings: () => ipcRenderer.invoke(ipcChannels.quickPromptGetSettings),
|
||||||
|
setQuickPromptSettings: (settings) => ipcRenderer.invoke(ipcChannels.quickPromptSetSettings, settings),
|
||||||
checkForUpdates: () => ipcRenderer.invoke(ipcChannels.checkForUpdates),
|
checkForUpdates: () => ipcRenderer.invoke(ipcChannels.checkForUpdates),
|
||||||
installUpdate: () => ipcRenderer.invoke(ipcChannels.installUpdate),
|
installUpdate: () => ipcRenderer.invoke(ipcChannels.installUpdate),
|
||||||
saveMcpServer: (input) => ipcRenderer.invoke(ipcChannels.saveMcpServer, input),
|
saveMcpServer: (input) => ipcRenderer.invoke(ipcChannels.saveMcpServer, input),
|
||||||
@@ -65,6 +68,8 @@ const api: ElectronApi = {
|
|||||||
setSessionPinned: (input) => ipcRenderer.invoke(ipcChannels.setSessionPinned, input),
|
setSessionPinned: (input) => ipcRenderer.invoke(ipcChannels.setSessionPinned, input),
|
||||||
setSessionArchived: (input) => ipcRenderer.invoke(ipcChannels.setSessionArchived, input),
|
setSessionArchived: (input) => ipcRenderer.invoke(ipcChannels.setSessionArchived, input),
|
||||||
deleteSession: (input) => ipcRenderer.invoke(ipcChannels.deleteSession, input),
|
deleteSession: (input) => ipcRenderer.invoke(ipcChannels.deleteSession, input),
|
||||||
|
batchSetSessionsArchived: (input) => ipcRenderer.invoke(ipcChannels.batchSetSessionsArchived, input),
|
||||||
|
batchDeleteSessions: (input) => ipcRenderer.invoke(ipcChannels.batchDeleteSessions, input),
|
||||||
regenerateSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.regenerateSessionMessage, input),
|
regenerateSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.regenerateSessionMessage, input),
|
||||||
editAndResendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.editAndResendSessionMessage, input),
|
editAndResendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.editAndResendSessionMessage, input),
|
||||||
sendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.sendSessionMessage, input),
|
sendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.sendSessionMessage, input),
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import electron from 'electron';
|
||||||
|
|
||||||
|
import type { QuickPromptElectronApi } from '@shared/contracts/ipc';
|
||||||
|
|
||||||
|
const { contextBridge, ipcRenderer } = electron;
|
||||||
|
|
||||||
|
// Channel constants are inlined here (not imported from @shared/contracts/channels)
|
||||||
|
// to avoid Rollup code-splitting a shared chunk that Electron's sandboxed preload
|
||||||
|
// environment cannot resolve at runtime.
|
||||||
|
const ch = {
|
||||||
|
send: 'quick-prompt:send',
|
||||||
|
discard: 'quick-prompt:discard',
|
||||||
|
close: 'quick-prompt:close',
|
||||||
|
continueInAryx: 'quick-prompt:continue-in-aryx',
|
||||||
|
cancelTurn: 'quick-prompt:cancel-turn',
|
||||||
|
getCapabilities: 'quick-prompt:get-capabilities',
|
||||||
|
setSettings: 'quick-prompt:set-settings',
|
||||||
|
sessionEvent: 'quick-prompt:session-event',
|
||||||
|
show: 'quick-prompt:show',
|
||||||
|
hide: 'quick-prompt:hide',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const api: QuickPromptElectronApi = {
|
||||||
|
send: (input) => ipcRenderer.invoke(ch.send, input),
|
||||||
|
discard: () => ipcRenderer.invoke(ch.discard),
|
||||||
|
close: () => ipcRenderer.invoke(ch.close),
|
||||||
|
continueInAryx: () => ipcRenderer.invoke(ch.continueInAryx),
|
||||||
|
cancelTurn: () => ipcRenderer.invoke(ch.cancelTurn),
|
||||||
|
getCapabilities: () => ipcRenderer.invoke(ch.getCapabilities),
|
||||||
|
setSettings: (settings) => ipcRenderer.invoke(ch.setSettings, settings),
|
||||||
|
onSessionEvent: (listener) => {
|
||||||
|
const handler = (_event: Electron.IpcRendererEvent, sessionEvent: Parameters<typeof listener>[0]) =>
|
||||||
|
listener(sessionEvent);
|
||||||
|
|
||||||
|
ipcRenderer.on(ch.sessionEvent, handler);
|
||||||
|
return () => ipcRenderer.off(ch.sessionEvent, handler);
|
||||||
|
},
|
||||||
|
onShow: (listener) => {
|
||||||
|
const handler = (_event: Electron.IpcRendererEvent, theme: string) => listener(theme);
|
||||||
|
ipcRenderer.on(ch.show, handler);
|
||||||
|
return () => ipcRenderer.off(ch.show, handler);
|
||||||
|
},
|
||||||
|
onHide: (listener) => {
|
||||||
|
const handler = () => listener();
|
||||||
|
ipcRenderer.on(ch.hide, handler);
|
||||||
|
return () => ipcRenderer.off(ch.hide, handler);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
contextBridge.exposeInMainWorld('quickPromptApi', api);
|
||||||
+24
-1
@@ -34,6 +34,7 @@ import { isScratchpadProject, SCRATCHPAD_PROJECT_ID } from '@shared/domain/proje
|
|||||||
import type { ProjectGitFileReference } from '@shared/domain/project';
|
import type { ProjectGitFileReference } from '@shared/domain/project';
|
||||||
import { applySessionModelConfig } from '@shared/domain/session';
|
import { applySessionModelConfig } from '@shared/domain/session';
|
||||||
import type { AppearanceTheme, LspProfileDefinition, McpServerDefinition } from '@shared/domain/tooling';
|
import type { AppearanceTheme, LspProfileDefinition, McpServerDefinition } from '@shared/domain/tooling';
|
||||||
|
import { createDefaultQuickPromptSettings, type QuickPromptSettings } from '@shared/domain/tooling';
|
||||||
import type { WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
import type { WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
||||||
import type { WorkspaceState } from '@shared/domain/workspace';
|
import type { WorkspaceState } from '@shared/domain/workspace';
|
||||||
import type { UpdateStatus } from '@shared/contracts/ipc';
|
import type { UpdateStatus } from '@shared/contracts/ipc';
|
||||||
@@ -59,7 +60,7 @@ const WelcomePane = lazy(() => import('@renderer/components/WelcomePane').then((
|
|||||||
const WorkflowPicker = lazy(() => import('@renderer/components/workflow/WorkflowPicker').then((m) => ({ default: m.WorkflowPicker })));
|
const WorkflowPicker = lazy(() => import('@renderer/components/workflow/WorkflowPicker').then((m) => ({ default: m.WorkflowPicker })));
|
||||||
|
|
||||||
// Re-export type-only imports from lazy modules so they're available without pulling in the bundle
|
// Re-export type-only imports from lazy modules so they're available without pulling in the bundle
|
||||||
type SettingsSection = 'appearance' | 'connection' | 'workflows' | 'agents' | 'mcp-servers' | 'lsp-profiles' | 'troubleshooting';
|
type SettingsSection = 'appearance' | 'connection' | 'workflows' | 'agents' | 'mcp-servers' | 'lsp-profiles' | 'quick-prompt' | 'troubleshooting';
|
||||||
type BottomPanelTab = 'terminal' | 'git';
|
type BottomPanelTab = 'terminal' | 'git';
|
||||||
|
|
||||||
// Constants duplicated from BottomPanel to avoid importing the full module at startup
|
// Constants duplicated from BottomPanel to avoid importing the full module at startup
|
||||||
@@ -180,6 +181,9 @@ export default function App() {
|
|||||||
// Commit composer state
|
// Commit composer state
|
||||||
const [commitComposerCtx, setCommitComposerCtx] = useState<{ projectId: string; sessionId: string; runId?: string }>();
|
const [commitComposerCtx, setCommitComposerCtx] = useState<{ projectId: string; sessionId: string; runId?: string }>();
|
||||||
|
|
||||||
|
// Quick prompt settings
|
||||||
|
const [quickPromptSettings, setQuickPromptSettings] = useState<QuickPromptSettings>(createDefaultQuickPromptSettings);
|
||||||
|
|
||||||
// Bottom panel state (terminal + git)
|
// Bottom panel state (terminal + git)
|
||||||
const [bottomPanelOpen, setBottomPanelOpen] = useState(false);
|
const [bottomPanelOpen, setBottomPanelOpen] = useState(false);
|
||||||
const [bottomPanelTab, setBottomPanelTab] = useState<BottomPanelTab>('terminal');
|
const [bottomPanelTab, setBottomPanelTab] = useState<BottomPanelTab>('terminal');
|
||||||
@@ -198,6 +202,11 @@ export default function App() {
|
|||||||
.then((ws) => !disposed && setWorkspace(ws))
|
.then((ws) => !disposed && setWorkspace(ws))
|
||||||
.catch((e) => !disposed && setError(e instanceof Error ? e.message : String(e)));
|
.catch((e) => !disposed && setError(e instanceof Error ? e.message : String(e)));
|
||||||
|
|
||||||
|
void api
|
||||||
|
.getQuickPromptSettings()
|
||||||
|
.then((s) => !disposed && setQuickPromptSettings(s))
|
||||||
|
.catch(() => { /* quick prompt settings unavailable, use defaults */ });
|
||||||
|
|
||||||
const offWorkspace = api.onWorkspaceUpdated((ws) => {
|
const offWorkspace = api.onWorkspaceUpdated((ws) => {
|
||||||
setWorkspace(ws);
|
setWorkspace(ws);
|
||||||
setError(undefined);
|
setError(undefined);
|
||||||
@@ -858,6 +867,14 @@ export default function App() {
|
|||||||
void api.resolveWorkspaceDiscoveredTooling({ serverIds, resolution });
|
void api.resolveWorkspaceDiscoveredTooling({ serverIds, resolution });
|
||||||
}}
|
}}
|
||||||
onGetQuota={() => api.getQuota()}
|
onGetQuota={() => api.getQuota()}
|
||||||
|
quickPromptSettings={quickPromptSettings}
|
||||||
|
onSetQuickPromptSettings={(patch) => {
|
||||||
|
const updated = { ...quickPromptSettings, ...patch };
|
||||||
|
setQuickPromptSettings(updated);
|
||||||
|
void api.setQuickPromptSettings(patch);
|
||||||
|
}}
|
||||||
|
openTelemetry={workspace.settings.openTelemetry}
|
||||||
|
onSetOpenTelemetry={(settings) => void api.setOpenTelemetry(settings)}
|
||||||
/>
|
/>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
) : null;
|
) : null;
|
||||||
@@ -925,6 +942,12 @@ export default function App() {
|
|||||||
onDeleteSession={(sessionId) => {
|
onDeleteSession={(sessionId) => {
|
||||||
void api.deleteSession({ sessionId });
|
void api.deleteSession({ sessionId });
|
||||||
}}
|
}}
|
||||||
|
onBatchArchiveSessions={(sessionIds, isArchived) => {
|
||||||
|
void api.batchSetSessionsArchived({ sessionIds, isArchived });
|
||||||
|
}}
|
||||||
|
onBatchDeleteSessions={(sessionIds) => {
|
||||||
|
void api.batchDeleteSessions({ sessionIds });
|
||||||
|
}}
|
||||||
onRefreshGitContext={(projectId) => {
|
onRefreshGitContext={(projectId) => {
|
||||||
void api.refreshProjectGitContext(projectId);
|
void api.refreshProjectGitContext(projectId);
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -228,9 +228,30 @@ export function ChatPane({
|
|||||||
const activeRun = runsByTrigger.get(lastUserMessageId);
|
const activeRun = runsByTrigger.get(lastUserMessageId);
|
||||||
if (activeRun && !consumedRunIds.has(activeRun.id)) {
|
if (activeRun && !consumedRunIds.has(activeRun.id)) {
|
||||||
items.push({ type: 'turn-activity', thinkingMessages: [], run: activeRun, turnStartedAt: activeRun.startedAt });
|
items.push({ type: 'turn-activity', thinkingMessages: [], run: activeRun, turnStartedAt: activeRun.startedAt });
|
||||||
|
consumedRunIds.add(activeRun.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Inject activity panels for any remaining unconsumed runs from
|
||||||
|
// previous turns (e.g. turns where thinking messages were not
|
||||||
|
// produced or were lost). Place each panel right after the trigger
|
||||||
|
// user message so it appears in the correct chronological position.
|
||||||
|
for (const run of session.runs) {
|
||||||
|
if (consumedRunIds.has(run.id)) continue;
|
||||||
|
const triggerIndex = items.findIndex(
|
||||||
|
(it) => it.type === 'message' && it.message.role === 'user' && it.message.id === run.triggerMessageId,
|
||||||
|
);
|
||||||
|
if (triggerIndex === -1) continue;
|
||||||
|
const panel: DisplayItem = {
|
||||||
|
type: 'turn-activity',
|
||||||
|
thinkingMessages: [],
|
||||||
|
run,
|
||||||
|
turnStartedAt: run.startedAt,
|
||||||
|
};
|
||||||
|
items.splice(triggerIndex + 1, 0, panel);
|
||||||
|
consumedRunIds.add(run.id);
|
||||||
|
}
|
||||||
|
|
||||||
// Tag the last turn-activity panel for each run so only it shows
|
// Tag the last turn-activity panel for each run so only it shows
|
||||||
// run-level metadata (git summary, discard button, etc.).
|
// run-level metadata (git summary, discard button, etc.).
|
||||||
const lastPanelIndexByRunId = new Map<string, number>();
|
const lastPanelIndexByRunId = new Map<string, number>();
|
||||||
@@ -530,7 +551,7 @@ export function ChatPane({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{isSessionBusy && !pendingApproval && !pendingUserInput && (() => {
|
{isSessionBusy && !pendingApproval && !pendingUserInput && (() => {
|
||||||
const label = summarizeSessionActivity(sessionActivity);
|
const label = session.currentIntent ?? summarizeSessionActivity(sessionActivity);
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-1.5 text-[12px] text-[var(--color-accent-sky)]">
|
<div className="flex items-center gap-1.5 text-[12px] text-[var(--color-accent-sky)]">
|
||||||
<span className="size-2 animate-pulse rounded-full bg-[var(--color-accent-sky)]" />
|
<span className="size-2 animate-pulse rounded-full bg-[var(--color-accent-sky)]" />
|
||||||
@@ -593,6 +614,7 @@ export function ChatPane({
|
|||||||
isActive={isTurnActive(item, itemIndex)}
|
isActive={isTurnActive(item, itemIndex)}
|
||||||
turnStartedAt={item.turnStartedAt}
|
turnStartedAt={item.turnStartedAt}
|
||||||
sessionId={session.id}
|
sessionId={session.id}
|
||||||
|
currentIntent={session.currentIntent}
|
||||||
agentNames={item.agentNames}
|
agentNames={item.agentNames}
|
||||||
isLastRunPanel={item.isLastRunPanel}
|
isLastRunPanel={item.isLastRunPanel}
|
||||||
onDiscard={onDiscardRunChanges}
|
onDiscard={onDiscardRunChanges}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { useEffect, useState, type ReactNode } from 'react';
|
import { useEffect, useState, type ReactNode } from 'react';
|
||||||
import { ChevronLeft, ChevronRight, CircleCheck, Code, Cpu, FolderOpen, GitBranch, Palette, Plus, RefreshCw, Server, TriangleAlert, UserCircle, Wrench } from 'lucide-react';
|
import { ChevronLeft, ChevronRight, CircleCheck, Code, Cpu, FolderOpen, GitBranch, Palette, Plus, RefreshCw, Server, Sparkles, TriangleAlert, UserCircle, Wrench, Activity } from 'lucide-react';
|
||||||
|
|
||||||
import { CopilotStatusCard } from '@renderer/components/CopilotStatusCard';
|
import { CopilotStatusCard } from '@renderer/components/CopilotStatusCard';
|
||||||
import { WorkflowEditor } from '@renderer/components/WorkflowEditor';
|
import { WorkflowEditor } from '@renderer/components/WorkflowEditor';
|
||||||
import { ToggleSwitch } from '@renderer/components/ui';
|
import { HotkeyRecorder, TextInput, ToggleSwitch } from '@renderer/components/ui';
|
||||||
import { LspProfileEditor } from '@renderer/components/settings/LspProfileEditor';
|
import { LspProfileEditor } from '@renderer/components/settings/LspProfileEditor';
|
||||||
import { McpServerEditor } from '@renderer/components/settings/McpServerEditor';
|
import { McpServerEditor } from '@renderer/components/settings/McpServerEditor';
|
||||||
import { WorkspaceAgentEditor } from '@renderer/components/settings/WorkspaceAgentEditor';
|
import { WorkspaceAgentEditor } from '@renderer/components/settings/WorkspaceAgentEditor';
|
||||||
@@ -18,9 +18,12 @@ import type { WorkflowTemplateCategory, WorkflowTemplateDefinition } from '@shar
|
|||||||
import {
|
import {
|
||||||
normalizeLspProfileDefinition,
|
normalizeLspProfileDefinition,
|
||||||
normalizeMcpServerDefinition,
|
normalizeMcpServerDefinition,
|
||||||
|
DEFAULT_OTEL_ENDPOINT,
|
||||||
type AppearanceTheme,
|
type AppearanceTheme,
|
||||||
type LspProfileDefinition,
|
type LspProfileDefinition,
|
||||||
type McpServerDefinition,
|
type McpServerDefinition,
|
||||||
|
type OpenTelemetrySettings,
|
||||||
|
type QuickPromptSettings,
|
||||||
type WorkspaceToolingSettings,
|
type WorkspaceToolingSettings,
|
||||||
} from '@shared/domain/tooling';
|
} from '@shared/domain/tooling';
|
||||||
import { normalizeWorkspaceAgentDefinition, findWorkspaceAgentUsages, type WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
import { normalizeWorkspaceAgentDefinition, findWorkspaceAgentUsages, type WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
||||||
@@ -62,9 +65,13 @@ interface SettingsPanelProps {
|
|||||||
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
|
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
|
||||||
workflowTemplates?: WorkflowTemplateDefinition[];
|
workflowTemplates?: WorkflowTemplateDefinition[];
|
||||||
onCreateWorkflowFromTemplate?: (templateId: string, name?: string) => Promise<void>;
|
onCreateWorkflowFromTemplate?: (templateId: string, name?: string) => Promise<void>;
|
||||||
|
quickPromptSettings?: QuickPromptSettings;
|
||||||
|
onSetQuickPromptSettings?: (patch: Partial<QuickPromptSettings>) => void;
|
||||||
|
openTelemetry?: OpenTelemetrySettings;
|
||||||
|
onSetOpenTelemetry?: (settings: OpenTelemetrySettings) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SettingsSection = 'appearance' | 'connection' | 'workflows' | 'agents' | 'mcp-servers' | 'lsp-profiles' | 'troubleshooting';
|
export type SettingsSection = 'appearance' | 'connection' | 'workflows' | 'agents' | 'mcp-servers' | 'lsp-profiles' | 'quick-prompt' | 'telemetry' | 'troubleshooting';
|
||||||
|
|
||||||
interface NavItem {
|
interface NavItem {
|
||||||
id: SettingsSection;
|
id: SettingsSection;
|
||||||
@@ -82,6 +89,8 @@ const navGroups: NavGroup[] = [
|
|||||||
label: 'General',
|
label: 'General',
|
||||||
items: [
|
items: [
|
||||||
{ id: 'appearance', label: 'Appearance', icon: <Palette className="size-3.5" /> },
|
{ id: 'appearance', label: 'Appearance', icon: <Palette className="size-3.5" /> },
|
||||||
|
{ id: 'quick-prompt', label: 'Quick Prompt', icon: <Sparkles className="size-3.5" /> },
|
||||||
|
{ id: 'telemetry', label: 'Telemetry', icon: <Activity className="size-3.5" /> },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -149,6 +158,10 @@ export function SettingsPanel({
|
|||||||
onGetQuota,
|
onGetQuota,
|
||||||
workflowTemplates,
|
workflowTemplates,
|
||||||
onCreateWorkflowFromTemplate,
|
onCreateWorkflowFromTemplate,
|
||||||
|
quickPromptSettings,
|
||||||
|
onSetQuickPromptSettings,
|
||||||
|
openTelemetry,
|
||||||
|
onSetOpenTelemetry,
|
||||||
}: SettingsPanelProps) {
|
}: SettingsPanelProps) {
|
||||||
const [activeSection, setActiveSection] = useState<SettingsSection>(initialSection ?? 'appearance');
|
const [activeSection, setActiveSection] = useState<SettingsSection>(initialSection ?? 'appearance');
|
||||||
const [editingWorkflow, setEditingWorkflow] = useState<WorkflowDefinition | null>(null);
|
const [editingWorkflow, setEditingWorkflow] = useState<WorkflowDefinition | null>(null);
|
||||||
@@ -192,6 +205,7 @@ export function SettingsPanel({
|
|||||||
}}
|
}}
|
||||||
workflow={editingWorkflow}
|
workflow={editingWorkflow}
|
||||||
workflows={workflows}
|
workflows={workflows}
|
||||||
|
workspaceAgents={workspaceAgents}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -380,6 +394,19 @@ export function SettingsPanel({
|
|||||||
profiles={toolingSettings.lspProfiles}
|
profiles={toolingSettings.lspProfiles}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{activeSection === 'quick-prompt' && (
|
||||||
|
<QuickPromptSettingsSection
|
||||||
|
settings={quickPromptSettings}
|
||||||
|
availableModels={availableModels}
|
||||||
|
onUpdate={onSetQuickPromptSettings}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{activeSection === 'telemetry' && (
|
||||||
|
<TelemetrySection
|
||||||
|
openTelemetry={openTelemetry}
|
||||||
|
onSetOpenTelemetry={onSetOpenTelemetry}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{activeSection === 'troubleshooting' && (
|
{activeSection === 'troubleshooting' && (
|
||||||
<TroubleshootingSection
|
<TroubleshootingSection
|
||||||
onOpenAppDataFolder={onOpenAppDataFolder}
|
onOpenAppDataFolder={onOpenAppDataFolder}
|
||||||
@@ -534,6 +561,67 @@ function AppearanceSection({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function TelemetrySection({
|
||||||
|
openTelemetry,
|
||||||
|
onSetOpenTelemetry,
|
||||||
|
}: {
|
||||||
|
openTelemetry?: OpenTelemetrySettings;
|
||||||
|
onSetOpenTelemetry?: (settings: OpenTelemetrySettings) => void;
|
||||||
|
}) {
|
||||||
|
const enabled = openTelemetry?.enabled ?? false;
|
||||||
|
const endpoint = openTelemetry?.endpoint ?? DEFAULT_OTEL_ENDPOINT;
|
||||||
|
|
||||||
|
const handleToggle = () => {
|
||||||
|
onSetOpenTelemetry?.({ enabled: !enabled, endpoint });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEndpointChange = (value: string) => {
|
||||||
|
onSetOpenTelemetry?.({ enabled, endpoint: value });
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-1">
|
||||||
|
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">OpenTelemetry</h3>
|
||||||
|
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
|
||||||
|
Export traces from the sidecar to an OTLP-compatible collector
|
||||||
|
</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={handleToggle}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
|
||||||
|
Enable OTLP export
|
||||||
|
</span>
|
||||||
|
<p className="text-[12px] text-[var(--color-text-muted)]">
|
||||||
|
Send traces to the configured OTLP endpoint when a new sidecar session starts
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<ToggleSwitch enabled={enabled} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="mt-5">
|
||||||
|
<label className="mb-1.5 block text-[12px] font-medium text-[var(--color-text-secondary)]">
|
||||||
|
OTLP endpoint
|
||||||
|
</label>
|
||||||
|
<TextInput
|
||||||
|
value={endpoint}
|
||||||
|
onChange={handleEndpointChange}
|
||||||
|
placeholder={DEFAULT_OTEL_ENDPOINT}
|
||||||
|
/>
|
||||||
|
<p className="mt-1.5 text-[11px] text-[var(--color-text-muted)]">
|
||||||
|
The URL of any OTLP-compatible collector (e.g. Jaeger, Aspire Dashboard, Grafana Alloy).
|
||||||
|
Changes take effect on the next session.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function ConnectionSection({
|
function ConnectionSection({
|
||||||
connection,
|
connection,
|
||||||
modelCount,
|
modelCount,
|
||||||
@@ -1304,3 +1392,221 @@ function TroubleshootingAction({
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function QuickPromptSettingsSection({
|
||||||
|
settings,
|
||||||
|
availableModels,
|
||||||
|
onUpdate,
|
||||||
|
}: {
|
||||||
|
settings?: QuickPromptSettings;
|
||||||
|
availableModels: ReadonlyArray<ModelDefinition>;
|
||||||
|
onUpdate?: (patch: Partial<QuickPromptSettings>) => void;
|
||||||
|
}) {
|
||||||
|
const [modelDropdownOpen, setModelDropdownOpen] = useState(false);
|
||||||
|
|
||||||
|
const enabled = settings?.enabled ?? true;
|
||||||
|
const hotkey = settings?.hotkey ?? 'Alt+Shift+C';
|
||||||
|
const defaultModel = settings?.defaultModel;
|
||||||
|
const defaultReasoning = settings?.defaultReasoningEffort;
|
||||||
|
|
||||||
|
const resolvedModel = defaultModel ? availableModels.find((m) => m.id === defaultModel) : undefined;
|
||||||
|
const modelSupportsReasoning = resolvedModel?.supportedReasoningEfforts?.length;
|
||||||
|
|
||||||
|
// Group models by tier for the dropdown
|
||||||
|
const tierOrder = ['premium', 'standard', 'fast'] as const;
|
||||||
|
const tierLabels: Record<string, string> = { premium: 'Premium', standard: 'Standard', fast: 'Fast' };
|
||||||
|
const groupedModels = tierOrder
|
||||||
|
.map((tier) => ({
|
||||||
|
tier,
|
||||||
|
label: tierLabels[tier],
|
||||||
|
models: availableModels.filter((m) => m.tier === tier),
|
||||||
|
}))
|
||||||
|
.filter((g) => g.models.length > 0);
|
||||||
|
|
||||||
|
// Models without a tier
|
||||||
|
const untypedModels = availableModels.filter((m) => !m.tier);
|
||||||
|
if (untypedModels.length > 0) {
|
||||||
|
groupedModels.push({ tier: 'other' as never, label: 'Other', models: untypedModels });
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-1">
|
||||||
|
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Quick Prompt</h3>
|
||||||
|
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
|
||||||
|
Press a global hotkey to ask the AI a quick question from anywhere
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Enable / Disable toggle */}
|
||||||
|
<div className="mt-5 flex items-center gap-3 rounded-lg border border-[var(--color-border)] px-4 py-3">
|
||||||
|
<button
|
||||||
|
className="flex flex-1 items-start gap-0 text-left"
|
||||||
|
onClick={() => onUpdate?.({ enabled: !enabled })}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<div className="flex-1">
|
||||||
|
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
|
||||||
|
Enable global hotkey
|
||||||
|
</span>
|
||||||
|
<p className="mt-0.5 text-[11px] text-[var(--color-text-muted)]">
|
||||||
|
Summon Quick Prompt from any app
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
<button onClick={() => onUpdate?.({ enabled: !enabled })} type="button">
|
||||||
|
<ToggleSwitch enabled={enabled} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Hotkey Recorder */}
|
||||||
|
<div className="mt-4">
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">
|
||||||
|
Keyboard shortcut
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<HotkeyRecorder
|
||||||
|
value={hotkey}
|
||||||
|
disabled={!enabled}
|
||||||
|
onChange={(newHotkey) => onUpdate?.({ hotkey: newHotkey })}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Default Model — compact dropdown selector */}
|
||||||
|
<div className="mt-6">
|
||||||
|
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Default Model</h3>
|
||||||
|
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
|
||||||
|
Override the workflow model for Quick Prompt sessions
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="relative mt-3">
|
||||||
|
{/* Trigger button */}
|
||||||
|
<button
|
||||||
|
onClick={() => setModelDropdownOpen((prev) => !prev)}
|
||||||
|
className={`flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left transition ${
|
||||||
|
modelDropdownOpen
|
||||||
|
? 'border-[var(--color-accent)]/40 bg-[var(--color-accent-muted)]'
|
||||||
|
: 'border-[var(--color-border)] hover:bg-[var(--color-surface-3)]/40'
|
||||||
|
}`}
|
||||||
|
type="button"
|
||||||
|
aria-haspopup="listbox"
|
||||||
|
aria-expanded={modelDropdownOpen}
|
||||||
|
>
|
||||||
|
<div className="flex-1">
|
||||||
|
<span className="text-[13px] font-medium text-[var(--color-text-primary)]">
|
||||||
|
{resolvedModel?.name ?? 'Workflow default'}
|
||||||
|
</span>
|
||||||
|
{resolvedModel?.tier && (
|
||||||
|
<span className={`ml-2 inline-flex items-center gap-1 rounded-[4px] px-1.5 py-px text-[10px] font-medium ${
|
||||||
|
resolvedModel.tier === 'premium' ? 'bg-amber-400/10 text-amber-400' :
|
||||||
|
resolvedModel.tier === 'fast' ? 'bg-emerald-400/10 text-emerald-400' :
|
||||||
|
'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
|
||||||
|
}`}>
|
||||||
|
{resolvedModel.tier}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ChevronRight className={`size-4 text-[var(--color-text-muted)] transition-transform ${modelDropdownOpen ? 'rotate-90' : ''}`} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Dropdown */}
|
||||||
|
{modelDropdownOpen && (
|
||||||
|
<div className="absolute top-full left-0 right-0 z-10 mt-1 overflow-hidden rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-xl shadow-black/40">
|
||||||
|
<div className="max-h-[280px] overflow-y-auto p-1.5">
|
||||||
|
{/* Workflow default option */}
|
||||||
|
<button
|
||||||
|
onClick={() => { onUpdate?.({ defaultModel: undefined }); setModelDropdownOpen(false); }}
|
||||||
|
className={`flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left transition ${
|
||||||
|
!defaultModel
|
||||||
|
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]'
|
||||||
|
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]'
|
||||||
|
}`}
|
||||||
|
type="button"
|
||||||
|
role="option"
|
||||||
|
aria-selected={!defaultModel}
|
||||||
|
>
|
||||||
|
<span className="flex-1 text-[12px] font-medium">Workflow default</span>
|
||||||
|
{!defaultModel && <CircleCheck className="size-3.5 text-[var(--color-accent)]" />}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Grouped models */}
|
||||||
|
{groupedModels.map((group) => (
|
||||||
|
<div key={group.tier}>
|
||||||
|
<div className="mx-2 mt-2 mb-1 border-t border-[var(--color-border-subtle)]/50" />
|
||||||
|
<div className="px-2.5 pt-1.5 pb-0.5 text-[10px] font-semibold tracking-wider text-[var(--color-text-muted)] uppercase">
|
||||||
|
{group.label}
|
||||||
|
</div>
|
||||||
|
{group.models.map((model) => {
|
||||||
|
const isSelected = defaultModel === model.id;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={model.id}
|
||||||
|
onClick={() => { onUpdate?.({ defaultModel: model.id }); setModelDropdownOpen(false); }}
|
||||||
|
className={`flex w-full items-center gap-2 rounded-lg px-3 py-[7px] text-left transition ${
|
||||||
|
isSelected
|
||||||
|
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]'
|
||||||
|
: 'text-[var(--color-text-secondary)] hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]'
|
||||||
|
}`}
|
||||||
|
type="button"
|
||||||
|
role="option"
|
||||||
|
aria-selected={isSelected}
|
||||||
|
>
|
||||||
|
<span className="flex-1 truncate text-[12px] font-medium">{model.name}</span>
|
||||||
|
{model.supportedReasoningEfforts?.length ? (
|
||||||
|
<span className="text-[9px] font-semibold tracking-wide text-[var(--color-text-muted)] uppercase">reasoning</span>
|
||||||
|
) : null}
|
||||||
|
{isSelected && <CircleCheck className="size-3.5 flex-none text-[var(--color-accent)]" />}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Reasoning Effort — only shown when selected model supports it */}
|
||||||
|
{modelSupportsReasoning ? (
|
||||||
|
<div className="mt-6">
|
||||||
|
<h3 className="font-display text-[13px] font-semibold text-[var(--color-text-primary)]">Reasoning Effort</h3>
|
||||||
|
<p className="mt-0.5 text-[12px] text-[var(--color-text-muted)]">
|
||||||
|
Higher effort produces more thorough answers but takes longer
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-3 flex gap-1.5">
|
||||||
|
{([undefined, 'low', 'medium', 'high'] as const).map((effort) => {
|
||||||
|
const isActive = defaultReasoning === effort;
|
||||||
|
const label = effort ?? 'Auto';
|
||||||
|
const displayLabel = label.charAt(0).toUpperCase() + label.slice(1);
|
||||||
|
|
||||||
|
// Only show efforts the model actually supports (plus "Auto")
|
||||||
|
if (effort && !resolvedModel?.supportedReasoningEfforts?.includes(effort)) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={displayLabel}
|
||||||
|
onClick={() => onUpdate?.({ defaultReasoningEffort: effort })}
|
||||||
|
className={`flex-1 rounded-lg border py-2 text-[12px] font-medium transition-all duration-150 ${
|
||||||
|
isActive
|
||||||
|
? 'border-[var(--color-accent)]/40 bg-[var(--color-accent)]/12 text-[var(--color-text-accent)]'
|
||||||
|
: 'border-[var(--color-border)] text-[var(--color-text-muted)] hover:border-[var(--color-border-glow)] hover:text-[var(--color-text-secondary)]'
|
||||||
|
}`}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{displayLabel}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : defaultModel ? (
|
||||||
|
<p className="mt-4 text-[11px] text-[var(--color-text-muted)]">
|
||||||
|
{resolvedModel?.name ?? 'Selected model'} does not support configurable reasoning effort.
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import appIconUrl from '../../../assets/icons/icon.png';
|
import appIconUrl from '../../../assets/icons/icon.png';
|
||||||
import { isMac } from '@renderer/lib/platform';
|
import { isMac } from '@renderer/lib/platform';
|
||||||
import {
|
import {
|
||||||
AlertTriangle,
|
AlertTriangle,
|
||||||
Archive,
|
Archive,
|
||||||
ArrowLeftRight,
|
ArrowLeftRight,
|
||||||
|
Check,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
Circle,
|
Circle,
|
||||||
@@ -35,6 +36,10 @@ import { querySessions } from '@shared/domain/sessionLibrary';
|
|||||||
import type { UpdateStatus } from '@shared/contracts/ipc';
|
import type { UpdateStatus } from '@shared/contracts/ipc';
|
||||||
import type { WorkspaceState } from '@shared/domain/workspace';
|
import type { WorkspaceState } from '@shared/domain/workspace';
|
||||||
import { UpdateBanner } from '@renderer/components/ui';
|
import { UpdateBanner } from '@renderer/components/ui';
|
||||||
|
import { useSessionSelection } from '@renderer/hooks/useSessionSelection';
|
||||||
|
import { BatchActionBar } from '@renderer/components/sidebar/BatchActionBar';
|
||||||
|
import { BatchDeleteConfirmDialog } from '@renderer/components/sidebar/BatchDeleteConfirmDialog';
|
||||||
|
import { UndoToast } from '@renderer/components/sidebar/UndoToast';
|
||||||
|
|
||||||
interface SidebarProps {
|
interface SidebarProps {
|
||||||
workspace: WorkspaceState;
|
workspace: WorkspaceState;
|
||||||
@@ -50,6 +55,8 @@ interface SidebarProps {
|
|||||||
onSetSessionPinned: (sessionId: string, isPinned: boolean) => void;
|
onSetSessionPinned: (sessionId: string, isPinned: boolean) => void;
|
||||||
onSetSessionArchived: (sessionId: string, isArchived: boolean) => void;
|
onSetSessionArchived: (sessionId: string, isArchived: boolean) => void;
|
||||||
onDeleteSession: (sessionId: string) => void;
|
onDeleteSession: (sessionId: string) => void;
|
||||||
|
onBatchArchiveSessions: (sessionIds: string[], isArchived: boolean) => void;
|
||||||
|
onBatchDeleteSessions: (sessionIds: string[]) => void;
|
||||||
onRefreshGitContext: (projectId: string) => void;
|
onRefreshGitContext: (projectId: string) => void;
|
||||||
updateStatus?: UpdateStatus;
|
updateStatus?: UpdateStatus;
|
||||||
onViewUpdateDetails?: () => void;
|
onViewUpdateDetails?: () => void;
|
||||||
@@ -183,6 +190,12 @@ function SessionItem({
|
|||||||
onOpenMenu,
|
onOpenMenu,
|
||||||
onRenameSubmit,
|
onRenameSubmit,
|
||||||
onRenameCancel,
|
onRenameCancel,
|
||||||
|
isSelecting,
|
||||||
|
isSelected,
|
||||||
|
selectionIndex,
|
||||||
|
onToggleSelection,
|
||||||
|
onEnterSelectionMode,
|
||||||
|
onShiftSelect,
|
||||||
}: {
|
}: {
|
||||||
session: SessionRecord;
|
session: SessionRecord;
|
||||||
workflow?: WorkflowDefinition;
|
workflow?: WorkflowDefinition;
|
||||||
@@ -192,6 +205,12 @@ function SessionItem({
|
|||||||
onOpenMenu: (e: React.MouseEvent) => void;
|
onOpenMenu: (e: React.MouseEvent) => void;
|
||||||
onRenameSubmit: (title: string) => void;
|
onRenameSubmit: (title: string) => void;
|
||||||
onRenameCancel: () => void;
|
onRenameCancel: () => void;
|
||||||
|
isSelecting?: boolean;
|
||||||
|
isSelected?: boolean;
|
||||||
|
selectionIndex?: number;
|
||||||
|
onToggleSelection?: () => void;
|
||||||
|
onEnterSelectionMode?: () => void;
|
||||||
|
onShiftSelect?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const isRunning = session.status === 'running';
|
const isRunning = session.status === 'running';
|
||||||
const isError = session.status === 'error';
|
const isError = session.status === 'error';
|
||||||
@@ -201,6 +220,7 @@ function SessionItem({
|
|||||||
const visual = modeVisuals[mode];
|
const visual = modeVisuals[mode];
|
||||||
const ModeIcon = visual.icon;
|
const ModeIcon = visual.icon;
|
||||||
const agentCount = workflow ? resolveWorkflowAgentNodes(workflow).length : 1;
|
const agentCount = workflow ? resolveWorkflowAgentNodes(workflow).length : 1;
|
||||||
|
const isSelectDisabled = isRunning;
|
||||||
|
|
||||||
const [renameText, setRenameText] = useState(session.title);
|
const [renameText, setRenameText] = useState(session.title);
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
@@ -232,34 +252,96 @@ function SessionItem({
|
|||||||
else onRenameCancel();
|
else onRenameCancel();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleClick(e: React.MouseEvent) {
|
||||||
|
if (isRenaming) return;
|
||||||
|
|
||||||
|
// Already in selection mode — toggle or range-select
|
||||||
|
if (isSelecting) {
|
||||||
|
if (isSelectDisabled) return;
|
||||||
|
if (e.shiftKey) {
|
||||||
|
onShiftSelect?.();
|
||||||
|
} else {
|
||||||
|
onToggleSelection?.();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not in selection mode — check for modifier key to enter it
|
||||||
|
const modKey = isMac ? e.metaKey : e.ctrlKey;
|
||||||
|
if (modKey && !isSelectDisabled) {
|
||||||
|
onEnterSelectionMode?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
onSelect();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleKeyDown(e: React.KeyboardEvent) {
|
||||||
|
if ((e.key === 'Enter' || e.key === ' ') && !isRenaming) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (isSelecting) {
|
||||||
|
if (!isSelectDisabled) onToggleSelection?.();
|
||||||
|
} else {
|
||||||
|
onSelect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
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 ${
|
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
|
isSelecting && isSelected
|
||||||
? 'bg-[var(--color-accent-muted)] ring-1 ring-[var(--color-border-glow)]'
|
? 'bg-[var(--color-accent-muted)] ring-1 ring-[var(--color-border-glow)]'
|
||||||
: 'hover:bg-[var(--color-surface-2)]/60'
|
: isActive && !isSelecting
|
||||||
} ${isRunning ? 'sidebar-running' : ''} ${session.isArchived ? 'opacity-50' : ''}`}
|
? 'bg-[var(--color-accent-muted)] ring-1 ring-[var(--color-border-glow)]'
|
||||||
onClick={isRenaming ? undefined : onSelect}
|
: 'hover:bg-[var(--color-surface-2)]/60'
|
||||||
role="button"
|
} ${isRunning ? 'sidebar-running' : ''} ${session.isArchived ? 'opacity-50' : ''} ${isSelectDisabled ? 'cursor-not-allowed opacity-40' : ''}`}
|
||||||
|
onClick={handleClick}
|
||||||
|
role={isSelecting ? 'checkbox' : 'button'}
|
||||||
|
aria-checked={isSelecting ? isSelected : undefined}
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
onKeyDown={(e) => { if ((e.key === 'Enter' || e.key === ' ') && !isRenaming) { e.preventDefault(); onSelect(); } }}
|
onKeyDown={handleKeyDown}
|
||||||
>
|
>
|
||||||
{/* Running/approval left accent bar */}
|
{/* Running/approval left accent bar */}
|
||||||
{isRunning && !hasPendingApproval && (
|
{isRunning && !hasPendingApproval && !isSelecting && (
|
||||||
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full accent-flow" />
|
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full accent-flow" />
|
||||||
)}
|
)}
|
||||||
{hasPendingApproval && (
|
{hasPendingApproval && !isSelecting && (
|
||||||
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-[var(--color-status-warning)]" />
|
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-[var(--color-status-warning)]" />
|
||||||
)}
|
)}
|
||||||
|
{/* Selection accent bar */}
|
||||||
|
{isSelecting && isSelected && (
|
||||||
|
<span className="absolute inset-y-1.5 left-0 w-[3px] rounded-full bg-[var(--color-accent)]" />
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Mode icon */}
|
{/* Mode icon or selection checkbox */}
|
||||||
<span
|
{isSelecting ? (
|
||||||
className={`mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-md ${
|
<span
|
||||||
isActive ? 'bg-[var(--color-accent-muted)]' : 'bg-[var(--color-surface-2)]'
|
className="selection-checkbox-enter mt-0.5 flex size-6 shrink-0 items-center justify-center"
|
||||||
}`}
|
style={{ animationDelay: `${(selectionIndex ?? 0) * 30}ms` }}
|
||||||
>
|
title={isSelectDisabled ? "Can't select running sessions" : undefined}
|
||||||
<ModeIcon className={`size-3.5 ${isActive ? 'text-[var(--color-accent)]' : visual.color}`} />
|
>
|
||||||
</span>
|
<span
|
||||||
|
className={`flex size-4 items-center justify-center rounded border transition-all duration-150 ${
|
||||||
|
isSelected
|
||||||
|
? 'checkbox-check border-[var(--color-accent)] bg-[var(--color-accent)]'
|
||||||
|
: isSelectDisabled
|
||||||
|
? 'border-[var(--color-text-muted)]/30 bg-transparent'
|
||||||
|
: 'border-[var(--color-text-muted)]/50 bg-transparent hover:border-[var(--color-accent)]/50'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{isSelected && <Check className="size-3 text-white" strokeWidth={3} />}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span
|
||||||
|
className={`mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-md ${
|
||||||
|
isActive ? 'bg-[var(--color-accent-muted)]' : 'bg-[var(--color-surface-2)]'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<ModeIcon className={`size-3.5 ${isActive ? 'text-[var(--color-accent)]' : visual.color}`} />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Content */}
|
{/* Content */}
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
@@ -342,8 +424,8 @@ function SessionItem({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Actions button (hidden during rename) */}
|
{/* Actions button (hidden during rename and selection mode) */}
|
||||||
{!isRenaming && (
|
{!isRenaming && !isSelecting && (
|
||||||
<button
|
<button
|
||||||
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"
|
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); }}
|
onClick={(e) => { e.stopPropagation(); onOpenMenu(e); }}
|
||||||
@@ -372,6 +454,11 @@ function ProjectGroup({
|
|||||||
onOpenProjectSettings,
|
onOpenProjectSettings,
|
||||||
onNewSession,
|
onNewSession,
|
||||||
newSessionLabel,
|
newSessionLabel,
|
||||||
|
isSelecting,
|
||||||
|
isSelected,
|
||||||
|
onToggleSelection,
|
||||||
|
onEnterSelectionMode,
|
||||||
|
onShiftSelect,
|
||||||
}: {
|
}: {
|
||||||
project: ProjectRecord;
|
project: ProjectRecord;
|
||||||
sessions: SessionRecord[];
|
sessions: SessionRecord[];
|
||||||
@@ -386,6 +473,11 @@ function ProjectGroup({
|
|||||||
onOpenProjectSettings?: (projectId: string) => void;
|
onOpenProjectSettings?: (projectId: string) => void;
|
||||||
onNewSession?: () => void;
|
onNewSession?: () => void;
|
||||||
newSessionLabel?: string;
|
newSessionLabel?: string;
|
||||||
|
isSelecting?: boolean;
|
||||||
|
isSelected?: (sessionId: string) => boolean;
|
||||||
|
onToggleSelection?: (sessionId: string) => void;
|
||||||
|
onEnterSelectionMode?: (sessionId: string) => void;
|
||||||
|
onShiftSelect?: (sessionId: string) => void;
|
||||||
}){
|
}){
|
||||||
const [expanded, setExpanded] = useState(true);
|
const [expanded, setExpanded] = useState(true);
|
||||||
const isScratchpad = isScratchpadProject(project);
|
const isScratchpad = isScratchpadProject(project);
|
||||||
@@ -508,7 +600,7 @@ function ProjectGroup({
|
|||||||
{expanded && (
|
{expanded && (
|
||||||
<div className="ml-2 mt-0.5 space-y-0.5 border-l border-[var(--color-border-subtle)] 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.length > 0 &&
|
||||||
visibleSessions.map((session) => (
|
visibleSessions.map((session, index) => (
|
||||||
<SessionItem
|
<SessionItem
|
||||||
isActive={selectedSessionId === session.id}
|
isActive={selectedSessionId === session.id}
|
||||||
isRenaming={renamingSessionId === session.id}
|
isRenaming={renamingSessionId === session.id}
|
||||||
@@ -519,6 +611,12 @@ function ProjectGroup({
|
|||||||
onRenameCancel={onRenameCancel}
|
onRenameCancel={onRenameCancel}
|
||||||
workflow={workflowMap.get(session.workflowId)}
|
workflow={workflowMap.get(session.workflowId)}
|
||||||
session={session}
|
session={session}
|
||||||
|
isSelecting={isSelecting}
|
||||||
|
isSelected={isSelected?.(session.id)}
|
||||||
|
selectionIndex={index}
|
||||||
|
onToggleSelection={() => onToggleSelection?.(session.id)}
|
||||||
|
onEnterSelectionMode={() => onEnterSelectionMode?.(session.id)}
|
||||||
|
onShiftSelect={() => onShiftSelect?.(session.id)}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
{onNewSession ? (
|
{onNewSession ? (
|
||||||
@@ -559,6 +657,8 @@ export function Sidebar({
|
|||||||
onSetSessionPinned,
|
onSetSessionPinned,
|
||||||
onSetSessionArchived,
|
onSetSessionArchived,
|
||||||
onDeleteSession,
|
onDeleteSession,
|
||||||
|
onBatchArchiveSessions,
|
||||||
|
onBatchDeleteSessions,
|
||||||
onRefreshGitContext,
|
onRefreshGitContext,
|
||||||
updateStatus,
|
updateStatus,
|
||||||
onViewUpdateDetails,
|
onViewUpdateDetails,
|
||||||
@@ -600,6 +700,7 @@ export function Sidebar({
|
|||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
function handleOpenMenu(sessionId: string, e: React.MouseEvent) {
|
function handleOpenMenu(sessionId: string, e: React.MouseEvent) {
|
||||||
|
if (selection.isSelecting) return;
|
||||||
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
||||||
setMenuState({
|
setMenuState({
|
||||||
sessionId,
|
sessionId,
|
||||||
@@ -621,6 +722,102 @@ export function Sidebar({
|
|||||||
? workspace.sessions.find((s) => s.id === menuState.sessionId)
|
? workspace.sessions.find((s) => s.id === menuState.sessionId)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
|
/* ── Multi-select state ────────────────────────────────────── */
|
||||||
|
|
||||||
|
const selection = useSessionSelection();
|
||||||
|
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||||
|
const [undoToast, setUndoToast] = useState<{ message: string; sessionIds: string[]; isArchived: boolean } | null>(null);
|
||||||
|
|
||||||
|
// All selectable (non-running) session IDs across the visible list
|
||||||
|
const allSelectableIds = useMemo(() => {
|
||||||
|
const sessions = workspace.sessions.filter((s) => !s.isArchived && s.status !== 'running');
|
||||||
|
return sessions.map((s) => s.id);
|
||||||
|
}, [workspace.sessions]);
|
||||||
|
|
||||||
|
// All visible session IDs (for range select and "select all")
|
||||||
|
const allVisibleIds = useMemo(() => {
|
||||||
|
if (isQueryActive) return queryResults.map((s) => s.id);
|
||||||
|
return workspace.sessions.filter((s) => !s.isArchived).map((s) => s.id);
|
||||||
|
}, [isQueryActive, queryResults, workspace.sessions]);
|
||||||
|
|
||||||
|
const allSelectedArchived = useMemo(() => {
|
||||||
|
if (selection.selectedIds.size === 0) return false;
|
||||||
|
return [...selection.selectedIds].every((id) => {
|
||||||
|
const session = workspace.sessions.find((s) => s.id === id);
|
||||||
|
return session?.isArchived;
|
||||||
|
});
|
||||||
|
}, [selection.selectedIds, workspace.sessions]);
|
||||||
|
|
||||||
|
const selectedSessions = useMemo(
|
||||||
|
() => workspace.sessions.filter((s) => selection.selectedIds.has(s.id)),
|
||||||
|
[selection.selectedIds, workspace.sessions],
|
||||||
|
);
|
||||||
|
|
||||||
|
function handleEnterSelectionMode(sessionId: string) {
|
||||||
|
const session = workspace.sessions.find((s) => s.id === sessionId);
|
||||||
|
if (session?.status === 'running') return;
|
||||||
|
selection.enterSelectionMode(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleToggleSelection(sessionId: string) {
|
||||||
|
const session = workspace.sessions.find((s) => s.id === sessionId);
|
||||||
|
if (session?.status === 'running') return;
|
||||||
|
selection.toggle(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleShiftSelect(sessionId: string) {
|
||||||
|
const session = workspace.sessions.find((s) => s.id === sessionId);
|
||||||
|
if (session?.status === 'running') return;
|
||||||
|
selection.rangeSelect(sessionId, allVisibleIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleBatchArchive = useCallback(() => {
|
||||||
|
const ids = [...selection.selectedIds];
|
||||||
|
const isArchived = !allSelectedArchived;
|
||||||
|
onBatchArchiveSessions(ids, isArchived);
|
||||||
|
selection.exitSelectionMode();
|
||||||
|
setUndoToast({
|
||||||
|
message: `${ids.length} session${ids.length === 1 ? '' : 's'} ${isArchived ? 'archived' : 'restored'}`,
|
||||||
|
sessionIds: ids,
|
||||||
|
isArchived,
|
||||||
|
});
|
||||||
|
}, [selection, allSelectedArchived, onBatchArchiveSessions]);
|
||||||
|
|
||||||
|
const handleBatchDeleteConfirm = useCallback(() => {
|
||||||
|
const ids = [...selection.selectedIds];
|
||||||
|
onBatchDeleteSessions(ids);
|
||||||
|
selection.exitSelectionMode();
|
||||||
|
setShowDeleteConfirm(false);
|
||||||
|
}, [selection, onBatchDeleteSessions]);
|
||||||
|
|
||||||
|
const handleUndoArchive = useCallback(() => {
|
||||||
|
if (!undoToast) return;
|
||||||
|
onBatchArchiveSessions(undoToast.sessionIds, !undoToast.isArchived);
|
||||||
|
setUndoToast(null);
|
||||||
|
}, [undoToast, onBatchArchiveSessions]);
|
||||||
|
|
||||||
|
// Exit selection mode on Escape
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selection.isSelecting) return;
|
||||||
|
function handleKeyDown(e: KeyboardEvent) {
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
selection.exitSelectionMode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener('keydown', handleKeyDown);
|
||||||
|
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||||
|
}, [selection.isSelecting, selection.exitSelectionMode]);
|
||||||
|
|
||||||
|
// Clean up selection when sessions are removed from workspace
|
||||||
|
useEffect(() => {
|
||||||
|
if (!selection.isSelecting) return;
|
||||||
|
const sessionIdSet = new Set(workspace.sessions.map((s) => s.id));
|
||||||
|
const stale = [...selection.selectedIds].filter((id) => !sessionIdSet.has(id));
|
||||||
|
if (stale.length > 0) {
|
||||||
|
for (const id of stale) selection.toggle(id);
|
||||||
|
}
|
||||||
|
}, [workspace.sessions, selection]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full flex-col">
|
<div className="flex h-full flex-col">
|
||||||
{/* Header — extra top padding clears the title bar overlay zone */}
|
{/* Header — extra top padding clears the title bar overlay zone */}
|
||||||
@@ -685,7 +882,7 @@ export function Sidebar({
|
|||||||
No sessions match your search
|
No sessions match your search
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
queryResults.map((session) => (
|
queryResults.map((session, index) => (
|
||||||
<SessionItem
|
<SessionItem
|
||||||
isActive={workspace.selectedSessionId === session.id}
|
isActive={workspace.selectedSessionId === session.id}
|
||||||
isRenaming={renamingSessionId === session.id}
|
isRenaming={renamingSessionId === session.id}
|
||||||
@@ -696,6 +893,12 @@ export function Sidebar({
|
|||||||
onRenameCancel={() => setRenamingSessionId(undefined)}
|
onRenameCancel={() => setRenamingSessionId(undefined)}
|
||||||
workflow={workflowMap.get(session.workflowId)}
|
workflow={workflowMap.get(session.workflowId)}
|
||||||
session={session}
|
session={session}
|
||||||
|
isSelecting={selection.isSelecting}
|
||||||
|
isSelected={selection.isSelected(session.id)}
|
||||||
|
selectionIndex={index}
|
||||||
|
onToggleSelection={() => handleToggleSelection(session.id)}
|
||||||
|
onEnterSelectionMode={() => handleEnterSelectionMode(session.id)}
|
||||||
|
onShiftSelect={() => handleShiftSelect(session.id)}
|
||||||
/>
|
/>
|
||||||
))
|
))
|
||||||
)}
|
)}
|
||||||
@@ -721,6 +924,11 @@ export function Sidebar({
|
|||||||
sessions={workspace.sessions.filter((session) => session.projectId === scratchpadProject.id)}
|
sessions={workspace.sessions.filter((session) => session.projectId === scratchpadProject.id)}
|
||||||
onNewSession={onCreateScratchpad}
|
onNewSession={onCreateScratchpad}
|
||||||
newSessionLabel="New Scratchpad"
|
newSessionLabel="New Scratchpad"
|
||||||
|
isSelecting={selection.isSelecting}
|
||||||
|
isSelected={selection.isSelected}
|
||||||
|
onToggleSelection={handleToggleSelection}
|
||||||
|
onEnterSelectionMode={handleEnterSelectionMode}
|
||||||
|
onShiftSelect={handleShiftSelect}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -769,6 +977,11 @@ export function Sidebar({
|
|||||||
selectedSessionId={workspace.selectedSessionId}
|
selectedSessionId={workspace.selectedSessionId}
|
||||||
sessions={workspace.sessions.filter((session) => session.projectId === project.id)}
|
sessions={workspace.sessions.filter((session) => session.projectId === project.id)}
|
||||||
onNewSession={() => onNewProjectSession(project.id)}
|
onNewSession={() => onNewProjectSession(project.id)}
|
||||||
|
isSelecting={selection.isSelecting}
|
||||||
|
isSelected={selection.isSelected}
|
||||||
|
onToggleSelection={handleToggleSelection}
|
||||||
|
onEnterSelectionMode={handleEnterSelectionMode}
|
||||||
|
onShiftSelect={handleShiftSelect}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -801,7 +1014,7 @@ export function Sidebar({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Context menu overlay */}
|
{/* Context menu overlay */}
|
||||||
{menuState && menuSession && (
|
{menuState && menuSession && !selection.isSelecting && (
|
||||||
<>
|
<>
|
||||||
<div className="fixed inset-0 z-40" onClick={closeMenu} onKeyDown={(e) => { if (e.key === 'Escape') closeMenu(); }} />
|
<div className="fixed inset-0 z-40" onClick={closeMenu} onKeyDown={(e) => { if (e.key === 'Escape') closeMenu(); }} />
|
||||||
<div
|
<div
|
||||||
@@ -853,6 +1066,38 @@ export function Sidebar({
|
|||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Batch action bar */}
|
||||||
|
{selection.isSelecting && selection.selectedIds.size > 0 && (
|
||||||
|
<BatchActionBar
|
||||||
|
selectedCount={selection.selectedIds.size}
|
||||||
|
allSelectedArchived={allSelectedArchived}
|
||||||
|
allSelected={allSelectableIds.length > 0 && allSelectableIds.every((id) => selection.selectedIds.has(id))}
|
||||||
|
onArchive={handleBatchArchive}
|
||||||
|
onDelete={() => setShowDeleteConfirm(true)}
|
||||||
|
onSelectAll={() => selection.selectAll(allSelectableIds)}
|
||||||
|
onDeselectAll={selection.deselectAll}
|
||||||
|
onCancel={selection.exitSelectionMode}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Undo toast */}
|
||||||
|
{undoToast && (
|
||||||
|
<UndoToast
|
||||||
|
message={undoToast.message}
|
||||||
|
onUndo={handleUndoArchive}
|
||||||
|
onDismiss={() => setUndoToast(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Batch delete confirmation */}
|
||||||
|
{showDeleteConfirm && selectedSessions.length > 0 && (
|
||||||
|
<BatchDeleteConfirmDialog
|
||||||
|
sessions={selectedSessions}
|
||||||
|
onConfirm={handleBatchDeleteConfirm}
|
||||||
|
onCancel={() => setShowDeleteConfirm(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import type {
|
|||||||
SubWorkflowConfig,
|
SubWorkflowConfig,
|
||||||
WorkflowStateScope,
|
WorkflowStateScope,
|
||||||
} from '@shared/domain/workflow';
|
} from '@shared/domain/workflow';
|
||||||
|
import type { WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
||||||
import { validateWorkflowDefinition, isBuilderBasedMode, syncBuilderModeEdgeIterations } from '@shared/domain/workflow';
|
import { validateWorkflowDefinition, isBuilderBasedMode, syncBuilderModeEdgeIterations } from '@shared/domain/workflow';
|
||||||
import { createId } from '@shared/utils/ids';
|
import { createId } from '@shared/utils/ids';
|
||||||
import { ToggleSwitch } from '@renderer/components/ui';
|
import { ToggleSwitch } from '@renderer/components/ui';
|
||||||
@@ -25,6 +26,7 @@ import { OrchestrationModePanel } from './workflow/OrchestrationModePanel';
|
|||||||
|
|
||||||
interface WorkflowEditorProps {
|
interface WorkflowEditorProps {
|
||||||
availableModels: ReadonlyArray<ModelDefinition>;
|
availableModels: ReadonlyArray<ModelDefinition>;
|
||||||
|
workspaceAgents: ReadonlyArray<WorkspaceAgentDefinition>;
|
||||||
workflow: WorkflowDefinition;
|
workflow: WorkflowDefinition;
|
||||||
workflows: ReadonlyArray<WorkflowDefinition>;
|
workflows: ReadonlyArray<WorkflowDefinition>;
|
||||||
onChange: (workflow: WorkflowDefinition) => void;
|
onChange: (workflow: WorkflowDefinition) => void;
|
||||||
@@ -152,6 +154,7 @@ function createMinimalInlineWorkflow(): WorkflowDefinition {
|
|||||||
|
|
||||||
export function WorkflowEditor({
|
export function WorkflowEditor({
|
||||||
availableModels,
|
availableModels,
|
||||||
|
workspaceAgents,
|
||||||
workflow,
|
workflow,
|
||||||
workflows,
|
workflows,
|
||||||
onChange,
|
onChange,
|
||||||
@@ -251,6 +254,36 @@ export function WorkflowEditor({
|
|||||||
setSelectedEdgeId(null);
|
setSelectedEdgeId(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleAddWorkspaceAgentNode(agentId: string) {
|
||||||
|
const agent = workspaceAgents.find((a) => a.id === agentId);
|
||||||
|
if (!agent) return;
|
||||||
|
const nodeId = createId('wf-agent');
|
||||||
|
const config: AgentNodeConfig = {
|
||||||
|
kind: 'agent',
|
||||||
|
id: createId('agent'),
|
||||||
|
name: agent.name,
|
||||||
|
description: agent.description,
|
||||||
|
instructions: agent.instructions,
|
||||||
|
model: agent.model,
|
||||||
|
reasoningEffort: agent.reasoningEffort,
|
||||||
|
copilot: agent.copilot,
|
||||||
|
workspaceAgentId: agent.id,
|
||||||
|
};
|
||||||
|
const newNode: WorkflowNode = {
|
||||||
|
id: nodeId,
|
||||||
|
kind: 'agent',
|
||||||
|
label: agent.name,
|
||||||
|
position: { x: 300, y: 200 },
|
||||||
|
config,
|
||||||
|
};
|
||||||
|
emitGraphChange({
|
||||||
|
...activeWorkflow.graph,
|
||||||
|
nodes: [...activeWorkflow.graph.nodes, newNode],
|
||||||
|
});
|
||||||
|
setSelectedNodeId(nodeId);
|
||||||
|
setSelectedEdgeId(null);
|
||||||
|
}
|
||||||
|
|
||||||
function handleNodeChange(nodeId: string, patch: Partial<WorkflowNode>) {
|
function handleNodeChange(nodeId: string, patch: Partial<WorkflowNode>) {
|
||||||
emitGraphChange({
|
emitGraphChange({
|
||||||
...activeWorkflow.graph,
|
...activeWorkflow.graph,
|
||||||
@@ -486,7 +519,12 @@ export function WorkflowEditor({
|
|||||||
<div className="flex min-h-0 flex-1">
|
<div className="flex min-h-0 flex-1">
|
||||||
{/* Left palette */}
|
{/* Left palette */}
|
||||||
<div className="w-40 shrink-0 overflow-y-auto border-r border-[var(--color-border)] bg-[var(--color-surface-1)]">
|
<div className="w-40 shrink-0 overflow-y-auto border-r border-[var(--color-border)] bg-[var(--color-surface-1)]">
|
||||||
<WorkflowNodePalette disabledKinds={disabledPaletteKinds} onAddNode={handleAddNode} />
|
<WorkflowNodePalette
|
||||||
|
disabledKinds={disabledPaletteKinds}
|
||||||
|
onAddNode={handleAddNode}
|
||||||
|
onAddWorkspaceAgentNode={handleAddWorkspaceAgentNode}
|
||||||
|
workspaceAgents={workspaceAgents}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Center column: validation + canvas + settings */}
|
{/* Center column: validation + canvas + settings */}
|
||||||
@@ -551,6 +589,7 @@ export function WorkflowEditor({
|
|||||||
validationIssues={issues}
|
validationIssues={issues}
|
||||||
workflow={activeWorkflow}
|
workflow={activeWorkflow}
|
||||||
workflows={workflows}
|
workflows={workflows}
|
||||||
|
workspaceAgents={workspaceAgents}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { Bot, Check, ChevronDown, Loader2, ShieldAlert, ShieldBan, ShieldCheck,
|
|||||||
|
|
||||||
import { MarkdownContent } from '@renderer/components/MarkdownContent';
|
import { MarkdownContent } from '@renderer/components/MarkdownContent';
|
||||||
import { permissionDetailSummary, PermissionDetailView } from '@renderer/components/chat/PermissionDetailView';
|
import { permissionDetailSummary, PermissionDetailView } from '@renderer/components/chat/PermissionDetailView';
|
||||||
import { resolveApprovalToolKey } from '@shared/domain/approval';
|
import { getPendingApprovalToolKey } from '@shared/domain/approval';
|
||||||
import type { ApprovalDecision, PendingApprovalRecord } from '@shared/domain/approval';
|
import type { ApprovalDecision, PendingApprovalRecord } from '@shared/domain/approval';
|
||||||
import { resolveToolLabel } from '@shared/domain/tooling';
|
import { resolveToolLabel } from '@shared/domain/tooling';
|
||||||
|
|
||||||
@@ -25,7 +25,7 @@ export function ApprovalBanner({
|
|||||||
const kindLabel = approval.kind === 'final-response' ? 'Final response review' : 'Tool call approval';
|
const kindLabel = approval.kind === 'final-response' ? 'Final response review' : 'Tool call approval';
|
||||||
const hasMessages = approval.messages && approval.messages.length > 0;
|
const hasMessages = approval.messages && approval.messages.length > 0;
|
||||||
const showPosition = position !== undefined && total !== undefined && total > 1;
|
const showPosition = position !== undefined && total !== undefined && total > 1;
|
||||||
const approvalToolKey = resolveApprovalToolKey(approval.toolName, approval.permissionKind);
|
const approvalToolKey = getPendingApprovalToolKey(approval);
|
||||||
const canAlwaysApprove = approval.kind === 'tool-call' && !!approvalToolKey;
|
const canAlwaysApprove = approval.kind === 'tool-call' && !!approvalToolKey;
|
||||||
const approvalToolLabel = approvalToolKey ? resolveToolLabel(approvalToolKey) : undefined;
|
const approvalToolLabel = approvalToolKey ? resolveToolLabel(approvalToolKey) : undefined;
|
||||||
|
|
||||||
|
|||||||
@@ -5,12 +5,12 @@ import type { ActiveSubagent } from '@renderer/lib/subagentTracker';
|
|||||||
|
|
||||||
const COMPLETION_GRACE_MS = 3000;
|
const COMPLETION_GRACE_MS = 3000;
|
||||||
|
|
||||||
function formatElapsed(startedAt: string): string {
|
import { formatElapsedMs } from '@renderer/hooks/useElapsedTimer';
|
||||||
const seconds = Math.floor((Date.now() - new Date(startedAt).getTime()) / 1000);
|
|
||||||
if (seconds < 60) return `${seconds}s`;
|
function formatElapsed(startedAt: string, endedAt?: string): string {
|
||||||
const minutes = Math.floor(seconds / 60);
|
const endMs = endedAt ? new Date(endedAt).getTime() : Date.now();
|
||||||
const remainder = seconds % 60;
|
const durationMs = endMs - new Date(startedAt).getTime();
|
||||||
return `${minutes}m ${remainder}s`;
|
return formatElapsedMs(durationMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
function StatusIcon({ status }: { status: ActiveSubagent['status'] }) {
|
function StatusIcon({ status }: { status: ActiveSubagent['status'] }) {
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ export interface TurnActivityPanelProps {
|
|||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
turnStartedAt?: string;
|
turnStartedAt?: string;
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
|
currentIntent?: string;
|
||||||
agentNames?: ReadonlySet<string>;
|
agentNames?: ReadonlySet<string>;
|
||||||
isLastRunPanel?: boolean;
|
isLastRunPanel?: boolean;
|
||||||
onDiscard?: (sessionId: string, runId: string, files?: ProjectGitFileReference[]) => Promise<unknown>;
|
onDiscard?: (sessionId: string, runId: string, files?: ProjectGitFileReference[]) => Promise<unknown>;
|
||||||
@@ -152,12 +153,12 @@ function ActivityTimelineEventRow({ event }: { event: RunTimelineEventRecord })
|
|||||||
const isTerminal = event.kind === 'run-completed' || event.kind === 'run-cancelled' || event.kind === 'run-failed';
|
const isTerminal = event.kind === 'run-completed' || event.kind === 'run-cancelled' || event.kind === 'run-failed';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="turn-activity-row flex gap-2 py-1">
|
<div className="turn-activity-row flex items-start gap-2 py-1">
|
||||||
<div className="mt-0.5 flex shrink-0 items-start">
|
<div className="flex h-[18px] w-4 shrink-0 items-center justify-center">
|
||||||
<ActivityEventIcon kind={event.kind} status={event.status} toolName={event.toolName} />
|
<ActivityEventIcon kind={event.kind} status={event.status} toolName={event.toolName} />
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<span className={`text-[12px] font-medium ${isTerminal ? 'text-[var(--color-text-muted)]' : 'text-[var(--color-text-secondary)]'}`}>
|
<span className={`text-[12px] leading-[18px] font-medium ${isTerminal ? 'text-[var(--color-text-muted)]' : 'text-[var(--color-text-secondary)]'}`}>
|
||||||
{label}
|
{label}
|
||||||
</span>
|
</span>
|
||||||
|
|
||||||
@@ -230,14 +231,14 @@ function GroupedToolCallRow({ toolName, events }: { toolName: string; events: Ru
|
|||||||
<div className="turn-activity-row py-0.5">
|
<div className="turn-activity-row py-0.5">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="flex w-full items-start gap-2 py-1 text-left transition-colors hover:bg-[var(--color-surface-2)]/30 rounded px-1 -mx-1"
|
className="flex w-full items-start gap-2 rounded px-1 -mx-1 py-1 text-left transition-colors hover:bg-[var(--color-surface-2)]/30"
|
||||||
onClick={() => setExpanded((prev) => !prev)}
|
onClick={() => setExpanded((prev) => !prev)}
|
||||||
aria-expanded={expanded}
|
aria-expanded={expanded}
|
||||||
>
|
>
|
||||||
<div className="mt-0.5 flex shrink-0 items-start">
|
<div className="flex h-[18px] w-4 shrink-0 items-center justify-center">
|
||||||
<ToolCategoryIcon toolName={toolName} />
|
<ToolCategoryIcon toolName={toolName} />
|
||||||
</div>
|
</div>
|
||||||
<span className="min-w-0 flex-1 text-[12px] font-medium text-[var(--color-text-secondary)]">
|
<span className="min-w-0 flex-1 text-[12px] leading-[18px] font-medium text-[var(--color-text-secondary)]">
|
||||||
{label}
|
{label}
|
||||||
</span>
|
</span>
|
||||||
<ChevronRight
|
<ChevronRight
|
||||||
@@ -249,7 +250,7 @@ function GroupedToolCallRow({ toolName, events }: { toolName: string; events: Ru
|
|||||||
|
|
||||||
{/* Collapsed preview: show snippets inline */}
|
{/* Collapsed preview: show snippets inline */}
|
||||||
{!expanded && snippets.length > 0 && (
|
{!expanded && snippets.length > 0 && (
|
||||||
<div className="ml-5 flex flex-wrap gap-x-2 gap-y-0.5 pb-0.5">
|
<div className="ml-6 flex flex-wrap gap-x-2 gap-y-0.5 pb-0.5">
|
||||||
{snippets.slice(0, 6).map((s, i) => (
|
{snippets.slice(0, 6).map((s, i) => (
|
||||||
<span key={i} className="truncate font-mono text-[10px] text-[var(--color-text-muted)]">
|
<span key={i} className="truncate font-mono text-[10px] text-[var(--color-text-muted)]">
|
||||||
{s}
|
{s}
|
||||||
@@ -265,7 +266,7 @@ function GroupedToolCallRow({ toolName, events }: { toolName: string; events: Ru
|
|||||||
|
|
||||||
{/* Expanded: full per-event rows */}
|
{/* Expanded: full per-event rows */}
|
||||||
{expanded && (
|
{expanded && (
|
||||||
<div className="ml-5 border-l border-[var(--color-border)]/30 pl-2">
|
<div className="ml-6 border-l border-[var(--color-border)]/30 pl-2">
|
||||||
{events.map((event) => (
|
{events.map((event) => (
|
||||||
<div key={event.id} className="py-0.5">
|
<div key={event.id} className="py-0.5">
|
||||||
<span className="text-[11px] text-[var(--color-text-secondary)]">
|
<span className="text-[11px] text-[var(--color-text-secondary)]">
|
||||||
@@ -284,7 +285,7 @@ function GroupedToolCallRow({ toolName, events }: { toolName: string; events: Ru
|
|||||||
|
|
||||||
{/* Aggregate file changes when collapsed */}
|
{/* Aggregate file changes when collapsed */}
|
||||||
{!expanded && hasFileChanges && (
|
{!expanded && hasFileChanges && (
|
||||||
<div className="ml-5 mt-0.5">
|
<div className="ml-6 mt-0.5">
|
||||||
{events
|
{events
|
||||||
.filter((e) => e.fileChanges && e.fileChanges.length > 0)
|
.filter((e) => e.fileChanges && e.fileChanges.length > 0)
|
||||||
.flatMap((e) => e.fileChanges!)
|
.flatMap((e) => e.fileChanges!)
|
||||||
@@ -303,9 +304,9 @@ function GroupedToolCallRow({ toolName, events }: { toolName: string; events: Ru
|
|||||||
|
|
||||||
function IntentDividerRow({ text }: { text: string }) {
|
function IntentDividerRow({ text }: { text: string }) {
|
||||||
return (
|
return (
|
||||||
<div className="turn-activity-row flex items-center gap-2 py-1.5" role="separator">
|
<div className="turn-activity-row flex items-center gap-2 py-2" role="separator">
|
||||||
<div className="h-px flex-1 bg-[var(--color-border)]/40" />
|
<div className="h-px flex-1 bg-[var(--color-border)]/40" />
|
||||||
<span className="shrink-0 text-[10px] font-medium tracking-wide text-[var(--color-text-muted)]">
|
<span className="shrink-0 rounded-full bg-[var(--color-surface-2)]/60 px-2 py-0.5 text-[10px] font-semibold tracking-wide text-[var(--color-text-muted)]">
|
||||||
{text}
|
{text}
|
||||||
</span>
|
</span>
|
||||||
<div className="h-px flex-1 bg-[var(--color-border)]/40" />
|
<div className="h-px flex-1 bg-[var(--color-border)]/40" />
|
||||||
@@ -321,8 +322,8 @@ function ThinkingStepRow({ message }: { message: ChatMessageRecord }) {
|
|||||||
if (message.pending && !message.content) return null;
|
if (message.pending && !message.content) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="turn-activity-row flex gap-2 py-1">
|
<div className="turn-activity-row flex items-start gap-2 py-1">
|
||||||
<div className="mt-0.5 flex shrink-0 items-start">
|
<div className="flex h-[18px] w-4 shrink-0 items-center justify-center">
|
||||||
<Brain className="size-3 text-[var(--color-accent-purple)]" />
|
<Brain className="size-3 text-[var(--color-accent-purple)]" />
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
@@ -348,8 +349,8 @@ function ThinkingGroupRow({ messages }: { messages: ChatMessageRecord[] }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="turn-activity-row py-0.5">
|
<div className="turn-activity-row py-0.5">
|
||||||
<div className="flex gap-2 py-1">
|
<div className="flex items-start gap-2 py-1">
|
||||||
<div className="mt-0.5 flex shrink-0 items-start">
|
<div className="flex h-[18px] w-4 shrink-0 items-center justify-center">
|
||||||
<Brain className="size-3 text-[var(--color-accent-purple)]" />
|
<Brain className="size-3 text-[var(--color-accent-purple)]" />
|
||||||
</div>
|
</div>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
@@ -369,7 +370,7 @@ function ThinkingGroupRow({ messages }: { messages: ChatMessageRecord[] }) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{expanded && (
|
{expanded && (
|
||||||
<div className="ml-5 space-y-0.5 border-l border-[var(--color-border)]/30 pl-2">
|
<div className="ml-6 space-y-0.5 border-l border-[var(--color-border)]/30 pl-2">
|
||||||
{visibleMessages.slice(0, -1).map((msg) => (
|
{visibleMessages.slice(0, -1).map((msg) => (
|
||||||
<p key={msg.id} className="text-[10px] italic leading-snug text-[var(--color-text-muted)]">
|
<p key={msg.id} className="text-[10px] italic leading-snug text-[var(--color-text-muted)]">
|
||||||
"{truncatePreview(msg.content, 140)}"
|
"{truncatePreview(msg.content, 140)}"
|
||||||
@@ -418,6 +419,7 @@ export function TurnActivityPanel({
|
|||||||
isActive,
|
isActive,
|
||||||
turnStartedAt,
|
turnStartedAt,
|
||||||
sessionId,
|
sessionId,
|
||||||
|
currentIntent,
|
||||||
agentNames,
|
agentNames,
|
||||||
isLastRunPanel,
|
isLastRunPanel,
|
||||||
onDiscard,
|
onDiscard,
|
||||||
@@ -459,6 +461,7 @@ export function TurnActivityPanel({
|
|||||||
const elapsed = useElapsedTimer(
|
const elapsed = useElapsedTimer(
|
||||||
thinkingMessages.length > 0 || run ? effectiveTurnStartedAt : undefined,
|
thinkingMessages.length > 0 || run ? effectiveTurnStartedAt : undefined,
|
||||||
isActive,
|
isActive,
|
||||||
|
run?.completedAt,
|
||||||
);
|
);
|
||||||
|
|
||||||
const summary = useMemo(
|
const summary = useMemo(
|
||||||
@@ -471,8 +474,12 @@ export function TurnActivityPanel({
|
|||||||
return groupActivityStream(stream);
|
return groupActivityStream(stream);
|
||||||
}, [thinkingMessages, scopedEvents]);
|
}, [thinkingMessages, scopedEvents]);
|
||||||
|
|
||||||
// Extract intent text for the header
|
// Prefer the session-level normalized intent when active; fall back to
|
||||||
const intentText = useMemo(() => extractLatestIntent(scopedEvents), [scopedEvents]);
|
// scanning run timeline for report_intent tool calls (backward compat).
|
||||||
|
const intentText = useMemo(
|
||||||
|
() => (isActive ? currentIntent : undefined) ?? extractLatestIntent(scopedEvents),
|
||||||
|
[isActive, currentIntent, scopedEvents],
|
||||||
|
);
|
||||||
const fallbackSummary = useMemo(
|
const fallbackSummary = useMemo(
|
||||||
() => !intentText ? generateActivitySummary(scopedEvents) : undefined,
|
() => !intentText ? generateActivitySummary(scopedEvents) : undefined,
|
||||||
[intentText, scopedEvents],
|
[intentText, scopedEvents],
|
||||||
@@ -510,17 +517,25 @@ export function TurnActivityPanel({
|
|||||||
: isCancelled
|
: isCancelled
|
||||||
? 'text-[var(--color-text-muted)]'
|
? 'text-[var(--color-text-muted)]'
|
||||||
: isActive
|
: isActive
|
||||||
? 'text-[var(--color-text-secondary)]'
|
? 'text-[var(--color-text-primary)]'
|
||||||
: 'text-[var(--color-text-secondary)]';
|
: 'text-[var(--color-text-secondary)]';
|
||||||
|
|
||||||
|
const statusDotClass = isFailed
|
||||||
|
? 'bg-[var(--color-status-error)]'
|
||||||
|
: isCancelled
|
||||||
|
? 'bg-[var(--color-text-muted)]'
|
||||||
|
: isActive
|
||||||
|
? 'bg-[var(--color-accent)]'
|
||||||
|
: 'bg-[var(--color-status-success)]';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={`turn-activity-enter overflow-hidden rounded-lg border bg-[var(--color-surface-1)]/60 transition-colors duration-200 ${
|
className={`turn-activity-enter overflow-hidden rounded-lg border transition-colors duration-200 ${
|
||||||
isActive
|
isActive
|
||||||
? 'border-[var(--color-accent)]/30'
|
? 'border-[var(--color-accent)]/30 bg-[var(--color-accent)]/[0.03]'
|
||||||
: isFailed
|
: isFailed
|
||||||
? 'border-[var(--color-status-error)]/20'
|
? 'border-[var(--color-status-error)]/20 bg-[var(--color-surface-1)]/60'
|
||||||
: 'border-[var(--color-border)]/50'
|
: 'border-[var(--color-border)]/50 bg-[var(--color-surface-1)]/60'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{/* Summary header */}
|
{/* Summary header */}
|
||||||
@@ -529,20 +544,23 @@ export function TurnActivityPanel({
|
|||||||
onClick={toggle}
|
onClick={toggle}
|
||||||
onKeyDown={(e) => { if (e.key === ' ') { e.preventDefault(); toggle(); } }}
|
onKeyDown={(e) => { if (e.key === ' ') { e.preventDefault(); toggle(); } }}
|
||||||
aria-expanded={expanded}
|
aria-expanded={expanded}
|
||||||
className={`flex w-full items-center gap-2 px-3 py-2 text-left text-[12px] transition-colors hover:bg-[var(--color-surface-2)]/50 ${
|
className="flex w-full items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-[var(--color-surface-2)]/50"
|
||||||
isActive ? 'bg-[var(--color-accent)]/[0.04]' : ''
|
|
||||||
}`}
|
|
||||||
>
|
>
|
||||||
<Zap className={`size-3.5 shrink-0 ${isActive ? 'text-[var(--color-accent)]' : 'text-[var(--color-text-muted)]'}`} />
|
{/* Status dot */}
|
||||||
|
<span className={`size-2 shrink-0 rounded-full ${statusDotClass} ${isActive ? 'animate-pulse' : ''}`} />
|
||||||
|
|
||||||
{isActive ? (
|
{/* Status label + elapsed */}
|
||||||
<span className="flex items-center gap-1.5">
|
<span className="flex items-center gap-1.5">
|
||||||
<span className={statusColorClass}>{summaryLabel}</span>
|
<span className={`text-[12px] font-semibold ${statusColorClass}`}>
|
||||||
<ActivityPulse />
|
{summaryLabel}
|
||||||
</span>
|
</span>
|
||||||
) : (
|
{isActive && <ActivityPulse />}
|
||||||
<span className={statusColorClass}>{summaryLabel}</span>
|
{elapsed && (
|
||||||
)}
|
<span className="tabular-nums text-[11px] text-[var(--color-text-muted)]">
|
||||||
|
{isActive ? elapsed : ''}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
|
||||||
{/* Intent / generated summary */}
|
{/* Intent / generated summary */}
|
||||||
{headerDetail && (
|
{headerDetail && (
|
||||||
@@ -554,7 +572,7 @@ export function TurnActivityPanel({
|
|||||||
|
|
||||||
{/* Inline counters */}
|
{/* Inline counters */}
|
||||||
{summaryParts.length > 0 && (
|
{summaryParts.length > 0 && (
|
||||||
<span className="shrink-0 font-mono text-[10px] text-[var(--color-text-muted)]">
|
<span className="shrink-0 tabular-nums text-[10px] text-[var(--color-text-muted)]">
|
||||||
{'· '}
|
{'· '}
|
||||||
{summaryParts.join(' · ')}
|
{summaryParts.join(' · ')}
|
||||||
</span>
|
</span>
|
||||||
@@ -570,7 +588,7 @@ export function TurnActivityPanel({
|
|||||||
{/* Expanded activity stream — grouped */}
|
{/* Expanded activity stream — grouped */}
|
||||||
{expanded && (
|
{expanded && (
|
||||||
<div className="border-t border-[var(--color-border)]/30 px-3 py-2">
|
<div className="border-t border-[var(--color-border)]/30 px-3 py-2">
|
||||||
<div className="space-y-0.5">
|
<div className="activity-timeline-spine relative space-y-px">
|
||||||
{groupedItems.map((item, index) => (
|
{groupedItems.map((item, index) => (
|
||||||
<GroupedItemRow key={index} item={item} />
|
<GroupedItemRow key={index} item={item} />
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -0,0 +1,265 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useMemo, useState } from 'react';
|
||||||
|
import { Check, Brain } from 'lucide-react';
|
||||||
|
|
||||||
|
import { ProviderIcon } from '@renderer/components/ProviderIcons';
|
||||||
|
import type { ModelDefinition, ModelProvider } from '@shared/domain/models';
|
||||||
|
import { providerMeta } from '@shared/domain/models';
|
||||||
|
import type { ReasoningEffort } from '@shared/domain/workflow';
|
||||||
|
|
||||||
|
interface ModelSelectorProps {
|
||||||
|
models: ReadonlyArray<ModelDefinition>;
|
||||||
|
selectedModelId?: string;
|
||||||
|
selectedReasoning?: ReasoningEffort;
|
||||||
|
onSelect: (model: ModelDefinition) => void;
|
||||||
|
onReasoningChange: (effort: ReasoningEffort | undefined) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const reasoningLevels: { value: ReasoningEffort; label: string; description: string }[] = [
|
||||||
|
{ value: 'low', label: 'Low', description: 'Fast, concise' },
|
||||||
|
{ value: 'medium', label: 'Med', description: 'Balanced' },
|
||||||
|
{ value: 'high', label: 'High', description: 'Thorough' },
|
||||||
|
{ value: 'xhigh', label: 'Max', description: 'Exhaustive' },
|
||||||
|
];
|
||||||
|
|
||||||
|
interface ProviderGroup {
|
||||||
|
provider: ModelProvider | 'other';
|
||||||
|
label: string;
|
||||||
|
models: ModelDefinition[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ModelSelector({
|
||||||
|
models,
|
||||||
|
selectedModelId,
|
||||||
|
selectedReasoning,
|
||||||
|
onSelect,
|
||||||
|
onReasoningChange,
|
||||||
|
onClose,
|
||||||
|
}: ModelSelectorProps) {
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const flatModels = useMemo(() => [...models], [models]);
|
||||||
|
const initialIndex = flatModels.findIndex((m) => m.id === selectedModelId);
|
||||||
|
const [focusedIndex, setFocusedIndex] = useState(initialIndex >= 0 ? initialIndex : 0);
|
||||||
|
const optionRefs = useRef<Map<number, HTMLButtonElement>>(new Map());
|
||||||
|
|
||||||
|
// Scroll the focused option into view whenever it changes
|
||||||
|
useEffect(() => {
|
||||||
|
optionRefs.current.get(focusedIndex)?.scrollIntoView({ block: 'nearest' });
|
||||||
|
}, [focusedIndex]);
|
||||||
|
|
||||||
|
const handleKeyDown = useCallback(
|
||||||
|
(e: React.KeyboardEvent) => {
|
||||||
|
switch (e.key) {
|
||||||
|
case 'ArrowDown': {
|
||||||
|
e.preventDefault();
|
||||||
|
setFocusedIndex((prev) => (prev + 1) % flatModels.length);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'ArrowUp': {
|
||||||
|
e.preventDefault();
|
||||||
|
setFocusedIndex((prev) => (prev - 1 + flatModels.length) % flatModels.length);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'Home': {
|
||||||
|
e.preventDefault();
|
||||||
|
setFocusedIndex(0);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'End': {
|
||||||
|
e.preventDefault();
|
||||||
|
setFocusedIndex(flatModels.length - 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'Enter':
|
||||||
|
case ' ': {
|
||||||
|
e.preventDefault();
|
||||||
|
const model = flatModels[focusedIndex];
|
||||||
|
if (model) onSelect(model);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'Escape': {
|
||||||
|
e.stopPropagation();
|
||||||
|
onClose();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[flatModels, focusedIndex, onSelect, onClose],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleClickOutside = (e: MouseEvent) => {
|
||||||
|
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousedown', handleClickOutside);
|
||||||
|
};
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
// Focus the container on mount so keyboard events are captured immediately
|
||||||
|
useEffect(() => {
|
||||||
|
containerRef.current?.focus();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const selectedModel = models.find((m) => m.id === selectedModelId);
|
||||||
|
const supportedEfforts = selectedModel?.supportedReasoningEfforts;
|
||||||
|
|
||||||
|
// Group models by provider
|
||||||
|
const groups = useMemo((): ProviderGroup[] => {
|
||||||
|
const providerOrder = providerMeta.map((p) => p.id);
|
||||||
|
const providerLabels = new Map(providerMeta.map((p) => [p.id, p.label]));
|
||||||
|
const grouped = new Map<string, ModelDefinition[]>();
|
||||||
|
|
||||||
|
for (const model of models) {
|
||||||
|
const key = model.provider ?? 'other';
|
||||||
|
const list = grouped.get(key) ?? [];
|
||||||
|
list.push(model);
|
||||||
|
grouped.set(key, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result: ProviderGroup[] = [];
|
||||||
|
for (const providerId of providerOrder) {
|
||||||
|
const providerModels = grouped.get(providerId);
|
||||||
|
if (providerModels) {
|
||||||
|
result.push({
|
||||||
|
provider: providerId,
|
||||||
|
label: providerLabels.get(providerId) ?? providerId,
|
||||||
|
models: providerModels,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Any models without a known provider
|
||||||
|
const other = grouped.get('other');
|
||||||
|
if (other) {
|
||||||
|
result.push({ provider: 'other', label: 'Other', models: other });
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}, [models]);
|
||||||
|
|
||||||
|
// Build a flat index for each model so we can map group-based rendering
|
||||||
|
// back to the flat focusedIndex.
|
||||||
|
let flatIndex = -1;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={containerRef}
|
||||||
|
className="qp-dropdown-enter absolute top-full left-3 right-3 z-10 mt-1 overflow-hidden rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)] outline-none"
|
||||||
|
role="listbox"
|
||||||
|
aria-label="Select model"
|
||||||
|
aria-activedescendant={flatModels[focusedIndex] ? `model-option-${flatModels[focusedIndex].id}` : undefined}
|
||||||
|
tabIndex={0}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
>
|
||||||
|
{/* Model list — grouped by provider */}
|
||||||
|
<div className="max-h-[280px] overflow-y-auto overscroll-contain p-1.5">
|
||||||
|
{groups.map((group, gi) => (
|
||||||
|
<div key={group.provider}>
|
||||||
|
{gi > 0 && <div className="mx-2 my-1 border-t border-[var(--color-border-subtle)]/50" />}
|
||||||
|
|
||||||
|
{/* Provider header */}
|
||||||
|
<div className="flex items-center gap-1.5 px-2.5 pt-2 pb-1">
|
||||||
|
{group.provider !== 'other' && (
|
||||||
|
<ProviderIcon provider={group.provider} className="size-3" />
|
||||||
|
)}
|
||||||
|
<span className="text-[10px] font-semibold tracking-wider text-[var(--color-text-muted)] uppercase">
|
||||||
|
{group.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Models in this provider group */}
|
||||||
|
{group.models.map((model) => {
|
||||||
|
flatIndex++;
|
||||||
|
const modelIndex = flatIndex;
|
||||||
|
const isSelected = model.id === selectedModelId;
|
||||||
|
const isFocused = modelIndex === focusedIndex;
|
||||||
|
const tierLabel = model.tier === 'premium' ? 'PRO' : model.tier === 'fast' ? 'FAST' : undefined;
|
||||||
|
const tierColor = model.tier === 'premium'
|
||||||
|
? 'text-amber-400 bg-amber-400/10'
|
||||||
|
: model.tier === 'fast'
|
||||||
|
? 'text-emerald-400 bg-emerald-400/10'
|
||||||
|
: '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={model.id}
|
||||||
|
id={`model-option-${model.id}`}
|
||||||
|
ref={(el) => {
|
||||||
|
if (el) optionRefs.current.set(modelIndex, el);
|
||||||
|
else optionRefs.current.delete(modelIndex);
|
||||||
|
}}
|
||||||
|
onClick={() => onSelect(model)}
|
||||||
|
onMouseEnter={() => setFocusedIndex(modelIndex)}
|
||||||
|
className={`flex w-full items-center gap-2 rounded-lg px-3 py-[7px] text-left transition-colors ${
|
||||||
|
isFocused
|
||||||
|
? 'bg-[var(--color-surface-2)] text-[var(--color-text-primary)]'
|
||||||
|
: isSelected
|
||||||
|
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-primary)]'
|
||||||
|
: 'text-[var(--color-text-secondary)]'
|
||||||
|
}`}
|
||||||
|
type="button"
|
||||||
|
role="option"
|
||||||
|
aria-selected={isSelected}
|
||||||
|
tabIndex={-1}
|
||||||
|
>
|
||||||
|
<span className="flex-1 truncate text-[12px] font-medium">{model.name}</span>
|
||||||
|
|
||||||
|
{tierLabel && (
|
||||||
|
<span className={`rounded-[4px] px-1.5 py-px text-[8px] font-bold tracking-wider ${tierColor}`}>
|
||||||
|
{tierLabel}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{model.supportedReasoningEfforts?.length ? (
|
||||||
|
<Brain className="size-3 flex-none text-[var(--color-text-muted)]/60" aria-label="Supports reasoning" />
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{isSelected && <Check className="size-3.5 flex-none text-[var(--color-accent)]" />}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Reasoning effort — only shown when selected model supports it */}
|
||||||
|
{supportedEfforts && supportedEfforts.length > 0 && (
|
||||||
|
<div className="border-t border-[var(--color-border-subtle)] px-3 py-2.5">
|
||||||
|
<div className="mb-2 flex items-center gap-1.5">
|
||||||
|
<Brain className="size-3 text-[var(--color-text-muted)]" />
|
||||||
|
<span className="text-[10px] font-semibold tracking-wider text-[var(--color-text-muted)] uppercase">
|
||||||
|
Reasoning Effort
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
{reasoningLevels
|
||||||
|
.filter((lvl) => supportedEfforts.includes(lvl.value))
|
||||||
|
.map((lvl) => {
|
||||||
|
const isActive = selectedReasoning === lvl.value;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={lvl.value}
|
||||||
|
onClick={() => onReasoningChange(isActive ? undefined : lvl.value)}
|
||||||
|
className={`group flex-1 rounded-lg py-1.5 text-center transition-all ${
|
||||||
|
isActive
|
||||||
|
? 'bg-[var(--color-accent)] text-white shadow-md shadow-[var(--color-accent)]/20'
|
||||||
|
: 'bg-[var(--color-surface-2)] text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]'
|
||||||
|
}`}
|
||||||
|
type="button"
|
||||||
|
title={lvl.description}
|
||||||
|
>
|
||||||
|
<span className="text-[11px] font-semibold">{lvl.label}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { ArrowRight, Trash2, X } from 'lucide-react';
|
||||||
|
|
||||||
|
interface QuickPromptActionsProps {
|
||||||
|
onDiscard: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
onContinueInAryx: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function QuickPromptActions({ onDiscard, onClose, onContinueInAryx }: QuickPromptActionsProps) {
|
||||||
|
return (
|
||||||
|
<div className="qp-actions-enter flex items-center gap-1.5 border-t border-[var(--color-border-subtle)]/60 px-4 py-2.5">
|
||||||
|
<button
|
||||||
|
onClick={onDiscard}
|
||||||
|
className="flex items-center gap-1.5 rounded-lg px-3 py-[6px] text-[11px] font-medium text-[var(--color-text-muted)] transition-colors hover:bg-[var(--color-status-error)]/8 hover:text-[var(--color-status-error)]"
|
||||||
|
type="button"
|
||||||
|
title="Delete this session permanently"
|
||||||
|
>
|
||||||
|
<Trash2 className="size-3" />
|
||||||
|
Discard
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="flex items-center gap-1.5 rounded-lg px-3 py-[6px] text-[11px] font-medium text-[var(--color-text-muted)] transition-colors hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
|
||||||
|
type="button"
|
||||||
|
title="Close and keep session for later"
|
||||||
|
>
|
||||||
|
<X className="size-3" />
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex-1" />
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={onContinueInAryx}
|
||||||
|
className="brand-gradient-bg flex items-center gap-1.5 rounded-lg px-4 py-[6px] text-[11px] font-semibold text-white shadow-sm shadow-[var(--color-accent)]/15 transition-all hover:shadow-md hover:shadow-[var(--color-accent)]/25 hover:brightness-110"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
Continue in Aryx
|
||||||
|
<ArrowRight className="size-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
import type { QuickPromptElectronApi, QuickPromptCapabilities } from '@shared/contracts/ipc';
|
||||||
|
import type { SessionEventRecord } from '@shared/domain/event';
|
||||||
|
import type { ReasoningEffort } from '@shared/domain/workflow';
|
||||||
|
import type { ModelDefinition } from '@shared/domain/models';
|
||||||
|
|
||||||
|
import { QuickPromptInput } from '@renderer/components/quick-prompt/QuickPromptInput';
|
||||||
|
import { QuickPromptResponse } from '@renderer/components/quick-prompt/QuickPromptResponse';
|
||||||
|
import { QuickPromptActions } from '@renderer/components/quick-prompt/QuickPromptActions';
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
quickPromptApi: QuickPromptElectronApi;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type PromptPhase = 'idle' | 'streaming' | 'complete' | 'error';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-message state tracked by messageId, mirroring the main app's
|
||||||
|
* SessionRecord.messages model. This is necessary because the sidecar's
|
||||||
|
* fire-and-forget event handlers can emit events out of order — e.g.
|
||||||
|
* `message-complete` and `status: idle` can arrive before all
|
||||||
|
* `message-delta` events have been emitted.
|
||||||
|
*/
|
||||||
|
interface TrackedMessage {
|
||||||
|
content: string;
|
||||||
|
messageKind?: string;
|
||||||
|
authorName: string;
|
||||||
|
pending: boolean;
|
||||||
|
finalized: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Derive display values from tracked messages. */
|
||||||
|
function deriveDisplay(messages: Map<string, TrackedMessage>) {
|
||||||
|
let content = '';
|
||||||
|
let thinkingContent = '';
|
||||||
|
let authorName = '';
|
||||||
|
let hasVisibleContent = false;
|
||||||
|
let allComplete = messages.size > 0;
|
||||||
|
|
||||||
|
for (const msg of messages.values()) {
|
||||||
|
if (msg.messageKind === 'thinking') {
|
||||||
|
if (msg.content) thinkingContent += (thinkingContent ? '\n' : '') + msg.content;
|
||||||
|
} else {
|
||||||
|
// Last non-thinking message wins as the response
|
||||||
|
content = msg.content;
|
||||||
|
authorName = msg.authorName;
|
||||||
|
if (msg.content.length > 0) hasVisibleContent = true;
|
||||||
|
}
|
||||||
|
if (msg.pending) allComplete = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { content, thinkingContent, authorName, isComplete: allComplete && hasVisibleContent };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function QuickPromptApp() {
|
||||||
|
const [phase, setPhase] = useState<PromptPhase>('idle');
|
||||||
|
const [displayContent, setDisplayContent] = useState('');
|
||||||
|
const [displayThinking, setDisplayThinking] = useState('');
|
||||||
|
const [displayAuthor, setDisplayAuthor] = useState('');
|
||||||
|
const [errorMessage, setErrorMessage] = useState<string>();
|
||||||
|
const [capabilities, setCapabilities] = useState<QuickPromptCapabilities>();
|
||||||
|
const [selectedModel, setSelectedModel] = useState<string>();
|
||||||
|
const [selectedReasoning, setSelectedReasoning] = useState<ReasoningEffort>();
|
||||||
|
const [visible, setVisible] = useState(false);
|
||||||
|
|
||||||
|
const sessionIdRef = useRef<string | null>(null);
|
||||||
|
const messagesRef = useRef<Map<string, TrackedMessage>>(new Map());
|
||||||
|
const api = window.quickPromptApi;
|
||||||
|
|
||||||
|
/** Push tracked-message state into React display state. */
|
||||||
|
const syncDisplay = useCallback(() => {
|
||||||
|
const display = deriveDisplay(messagesRef.current);
|
||||||
|
setDisplayContent(display.content);
|
||||||
|
setDisplayThinking(display.thinkingContent);
|
||||||
|
setDisplayAuthor(display.authorName);
|
||||||
|
return display;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Load capabilities on mount
|
||||||
|
useEffect(() => {
|
||||||
|
api.getCapabilities().then((caps) => {
|
||||||
|
setCapabilities(caps);
|
||||||
|
setSelectedModel(caps.defaultModel ?? caps.models[0]?.id);
|
||||||
|
setSelectedReasoning(caps.defaultReasoningEffort);
|
||||||
|
});
|
||||||
|
}, [api]);
|
||||||
|
|
||||||
|
// Subscribe to show/hide events from main process
|
||||||
|
useEffect(() => {
|
||||||
|
const offShow = api.onShow((theme: string) => {
|
||||||
|
const effective = theme === 'system'
|
||||||
|
? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
|
||||||
|
: theme;
|
||||||
|
document.documentElement.dataset.theme = effective;
|
||||||
|
|
||||||
|
setVisible(true);
|
||||||
|
resetState();
|
||||||
|
});
|
||||||
|
const offHide = api.onHide(() => setVisible(false));
|
||||||
|
return () => {
|
||||||
|
offShow();
|
||||||
|
offHide();
|
||||||
|
};
|
||||||
|
}, [api]);
|
||||||
|
|
||||||
|
// Subscribe to session events (streaming) — processes events using
|
||||||
|
// message-by-ID tracking that tolerates out-of-order delivery.
|
||||||
|
useEffect(() => {
|
||||||
|
const off = api.onSessionEvent((event: SessionEventRecord) => {
|
||||||
|
const msgs = messagesRef.current;
|
||||||
|
|
||||||
|
if (event.kind === 'message-delta' && event.messageId && (event.contentDelta || event.content !== undefined)) {
|
||||||
|
const existing = msgs.get(event.messageId);
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
// Skip deltas that arrive after message-complete replaced the
|
||||||
|
// content with the authoritative final version.
|
||||||
|
if (existing.finalized) return;
|
||||||
|
|
||||||
|
if (event.content !== undefined) {
|
||||||
|
existing.content = event.content;
|
||||||
|
} else if (event.contentDelta) {
|
||||||
|
existing.content += event.contentDelta;
|
||||||
|
}
|
||||||
|
existing.authorName = event.authorName ?? existing.authorName;
|
||||||
|
} else {
|
||||||
|
msgs.set(event.messageId, {
|
||||||
|
content: event.contentDelta ?? event.content ?? '',
|
||||||
|
messageKind: event.messageKind,
|
||||||
|
authorName: event.authorName ?? '',
|
||||||
|
pending: true,
|
||||||
|
finalized: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
syncDisplay();
|
||||||
|
setPhase('streaming');
|
||||||
|
|
||||||
|
} else if (event.kind === 'message-complete' && event.messageId) {
|
||||||
|
const existing = msgs.get(event.messageId);
|
||||||
|
if (existing) {
|
||||||
|
if (event.content !== undefined) existing.content = event.content;
|
||||||
|
existing.pending = false;
|
||||||
|
existing.finalized = true;
|
||||||
|
} else {
|
||||||
|
msgs.set(event.messageId, {
|
||||||
|
content: event.content ?? '',
|
||||||
|
messageKind: undefined,
|
||||||
|
authorName: event.authorName ?? '',
|
||||||
|
pending: false,
|
||||||
|
finalized: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const display = syncDisplay();
|
||||||
|
if (display.isComplete) setPhase('complete');
|
||||||
|
|
||||||
|
} else if (event.kind === 'message-reclassified' && event.messageId && event.messageKind) {
|
||||||
|
const existing = msgs.get(event.messageId);
|
||||||
|
if (existing) {
|
||||||
|
existing.messageKind = event.messageKind;
|
||||||
|
syncDisplay();
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if (event.kind === 'status' && event.status === 'idle') {
|
||||||
|
for (const msg of msgs.values()) {
|
||||||
|
msg.pending = false;
|
||||||
|
}
|
||||||
|
const display = syncDisplay();
|
||||||
|
if (display.isComplete) setPhase('complete');
|
||||||
|
|
||||||
|
} else if (event.kind === 'error') {
|
||||||
|
setErrorMessage(event.error ?? 'An unexpected error occurred.');
|
||||||
|
setPhase('error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return off;
|
||||||
|
}, [api, syncDisplay]);
|
||||||
|
|
||||||
|
const resetState = useCallback(() => {
|
||||||
|
setPhase('idle');
|
||||||
|
setDisplayContent('');
|
||||||
|
setDisplayThinking('');
|
||||||
|
setDisplayAuthor('');
|
||||||
|
setErrorMessage(undefined);
|
||||||
|
sessionIdRef.current = null;
|
||||||
|
messagesRef.current = new Map();
|
||||||
|
api.getCapabilities().then((caps) => {
|
||||||
|
setCapabilities(caps);
|
||||||
|
setSelectedModel(caps.defaultModel ?? caps.models[0]?.id);
|
||||||
|
setSelectedReasoning(caps.defaultReasoningEffort);
|
||||||
|
});
|
||||||
|
}, [api]);
|
||||||
|
|
||||||
|
const handleSend = useCallback(async (content: string) => {
|
||||||
|
if (!content.trim() || phase === 'streaming') return;
|
||||||
|
|
||||||
|
setPhase('streaming');
|
||||||
|
setDisplayContent('');
|
||||||
|
setDisplayThinking('');
|
||||||
|
setDisplayAuthor('');
|
||||||
|
setErrorMessage(undefined);
|
||||||
|
messagesRef.current = new Map();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await api.send({
|
||||||
|
content,
|
||||||
|
model: selectedModel,
|
||||||
|
reasoningEffort: selectedReasoning,
|
||||||
|
});
|
||||||
|
sessionIdRef.current = result.sessionId;
|
||||||
|
} catch (err) {
|
||||||
|
setErrorMessage(err instanceof Error ? err.message : 'Failed to send message.');
|
||||||
|
setPhase('error');
|
||||||
|
}
|
||||||
|
}, [api, phase, selectedModel, selectedReasoning]);
|
||||||
|
|
||||||
|
const handleCancel = useCallback(() => {
|
||||||
|
api.cancelTurn();
|
||||||
|
setPhase('complete');
|
||||||
|
}, [api]);
|
||||||
|
|
||||||
|
const handleDiscard = useCallback(() => {
|
||||||
|
api.discard();
|
||||||
|
resetState();
|
||||||
|
}, [api, resetState]);
|
||||||
|
|
||||||
|
const handleClose = useCallback(() => {
|
||||||
|
api.close();
|
||||||
|
resetState();
|
||||||
|
}, [api, resetState]);
|
||||||
|
|
||||||
|
const handleContinueInAryx = useCallback(() => {
|
||||||
|
api.continueInAryx();
|
||||||
|
resetState();
|
||||||
|
}, [api, resetState]);
|
||||||
|
|
||||||
|
const handleModelChange = useCallback((model: ModelDefinition) => {
|
||||||
|
setSelectedModel(model.id);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleReasoningChange = useCallback((effort: ReasoningEffort | undefined) => {
|
||||||
|
setSelectedReasoning(effort);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Global keyboard handler
|
||||||
|
useEffect(() => {
|
||||||
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (phase === 'streaming') {
|
||||||
|
handleCancel();
|
||||||
|
} else if (phase === 'complete' || phase === 'error') {
|
||||||
|
handleClose();
|
||||||
|
} else {
|
||||||
|
api.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('keydown', handleKeyDown);
|
||||||
|
return () => document.removeEventListener('keydown', handleKeyDown);
|
||||||
|
}, [phase, handleCancel, handleClose, api]);
|
||||||
|
|
||||||
|
if (!visible) return null;
|
||||||
|
|
||||||
|
const hasResponse = phase !== 'idle';
|
||||||
|
const resolvedModel = capabilities?.models.find((m) => m.id === selectedModel);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="qp-container flex h-screen w-screen items-start justify-center pt-0">
|
||||||
|
<div
|
||||||
|
className={`qp-panel qp-panel-enter flex w-full max-w-[680px] flex-col rounded-2xl ${
|
||||||
|
phase === 'streaming' ? 'qp-border-streaming' : hasResponse ? 'qp-border-complete' : 'qp-border-idle'
|
||||||
|
}`}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label="Quick Prompt"
|
||||||
|
>
|
||||||
|
{/* Input area */}
|
||||||
|
<QuickPromptInput
|
||||||
|
onSend={handleSend}
|
||||||
|
onCancel={handleCancel}
|
||||||
|
phase={phase}
|
||||||
|
models={capabilities?.models}
|
||||||
|
selectedModel={resolvedModel}
|
||||||
|
selectedReasoning={selectedReasoning}
|
||||||
|
onModelChange={handleModelChange}
|
||||||
|
onReasoningChange={handleReasoningChange}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Response area — grows dynamically */}
|
||||||
|
{hasResponse && (
|
||||||
|
<QuickPromptResponse
|
||||||
|
content={displayContent}
|
||||||
|
thinkingContent={displayThinking}
|
||||||
|
authorName={displayAuthor}
|
||||||
|
phase={phase}
|
||||||
|
error={errorMessage}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Action bar */}
|
||||||
|
{(phase === 'complete' || phase === 'error') && (
|
||||||
|
<QuickPromptActions
|
||||||
|
onDiscard={handleDiscard}
|
||||||
|
onClose={handleClose}
|
||||||
|
onContinueInAryx={handleContinueInAryx}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { ChevronDown, Loader2, Square, Sparkles } from 'lucide-react';
|
||||||
|
|
||||||
|
import type { ModelDefinition } from '@shared/domain/models';
|
||||||
|
import type { ReasoningEffort } from '@shared/domain/workflow';
|
||||||
|
|
||||||
|
import { ModelSelector } from '@renderer/components/quick-prompt/ModelSelector';
|
||||||
|
|
||||||
|
type PromptPhase = 'idle' | 'streaming' | 'complete' | 'error';
|
||||||
|
|
||||||
|
interface QuickPromptInputProps {
|
||||||
|
onSend: (content: string) => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
phase: PromptPhase;
|
||||||
|
models?: ReadonlyArray<ModelDefinition>;
|
||||||
|
selectedModel?: ModelDefinition;
|
||||||
|
selectedReasoning?: ReasoningEffort;
|
||||||
|
onModelChange: (model: ModelDefinition) => void;
|
||||||
|
onReasoningChange: (effort: ReasoningEffort | undefined) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function QuickPromptInput({
|
||||||
|
onSend,
|
||||||
|
onCancel,
|
||||||
|
phase,
|
||||||
|
models,
|
||||||
|
selectedModel,
|
||||||
|
selectedReasoning,
|
||||||
|
onModelChange,
|
||||||
|
onReasoningChange,
|
||||||
|
}: QuickPromptInputProps) {
|
||||||
|
const [value, setValue] = useState('');
|
||||||
|
const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
|
||||||
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
// Auto-focus when phase resets to idle
|
||||||
|
useEffect(() => {
|
||||||
|
if (phase === 'idle') {
|
||||||
|
setTimeout(() => textareaRef.current?.focus(), 50);
|
||||||
|
}
|
||||||
|
}, [phase]);
|
||||||
|
|
||||||
|
// Auto-resize textarea
|
||||||
|
useEffect(() => {
|
||||||
|
const el = textareaRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
el.style.height = 'auto';
|
||||||
|
el.style.height = `${Math.min(el.scrollHeight, 120)}px`;
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
const handleKeyDown = useCallback(
|
||||||
|
(e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === 'Enter' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (phase === 'idle' && value.trim()) {
|
||||||
|
onSend(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[onSend, value, phase],
|
||||||
|
);
|
||||||
|
|
||||||
|
const reasoningLabel = selectedReasoning
|
||||||
|
? selectedReasoning === 'xhigh' ? 'xHigh' : selectedReasoning.charAt(0).toUpperCase() + selectedReasoning.slice(1)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative flex flex-col">
|
||||||
|
{/* Primary input area */}
|
||||||
|
<div className="flex items-start gap-3 px-5 pt-4 pb-2">
|
||||||
|
<div className="mt-1 flex-none">
|
||||||
|
{phase === 'streaming' ? (
|
||||||
|
<Loader2 className="size-[18px] animate-spin text-[var(--color-accent)]" aria-label="Processing" />
|
||||||
|
) : (
|
||||||
|
<Sparkles className="size-[18px] text-[var(--color-text-muted)]" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<textarea
|
||||||
|
ref={textareaRef}
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => setValue(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
placeholder="Ask anything…"
|
||||||
|
disabled={phase === 'streaming'}
|
||||||
|
rows={1}
|
||||||
|
className="min-h-[28px] max-h-[120px] flex-1 resize-none bg-transparent font-[var(--font-body)] text-[14px] leading-[1.6] text-[var(--color-text-primary)] outline-none placeholder:text-[var(--color-text-muted)]/60 disabled:opacity-40"
|
||||||
|
aria-label="Quick prompt input"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{phase === 'streaming' && (
|
||||||
|
<button
|
||||||
|
onClick={onCancel}
|
||||||
|
className="mt-0.5 flex flex-none items-center gap-1.5 rounded-md border border-[var(--color-border)] bg-[var(--color-surface-2)] px-2.5 py-1 text-[11px] font-medium text-[var(--color-text-secondary)] transition hover:border-[var(--color-status-error)]/40 hover:bg-[var(--color-status-error)]/10 hover:text-[var(--color-status-error)]"
|
||||||
|
type="button"
|
||||||
|
aria-label="Stop generating"
|
||||||
|
>
|
||||||
|
<Square className="size-2.5 fill-current" />
|
||||||
|
Stop
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Footer bar: model selector + shortcuts */}
|
||||||
|
<div className="flex items-center gap-2 border-t border-[var(--color-border-subtle)]/60 px-5 py-2">
|
||||||
|
<button
|
||||||
|
onClick={() => setModelSelectorOpen((prev) => !prev)}
|
||||||
|
className={`flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[11px] transition ${
|
||||||
|
modelSelectorOpen
|
||||||
|
? 'bg-[var(--color-accent-muted)] text-[var(--color-text-accent)]'
|
||||||
|
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-secondary)]'
|
||||||
|
}`}
|
||||||
|
type="button"
|
||||||
|
aria-haspopup="listbox"
|
||||||
|
aria-expanded={modelSelectorOpen}
|
||||||
|
>
|
||||||
|
<span className="max-w-[160px] truncate font-medium">{selectedModel?.name ?? 'Select model'}</span>
|
||||||
|
{reasoningLabel && (
|
||||||
|
<span className="rounded-[4px] bg-[var(--color-accent)]/15 px-1.5 py-px text-[9px] font-semibold tracking-wide text-[var(--color-text-accent)] uppercase">
|
||||||
|
{reasoningLabel}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<ChevronDown className={`size-3 transition-transform ${modelSelectorOpen ? 'rotate-180' : ''}`} />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<span className="ml-auto flex items-center gap-3 text-[10px] text-[var(--color-text-muted)] select-none opacity-50">
|
||||||
|
<kbd className="rounded border border-[var(--color-border-subtle)] bg-[var(--color-surface-2)] px-1 py-px font-mono text-[9px]">
|
||||||
|
↵
|
||||||
|
</kbd>
|
||||||
|
<span>Send</span>
|
||||||
|
<kbd className="rounded border border-[var(--color-border-subtle)] bg-[var(--color-surface-2)] px-1 py-px font-mono text-[9px]">
|
||||||
|
Esc
|
||||||
|
</kbd>
|
||||||
|
<span>Dismiss</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Model selector dropdown */}
|
||||||
|
{modelSelectorOpen && models && (
|
||||||
|
<ModelSelector
|
||||||
|
models={models}
|
||||||
|
selectedModelId={selectedModel?.id}
|
||||||
|
selectedReasoning={selectedReasoning}
|
||||||
|
onSelect={(model) => {
|
||||||
|
onModelChange(model);
|
||||||
|
setModelSelectorOpen(false);
|
||||||
|
}}
|
||||||
|
onReasoningChange={onReasoningChange}
|
||||||
|
onClose={() => setModelSelectorOpen(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import ReactMarkdown from 'react-markdown';
|
||||||
|
import remarkGfm from 'remark-gfm';
|
||||||
|
import { AlertCircle, Brain } from 'lucide-react';
|
||||||
|
|
||||||
|
type PromptPhase = 'idle' | 'streaming' | 'complete' | 'error';
|
||||||
|
|
||||||
|
interface QuickPromptResponseProps {
|
||||||
|
content: string;
|
||||||
|
thinkingContent: string;
|
||||||
|
authorName: string;
|
||||||
|
phase: PromptPhase;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function QuickPromptResponse({
|
||||||
|
content,
|
||||||
|
thinkingContent,
|
||||||
|
phase,
|
||||||
|
error,
|
||||||
|
}: QuickPromptResponseProps) {
|
||||||
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Auto-scroll to bottom during streaming
|
||||||
|
useEffect(() => {
|
||||||
|
if (phase === 'streaming' && scrollRef.current) {
|
||||||
|
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||||
|
}
|
||||||
|
}, [content, thinkingContent, phase]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={scrollRef}
|
||||||
|
className="qp-response-enter max-h-[min(50vh,480px)] overflow-y-auto overscroll-contain border-t border-[var(--color-border-subtle)]/60"
|
||||||
|
>
|
||||||
|
{/* Error state */}
|
||||||
|
{phase === 'error' && error && (
|
||||||
|
<div className="flex items-start gap-3 px-5 py-4">
|
||||||
|
<AlertCircle className="mt-0.5 size-4 flex-none text-[var(--color-status-error)]" />
|
||||||
|
<div>
|
||||||
|
<p className="text-[12px] font-semibold text-[var(--color-status-error)]">Something went wrong</p>
|
||||||
|
<p className="mt-1 text-[12px] leading-relaxed text-[var(--color-status-error)]/80">{error}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Thinking block — compact collapsed visualization */}
|
||||||
|
{thinkingContent && (
|
||||||
|
<div className="mx-5 mt-3 mb-1 rounded-lg border border-[var(--color-border-subtle)]/50 bg-[var(--color-surface-0)]/40 px-3.5 py-2.5">
|
||||||
|
<div className="flex items-center gap-2 text-[10px] font-semibold tracking-wide text-[var(--color-text-muted)] uppercase">
|
||||||
|
<Brain className="size-3" />
|
||||||
|
<span>Reasoning</span>
|
||||||
|
{phase === 'streaming' && !content && (
|
||||||
|
<span className="ml-0.5 flex gap-[3px]">
|
||||||
|
<span className="thinking-dot inline-block size-[3px] rounded-full bg-[var(--color-text-muted)]" />
|
||||||
|
<span className="thinking-dot inline-block size-[3px] rounded-full bg-[var(--color-text-muted)]" />
|
||||||
|
<span className="thinking-dot inline-block size-[3px] rounded-full bg-[var(--color-text-muted)]" />
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-[11px] leading-relaxed text-[var(--color-text-muted)]/70 italic line-clamp-2">
|
||||||
|
{thinkingContent.slice(-200)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Main response content */}
|
||||||
|
{content && (
|
||||||
|
<div className="px-5 py-3.5">
|
||||||
|
<div className="markdown-content text-[13px] leading-[1.7] text-[var(--color-text-primary)]">
|
||||||
|
<ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Streaming indicator when no content yet */}
|
||||||
|
{phase === 'streaming' && !content && !thinkingContent && (
|
||||||
|
<div className="flex items-center gap-3 px-5 py-4">
|
||||||
|
<span className="flex gap-[3px]">
|
||||||
|
<span className="thinking-dot inline-block size-[5px] rounded-full bg-[var(--color-accent)]" />
|
||||||
|
<span className="thinking-dot inline-block size-[5px] rounded-full bg-[var(--color-accent)]" />
|
||||||
|
<span className="thinking-dot inline-block size-[5px] rounded-full bg-[var(--color-accent)]" />
|
||||||
|
</span>
|
||||||
|
<span className="text-[12px] text-[var(--color-text-muted)]">Generating…</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { Archive, ArchiveRestore, CheckSquare, Square, Trash2, X } from 'lucide-react';
|
||||||
|
|
||||||
|
interface BatchActionBarProps {
|
||||||
|
selectedCount: number;
|
||||||
|
allSelectedArchived: boolean;
|
||||||
|
onArchive: () => void;
|
||||||
|
onDelete: () => void;
|
||||||
|
onSelectAll: () => void;
|
||||||
|
onDeselectAll: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
allSelected: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BatchActionBar({
|
||||||
|
selectedCount,
|
||||||
|
allSelectedArchived,
|
||||||
|
onArchive,
|
||||||
|
onDelete,
|
||||||
|
onSelectAll,
|
||||||
|
onDeselectAll,
|
||||||
|
onCancel,
|
||||||
|
allSelected,
|
||||||
|
}: BatchActionBarProps) {
|
||||||
|
const archiveLabel = allSelectedArchived ? 'Restore' : 'Archive';
|
||||||
|
const ArchiveIcon = allSelectedArchived ? ArchiveRestore : Archive;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="batch-action-bar-enter border-t border-[var(--color-border)] bg-[var(--color-surface-1)]/95 px-3 py-2.5 backdrop-blur-md"
|
||||||
|
role="toolbar"
|
||||||
|
aria-label="Batch session actions"
|
||||||
|
>
|
||||||
|
{/* Top row — selection count + select all/none */}
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<span
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-full bg-[var(--color-accent)]/15 px-2.5 py-1 text-[11px] font-semibold text-[var(--color-accent)]"
|
||||||
|
aria-live="polite"
|
||||||
|
>
|
||||||
|
{selectedCount} selected
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]"
|
||||||
|
onClick={allSelected ? onDeselectAll : onSelectAll}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{allSelected ? (
|
||||||
|
<>
|
||||||
|
<Square className="size-3" />
|
||||||
|
None
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<CheckSquare className="size-3" />
|
||||||
|
All
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bottom row — action buttons */}
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<button
|
||||||
|
className="flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-[var(--color-surface-2)] px-3 py-1.5 text-[12px] font-medium text-[var(--color-text-primary)] transition-all duration-150 hover:bg-[var(--color-surface-3)]"
|
||||||
|
onClick={onArchive}
|
||||||
|
type="button"
|
||||||
|
title={`${archiveLabel} ${selectedCount} session${selectedCount === 1 ? '' : 's'}`}
|
||||||
|
>
|
||||||
|
<ArchiveIcon className="size-3.5" />
|
||||||
|
{archiveLabel}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-[var(--color-status-error)]/10 px-3 py-1.5 text-[12px] font-medium text-[var(--color-status-error)] transition-all duration-150 hover:bg-[var(--color-status-error)]/20"
|
||||||
|
onClick={onDelete}
|
||||||
|
type="button"
|
||||||
|
title={`Delete ${selectedCount} session${selectedCount === 1 ? '' : 's'}`}
|
||||||
|
>
|
||||||
|
<Trash2 className="size-3.5" />
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="flex size-7 shrink-0 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={onCancel}
|
||||||
|
type="button"
|
||||||
|
aria-label="Exit multi-select"
|
||||||
|
title="Exit multi-select (Esc)"
|
||||||
|
>
|
||||||
|
<X className="size-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { AlertTriangle, Trash2, X } from 'lucide-react';
|
||||||
|
import type { SessionRecord } from '@shared/domain/session';
|
||||||
|
|
||||||
|
interface BatchDeleteConfirmDialogProps {
|
||||||
|
sessions: SessionRecord[];
|
||||||
|
onConfirm: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const HOLD_DURATION_MS = 1500;
|
||||||
|
const HOLD_THRESHOLD = 3;
|
||||||
|
|
||||||
|
export function BatchDeleteConfirmDialog({
|
||||||
|
sessions,
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
}: BatchDeleteConfirmDialogProps) {
|
||||||
|
const requiresHold = sessions.length >= HOLD_THRESHOLD;
|
||||||
|
const [holdProgress, setHoldProgress] = useState(0);
|
||||||
|
const holdTimerRef = useRef<number | null>(null);
|
||||||
|
const holdStartRef = useRef<number | null>(null);
|
||||||
|
const dialogRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Focus trap
|
||||||
|
useEffect(() => {
|
||||||
|
const el = dialogRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
|
||||||
|
const focusable = el.querySelectorAll<HTMLElement>(
|
||||||
|
'button, [tabindex]:not([tabindex="-1"])',
|
||||||
|
);
|
||||||
|
const first = focusable[0];
|
||||||
|
const last = focusable[focusable.length - 1];
|
||||||
|
|
||||||
|
first?.focus();
|
||||||
|
|
||||||
|
function handleTab(e: KeyboardEvent) {
|
||||||
|
if (e.key !== 'Tab') return;
|
||||||
|
if (!first || !last) return;
|
||||||
|
|
||||||
|
if (e.shiftKey) {
|
||||||
|
if (document.activeElement === first) {
|
||||||
|
e.preventDefault();
|
||||||
|
last.focus();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (document.activeElement === last) {
|
||||||
|
e.preventDefault();
|
||||||
|
first.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleEscape(e: KeyboardEvent) {
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
e.stopPropagation();
|
||||||
|
onCancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('keydown', handleTab);
|
||||||
|
document.addEventListener('keydown', handleEscape);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('keydown', handleTab);
|
||||||
|
document.removeEventListener('keydown', handleEscape);
|
||||||
|
};
|
||||||
|
}, [onCancel]);
|
||||||
|
|
||||||
|
const startHold = useCallback(() => {
|
||||||
|
if (!requiresHold) return;
|
||||||
|
holdStartRef.current = performance.now();
|
||||||
|
|
||||||
|
const tick = () => {
|
||||||
|
if (!holdStartRef.current) return;
|
||||||
|
const elapsed = performance.now() - holdStartRef.current;
|
||||||
|
const progress = Math.min(elapsed / HOLD_DURATION_MS, 1);
|
||||||
|
setHoldProgress(progress);
|
||||||
|
|
||||||
|
if (progress >= 1) {
|
||||||
|
onConfirm();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
holdTimerRef.current = requestAnimationFrame(tick);
|
||||||
|
};
|
||||||
|
holdTimerRef.current = requestAnimationFrame(tick);
|
||||||
|
}, [requiresHold, onConfirm]);
|
||||||
|
|
||||||
|
const cancelHold = useCallback(() => {
|
||||||
|
holdStartRef.current = null;
|
||||||
|
if (holdTimerRef.current !== null) {
|
||||||
|
cancelAnimationFrame(holdTimerRef.current);
|
||||||
|
holdTimerRef.current = null;
|
||||||
|
}
|
||||||
|
setHoldProgress(0);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Clean up on unmount
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (holdTimerRef.current !== null) cancelAnimationFrame(holdTimerRef.current);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Backdrop */}
|
||||||
|
<div
|
||||||
|
className="overlay-backdrop-enter fixed inset-0 z-50 bg-black/60"
|
||||||
|
onClick={onCancel}
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Dialog */}
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4" role="presentation">
|
||||||
|
<div
|
||||||
|
ref={dialogRef}
|
||||||
|
className="overlay-panel-enter w-full max-w-sm rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface-1)] shadow-[0_24px_80px_rgba(0,0,0,0.5)]"
|
||||||
|
role="alertdialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-labelledby="batch-delete-title"
|
||||||
|
aria-describedby="batch-delete-desc"
|
||||||
|
>
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-start justify-between p-5 pb-3">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex size-10 items-center justify-center rounded-xl bg-[var(--color-status-error)]/10">
|
||||||
|
<Trash2 className="size-5 text-[var(--color-status-error)]" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2
|
||||||
|
id="batch-delete-title"
|
||||||
|
className="text-[15px] font-semibold text-[var(--color-text-primary)]"
|
||||||
|
>
|
||||||
|
Delete {sessions.length} session{sessions.length === 1 ? '' : 's'}?
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
className="flex size-7 items-center justify-center rounded-lg text-[var(--color-text-muted)] transition hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]"
|
||||||
|
onClick={onCancel}
|
||||||
|
type="button"
|
||||||
|
aria-label="Cancel"
|
||||||
|
>
|
||||||
|
<X className="size-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Session list */}
|
||||||
|
<div className="px-5">
|
||||||
|
<div className="max-h-[200px] overflow-y-auto rounded-lg border border-[var(--color-border-subtle)] bg-[var(--color-surface-0)]/60 px-3 py-2">
|
||||||
|
{sessions.map((session) => (
|
||||||
|
<div
|
||||||
|
key={session.id}
|
||||||
|
className="truncate py-1 text-[12px] text-[var(--color-text-secondary)]"
|
||||||
|
>
|
||||||
|
{session.title}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Warning */}
|
||||||
|
<div className="px-5 pt-3" id="batch-delete-desc">
|
||||||
|
<div className="flex items-start gap-2 rounded-lg bg-[var(--color-status-error)]/5 px-3 py-2 text-[12px] text-[var(--color-status-error)]">
|
||||||
|
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
|
||||||
|
<span>This action cannot be undone. All messages and session data will be permanently removed.</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
<div className="flex items-center justify-end gap-2 p-5">
|
||||||
|
<button
|
||||||
|
className="rounded-lg px-4 py-2 text-[13px] font-medium text-[var(--color-text-secondary)] transition hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-primary)]"
|
||||||
|
onClick={onCancel}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
{requiresHold ? (
|
||||||
|
<button
|
||||||
|
className="hold-to-confirm relative overflow-hidden rounded-lg bg-[var(--color-status-error)] px-4 py-2 text-[13px] font-medium text-white transition-all select-none"
|
||||||
|
onMouseDown={startHold}
|
||||||
|
onMouseUp={cancelHold}
|
||||||
|
onMouseLeave={cancelHold}
|
||||||
|
onTouchStart={startHold}
|
||||||
|
onTouchEnd={cancelHold}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{/* Progress fill */}
|
||||||
|
<span
|
||||||
|
className="absolute inset-0 origin-left bg-white/20 transition-none"
|
||||||
|
style={{ transform: `scaleX(${holdProgress})` }}
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
<span className="relative flex items-center gap-1.5">
|
||||||
|
<Trash2 className="size-3.5" />
|
||||||
|
{holdProgress > 0 ? 'Hold to delete…' : 'Hold to delete'}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
className="rounded-lg bg-[var(--color-status-error)] px-4 py-2 text-[13px] font-medium text-white transition hover:bg-[var(--color-status-error)]/80"
|
||||||
|
onClick={onConfirm}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-1.5">
|
||||||
|
<Trash2 className="size-3.5" />
|
||||||
|
Delete
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { Undo2, X } from 'lucide-react';
|
||||||
|
|
||||||
|
interface UndoToastProps {
|
||||||
|
message: string;
|
||||||
|
onUndo: () => void;
|
||||||
|
onDismiss: () => void;
|
||||||
|
duration?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UndoToast({
|
||||||
|
message,
|
||||||
|
onUndo,
|
||||||
|
onDismiss,
|
||||||
|
duration = 5000,
|
||||||
|
}: UndoToastProps) {
|
||||||
|
const [exiting, setExiting] = useState(false);
|
||||||
|
const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
timerRef.current = setTimeout(() => {
|
||||||
|
setExiting(true);
|
||||||
|
setTimeout(onDismiss, 200);
|
||||||
|
}, duration);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (timerRef.current) clearTimeout(timerRef.current);
|
||||||
|
};
|
||||||
|
}, [duration, onDismiss]);
|
||||||
|
|
||||||
|
function handleUndo() {
|
||||||
|
if (timerRef.current) clearTimeout(timerRef.current);
|
||||||
|
onUndo();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDismiss() {
|
||||||
|
if (timerRef.current) clearTimeout(timerRef.current);
|
||||||
|
setExiting(true);
|
||||||
|
setTimeout(onDismiss, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`${exiting ? 'undo-toast-exit' : 'undo-toast-enter'} pointer-events-auto mx-3 mb-2 flex items-center gap-2 rounded-xl border border-[var(--color-border)] bg-[var(--color-surface-1)]/95 px-3 py-2.5 shadow-[0_8px_32px_rgba(0,0,0,0.3)] backdrop-blur-md`}
|
||||||
|
role="alert"
|
||||||
|
>
|
||||||
|
<span className="flex-1 text-[12px] text-[var(--color-text-primary)]">
|
||||||
|
{message}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-semibold text-[var(--color-accent)] transition hover:bg-[var(--color-accent)]/10"
|
||||||
|
onClick={handleUndo}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Undo2 className="size-3" />
|
||||||
|
Undo
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="flex size-5 items-center justify-center rounded text-[var(--color-text-muted)] transition hover:text-[var(--color-text-primary)]"
|
||||||
|
onClick={handleDismiss}
|
||||||
|
type="button"
|
||||||
|
aria-label="Dismiss"
|
||||||
|
>
|
||||||
|
<X className="size-3" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Auto-dismiss progress bar */}
|
||||||
|
<span
|
||||||
|
className="absolute bottom-0 left-0 right-0 h-[2px] origin-left rounded-b-xl bg-[var(--color-accent)]/30"
|
||||||
|
style={{
|
||||||
|
animation: `toast-progress ${duration}ms linear forwards`,
|
||||||
|
}}
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
import { isMac } from '@renderer/lib/platform';
|
||||||
|
|
||||||
|
/** Modifier keys we recognise, in canonical display order. */
|
||||||
|
const MODIFIER_KEYS = new Set(['Control', 'Alt', 'Shift', 'Meta']);
|
||||||
|
|
||||||
|
/** Keys that should never be accepted as the primary (non-modifier) key. */
|
||||||
|
const IGNORED_KEYS = new Set([
|
||||||
|
'Dead', 'Unidentified', 'Process', 'CapsLock', 'NumLock', 'ScrollLock',
|
||||||
|
'Fn', 'FnLock', 'Hyper', 'Super', 'OS',
|
||||||
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a portable hotkey string (e.g. `"Alt+Shift+C"`) into
|
||||||
|
* platform-aware display tokens.
|
||||||
|
*/
|
||||||
|
export function hotkeyToDisplayTokens(hotkey: string): string[] {
|
||||||
|
return hotkey
|
||||||
|
.replace(/\bSuper\b/g, isMac ? '⌘' : 'Win')
|
||||||
|
.replace(/\bMeta\b/g, isMac ? '⌘' : 'Win')
|
||||||
|
.replace(/\bCtrl\b/g, isMac ? '⌃' : 'Ctrl')
|
||||||
|
.replace(/\bControl\b/g, isMac ? '⌃' : 'Ctrl')
|
||||||
|
.replace(/\bAlt\b/g, isMac ? '⌥' : 'Alt')
|
||||||
|
.replace(/\bShift\b/g, isMac ? '⇧' : 'Shift')
|
||||||
|
.split('+')
|
||||||
|
.map((k) => k.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalise a `KeyboardEvent` key name into the portable format used in
|
||||||
|
* settings (Electron accelerator-compatible).
|
||||||
|
*/
|
||||||
|
function normaliseKeyName(key: string): string | undefined {
|
||||||
|
if (MODIFIER_KEYS.has(key) || IGNORED_KEYS.has(key)) return undefined;
|
||||||
|
|
||||||
|
// Letters → uppercase
|
||||||
|
if (/^[a-zA-Z]$/.test(key)) return key.toUpperCase();
|
||||||
|
|
||||||
|
// Digits
|
||||||
|
if (/^[0-9]$/.test(key)) return key;
|
||||||
|
|
||||||
|
// F-keys
|
||||||
|
if (/^F\d{1,2}$/.test(key)) return key;
|
||||||
|
|
||||||
|
// Named keys
|
||||||
|
const named: Record<string, string> = {
|
||||||
|
' ': 'Space', Enter: 'Enter', Tab: 'Tab', Escape: 'Escape',
|
||||||
|
Backspace: 'Backspace', Delete: 'Delete', Insert: 'Insert',
|
||||||
|
Home: 'Home', End: 'End', PageUp: 'PageUp', PageDown: 'PageDown',
|
||||||
|
ArrowUp: 'Up', ArrowDown: 'Down', ArrowLeft: 'Left', ArrowRight: 'Right',
|
||||||
|
'+': 'Plus', '-': 'Minus', '=': 'Equal',
|
||||||
|
'[': 'BracketLeft', ']': 'BracketRight',
|
||||||
|
'\\': 'Backslash', '/': 'Slash',
|
||||||
|
';': 'Semicolon', "'": 'Quote', ',': 'Comma', '.': 'Period',
|
||||||
|
'`': 'Backquote',
|
||||||
|
};
|
||||||
|
return named[key] ?? key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build the portable hotkey string from modifier flags and a key name. */
|
||||||
|
function buildHotkeyString(mods: { ctrl: boolean; alt: boolean; shift: boolean; meta: boolean }, key: string): string {
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (mods.ctrl) parts.push('Ctrl');
|
||||||
|
if (mods.alt) parts.push('Alt');
|
||||||
|
if (mods.shift) parts.push('Shift');
|
||||||
|
if (mods.meta) parts.push('Super');
|
||||||
|
parts.push(key);
|
||||||
|
return parts.join('+');
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HotkeyRecorderProps {
|
||||||
|
value: string;
|
||||||
|
onChange: (hotkey: string) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HotkeyRecorder({ value, onChange, disabled }: HotkeyRecorderProps) {
|
||||||
|
const [recording, setRecording] = useState(false);
|
||||||
|
const [liveKeys, setLiveKeys] = useState<string | null>(null);
|
||||||
|
const recorderRef = useRef<HTMLButtonElement>(null);
|
||||||
|
|
||||||
|
const displayTokens = hotkeyToDisplayTokens(liveKeys ?? value);
|
||||||
|
|
||||||
|
const stopRecording = useCallback(() => {
|
||||||
|
setRecording(false);
|
||||||
|
setLiveKeys(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Escape cancels recording
|
||||||
|
// Valid combo (modifier + key) commits immediately
|
||||||
|
useEffect(() => {
|
||||||
|
if (!recording) return;
|
||||||
|
|
||||||
|
function handleKeyDown(e: KeyboardEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
|
||||||
|
// Escape cancels
|
||||||
|
if (e.key === 'Escape') {
|
||||||
|
stopRecording();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mods = { ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey, meta: e.metaKey };
|
||||||
|
const hasModifier = mods.ctrl || mods.alt || mods.shift || mods.meta;
|
||||||
|
const key = normaliseKeyName(e.key);
|
||||||
|
|
||||||
|
if (key && hasModifier) {
|
||||||
|
const hotkey = buildHotkeyString(mods, key);
|
||||||
|
onChange(hotkey);
|
||||||
|
setRecording(false);
|
||||||
|
setLiveKeys(null);
|
||||||
|
} else if (!key) {
|
||||||
|
// Only modifiers held — show live preview
|
||||||
|
const preview = buildModifierPreview(mods);
|
||||||
|
if (preview) setLiveKeys(preview);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleKeyUp(e: KeyboardEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('keydown', handleKeyDown, true);
|
||||||
|
window.addEventListener('keyup', handleKeyUp, true);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('keydown', handleKeyDown, true);
|
||||||
|
window.removeEventListener('keyup', handleKeyUp, true);
|
||||||
|
};
|
||||||
|
}, [recording, onChange, stopRecording]);
|
||||||
|
|
||||||
|
// Click outside cancels recording
|
||||||
|
useEffect(() => {
|
||||||
|
if (!recording) return;
|
||||||
|
function handleClick(e: MouseEvent) {
|
||||||
|
if (recorderRef.current && !recorderRef.current.contains(e.target as Node)) {
|
||||||
|
stopRecording();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener('mousedown', handleClick);
|
||||||
|
return () => document.removeEventListener('mousedown', handleClick);
|
||||||
|
}, [recording, stopRecording]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
ref={recorderRef}
|
||||||
|
type="button"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => {
|
||||||
|
if (!disabled) {
|
||||||
|
setRecording(true);
|
||||||
|
setLiveKeys(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
aria-label={recording ? 'Press a key combination to set shortcut' : `Change shortcut, currently ${value}`}
|
||||||
|
className={`
|
||||||
|
group relative flex items-center gap-2.5 rounded-lg border px-4 py-3 text-left
|
||||||
|
transition-all duration-200 outline-none
|
||||||
|
${recording
|
||||||
|
? 'border-[var(--color-accent)]/50 bg-[var(--color-accent)]/[0.06] ring-1 ring-[var(--color-accent)]/20'
|
||||||
|
: disabled
|
||||||
|
? 'cursor-not-allowed border-[var(--color-border)] opacity-50'
|
||||||
|
: 'border-[var(--color-border)] hover:border-[var(--color-border-glow)] hover:bg-[var(--color-surface-3)]/30 cursor-pointer'
|
||||||
|
}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{/* Key display */}
|
||||||
|
<div className="flex flex-1 items-center gap-1.5">
|
||||||
|
{recording && !liveKeys ? (
|
||||||
|
<span className="flex items-center gap-2 text-[12px] text-[var(--color-text-accent)]">
|
||||||
|
<span className="relative flex size-2">
|
||||||
|
<span className="absolute inline-flex size-full animate-ping rounded-full bg-[var(--color-accent)] opacity-40" />
|
||||||
|
<span className="relative inline-flex size-2 rounded-full bg-[var(--color-accent)]" />
|
||||||
|
</span>
|
||||||
|
Press a key combo…
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
displayTokens.map((key, i) => (
|
||||||
|
<kbd
|
||||||
|
key={`${key}-${i}`}
|
||||||
|
className={`
|
||||||
|
rounded-[5px] border px-2 py-[3px] font-mono text-[11px] font-medium leading-none shadow-sm
|
||||||
|
transition-all duration-200
|
||||||
|
${recording
|
||||||
|
? 'border-[var(--color-accent)]/30 bg-[var(--color-accent)]/10 text-[var(--color-text-accent)] shadow-[var(--color-accent)]/10'
|
||||||
|
: 'border-[var(--color-border)] bg-[var(--color-surface-2)] text-[var(--color-text-secondary)] shadow-black/20'
|
||||||
|
}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{key}
|
||||||
|
</kbd>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Action hint */}
|
||||||
|
<span
|
||||||
|
className={`
|
||||||
|
shrink-0 rounded-md px-2 py-1 text-[10px] font-semibold tracking-wide uppercase
|
||||||
|
transition-all duration-200
|
||||||
|
${recording
|
||||||
|
? 'bg-[var(--color-accent)]/15 text-[var(--color-text-accent)]'
|
||||||
|
: 'text-[var(--color-text-muted)] opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100'
|
||||||
|
}
|
||||||
|
`}
|
||||||
|
>
|
||||||
|
{recording ? 'Esc to cancel' : 'Click to change'}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildModifierPreview(mods: { ctrl: boolean; alt: boolean; shift: boolean; meta: boolean }): string | null {
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (mods.ctrl) parts.push('Ctrl');
|
||||||
|
if (mods.alt) parts.push('Alt');
|
||||||
|
if (mods.shift) parts.push('Shift');
|
||||||
|
if (mods.meta) parts.push('Super');
|
||||||
|
return parts.length > 0 ? parts.join('+') + '+…' : null;
|
||||||
|
}
|
||||||
@@ -7,5 +7,6 @@ export { TextInput } from './TextInput';
|
|||||||
export { TextareaInput } from './TextareaInput';
|
export { TextareaInput } from './TextareaInput';
|
||||||
export { SelectInput } from './SelectInput';
|
export { SelectInput } from './SelectInput';
|
||||||
export { InfoCallout } from './InfoCallout';
|
export { InfoCallout } from './InfoCallout';
|
||||||
|
export { HotkeyRecorder, hotkeyToDisplayTokens } from './HotkeyRecorder';
|
||||||
export type { UpdateBannerProps } from './UpdateBanner';
|
export type { UpdateBannerProps } from './UpdateBanner';
|
||||||
export { UpdateBanner } from './UpdateBanner';
|
export { UpdateBanner } from './UpdateBanner';
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useCallback } from 'react';
|
import { useCallback, useMemo } from 'react';
|
||||||
import { AlertCircle, Bot, FunctionSquare, GitBranch, Info, Radio, Trash2 } from 'lucide-react';
|
import { AlertCircle, Bot, FunctionSquare, GitBranch, Info, Link2, Radio, RotateCcw, Trash2, Unlink } from 'lucide-react';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
findModel,
|
findModel,
|
||||||
@@ -16,8 +16,10 @@ import type {
|
|||||||
WorkflowOrchestrationMode,
|
WorkflowOrchestrationMode,
|
||||||
WorkflowValidationIssue,
|
WorkflowValidationIssue,
|
||||||
AgentNodeConfig,
|
AgentNodeConfig,
|
||||||
|
WorkflowAgentOverrides,
|
||||||
} from '@shared/domain/workflow';
|
} from '@shared/domain/workflow';
|
||||||
import { isBuilderBasedMode } from '@shared/domain/workflow';
|
import { isBuilderBasedMode } from '@shared/domain/workflow';
|
||||||
|
import type { WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
||||||
import { ModelSelect, ReasoningEffortSelect } from '@renderer/components/AgentConfigFields';
|
import { ModelSelect, ReasoningEffortSelect } from '@renderer/components/AgentConfigFields';
|
||||||
import { InvokeFunctionInspector } from '@renderer/components/workflow/InvokeFunctionInspector';
|
import { InvokeFunctionInspector } from '@renderer/components/workflow/InvokeFunctionInspector';
|
||||||
import { ConditionEditor } from '@renderer/components/workflow/ConditionEditor';
|
import { ConditionEditor } from '@renderer/components/workflow/ConditionEditor';
|
||||||
@@ -26,6 +28,7 @@ import { SubWorkflowInspector } from '@renderer/components/workflow/SubWorkflowI
|
|||||||
|
|
||||||
interface WorkflowGraphInspectorProps {
|
interface WorkflowGraphInspectorProps {
|
||||||
availableModels: ReadonlyArray<ModelDefinition>;
|
availableModels: ReadonlyArray<ModelDefinition>;
|
||||||
|
workspaceAgents: ReadonlyArray<WorkspaceAgentDefinition>;
|
||||||
workflow: WorkflowDefinition;
|
workflow: WorkflowDefinition;
|
||||||
workflows: ReadonlyArray<WorkflowDefinition>;
|
workflows: ReadonlyArray<WorkflowDefinition>;
|
||||||
selectedNodeId: string | null;
|
selectedNodeId: string | null;
|
||||||
@@ -39,6 +42,12 @@ interface WorkflowGraphInspectorProps {
|
|||||||
onDrillIntoSubWorkflow: (node: WorkflowNode) => void;
|
onDrillIntoSubWorkflow: (node: WorkflowNode) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const inputBaseClass =
|
||||||
|
'w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] px-3 py-2 text-[13px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] outline-none transition focus:border-[var(--color-accent)]/50';
|
||||||
|
|
||||||
|
const selectClass =
|
||||||
|
'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)] outline-none transition focus:border-[var(--color-accent)]/50';
|
||||||
|
|
||||||
function InputField({
|
function InputField({
|
||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
@@ -52,21 +61,19 @@ function InputField({
|
|||||||
multiline?: boolean;
|
multiline?: boolean;
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
}) {
|
}) {
|
||||||
const base =
|
|
||||||
'w-full rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-1)] px-3 py-2 text-[13px] text-[var(--color-text-primary)] placeholder-[var(--color-text-muted)] outline-none transition focus:border-[var(--color-accent)]/50';
|
|
||||||
return (
|
return (
|
||||||
<label className="block space-y-1.5">
|
<label className="block space-y-1.5">
|
||||||
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
|
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
|
||||||
{multiline ? (
|
{multiline ? (
|
||||||
<textarea
|
<textarea
|
||||||
className={`${base} min-h-20 resize-y`}
|
className={`${inputBaseClass} min-h-20 resize-y`}
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={(e) => onChange(e.target.value)}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
value={value}
|
value={value}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<input
|
<input
|
||||||
className={base}
|
className={inputBaseClass}
|
||||||
onChange={(e) => onChange(e.target.value)}
|
onChange={(e) => onChange(e.target.value)}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
value={value}
|
value={value}
|
||||||
@@ -76,37 +83,176 @@ function InputField({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Overridable field ─────────────────────────────────────── */
|
||||||
|
|
||||||
|
function OverridableField({
|
||||||
|
label,
|
||||||
|
baseValue,
|
||||||
|
overrideValue,
|
||||||
|
onChange,
|
||||||
|
onReset,
|
||||||
|
multiline,
|
||||||
|
placeholder,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
baseValue: string;
|
||||||
|
overrideValue: string | undefined;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
onReset: () => void;
|
||||||
|
multiline?: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
}) {
|
||||||
|
const isOverridden = overrideValue !== undefined;
|
||||||
|
const displayValue = overrideValue ?? baseValue;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">{label}</span>
|
||||||
|
{isOverridden && (
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-accent)] transition hover:bg-[var(--color-accent)]/10"
|
||||||
|
onClick={onReset}
|
||||||
|
title="Reset to saved agent value"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<RotateCcw className="size-2.5" />
|
||||||
|
Reset
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{multiline ? (
|
||||||
|
<textarea
|
||||||
|
className={`${inputBaseClass} min-h-20 resize-y ${isOverridden ? 'border-[var(--color-accent)]/30' : ''}`}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
placeholder={placeholder ?? baseValue}
|
||||||
|
value={displayValue}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<input
|
||||||
|
className={`${inputBaseClass} ${isOverridden ? 'border-[var(--color-accent)]/30' : ''}`}
|
||||||
|
onChange={(e) => onChange(e.target.value)}
|
||||||
|
placeholder={placeholder ?? baseValue}
|
||||||
|
value={displayValue}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Agent node inspector ──────────────────────────────────── */
|
/* ── Agent node inspector ──────────────────────────────────── */
|
||||||
|
|
||||||
function AgentNodeInspector({
|
function AgentNodeInspector({
|
||||||
node,
|
node,
|
||||||
availableModels,
|
availableModels,
|
||||||
|
workspaceAgents,
|
||||||
onNodeChange,
|
onNodeChange,
|
||||||
onNodeConfigChange,
|
onNodeConfigChange,
|
||||||
onNodeRemove,
|
onNodeRemove,
|
||||||
}: {
|
}: {
|
||||||
node: WorkflowNode;
|
node: WorkflowNode;
|
||||||
availableModels: ReadonlyArray<ModelDefinition>;
|
availableModels: ReadonlyArray<ModelDefinition>;
|
||||||
|
workspaceAgents: ReadonlyArray<WorkspaceAgentDefinition>;
|
||||||
onNodeChange: (nodeId: string, patch: Partial<WorkflowNode>) => void;
|
onNodeChange: (nodeId: string, patch: Partial<WorkflowNode>) => void;
|
||||||
onNodeConfigChange: (nodeId: string, config: WorkflowNodeConfig) => void;
|
onNodeConfigChange: (nodeId: string, config: WorkflowNodeConfig) => void;
|
||||||
onNodeRemove: (nodeId: string) => void;
|
onNodeRemove: (nodeId: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const config = node.config as AgentNodeConfig;
|
const config = node.config as AgentNodeConfig;
|
||||||
const model = findModel(config.model, availableModels);
|
const isLinked = !!config.workspaceAgentId;
|
||||||
|
const baseAgent = useMemo(
|
||||||
|
() => isLinked ? workspaceAgents.find((a) => a.id === config.workspaceAgentId) : undefined,
|
||||||
|
[isLinked, config.workspaceAgentId, workspaceAgents],
|
||||||
|
);
|
||||||
|
const isStale = isLinked && !baseAgent;
|
||||||
|
|
||||||
|
const resolvedModel = isLinked && baseAgent
|
||||||
|
? config.overrides?.model ?? baseAgent.model
|
||||||
|
: config.model;
|
||||||
|
const model = findModel(resolvedModel, availableModels);
|
||||||
|
|
||||||
|
function setConfig(next: AgentNodeConfig) {
|
||||||
|
onNodeConfigChange(node.id, next);
|
||||||
|
}
|
||||||
|
|
||||||
function patchConfig(patch: Partial<AgentNodeConfig>) {
|
function patchConfig(patch: Partial<AgentNodeConfig>) {
|
||||||
onNodeConfigChange(node.id, { ...config, ...patch });
|
setConfig({ ...config, ...patch });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function patchOverride<K extends keyof WorkflowAgentOverrides>(
|
||||||
|
field: K,
|
||||||
|
value: WorkflowAgentOverrides[K],
|
||||||
|
) {
|
||||||
|
if (!baseAgent) return;
|
||||||
|
const baseValue = baseAgent[field];
|
||||||
|
if (value === baseValue) {
|
||||||
|
// Value matches base — remove the override
|
||||||
|
resetOverride(field);
|
||||||
|
} else {
|
||||||
|
setConfig({
|
||||||
|
...config,
|
||||||
|
overrides: { ...config.overrides, [field]: value },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetOverride(field: keyof WorkflowAgentOverrides) {
|
||||||
|
if (!config.overrides) return;
|
||||||
|
const { [field]: _, ...rest } = config.overrides;
|
||||||
|
const cleaned = Object.keys(rest).length > 0 ? rest : undefined;
|
||||||
|
setConfig({ ...config, overrides: cleaned });
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSelectWorkspaceAgent(agentId: string) {
|
||||||
|
const agent = workspaceAgents.find((a) => a.id === agentId);
|
||||||
|
if (!agent) return;
|
||||||
|
setConfig({
|
||||||
|
...config,
|
||||||
|
workspaceAgentId: agentId,
|
||||||
|
name: agent.name,
|
||||||
|
description: agent.description,
|
||||||
|
instructions: agent.instructions,
|
||||||
|
model: agent.model,
|
||||||
|
reasoningEffort: agent.reasoningEffort,
|
||||||
|
copilot: agent.copilot,
|
||||||
|
overrides: undefined,
|
||||||
|
});
|
||||||
|
onNodeChange(node.id, { label: agent.name });
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleDetach() {
|
||||||
|
if (!baseAgent) return;
|
||||||
|
const overrides = config.overrides ?? {};
|
||||||
|
setConfig({
|
||||||
|
...config,
|
||||||
|
workspaceAgentId: undefined,
|
||||||
|
overrides: undefined,
|
||||||
|
name: overrides.name ?? baseAgent.name,
|
||||||
|
description: overrides.description ?? baseAgent.description,
|
||||||
|
instructions: overrides.instructions ?? baseAgent.instructions,
|
||||||
|
model: overrides.model ?? baseAgent.model,
|
||||||
|
reasoningEffort: overrides.reasoningEffort ?? baseAgent.reasoningEffort,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSwitchToLinked() {
|
||||||
|
if (workspaceAgents.length === 0) return;
|
||||||
|
handleSelectWorkspaceAgent(workspaceAgents[0].id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const displayName = isLinked && baseAgent
|
||||||
|
? config.overrides?.name ?? baseAgent.name
|
||||||
|
: config.name;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{/* Header */}
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex items-center gap-2.5">
|
<div className="flex items-center gap-2.5">
|
||||||
<div className="flex size-8 items-center justify-center rounded-lg bg-[var(--color-surface-2)]">
|
<div className="flex size-8 items-center justify-center rounded-lg bg-[var(--color-surface-2)]">
|
||||||
<Bot className="size-4 text-[var(--color-text-primary)]" />
|
<Bot className="size-4 text-[var(--color-text-primary)]" />
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[13px] font-semibold text-[var(--color-text-primary)]">
|
<div className="text-[13px] font-semibold text-[var(--color-text-primary)]">
|
||||||
{config.name || 'Unnamed Agent'}
|
{displayName || 'Unnamed Agent'}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
@@ -119,56 +265,229 @@ function AgentNodeInspector({
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Source selector */}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">Source</span>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<button
|
||||||
|
className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12px] font-medium transition-all ${
|
||||||
|
!isLinked
|
||||||
|
? 'bg-[var(--color-accent)]/15 text-[var(--color-accent)] ring-1 ring-[var(--color-accent)]/25'
|
||||||
|
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-secondary)]'
|
||||||
|
}`}
|
||||||
|
onClick={() => { if (isLinked) handleDetach(); }}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
Inline
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12px] font-medium transition-all ${
|
||||||
|
isLinked
|
||||||
|
? 'bg-[var(--color-accent)]/15 text-[var(--color-accent)] ring-1 ring-[var(--color-accent)]/25'
|
||||||
|
: 'text-[var(--color-text-muted)] hover:bg-[var(--color-surface-2)] hover:text-[var(--color-text-secondary)]'
|
||||||
|
}`}
|
||||||
|
onClick={() => { if (!isLinked) handleSwitchToLinked(); }}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Link2 className="size-3" />
|
||||||
|
Saved Agent
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Workspace agent picker (linked mode) */}
|
||||||
|
{isLinked && (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">Agent</span>
|
||||||
|
{workspaceAgents.length > 0 ? (
|
||||||
|
<select
|
||||||
|
className={selectClass}
|
||||||
|
onChange={(e) => handleSelectWorkspaceAgent(e.target.value)}
|
||||||
|
value={config.workspaceAgentId ?? ''}
|
||||||
|
>
|
||||||
|
{isStale && (
|
||||||
|
<option disabled value={config.workspaceAgentId}>
|
||||||
|
(Deleted agent)
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{workspaceAgents.map((agent) => (
|
||||||
|
<option key={agent.id} value={agent.id}>
|
||||||
|
{agent.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<p className="rounded-lg bg-[var(--color-surface-2)] px-3 py-2 text-[12px] text-[var(--color-text-muted)]">
|
||||||
|
No saved agents. Create agents in Settings → Agents.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isStale && (
|
||||||
|
<div className="flex items-start gap-1.5 rounded-lg bg-[var(--color-status-warning)]/10 px-2.5 py-1.5 text-[11px] text-[var(--color-status-warning)]">
|
||||||
|
<AlertCircle className="mt-0.5 size-3 shrink-0" />
|
||||||
|
<span>The linked agent was deleted. Select another or switch to inline.</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{baseAgent && (
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1.5 text-[11px] text-[var(--color-text-muted)] transition hover:text-[var(--color-text-secondary)]"
|
||||||
|
onClick={handleDetach}
|
||||||
|
title="Detach from saved agent and use inline configuration"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Unlink className="size-3" />
|
||||||
|
Detach to inline
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Label field (always shown) */}
|
||||||
<InputField
|
<InputField
|
||||||
label="Label"
|
label="Label"
|
||||||
onChange={(v) => onNodeChange(node.id, { label: v })}
|
onChange={(v) => onNodeChange(node.id, { label: v })}
|
||||||
placeholder="Display label"
|
placeholder="Display label"
|
||||||
value={node.label}
|
value={node.label}
|
||||||
/>
|
/>
|
||||||
<InputField
|
|
||||||
label="Agent Name"
|
|
||||||
onChange={(v) => patchConfig({ name: v })}
|
|
||||||
placeholder="Agent name"
|
|
||||||
value={config.name}
|
|
||||||
/>
|
|
||||||
<InputField
|
|
||||||
label="Description"
|
|
||||||
onChange={(v) => patchConfig({ description: v })}
|
|
||||||
placeholder="What this agent does"
|
|
||||||
value={config.description}
|
|
||||||
/>
|
|
||||||
<InputField
|
|
||||||
label="Instructions"
|
|
||||||
multiline
|
|
||||||
onChange={(v) => patchConfig({ instructions: v })}
|
|
||||||
placeholder="System instructions for this agent"
|
|
||||||
value={config.instructions}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="space-y-3">
|
{/* Inline mode — direct editing */}
|
||||||
<ModelSelect
|
{!isLinked && (
|
||||||
models={availableModels}
|
<>
|
||||||
onChange={(value) => {
|
<InputField
|
||||||
const m = findModel(value, availableModels);
|
label="Agent Name"
|
||||||
patchConfig({
|
onChange={(v) => patchConfig({ name: v })}
|
||||||
model: value,
|
placeholder="Agent name"
|
||||||
reasoningEffort: resolveReasoningEffort(m, config.reasoningEffort),
|
value={config.name}
|
||||||
});
|
|
||||||
}}
|
|
||||||
value={config.model}
|
|
||||||
/>
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<ReasoningEffortSelect
|
|
||||||
label="Reasoning"
|
|
||||||
onChange={(value) => patchConfig({ reasoningEffort: value })}
|
|
||||||
supportedEfforts={getSupportedReasoningEfforts(model)}
|
|
||||||
value={config.reasoningEffort}
|
|
||||||
/>
|
/>
|
||||||
<p className="text-[11px] leading-relaxed text-[var(--color-text-muted)]">
|
<InputField
|
||||||
Controls how much the model reasons before responding. Higher values produce more careful, thorough answers.
|
label="Description"
|
||||||
</p>
|
onChange={(v) => patchConfig({ description: v })}
|
||||||
</div>
|
placeholder="What this agent does"
|
||||||
</div>
|
value={config.description}
|
||||||
|
/>
|
||||||
|
<InputField
|
||||||
|
label="Instructions"
|
||||||
|
multiline
|
||||||
|
onChange={(v) => patchConfig({ instructions: v })}
|
||||||
|
placeholder="System instructions for this agent"
|
||||||
|
value={config.instructions}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
<ModelSelect
|
||||||
|
models={availableModels}
|
||||||
|
onChange={(value) => {
|
||||||
|
const m = findModel(value, availableModels);
|
||||||
|
patchConfig({
|
||||||
|
model: value,
|
||||||
|
reasoningEffort: resolveReasoningEffort(m, config.reasoningEffort),
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
value={config.model}
|
||||||
|
/>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<ReasoningEffortSelect
|
||||||
|
label="Reasoning"
|
||||||
|
onChange={(value) => patchConfig({ reasoningEffort: value })}
|
||||||
|
supportedEfforts={getSupportedReasoningEfforts(model)}
|
||||||
|
value={config.reasoningEffort}
|
||||||
|
/>
|
||||||
|
<p className="text-[11px] leading-relaxed text-[var(--color-text-muted)]">
|
||||||
|
Controls how much the model reasons before responding. Higher values produce more careful, thorough answers.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Linked mode — overridable fields */}
|
||||||
|
{isLinked && baseAgent && (
|
||||||
|
<>
|
||||||
|
<div className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface-2)]/50 px-3 py-2 text-[11px] leading-relaxed text-[var(--color-text-muted)]">
|
||||||
|
Configuration inherited from <strong className="text-[var(--color-text-secondary)]">{baseAgent.name}</strong>. Edit fields below to override per-node.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<OverridableField
|
||||||
|
baseValue={baseAgent.name}
|
||||||
|
label="Agent Name"
|
||||||
|
onChange={(v) => patchOverride('name', v)}
|
||||||
|
onReset={() => resetOverride('name')}
|
||||||
|
overrideValue={config.overrides?.name}
|
||||||
|
placeholder="Agent name"
|
||||||
|
/>
|
||||||
|
<OverridableField
|
||||||
|
baseValue={baseAgent.description}
|
||||||
|
label="Description"
|
||||||
|
onChange={(v) => patchOverride('description', v)}
|
||||||
|
onReset={() => resetOverride('description')}
|
||||||
|
overrideValue={config.overrides?.description}
|
||||||
|
placeholder="What this agent does"
|
||||||
|
/>
|
||||||
|
<OverridableField
|
||||||
|
baseValue={baseAgent.instructions}
|
||||||
|
label="Instructions"
|
||||||
|
multiline
|
||||||
|
onChange={(v) => patchOverride('instructions', v)}
|
||||||
|
onReset={() => resetOverride('instructions')}
|
||||||
|
overrideValue={config.overrides?.instructions}
|
||||||
|
placeholder="System instructions for this agent"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">Model</span>
|
||||||
|
{config.overrides?.model !== undefined && (
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-accent)] transition hover:bg-[var(--color-accent)]/10"
|
||||||
|
onClick={() => resetOverride('model')}
|
||||||
|
title="Reset to saved agent value"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<RotateCcw className="size-2.5" />
|
||||||
|
Reset
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ModelSelect
|
||||||
|
models={availableModels}
|
||||||
|
onChange={(value) => {
|
||||||
|
const m = findModel(value, availableModels);
|
||||||
|
patchOverride('model', value);
|
||||||
|
patchOverride('reasoningEffort', resolveReasoningEffort(m, config.overrides?.reasoningEffort ?? baseAgent.reasoningEffort));
|
||||||
|
}}
|
||||||
|
value={resolvedModel}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-[12px] font-medium text-[var(--color-text-secondary)]">Reasoning</span>
|
||||||
|
{config.overrides?.reasoningEffort !== undefined && (
|
||||||
|
<button
|
||||||
|
className="flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] font-medium text-[var(--color-accent)] transition hover:bg-[var(--color-accent)]/10"
|
||||||
|
onClick={() => resetOverride('reasoningEffort')}
|
||||||
|
title="Reset to saved agent value"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<RotateCcw className="size-2.5" />
|
||||||
|
Reset
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<ReasoningEffortSelect
|
||||||
|
label=""
|
||||||
|
onChange={(value) => patchOverride('reasoningEffort', value)}
|
||||||
|
supportedEfforts={getSupportedReasoningEfforts(model)}
|
||||||
|
value={config.overrides?.reasoningEffort ?? baseAgent.reasoningEffort}
|
||||||
|
/>
|
||||||
|
<p className="text-[11px] leading-relaxed text-[var(--color-text-muted)]">
|
||||||
|
Controls how much the model reasons before responding. Higher values produce more careful, thorough answers.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -404,6 +723,7 @@ function EdgeInspector({
|
|||||||
|
|
||||||
export function WorkflowGraphInspector({
|
export function WorkflowGraphInspector({
|
||||||
availableModels,
|
availableModels,
|
||||||
|
workspaceAgents,
|
||||||
workflow,
|
workflow,
|
||||||
workflows,
|
workflows,
|
||||||
selectedNodeId,
|
selectedNodeId,
|
||||||
@@ -464,6 +784,7 @@ export function WorkflowGraphInspector({
|
|||||||
onNodeChange={onNodeChange}
|
onNodeChange={onNodeChange}
|
||||||
onNodeConfigChange={onNodeConfigChange}
|
onNodeConfigChange={onNodeConfigChange}
|
||||||
onNodeRemove={onNodeRemove}
|
onNodeRemove={onNodeRemove}
|
||||||
|
workspaceAgents={workspaceAgents}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import { Bot, FunctionSquare, GitBranch, Play, Radio, Square } from 'lucide-react';
|
import { Bot, FunctionSquare, GitBranch, Link2, Play, Radio, Square } from 'lucide-react';
|
||||||
|
|
||||||
import type { WorkflowNodeKind } from '@shared/domain/workflow';
|
import type { WorkflowNodeKind } from '@shared/domain/workflow';
|
||||||
|
import type { WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
||||||
|
|
||||||
interface WorkflowNodePaletteProps {
|
interface WorkflowNodePaletteProps {
|
||||||
onAddNode: (kind: WorkflowNodeKind) => void;
|
onAddNode: (kind: WorkflowNodeKind) => void;
|
||||||
|
onAddWorkspaceAgentNode: (agentId: string) => void;
|
||||||
|
workspaceAgents: ReadonlyArray<WorkspaceAgentDefinition>;
|
||||||
disabledKinds?: ReadonlySet<WorkflowNodeKind>;
|
disabledKinds?: ReadonlySet<WorkflowNodeKind>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,7 +33,7 @@ const paletteGroups: PaletteGroup[] = [
|
|||||||
{
|
{
|
||||||
label: 'Agents',
|
label: 'Agents',
|
||||||
items: [
|
items: [
|
||||||
{ kind: 'agent', label: 'Agent', icon: Bot, color: 'text-[var(--color-accent)]' },
|
{ kind: 'agent', label: 'New Agent', icon: Bot, color: 'text-[var(--color-accent)]' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -48,7 +51,7 @@ const paletteGroups: PaletteGroup[] = [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export function WorkflowNodePalette({ onAddNode, disabledKinds }: WorkflowNodePaletteProps) {
|
export function WorkflowNodePalette({ onAddNode, onAddWorkspaceAgentNode, workspaceAgents, disabledKinds }: WorkflowNodePaletteProps) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4 p-3">
|
<div className="space-y-4 p-3">
|
||||||
<h4 className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
<h4 className="text-[10px] font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">
|
||||||
@@ -81,6 +84,25 @@ export function WorkflowNodePalette({ onAddNode, disabledKinds }: WorkflowNodePa
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
|
{/* Saved workspace agents in the Agents group */}
|
||||||
|
{group.label === 'Agents' && workspaceAgents.length > 0 && (
|
||||||
|
<>
|
||||||
|
<div className="mx-1 my-1.5 border-t border-[var(--color-border)]" />
|
||||||
|
{workspaceAgents.map((agent) => (
|
||||||
|
<button
|
||||||
|
className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[12px] text-[var(--color-text-secondary)] transition-all duration-200 hover:bg-[var(--color-surface-3)] hover:text-[var(--color-text-primary)]"
|
||||||
|
key={agent.id}
|
||||||
|
onClick={() => onAddWorkspaceAgentNode(agent.id)}
|
||||||
|
title={agent.description || agent.name}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Link2 className="size-3.5 text-[var(--color-accent)]" />
|
||||||
|
<span className="truncate">{agent.name}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,39 +1,56 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
function formatElapsed(startMs: number): string {
|
/** Format a millisecond duration as a human-readable elapsed string. */
|
||||||
const seconds = Math.max(0, Math.floor((Date.now() - startMs) / 1000));
|
export function formatElapsedMs(durationMs: number): string {
|
||||||
|
const seconds = Math.max(0, Math.floor(durationMs / 1000));
|
||||||
if (seconds < 60) return `${seconds}s`;
|
if (seconds < 60) return `${seconds}s`;
|
||||||
const minutes = Math.floor(seconds / 60);
|
const minutes = Math.floor(seconds / 60);
|
||||||
const remainder = seconds % 60;
|
const remainder = seconds % 60;
|
||||||
return `${minutes}m ${remainder}s`;
|
return remainder > 0 ? `${minutes}m ${remainder}s` : `${minutes}m`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a live-ticking elapsed-time string while `active` is true.
|
* Returns a live-ticking elapsed-time string while `active` is true.
|
||||||
* Freezes the display when `active` becomes false.
|
*
|
||||||
|
* When the timer is no longer active and `completedAt` is provided, the
|
||||||
|
* duration is computed as `completedAt − startedAt` — giving an accurate
|
||||||
|
* frozen value even when the session is reopened much later. Without
|
||||||
|
* `completedAt` the hook falls back to `Date.now() − startedAt` at the
|
||||||
|
* moment `active` becomes false.
|
||||||
*/
|
*/
|
||||||
export function useElapsedTimer(startedAt: string | undefined, active: boolean): string | undefined {
|
export function useElapsedTimer(
|
||||||
|
startedAt: string | undefined,
|
||||||
|
active: boolean,
|
||||||
|
completedAt?: string,
|
||||||
|
): string | undefined {
|
||||||
const startMs = startedAt ? new Date(startedAt).getTime() : undefined;
|
const startMs = startedAt ? new Date(startedAt).getTime() : undefined;
|
||||||
|
const endMs = completedAt ? new Date(completedAt).getTime() : undefined;
|
||||||
|
|
||||||
const [elapsed, setElapsed] = useState<string | undefined>(() => {
|
const computeElapsed = (): string | undefined => {
|
||||||
if (!startMs) return undefined;
|
if (!startMs || Number.isNaN(startMs)) return undefined;
|
||||||
return formatElapsed(startMs);
|
if (!active && endMs && !Number.isNaN(endMs)) {
|
||||||
});
|
return formatElapsedMs(endMs - startMs);
|
||||||
|
}
|
||||||
|
return formatElapsedMs(Date.now() - startMs);
|
||||||
|
};
|
||||||
|
|
||||||
|
const [elapsed, setElapsed] = useState<string | undefined>(computeElapsed);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!startMs) {
|
if (!startMs || Number.isNaN(startMs)) {
|
||||||
setElapsed(undefined);
|
setElapsed(undefined);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Always sync to current value immediately
|
// Sync immediately
|
||||||
setElapsed(formatElapsed(startMs));
|
setElapsed(computeElapsed());
|
||||||
|
|
||||||
if (!active) return;
|
if (!active) return;
|
||||||
|
|
||||||
const id = setInterval(() => setElapsed(formatElapsed(startMs)), 1000);
|
const id = setInterval(() => setElapsed(formatElapsedMs(Date.now() - startMs)), 1000);
|
||||||
return () => clearInterval(id);
|
return () => clearInterval(id);
|
||||||
}, [startMs, active]);
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [startMs, endMs, active]);
|
||||||
|
|
||||||
return elapsed;
|
return elapsed;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { useCallback, useRef, useState } from 'react';
|
||||||
|
|
||||||
|
export interface SessionSelectionState {
|
||||||
|
/** Currently selected session IDs */
|
||||||
|
selectedIds: Set<string>;
|
||||||
|
/** Whether multi-select mode is active */
|
||||||
|
isSelecting: boolean;
|
||||||
|
/** Toggle a single session's selection */
|
||||||
|
toggle: (sessionId: string) => void;
|
||||||
|
/** Shift+click range selection: selects everything between the last anchor and the target */
|
||||||
|
rangeSelect: (sessionId: string, allVisibleIds: string[]) => void;
|
||||||
|
/** Select all provided session IDs */
|
||||||
|
selectAll: (sessionIds: string[]) => void;
|
||||||
|
/** Deselect all */
|
||||||
|
deselectAll: () => void;
|
||||||
|
/** Enter multi-select mode with an initial selection */
|
||||||
|
enterSelectionMode: (initialId: string) => void;
|
||||||
|
/** Exit multi-select mode and clear selection */
|
||||||
|
exitSelectionMode: () => void;
|
||||||
|
/** Check if a session is selected */
|
||||||
|
isSelected: (sessionId: string) => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSessionSelection(): SessionSelectionState {
|
||||||
|
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||||
|
const [isSelecting, setIsSelecting] = useState(false);
|
||||||
|
|
||||||
|
// Tracks the last explicitly toggled session for shift+click range behaviour
|
||||||
|
const anchorRef = useRef<string | null>(null);
|
||||||
|
|
||||||
|
const enterSelectionMode = useCallback((initialId: string) => {
|
||||||
|
setIsSelecting(true);
|
||||||
|
setSelectedIds(new Set([initialId]));
|
||||||
|
anchorRef.current = initialId;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const exitSelectionMode = useCallback(() => {
|
||||||
|
setIsSelecting(false);
|
||||||
|
setSelectedIds(new Set());
|
||||||
|
anchorRef.current = null;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const toggle = useCallback((sessionId: string) => {
|
||||||
|
setSelectedIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (next.has(sessionId)) {
|
||||||
|
next.delete(sessionId);
|
||||||
|
} else {
|
||||||
|
next.add(sessionId);
|
||||||
|
}
|
||||||
|
anchorRef.current = sessionId;
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const rangeSelect = useCallback((sessionId: string, allVisibleIds: string[]) => {
|
||||||
|
const anchor = anchorRef.current;
|
||||||
|
if (!anchor) {
|
||||||
|
// No anchor yet — treat as a simple toggle
|
||||||
|
setSelectedIds(new Set([sessionId]));
|
||||||
|
anchorRef.current = sessionId;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const anchorIdx = allVisibleIds.indexOf(anchor);
|
||||||
|
const targetIdx = allVisibleIds.indexOf(sessionId);
|
||||||
|
if (anchorIdx === -1 || targetIdx === -1) return;
|
||||||
|
|
||||||
|
const start = Math.min(anchorIdx, targetIdx);
|
||||||
|
const end = Math.max(anchorIdx, targetIdx);
|
||||||
|
const rangeIds = allVisibleIds.slice(start, end + 1);
|
||||||
|
|
||||||
|
setSelectedIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
for (const id of rangeIds) {
|
||||||
|
next.add(id);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
// Anchor stays the same for contiguous range extension
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const selectAll = useCallback((sessionIds: string[]) => {
|
||||||
|
setSelectedIds(new Set(sessionIds));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const deselectAll = useCallback(() => {
|
||||||
|
setSelectedIds(new Set());
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const isSelected = useCallback((sessionId: string) => selectedIds.has(sessionId), [selectedIds]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
selectedIds,
|
||||||
|
isSelecting,
|
||||||
|
toggle,
|
||||||
|
rangeSelect,
|
||||||
|
selectAll,
|
||||||
|
deselectAll,
|
||||||
|
enterSelectionMode,
|
||||||
|
exitSelectionMode,
|
||||||
|
isSelected,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ function CodeBlock({ language, children }: { language: string; children: string
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="group relative my-3 overflow-hidden rounded-lg border border-zinc-800 bg-[#0d0d10]">
|
<div className="group relative my-3 overflow-hidden rounded-lg border border-zinc-800 bg-surface-1">
|
||||||
<div className="flex items-center justify-between border-b border-zinc-800/80 px-4 py-1.5">
|
<div className="flex items-center justify-between border-b border-zinc-800/80 px-4 py-1.5">
|
||||||
<span className="select-none text-[11px] text-zinc-500">
|
<span className="select-none text-[11px] text-zinc-500">
|
||||||
{language || 'text'}
|
{language || 'text'}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import type { SessionEventRecord } from '@shared/domain/event';
|
|||||||
import { upsertSessionRunRecord } from '@shared/domain/runTimeline';
|
import { upsertSessionRunRecord } from '@shared/domain/runTimeline';
|
||||||
import type { ChatMessageRecord, SessionRecord } from '@shared/domain/session';
|
import type { ChatMessageRecord, SessionRecord } from '@shared/domain/session';
|
||||||
import type { WorkspaceState } from '@shared/domain/workspace';
|
import type { WorkspaceState } from '@shared/domain/workspace';
|
||||||
import { mergeStreamingText } from '@shared/utils/streamingText';
|
|
||||||
|
|
||||||
export function applySessionEventWorkspace(
|
export function applySessionEventWorkspace(
|
||||||
current: WorkspaceState | undefined,
|
current: WorkspaceState | undefined,
|
||||||
@@ -45,6 +44,8 @@ function applySessionEvent(session: SessionRecord, event: SessionEventRecord): S
|
|||||||
return applyMessageReclassifiedEvent(session, event);
|
return applyMessageReclassifiedEvent(session, event);
|
||||||
case 'run-updated':
|
case 'run-updated':
|
||||||
return applyRunUpdatedEvent(session, event);
|
return applyRunUpdatedEvent(session, event);
|
||||||
|
case 'assistant-intent':
|
||||||
|
return applyAssistantIntentEvent(session, event);
|
||||||
default:
|
default:
|
||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
@@ -63,6 +64,7 @@ function applyStatusEvent(session: SessionRecord, event: SessionEventRecord): Se
|
|||||||
...session,
|
...session,
|
||||||
status: event.status,
|
status: event.status,
|
||||||
lastError: event.status === 'error' ? session.lastError : undefined,
|
lastError: event.status === 'error' ? session.lastError : undefined,
|
||||||
|
currentIntent: event.status === 'idle' ? undefined : session.currentIntent,
|
||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -86,14 +88,19 @@ function applyMessageDeltaEvent(session: SessionRecord, event: SessionEventRecor
|
|||||||
return session;
|
return session;
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolvedContent = event.content ?? event.contentDelta ?? '';
|
|
||||||
const messageIndex = session.messages.findIndex((message) => message.id === event.messageId);
|
const messageIndex = session.messages.findIndex((message) => message.id === event.messageId);
|
||||||
if (messageIndex >= 0) {
|
if (messageIndex >= 0) {
|
||||||
const existing = session.messages[messageIndex];
|
const existing = session.messages[messageIndex];
|
||||||
|
// The main process resolves content authoritatively; prefer event.content
|
||||||
|
// (full assembled text) and fall back to simple append for backward compat.
|
||||||
|
const nextContent =
|
||||||
|
event.content !== undefined
|
||||||
|
? event.content
|
||||||
|
: existing.content + (event.contentDelta ?? '');
|
||||||
const nextMessage: ChatMessageRecord = {
|
const nextMessage: ChatMessageRecord = {
|
||||||
...existing,
|
...existing,
|
||||||
authorName: event.authorName ?? existing.authorName,
|
authorName: event.authorName ?? existing.authorName,
|
||||||
content: event.content ?? mergeStreamingText(existing.content, resolvedContent),
|
content: nextContent,
|
||||||
pending: true,
|
pending: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -114,6 +121,8 @@ function applyMessageDeltaEvent(session: SessionRecord, event: SessionEventRecor
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const resolvedContent = event.content ?? event.contentDelta ?? '';
|
||||||
|
|
||||||
// Auto-complete any previously pending assistant messages so only
|
// Auto-complete any previously pending assistant messages so only
|
||||||
// the new message shows the "Thinking" indicator.
|
// the new message shows the "Thinking" indicator.
|
||||||
const completedMessages = session.messages.map((message) =>
|
const completedMessages = session.messages.map((message) =>
|
||||||
@@ -217,3 +226,15 @@ function applyRunUpdatedEvent(session: SessionRecord, event: SessionEventRecord)
|
|||||||
updatedAt: event.occurredAt,
|
updatedAt: event.occurredAt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function applyAssistantIntentEvent(session: SessionRecord, event: SessionEventRecord): SessionRecord {
|
||||||
|
if (!event.intent || session.currentIntent === event.intent) {
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...session,
|
||||||
|
currentIntent: event.intent,
|
||||||
|
updatedAt: event.occurredAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en" style="background: transparent;">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta
|
||||||
|
name="viewport"
|
||||||
|
content="width=device-width, initial-scale=1.0"
|
||||||
|
/>
|
||||||
|
<title>Aryx Quick Prompt</title>
|
||||||
|
</head>
|
||||||
|
<body data-quickprompt style="margin: 0; background: transparent; overflow: hidden;">
|
||||||
|
<div id="root"></div>
|
||||||
|
<script
|
||||||
|
type="module"
|
||||||
|
src="./quickprompt.tsx"
|
||||||
|
></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { StrictMode } from 'react';
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
|
||||||
|
import '@fontsource-variable/outfit';
|
||||||
|
import '@fontsource-variable/dm-sans';
|
||||||
|
import '@fontsource-variable/jetbrains-mono';
|
||||||
|
|
||||||
|
import { QuickPromptApp } from '@renderer/components/quick-prompt/QuickPromptApp';
|
||||||
|
import '@renderer/styles.css';
|
||||||
|
|
||||||
|
const container = document.getElementById('root');
|
||||||
|
if (!container) {
|
||||||
|
throw new Error('Could not find the root element.');
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(container).render(
|
||||||
|
<StrictMode>
|
||||||
|
<QuickPromptApp />
|
||||||
|
</StrictMode>,
|
||||||
|
);
|
||||||
+283
-1
@@ -674,6 +674,125 @@ body {
|
|||||||
animation: intent-divider-in 0.2s cubic-bezier(0.16, 1, 0.3, 1) both;
|
animation: intent-divider-in 0.2s cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Timeline spine connecting activity items */
|
||||||
|
.activity-timeline-spine > .turn-activity-row:not([role="separator"]) {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.activity-timeline-spine > .turn-activity-row:not([role="separator"]):not(:last-child)::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
left: 7px; /* center of the 16px (w-4) icon column */
|
||||||
|
top: 22px; /* below the icon center */
|
||||||
|
bottom: 0;
|
||||||
|
width: 1px;
|
||||||
|
background: var(--color-border);
|
||||||
|
opacity: 0.25;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Batch selection animations ──────────────────────────────── */
|
||||||
|
|
||||||
|
@keyframes selection-checkbox-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: scale(0);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes selection-checkbox-out {
|
||||||
|
from {
|
||||||
|
opacity: 1;
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 0;
|
||||||
|
transform: scale(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.selection-checkbox-enter {
|
||||||
|
animation: selection-checkbox-in 0.2s cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.selection-checkbox-exit {
|
||||||
|
animation: selection-checkbox-out 0.15s cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes checkbox-check {
|
||||||
|
0% {
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
40% {
|
||||||
|
transform: scale(1.2);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-check {
|
||||||
|
animation: checkbox-check 0.2s cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes batch-action-bar-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(100%);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.batch-action-bar-enter {
|
||||||
|
animation: batch-action-bar-in 0.25s cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes undo-toast-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(8px) scale(0.96);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes undo-toast-out {
|
||||||
|
from {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(8px) scale(0.96);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.undo-toast-enter {
|
||||||
|
animation: undo-toast-in 0.25s cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.undo-toast-exit {
|
||||||
|
animation: undo-toast-out 0.2s cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes toast-progress {
|
||||||
|
from {
|
||||||
|
transform: scaleX(1);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
transform: scaleX(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Respect reduced motion ──────────────────────────────────── */
|
/* ── Respect reduced motion ──────────────────────────────────── */
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
@@ -689,9 +808,133 @@ body {
|
|||||||
.update-banner-enter,
|
.update-banner-enter,
|
||||||
.turn-activity-enter,
|
.turn-activity-enter,
|
||||||
.turn-activity-row,
|
.turn-activity-row,
|
||||||
.turn-activity-row[role="separator"] {
|
.turn-activity-row[role="separator"],
|
||||||
|
.qp-panel-enter,
|
||||||
|
.qp-response-enter,
|
||||||
|
.qp-actions-enter,
|
||||||
|
.qp-dropdown-enter {
|
||||||
animation: none;
|
animation: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.selection-checkbox-enter,
|
||||||
|
.selection-checkbox-exit,
|
||||||
|
.checkbox-check,
|
||||||
|
.batch-action-bar-enter,
|
||||||
|
.undo-toast-enter,
|
||||||
|
.undo-toast-exit {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-border-streaming {
|
||||||
|
animation: none;
|
||||||
|
border-color: var(--color-accent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Quick Prompt — Glass Command Bar ────────────────────────── */
|
||||||
|
|
||||||
|
/* Override body/root backgrounds when inside the quickprompt window so the
|
||||||
|
transparent BrowserWindow doesn't show a colored rectangle behind the
|
||||||
|
rounded panel. The data attribute is set on the <body> in quickprompt.html. */
|
||||||
|
body[data-quickprompt],
|
||||||
|
body[data-quickprompt] #root {
|
||||||
|
background: transparent !important;
|
||||||
|
min-height: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
html:has(body[data-quickprompt]) {
|
||||||
|
background: transparent !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-container {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-panel {
|
||||||
|
background: var(--color-surface-1);
|
||||||
|
/* No box-shadow — on Windows transparent windows, shadows paint visibly
|
||||||
|
on the transparent canvas and create a visible dark rectangle. */
|
||||||
|
transition: border-color 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Border states */
|
||||||
|
.qp-border-idle {
|
||||||
|
border: 1px solid var(--color-glass-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-border-complete {
|
||||||
|
border: 1px solid var(--color-border-glow);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Animated breathing border during streaming */
|
||||||
|
@keyframes qp-border-breathe {
|
||||||
|
0%, 100% {
|
||||||
|
border-color: rgba(36, 92, 249, 0.35);
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
border-color: rgba(138, 41, 230, 0.4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-border-streaming {
|
||||||
|
border: 1px solid rgba(36, 92, 249, 0.35);
|
||||||
|
animation: qp-border-breathe 2.5s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Panel entrance animation */
|
||||||
|
@keyframes qp-panel-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: scale(0.96) translateY(-6px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-panel-enter {
|
||||||
|
animation: qp-panel-in 0.2s cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Response area entrance */
|
||||||
|
@keyframes qp-response-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
max-height: 0;
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
max-height: min(55vh, 520px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-response-enter {
|
||||||
|
animation: qp-response-in 0.25s cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Action bar entrance */
|
||||||
|
@keyframes qp-actions-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(4px);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-actions-enter {
|
||||||
|
animation: qp-actions-in 0.2s cubic-bezier(0.16, 1, 0.3, 1) 0.05s both;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dropdown entrance — opens downward */
|
||||||
|
@keyframes qp-dropdown-in {
|
||||||
|
from {
|
||||||
|
opacity: 0;
|
||||||
|
transform: translateY(-6px) scale(0.97);
|
||||||
|
}
|
||||||
|
to {
|
||||||
|
opacity: 1;
|
||||||
|
transform: translateY(0) scale(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.qp-dropdown-enter {
|
||||||
|
animation: qp-dropdown-in 0.15s cubic-bezier(0.16, 1, 0.3, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Markdown prose styles ───────────────────────────────────── */
|
/* ── Markdown prose styles ───────────────────────────────────── */
|
||||||
@@ -800,3 +1043,42 @@ body {
|
|||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.markdown-content code {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 0.85em;
|
||||||
|
background: var(--color-surface-2);
|
||||||
|
border: 1px solid var(--color-border-subtle);
|
||||||
|
border-radius: 0.25rem;
|
||||||
|
padding: 0.15em 0.35em;
|
||||||
|
color: var(--color-text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-content pre {
|
||||||
|
background: var(--color-surface-0);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
padding: 0.875em 1em;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin-top: 0.75em;
|
||||||
|
margin-bottom: 0.75em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-content pre code {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-content a {
|
||||||
|
color: var(--color-text-accent);
|
||||||
|
text-decoration: underline;
|
||||||
|
text-decoration-color: var(--color-text-accent);
|
||||||
|
text-underline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-content a:hover {
|
||||||
|
color: var(--color-accent-hover);
|
||||||
|
}
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ export const ipcChannels = {
|
|||||||
setNotificationsEnabled: 'settings:set-notifications-enabled',
|
setNotificationsEnabled: 'settings:set-notifications-enabled',
|
||||||
setMinimizeToTray: 'settings:set-minimize-to-tray',
|
setMinimizeToTray: 'settings:set-minimize-to-tray',
|
||||||
setGitAutoRefreshEnabled: 'settings:set-git-auto-refresh-enabled',
|
setGitAutoRefreshEnabled: 'settings:set-git-auto-refresh-enabled',
|
||||||
|
setOpenTelemetry: 'settings:set-opentelemetry',
|
||||||
checkForUpdates: 'app:check-for-updates',
|
checkForUpdates: 'app:check-for-updates',
|
||||||
installUpdate: 'app:install-update',
|
installUpdate: 'app:install-update',
|
||||||
saveMcpServer: 'tooling:mcp:save',
|
saveMcpServer: 'tooling:mcp:save',
|
||||||
@@ -49,6 +50,8 @@ export const ipcChannels = {
|
|||||||
setSessionPinned: 'sessions:set-pinned',
|
setSessionPinned: 'sessions:set-pinned',
|
||||||
setSessionArchived: 'sessions:set-archived',
|
setSessionArchived: 'sessions:set-archived',
|
||||||
deleteSession: 'sessions:delete',
|
deleteSession: 'sessions:delete',
|
||||||
|
batchSetSessionsArchived: 'sessions:batch-set-archived',
|
||||||
|
batchDeleteSessions: 'sessions:batch-delete',
|
||||||
regenerateSessionMessage: 'sessions:regenerate-message',
|
regenerateSessionMessage: 'sessions:regenerate-message',
|
||||||
editAndResendSessionMessage: 'sessions:edit-and-resend-message',
|
editAndResendSessionMessage: 'sessions:edit-and-resend-message',
|
||||||
sendSessionMessage: 'sessions:send-message',
|
sendSessionMessage: 'sessions:send-message',
|
||||||
@@ -83,4 +86,18 @@ export const ipcChannels = {
|
|||||||
updateStatus: 'app:update-status',
|
updateStatus: 'app:update-status',
|
||||||
getQuota: 'sidecar:get-quota',
|
getQuota: 'sidecar:get-quota',
|
||||||
trayCreateScratchpad: 'tray:create-scratchpad',
|
trayCreateScratchpad: 'tray:create-scratchpad',
|
||||||
|
|
||||||
|
// Quick Prompt
|
||||||
|
quickPromptSend: 'quick-prompt:send',
|
||||||
|
quickPromptDiscard: 'quick-prompt:discard',
|
||||||
|
quickPromptClose: 'quick-prompt:close',
|
||||||
|
quickPromptContinueInAryx: 'quick-prompt:continue-in-aryx',
|
||||||
|
quickPromptCancelTurn: 'quick-prompt:cancel-turn',
|
||||||
|
quickPromptSetSettings: 'quick-prompt:set-settings',
|
||||||
|
quickPromptGetSettings: 'quick-prompt:get-settings',
|
||||||
|
quickPromptGetCapabilities: 'quick-prompt:get-capabilities',
|
||||||
|
quickPromptSessionCreated: 'quick-prompt:session-created',
|
||||||
|
quickPromptSessionEvent: 'quick-prompt:session-event',
|
||||||
|
quickPromptShow: 'quick-prompt:show',
|
||||||
|
quickPromptHide: 'quick-prompt:hide',
|
||||||
} as const;
|
} as const;
|
||||||
|
|||||||
@@ -19,11 +19,14 @@ import type {
|
|||||||
McpServerDefinition,
|
McpServerDefinition,
|
||||||
SessionToolingSelection,
|
SessionToolingSelection,
|
||||||
AppearanceTheme,
|
AppearanceTheme,
|
||||||
|
QuickPromptSettings,
|
||||||
|
OpenTelemetrySettings,
|
||||||
} from '@shared/domain/tooling';
|
} from '@shared/domain/tooling';
|
||||||
import type { WorkspaceState } from '@shared/domain/workspace';
|
import type { WorkspaceState } from '@shared/domain/workspace';
|
||||||
import type { ChatMessageAttachment } from '@shared/domain/attachment';
|
import type { ChatMessageAttachment } from '@shared/domain/attachment';
|
||||||
import type { ProjectPromptInvocation } from '@shared/domain/projectCustomization';
|
import type { ProjectPromptInvocation } from '@shared/domain/projectCustomization';
|
||||||
import type { WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
import type { WorkspaceAgentDefinition } from '@shared/domain/workspaceAgent';
|
||||||
|
import type { ModelDefinition } from '@shared/domain/models';
|
||||||
|
|
||||||
export interface CreateSessionInput {
|
export interface CreateSessionInput {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
@@ -216,6 +219,15 @@ export interface DeleteSessionInput {
|
|||||||
sessionId: string;
|
sessionId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BatchSetSessionsArchivedInput {
|
||||||
|
sessionIds: string[];
|
||||||
|
isArchived: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BatchDeleteSessionsInput {
|
||||||
|
sessionIds: string[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface ResizeTerminalInput {
|
export interface ResizeTerminalInput {
|
||||||
cols: number;
|
cols: number;
|
||||||
rows: number;
|
rows: number;
|
||||||
@@ -332,6 +344,8 @@ export interface ElectronApi {
|
|||||||
setSessionPinned(input: SetSessionPinnedInput): Promise<WorkspaceState>;
|
setSessionPinned(input: SetSessionPinnedInput): Promise<WorkspaceState>;
|
||||||
setSessionArchived(input: SetSessionArchivedInput): Promise<WorkspaceState>;
|
setSessionArchived(input: SetSessionArchivedInput): Promise<WorkspaceState>;
|
||||||
deleteSession(input: DeleteSessionInput): Promise<WorkspaceState>;
|
deleteSession(input: DeleteSessionInput): Promise<WorkspaceState>;
|
||||||
|
batchSetSessionsArchived(input: BatchSetSessionsArchivedInput): Promise<WorkspaceState>;
|
||||||
|
batchDeleteSessions(input: BatchDeleteSessionsInput): Promise<WorkspaceState>;
|
||||||
regenerateSessionMessage(input: RegenerateSessionMessageInput): Promise<void>;
|
regenerateSessionMessage(input: RegenerateSessionMessageInput): Promise<void>;
|
||||||
editAndResendSessionMessage(input: EditAndResendSessionMessageInput): Promise<void>;
|
editAndResendSessionMessage(input: EditAndResendSessionMessageInput): Promise<void>;
|
||||||
sendSessionMessage(input: SendSessionMessageInput): Promise<void>;
|
sendSessionMessage(input: SendSessionMessageInput): Promise<void>;
|
||||||
@@ -351,6 +365,7 @@ export interface ElectronApi {
|
|||||||
setNotificationsEnabled(enabled: boolean): Promise<WorkspaceState>;
|
setNotificationsEnabled(enabled: boolean): Promise<WorkspaceState>;
|
||||||
setMinimizeToTray(enabled: boolean): Promise<WorkspaceState>;
|
setMinimizeToTray(enabled: boolean): Promise<WorkspaceState>;
|
||||||
setGitAutoRefreshEnabled(enabled: boolean): Promise<WorkspaceState>;
|
setGitAutoRefreshEnabled(enabled: boolean): Promise<WorkspaceState>;
|
||||||
|
setOpenTelemetry(settings: OpenTelemetrySettings): Promise<WorkspaceState>;
|
||||||
checkForUpdates(): Promise<UpdateStatus>;
|
checkForUpdates(): Promise<UpdateStatus>;
|
||||||
installUpdate(): Promise<void>;
|
installUpdate(): Promise<void>;
|
||||||
describeTerminal(): Promise<TerminalSnapshot | undefined>;
|
describeTerminal(): Promise<TerminalSnapshot | undefined>;
|
||||||
@@ -381,9 +396,42 @@ export interface ElectronApi {
|
|||||||
onSessionEvent(listener: (event: SessionEventRecord) => void): () => void;
|
onSessionEvent(listener: (event: SessionEventRecord) => void): () => void;
|
||||||
onUpdateStatus(listener: (status: UpdateStatus) => void): () => void;
|
onUpdateStatus(listener: (status: UpdateStatus) => void): () => void;
|
||||||
onTrayCreateScratchpad(listener: () => void): () => void;
|
onTrayCreateScratchpad(listener: () => void): () => void;
|
||||||
|
getQuickPromptSettings(): Promise<QuickPromptSettings>;
|
||||||
|
setQuickPromptSettings(settings: Partial<QuickPromptSettings>): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RendererSelectionState {
|
export interface RendererSelectionState {
|
||||||
selectedProject?: ProjectRecord;
|
selectedProject?: ProjectRecord;
|
||||||
selectedWorkflow?: WorkflowDefinition;
|
selectedWorkflow?: WorkflowDefinition;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Quick Prompt contracts ---
|
||||||
|
|
||||||
|
export interface QuickPromptSendInput {
|
||||||
|
content: string;
|
||||||
|
model?: string;
|
||||||
|
reasoningEffort?: ReasoningEffort;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QuickPromptSessionInfo {
|
||||||
|
sessionId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QuickPromptCapabilities {
|
||||||
|
models: ReadonlyArray<ModelDefinition>;
|
||||||
|
defaultModel?: string;
|
||||||
|
defaultReasoningEffort?: ReasoningEffort;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QuickPromptElectronApi {
|
||||||
|
send(input: QuickPromptSendInput): Promise<QuickPromptSessionInfo>;
|
||||||
|
discard(): Promise<void>;
|
||||||
|
close(): Promise<void>;
|
||||||
|
continueInAryx(): Promise<void>;
|
||||||
|
cancelTurn(): Promise<void>;
|
||||||
|
getCapabilities(): Promise<QuickPromptCapabilities>;
|
||||||
|
setSettings(settings: Partial<QuickPromptSettings>): Promise<void>;
|
||||||
|
onSessionEvent(listener: (event: SessionEventRecord) => void): () => void;
|
||||||
|
onShow(listener: (theme: string) => void): () => void;
|
||||||
|
onHide(listener: () => void): () => void;
|
||||||
|
}
|
||||||
|
|||||||
@@ -518,6 +518,7 @@ export interface ApprovalRequestedEvent {
|
|||||||
agentName?: string;
|
agentName?: string;
|
||||||
toolName?: string;
|
toolName?: string;
|
||||||
permissionKind?: string;
|
permissionKind?: string;
|
||||||
|
approvalToolKey?: string;
|
||||||
title: string;
|
title: string;
|
||||||
detail?: string;
|
detail?: string;
|
||||||
permissionDetail?: PermissionDetail;
|
permissionDetail?: PermissionDetail;
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ export interface PendingApprovalRecord {
|
|||||||
agentName?: string;
|
agentName?: string;
|
||||||
toolName?: string;
|
toolName?: string;
|
||||||
permissionKind?: string;
|
permissionKind?: string;
|
||||||
|
approvalToolKey?: string;
|
||||||
title: string;
|
title: string;
|
||||||
detail?: string;
|
detail?: string;
|
||||||
messages?: PendingApprovalMessageRecord[];
|
messages?: PendingApprovalMessageRecord[];
|
||||||
@@ -215,6 +216,22 @@ export function resolveApprovalToolKey(
|
|||||||
return toolName;
|
return toolName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the canonical approval key for a pending approval.
|
||||||
|
*
|
||||||
|
* Prefers the explicit `approvalToolKey` supplied by the sidecar. Falls back to
|
||||||
|
* re-deriving the key from `toolName` and `permissionKind` to support legacy
|
||||||
|
* records persisted before the sidecar contract change.
|
||||||
|
*/
|
||||||
|
export function getPendingApprovalToolKey(
|
||||||
|
record: Pick<PendingApprovalRecord, 'approvalToolKey' | 'toolName' | 'permissionKind'>,
|
||||||
|
): string | undefined {
|
||||||
|
return (
|
||||||
|
normalizeOptionalString(record.approvalToolKey)
|
||||||
|
?? resolveApprovalToolKey(record.toolName, record.permissionKind)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function approvalPolicyAutoApprovesTool(
|
export function approvalPolicyAutoApprovesTool(
|
||||||
policy: ApprovalPolicy | undefined,
|
policy: ApprovalPolicy | undefined,
|
||||||
toolName?: string,
|
toolName?: string,
|
||||||
@@ -312,6 +329,7 @@ export function normalizePendingApproval(
|
|||||||
agentName: normalizeOptionalString(approval?.agentName),
|
agentName: normalizeOptionalString(approval?.agentName),
|
||||||
toolName: normalizeOptionalString(approval?.toolName),
|
toolName: normalizeOptionalString(approval?.toolName),
|
||||||
permissionKind: normalizeOptionalString(approval?.permissionKind),
|
permissionKind: normalizeOptionalString(approval?.permissionKind),
|
||||||
|
approvalToolKey: normalizeOptionalString(approval?.approvalToolKey),
|
||||||
title,
|
title,
|
||||||
detail: normalizeOptionalString(approval?.detail),
|
detail: normalizeOptionalString(approval?.detail),
|
||||||
messages: normalizePendingApprovalMessages(approval?.messages),
|
messages: normalizePendingApprovalMessages(approval?.messages),
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ export type SessionEventKind =
|
|||||||
| 'session-compaction'
|
| 'session-compaction'
|
||||||
| 'pending-messages-modified'
|
| 'pending-messages-modified'
|
||||||
| 'assistant-usage'
|
| 'assistant-usage'
|
||||||
|
| 'assistant-intent'
|
||||||
|
| 'reasoning-delta'
|
||||||
| 'workflow-diagnostic';
|
| 'workflow-diagnostic';
|
||||||
|
|
||||||
export type SubagentEventKind = 'started' | 'completed' | 'failed' | 'selected' | 'deselected';
|
export type SubagentEventKind = 'started' | 'completed' | 'failed' | 'selected' | 'deselected';
|
||||||
@@ -102,6 +104,13 @@ export interface SessionEventRecord {
|
|||||||
usageTotalNanoAiu?: number;
|
usageTotalNanoAiu?: number;
|
||||||
usageQuotaSnapshots?: Record<string, QuotaSnapshot>;
|
usageQuotaSnapshots?: Record<string, QuotaSnapshot>;
|
||||||
|
|
||||||
|
// Assistant intent fields
|
||||||
|
intent?: string;
|
||||||
|
|
||||||
|
// Reasoning delta fields
|
||||||
|
reasoningId?: string;
|
||||||
|
reasoningDelta?: string;
|
||||||
|
|
||||||
// Workflow diagnostic fields
|
// Workflow diagnostic fields
|
||||||
diagnosticSeverity?: WorkflowDiagnosticSeverity;
|
diagnosticSeverity?: WorkflowDiagnosticSeverity;
|
||||||
diagnosticKind?: WorkflowDiagnosticKind;
|
diagnosticKind?: WorkflowDiagnosticKind;
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ export interface SessionRecord {
|
|||||||
pendingPlanReview?: PendingPlanReviewRecord;
|
pendingPlanReview?: PendingPlanReviewRecord;
|
||||||
pendingMcpAuth?: PendingMcpAuthRecord;
|
pendingMcpAuth?: PendingMcpAuthRecord;
|
||||||
runs: SessionRunRecord[];
|
runs: SessionRunRecord[];
|
||||||
|
currentIntent?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeOptionalString(value?: string): string | undefined {
|
function normalizeOptionalString(value?: string): string | undefined {
|
||||||
|
|||||||
@@ -61,6 +61,27 @@ export interface WorkspaceToolingSettings {
|
|||||||
|
|
||||||
export type AppearanceTheme = 'dark' | 'light' | 'system';
|
export type AppearanceTheme = 'dark' | 'light' | 'system';
|
||||||
|
|
||||||
|
export interface QuickPromptSettings {
|
||||||
|
enabled: boolean;
|
||||||
|
hotkey: string;
|
||||||
|
defaultModel?: string;
|
||||||
|
defaultReasoningEffort?: 'low' | 'medium' | 'high' | 'xhigh';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OpenTelemetrySettings {
|
||||||
|
enabled: boolean;
|
||||||
|
endpoint: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_OTEL_ENDPOINT = 'http://localhost:4317';
|
||||||
|
|
||||||
|
export function createDefaultQuickPromptSettings(): QuickPromptSettings {
|
||||||
|
return {
|
||||||
|
enabled: true,
|
||||||
|
hotkey: 'Alt+Shift+C',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export interface WorkspaceSettings {
|
export interface WorkspaceSettings {
|
||||||
theme: AppearanceTheme;
|
theme: AppearanceTheme;
|
||||||
tooling: WorkspaceToolingSettings;
|
tooling: WorkspaceToolingSettings;
|
||||||
@@ -70,6 +91,8 @@ export interface WorkspaceSettings {
|
|||||||
notificationsEnabled?: boolean;
|
notificationsEnabled?: boolean;
|
||||||
minimizeToTray?: boolean;
|
minimizeToTray?: boolean;
|
||||||
gitAutoRefreshEnabled?: boolean;
|
gitAutoRefreshEnabled?: boolean;
|
||||||
|
quickPrompt?: QuickPromptSettings;
|
||||||
|
openTelemetry?: OpenTelemetrySettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SessionToolingSelection {
|
export interface SessionToolingSelection {
|
||||||
@@ -215,6 +238,17 @@ export function normalizeWorkspaceSettings(settings?: Partial<WorkspaceSettings>
|
|||||||
...(settings?.notificationsEnabled !== undefined ? { notificationsEnabled: settings.notificationsEnabled } : {}),
|
...(settings?.notificationsEnabled !== undefined ? { notificationsEnabled: settings.notificationsEnabled } : {}),
|
||||||
...(settings?.minimizeToTray !== undefined ? { minimizeToTray: settings.minimizeToTray } : {}),
|
...(settings?.minimizeToTray !== undefined ? { minimizeToTray: settings.minimizeToTray } : {}),
|
||||||
...(settings?.gitAutoRefreshEnabled !== undefined ? { gitAutoRefreshEnabled: settings.gitAutoRefreshEnabled } : {}),
|
...(settings?.gitAutoRefreshEnabled !== undefined ? { gitAutoRefreshEnabled: settings.gitAutoRefreshEnabled } : {}),
|
||||||
|
...(settings?.quickPrompt !== undefined ? { quickPrompt: settings.quickPrompt } : {}),
|
||||||
|
...(settings?.openTelemetry !== undefined ? { openTelemetry: normalizeOpenTelemetrySettings(settings.openTelemetry) } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeOpenTelemetrySettings(settings?: Partial<OpenTelemetrySettings>): OpenTelemetrySettings {
|
||||||
|
return {
|
||||||
|
enabled: settings?.enabled === true,
|
||||||
|
endpoint: typeof settings?.endpoint === 'string' && settings.endpoint.trim() !== ''
|
||||||
|
? settings.endpoint.trim()
|
||||||
|
: DEFAULT_OTEL_ENDPOINT,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,52 +5,6 @@ function tokenize(value: string): string[] {
|
|||||||
.filter((token) => token.length > 0);
|
.filter((token) => token.length > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
function shouldInsertNewlineBoundary(current: string, incoming: string): boolean {
|
|
||||||
if (current.endsWith('\n')) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return /^(?:#{1,6}\s|[-*+]\s|\d+\.\s|>\s|```)/.test(incoming.trimStart());
|
|
||||||
}
|
|
||||||
|
|
||||||
function shouldInsertSpaceBoundary(current: string, incoming: string): boolean {
|
|
||||||
const lastChar = current.at(-1);
|
|
||||||
const firstChar = incoming[0];
|
|
||||||
if (!lastChar || !firstChar) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (/\s/.test(lastChar) || /\s/.test(firstChar) || /[([{/"'`]/.test(lastChar)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (/^[.,!?;:%)\]}]/.test(firstChar)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (/^[*_`~\[]/.test(firstChar) || /^[A-Z0-9]/.test(firstChar)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentTokens = tokenize(current);
|
|
||||||
const incomingTokens = tokenize(incoming);
|
|
||||||
const firstIncomingToken = incomingTokens[0] ?? '';
|
|
||||||
|
|
||||||
return currentTokens.length >= 2 && incomingTokens.length >= 2 && firstIncomingToken.length >= 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
function appendWithNaturalBoundary(current: string, incoming: string): string {
|
|
||||||
if (shouldInsertNewlineBoundary(current, incoming)) {
|
|
||||||
return `${current}\n${incoming}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shouldInsertSpaceBoundary(current, incoming)) {
|
|
||||||
return `${current} ${incoming}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return current + incoming;
|
|
||||||
}
|
|
||||||
|
|
||||||
function computeSuffixPrefixOverlap(current: string, incoming: string): number {
|
function computeSuffixPrefixOverlap(current: string, incoming: string): number {
|
||||||
const maxOverlap = Math.min(current.length, incoming.length);
|
const maxOverlap = Math.min(current.length, incoming.length);
|
||||||
for (let length = maxOverlap; length > 0; length -= 1) {
|
for (let length = maxOverlap; length > 0; length -= 1) {
|
||||||
@@ -109,5 +63,5 @@ export function mergeStreamingText(current: string, incoming: string): string {
|
|||||||
return incoming;
|
return incoming;
|
||||||
}
|
}
|
||||||
|
|
||||||
return appendWithNaturalBoundary(current, incoming);
|
return current + incoming;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,4 +37,46 @@ describe('createSidecarEnvironment', () => {
|
|||||||
HTTPS_PROXY: 'http://proxy.local:8080',
|
HTTPS_PROXY: 'http://proxy.local:8080',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('injects OTEL_EXPORTER_OTLP_ENDPOINT when OpenTelemetry is enabled', () => {
|
||||||
|
expect(
|
||||||
|
createSidecarEnvironment(
|
||||||
|
{ PATH: 'C:\\tools' },
|
||||||
|
{ enabled: true, endpoint: 'http://localhost:4317' },
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
PATH: 'C:\\tools',
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: 'http://localhost:4317',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not inject OTEL_EXPORTER_OTLP_ENDPOINT when OpenTelemetry is disabled', () => {
|
||||||
|
expect(
|
||||||
|
createSidecarEnvironment(
|
||||||
|
{ PATH: 'C:\\tools' },
|
||||||
|
{ enabled: false, endpoint: 'http://localhost:4317' },
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
PATH: 'C:\\tools',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not inject OTEL_EXPORTER_OTLP_ENDPOINT when settings are undefined', () => {
|
||||||
|
expect(
|
||||||
|
createSidecarEnvironment({ PATH: 'C:\\tools' }),
|
||||||
|
).toEqual({
|
||||||
|
PATH: 'C:\\tools',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not inject OTEL_EXPORTER_OTLP_ENDPOINT when endpoint is empty', () => {
|
||||||
|
expect(
|
||||||
|
createSidecarEnvironment(
|
||||||
|
{ PATH: 'C:\\tools' },
|
||||||
|
{ enabled: true, endpoint: '' },
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
PATH: 'C:\\tools',
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test the core selection logic extracted from useSessionSelection.
|
||||||
|
* Since the hook is thin state wrapper, we test the pure logic operations directly.
|
||||||
|
*/
|
||||||
|
|
||||||
|
describe('session selection logic', () => {
|
||||||
|
// Helpers that mirror the hook's internal logic
|
||||||
|
function toggle(selected: Set<string>, sessionId: string): Set<string> {
|
||||||
|
const next = new Set(selected);
|
||||||
|
if (next.has(sessionId)) next.delete(sessionId);
|
||||||
|
else next.add(sessionId);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rangeSelect(
|
||||||
|
selected: Set<string>,
|
||||||
|
anchor: string | null,
|
||||||
|
target: string,
|
||||||
|
allVisibleIds: string[],
|
||||||
|
): Set<string> {
|
||||||
|
if (!anchor) return new Set([target]);
|
||||||
|
const anchorIdx = allVisibleIds.indexOf(anchor);
|
||||||
|
const targetIdx = allVisibleIds.indexOf(target);
|
||||||
|
if (anchorIdx === -1 || targetIdx === -1) return selected;
|
||||||
|
const start = Math.min(anchorIdx, targetIdx);
|
||||||
|
const end = Math.max(anchorIdx, targetIdx);
|
||||||
|
const next = new Set(selected);
|
||||||
|
for (const id of allVisibleIds.slice(start, end + 1)) next.add(id);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAll(sessionIds: string[]): Set<string> {
|
||||||
|
return new Set(sessionIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
function filterSelectable(sessions: { id: string; status: string }[]): string[] {
|
||||||
|
return sessions.filter((s) => s.status !== 'running').map((s) => s.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('toggle', () => {
|
||||||
|
test('adds a session to empty selection', () => {
|
||||||
|
const result = toggle(new Set(), 'a');
|
||||||
|
expect(result.has('a')).toBe(true);
|
||||||
|
expect(result.size).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('removes an already-selected session', () => {
|
||||||
|
const result = toggle(new Set(['a', 'b']), 'a');
|
||||||
|
expect(result.has('a')).toBe(false);
|
||||||
|
expect(result.has('b')).toBe(true);
|
||||||
|
expect(result.size).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('adds to existing selection', () => {
|
||||||
|
const result = toggle(new Set(['a']), 'b');
|
||||||
|
expect(result.has('a')).toBe(true);
|
||||||
|
expect(result.has('b')).toBe(true);
|
||||||
|
expect(result.size).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('rangeSelect', () => {
|
||||||
|
const visible = ['a', 'b', 'c', 'd', 'e'];
|
||||||
|
|
||||||
|
test('selects range from anchor to target (forward)', () => {
|
||||||
|
const result = rangeSelect(new Set(['b']), 'b', 'd', visible);
|
||||||
|
expect([...result].sort()).toEqual(['b', 'c', 'd']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('selects range from anchor to target (backward)', () => {
|
||||||
|
const result = rangeSelect(new Set(['d']), 'd', 'b', visible);
|
||||||
|
expect([...result].sort()).toEqual(['b', 'c', 'd']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('preserves existing selections outside the range', () => {
|
||||||
|
const result = rangeSelect(new Set(['a', 'c']), 'c', 'e', visible);
|
||||||
|
expect([...result].sort()).toEqual(['a', 'c', 'd', 'e']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to single selection when no anchor', () => {
|
||||||
|
const result = rangeSelect(new Set(), null, 'c', visible);
|
||||||
|
expect([...result]).toEqual(['c']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no-ops when anchor is not in visible list', () => {
|
||||||
|
const result = rangeSelect(new Set(['x']), 'x', 'c', visible);
|
||||||
|
expect([...result]).toEqual(['x']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no-ops when target is not in visible list', () => {
|
||||||
|
const result = rangeSelect(new Set(['a']), 'a', 'z', visible);
|
||||||
|
expect([...result]).toEqual(['a']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('selectAll', () => {
|
||||||
|
test('selects all provided IDs', () => {
|
||||||
|
const result = selectAll(['a', 'b', 'c']);
|
||||||
|
expect(result.size).toBe(3);
|
||||||
|
expect(result.has('a')).toBe(true);
|
||||||
|
expect(result.has('b')).toBe(true);
|
||||||
|
expect(result.has('c')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('handles empty list', () => {
|
||||||
|
const result = selectAll([]);
|
||||||
|
expect(result.size).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('filterSelectable (running session exclusion)', () => {
|
||||||
|
test('excludes running sessions', () => {
|
||||||
|
const sessions = [
|
||||||
|
{ id: 'a', status: 'idle' },
|
||||||
|
{ id: 'b', status: 'running' },
|
||||||
|
{ id: 'c', status: 'error' },
|
||||||
|
{ id: 'd', status: 'running' },
|
||||||
|
];
|
||||||
|
const result = filterSelectable(sessions);
|
||||||
|
expect(result).toEqual(['a', 'c']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('includes all when none are running', () => {
|
||||||
|
const sessions = [
|
||||||
|
{ id: 'a', status: 'idle' },
|
||||||
|
{ id: 'b', status: 'idle' },
|
||||||
|
];
|
||||||
|
const result = filterSelectable(sessions);
|
||||||
|
expect(result).toEqual(['a', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns empty when all are running', () => {
|
||||||
|
const sessions = [
|
||||||
|
{ id: 'a', status: 'running' },
|
||||||
|
{ id: 'b', status: 'running' },
|
||||||
|
];
|
||||||
|
const result = filterSelectable(sessions);
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('enter and exit selection mode', () => {
|
||||||
|
test('entering with an initial ID creates a set with that ID', () => {
|
||||||
|
const selected = new Set(['initial']);
|
||||||
|
expect(selected.size).toBe(1);
|
||||||
|
expect(selected.has('initial')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('exiting clears all selections', () => {
|
||||||
|
const selected = new Set(['a', 'b', 'c']);
|
||||||
|
const cleared = new Set<string>();
|
||||||
|
expect(cleared.size).toBe(0);
|
||||||
|
expect(selected.size).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('batch archive determination', () => {
|
||||||
|
test('allSelectedArchived is true when all selected are archived', () => {
|
||||||
|
const sessions = [
|
||||||
|
{ id: 'a', isArchived: true },
|
||||||
|
{ id: 'b', isArchived: true },
|
||||||
|
{ id: 'c', isArchived: false },
|
||||||
|
];
|
||||||
|
const selected = new Set(['a', 'b']);
|
||||||
|
const allArchived = [...selected].every((id) => {
|
||||||
|
const s = sessions.find((s) => s.id === id);
|
||||||
|
return s?.isArchived;
|
||||||
|
});
|
||||||
|
expect(allArchived).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('allSelectedArchived is false when any selected is not archived', () => {
|
||||||
|
const sessions = [
|
||||||
|
{ id: 'a', isArchived: true },
|
||||||
|
{ id: 'b', isArchived: false },
|
||||||
|
];
|
||||||
|
const selected = new Set(['a', 'b']);
|
||||||
|
const allArchived = [...selected].every((id) => {
|
||||||
|
const s = sessions.find((s) => s.id === id);
|
||||||
|
return s?.isArchived;
|
||||||
|
});
|
||||||
|
expect(allArchived).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -351,4 +351,355 @@ describe('session workspace helpers', () => {
|
|||||||
|
|
||||||
expect(result).toBe(workspace);
|
expect(result).toBe(workspace);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('uses resolved content from main process and falls back to simple append', () => {
|
||||||
|
// When content is present (main process resolved it), use it directly
|
||||||
|
const first = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
authorName: 'Agent',
|
||||||
|
contentDelta: 'Hello',
|
||||||
|
content: 'Hello',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
// Main process sends full resolved content on every delta
|
||||||
|
const second = applySessionEventWorkspace(first, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
authorName: 'Agent',
|
||||||
|
contentDelta: ' world',
|
||||||
|
content: 'Hello world',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(second?.sessions[0].messages[0].content).toBe('Hello world');
|
||||||
|
|
||||||
|
// Backward compat: if content is missing, simple append of contentDelta
|
||||||
|
const fallback = applySessionEventWorkspace(second, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:03.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
authorName: 'Agent',
|
||||||
|
contentDelta: '!',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(fallback?.sessions[0].messages[0].content).toBe('Hello world!');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sets currentIntent from assistant-intent events', () => {
|
||||||
|
const workspace = createWorkspace();
|
||||||
|
const updated = applySessionEventWorkspace(workspace, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'assistant-intent',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
intent: 'Exploring codebase',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(updated?.sessions[0].currentIntent).toBe('Exploring codebase');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clears currentIntent when session transitions to idle', () => {
|
||||||
|
let workspace = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'status',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
status: 'running',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
workspace = applySessionEventWorkspace(workspace, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'assistant-intent',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
intent: 'Writing tests',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(workspace?.sessions[0].currentIntent).toBe('Writing tests');
|
||||||
|
|
||||||
|
workspace = applySessionEventWorkspace(workspace, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'status',
|
||||||
|
occurredAt: '2026-03-23T00:00:03.000Z',
|
||||||
|
status: 'idle',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(workspace?.sessions[0].currentIntent).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ignores duplicate assistant-intent events', () => {
|
||||||
|
const workspace = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'assistant-intent',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
intent: 'Exploring codebase',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
const duplicate = applySessionEventWorkspace(workspace, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'assistant-intent',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
intent: 'Exploring codebase',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(duplicate).toBe(workspace);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('preserves currentIntent when status changes to running', () => {
|
||||||
|
let workspace = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'assistant-intent',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
intent: 'Analyzing code',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
workspace = applySessionEventWorkspace(workspace, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'status',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
status: 'running',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(workspace?.sessions[0].currentIntent).toBe('Analyzing code');
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ── Streaming regression tests ──────────────────────────── */
|
||||||
|
|
||||||
|
test('thinking-to-response transition: reclassified message stays hidden, new message becomes final', () => {
|
||||||
|
// Step 1: first message streams as normal assistant content
|
||||||
|
let ws = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
authorName: 'Agent',
|
||||||
|
contentDelta: 'Let me look into this...',
|
||||||
|
content: 'Let me look into this...',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
// Step 2: reclassified as thinking (the agent decided to search first)
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-reclassified',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
messageKind: 'thinking',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(ws?.sessions[0].messages[0]).toMatchObject({
|
||||||
|
id: 'assistant-1',
|
||||||
|
messageKind: 'thinking',
|
||||||
|
pending: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Step 3: a new actual response message starts streaming
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:03.000Z',
|
||||||
|
messageId: 'assistant-2',
|
||||||
|
authorName: 'Agent',
|
||||||
|
contentDelta: 'Here is the answer.',
|
||||||
|
content: 'Here is the answer.',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
// The thinking message should be auto-completed, new one is pending
|
||||||
|
expect(ws?.sessions[0].messages).toHaveLength(2);
|
||||||
|
expect(ws?.sessions[0].messages[0]).toMatchObject({
|
||||||
|
id: 'assistant-1',
|
||||||
|
messageKind: 'thinking',
|
||||||
|
pending: false,
|
||||||
|
});
|
||||||
|
expect(ws?.sessions[0].messages[1]).toMatchObject({
|
||||||
|
id: 'assistant-2',
|
||||||
|
content: 'Here is the answer.',
|
||||||
|
pending: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('concurrent multi-message streaming keeps messages independent', () => {
|
||||||
|
// Two different assistant messages stream interleaved (e.g. multi-agent)
|
||||||
|
let ws = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
messageId: 'msg-agent-a',
|
||||||
|
authorName: 'Architect',
|
||||||
|
contentDelta: 'Design: ',
|
||||||
|
content: 'Design: ',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
messageId: 'msg-agent-a',
|
||||||
|
authorName: 'Architect',
|
||||||
|
contentDelta: 'Use modules.',
|
||||||
|
content: 'Design: Use modules.',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
// Complete one message, verify others are unaffected
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-complete',
|
||||||
|
occurredAt: '2026-03-23T00:00:04.000Z',
|
||||||
|
messageId: 'msg-agent-a',
|
||||||
|
authorName: 'Architect',
|
||||||
|
content: 'Design: Use modules.',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(ws?.sessions[0].messages).toHaveLength(1);
|
||||||
|
expect(ws?.sessions[0].messages[0]).toMatchObject({
|
||||||
|
id: 'msg-agent-a',
|
||||||
|
content: 'Design: Use modules.',
|
||||||
|
pending: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('run-updated replaces existing run by id and handles new runs', () => {
|
||||||
|
const runV1: SessionRunRecord = {
|
||||||
|
id: 'run-1',
|
||||||
|
requestId: 'turn-1',
|
||||||
|
projectId: 'project-1',
|
||||||
|
projectPath: 'C:\\workspace',
|
||||||
|
workspaceKind: 'project',
|
||||||
|
workflowId: 'workflow-1',
|
||||||
|
workflowName: 'Review',
|
||||||
|
workflowMode: 'sequential',
|
||||||
|
triggerMessageId: 'msg-user-1',
|
||||||
|
startedAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
status: 'running',
|
||||||
|
agents: [],
|
||||||
|
events: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
let ws = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'run-updated',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
run: runV1,
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(ws?.sessions[0].runs).toHaveLength(1);
|
||||||
|
expect(ws?.sessions[0].runs[0].status).toBe('running');
|
||||||
|
|
||||||
|
// Run updated with new status and events
|
||||||
|
const runV2: SessionRunRecord = {
|
||||||
|
...runV1,
|
||||||
|
status: 'completed',
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
id: 'evt-1',
|
||||||
|
kind: 'run-started',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
status: 'completed',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'run-updated',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
run: runV2,
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
// Should replace, not duplicate
|
||||||
|
expect(ws?.sessions[0].runs).toHaveLength(1);
|
||||||
|
expect(ws?.sessions[0].runs[0].status).toBe('completed');
|
||||||
|
expect(ws?.sessions[0].runs[0].events).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('full turn lifecycle: intent → deltas → complete → idle clears intent', () => {
|
||||||
|
let ws = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'status',
|
||||||
|
occurredAt: '2026-03-23T00:00:00.000Z',
|
||||||
|
status: 'running',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'assistant-intent',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
intent: 'Exploring codebase',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
authorName: 'Agent',
|
||||||
|
contentDelta: 'Found the issue.',
|
||||||
|
content: 'Found the issue.',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
// Intent survives during message streaming
|
||||||
|
expect(ws?.sessions[0].currentIntent).toBe('Exploring codebase');
|
||||||
|
expect(ws?.sessions[0].messages[0].pending).toBe(true);
|
||||||
|
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'assistant-intent',
|
||||||
|
occurredAt: '2026-03-23T00:00:03.000Z',
|
||||||
|
intent: 'Fixing bug',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(ws?.sessions[0].currentIntent).toBe('Fixing bug');
|
||||||
|
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-complete',
|
||||||
|
occurredAt: '2026-03-23T00:00:04.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
authorName: 'Agent',
|
||||||
|
content: 'Found the issue. Here is the fix.',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
// Intent still active until idle
|
||||||
|
expect(ws?.sessions[0].currentIntent).toBe('Fixing bug');
|
||||||
|
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'status',
|
||||||
|
occurredAt: '2026-03-23T00:00:05.000Z',
|
||||||
|
status: 'idle',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(ws?.sessions[0].currentIntent).toBeUndefined();
|
||||||
|
expect(ws?.sessions[0].status).toBe('idle');
|
||||||
|
expect(ws?.sessions[0].messages[0].content).toBe('Found the issue. Here is the fix.');
|
||||||
|
expect(ws?.sessions[0].messages[0].pending).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('message-complete content overrides previously streamed content', () => {
|
||||||
|
let ws = applySessionEventWorkspace(createWorkspace(), {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-delta',
|
||||||
|
occurredAt: '2026-03-23T00:00:01.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
authorName: 'Agent',
|
||||||
|
contentDelta: 'Partial draft...',
|
||||||
|
content: 'Partial draft...',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
// Backend sends final authoritative content on completion
|
||||||
|
ws = applySessionEventWorkspace(ws, {
|
||||||
|
sessionId: 'session-1',
|
||||||
|
kind: 'message-complete',
|
||||||
|
occurredAt: '2026-03-23T00:00:02.000Z',
|
||||||
|
messageId: 'assistant-1',
|
||||||
|
authorName: 'Agent',
|
||||||
|
content: 'The complete, polished final answer with all details.',
|
||||||
|
} satisfies SessionEventRecord);
|
||||||
|
|
||||||
|
expect(ws?.sessions[0].messages[0]).toMatchObject({
|
||||||
|
content: 'The complete, polished final answer with all details.',
|
||||||
|
pending: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
|
||||||
|
import { formatElapsedMs } from '@renderer/hooks/useElapsedTimer';
|
||||||
|
|
||||||
|
describe('formatElapsedMs', () => {
|
||||||
|
test('formats sub-second durations as 0s', () => {
|
||||||
|
expect(formatElapsedMs(0)).toBe('0s');
|
||||||
|
expect(formatElapsedMs(500)).toBe('0s');
|
||||||
|
expect(formatElapsedMs(999)).toBe('0s');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('formats seconds under a minute', () => {
|
||||||
|
expect(formatElapsedMs(1000)).toBe('1s');
|
||||||
|
expect(formatElapsedMs(5_000)).toBe('5s');
|
||||||
|
expect(formatElapsedMs(59_000)).toBe('59s');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('formats minutes with remaining seconds', () => {
|
||||||
|
expect(formatElapsedMs(60_000)).toBe('1m');
|
||||||
|
expect(formatElapsedMs(90_000)).toBe('1m 30s');
|
||||||
|
expect(formatElapsedMs(125_000)).toBe('2m 5s');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('formats exact minutes without trailing seconds', () => {
|
||||||
|
expect(formatElapsedMs(120_000)).toBe('2m');
|
||||||
|
expect(formatElapsedMs(300_000)).toBe('5m');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clamps negative durations to 0s', () => {
|
||||||
|
expect(formatElapsedMs(-5000)).toBe('0s');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('formats large durations correctly', () => {
|
||||||
|
// 2 hours, 30 minutes, 15 seconds = 9015s = 150m 15s
|
||||||
|
expect(formatElapsedMs(9_015_000)).toBe('150m 15s');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
|
||||||
|
import {
|
||||||
|
aspireDashboardContainerName,
|
||||||
|
aspireDashboardImage,
|
||||||
|
aspireDashboardUrls,
|
||||||
|
createAspireDashboardRunArgs,
|
||||||
|
createOpenTelemetryEnvironment,
|
||||||
|
} from '../../scripts/aspireDashboard';
|
||||||
|
|
||||||
|
describe('aspire dashboard helpers', () => {
|
||||||
|
test('creates the official standalone Docker command with mapped OTLP ports', () => {
|
||||||
|
expect(createAspireDashboardRunArgs()).toEqual([
|
||||||
|
'run',
|
||||||
|
'--rm',
|
||||||
|
'-d',
|
||||||
|
'--name',
|
||||||
|
aspireDashboardContainerName,
|
||||||
|
'-p',
|
||||||
|
'18888:18888',
|
||||||
|
'-p',
|
||||||
|
'4317:18889',
|
||||||
|
'-p',
|
||||||
|
'4318:18890',
|
||||||
|
'-e',
|
||||||
|
'ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS=true',
|
||||||
|
aspireDashboardImage,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('injects OTLP exporter settings for local Aspire development', () => {
|
||||||
|
expect(
|
||||||
|
createOpenTelemetryEnvironment(
|
||||||
|
{
|
||||||
|
PATH: 'C:\\tools',
|
||||||
|
},
|
||||||
|
aspireDashboardUrls.otlpGrpc,
|
||||||
|
),
|
||||||
|
).toEqual({
|
||||||
|
PATH: 'C:\\tools',
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: aspireDashboardUrls.otlpGrpc,
|
||||||
|
OTEL_EXPORTER_OTLP_PROTOCOL: 'grpc',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
|
||||||
|
import {
|
||||||
|
incrementVersion,
|
||||||
|
parseReleaseBump,
|
||||||
|
runReleaseWorkflow,
|
||||||
|
type GitCommandResult,
|
||||||
|
type ReleaseDependencies,
|
||||||
|
} from '../../scripts/release';
|
||||||
|
|
||||||
|
const testRepositoryRoot = resolve('/test-workspace/aryx');
|
||||||
|
const testPackageJsonPath = join(testRepositoryRoot, 'package.json');
|
||||||
|
|
||||||
|
function gitSuccess(stdout = '', stderr = ''): GitCommandResult {
|
||||||
|
return {
|
||||||
|
exitCode: 0,
|
||||||
|
stdout,
|
||||||
|
stderr,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function gitFailure(exitCode = 1, stdout = '', stderr = ''): GitCommandResult {
|
||||||
|
return {
|
||||||
|
exitCode,
|
||||||
|
stdout,
|
||||||
|
stderr,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createReleaseDependencies(options?: {
|
||||||
|
packageJsonText?: string;
|
||||||
|
gitResults?: GitCommandResult[];
|
||||||
|
}) {
|
||||||
|
let packageJsonText =
|
||||||
|
options?.packageJsonText ??
|
||||||
|
`{
|
||||||
|
"name": "aryx",
|
||||||
|
"version": "0.0.26"
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const gitResults = [...(options?.gitResults ?? [])];
|
||||||
|
const commands: string[][] = [];
|
||||||
|
const writes: Array<{ path: string; content: string }> = [];
|
||||||
|
const logs: string[] = [];
|
||||||
|
|
||||||
|
const dependencies: ReleaseDependencies = {
|
||||||
|
readText: async () => packageJsonText,
|
||||||
|
writeText: async (path, content) => {
|
||||||
|
packageJsonText = content;
|
||||||
|
writes.push({ path, content });
|
||||||
|
},
|
||||||
|
runGit: async (args) => {
|
||||||
|
commands.push(args);
|
||||||
|
const result = gitResults.shift();
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
throw new Error(`Unexpected git command: ${args.join(' ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
log: (message) => {
|
||||||
|
logs.push(message);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
dependencies,
|
||||||
|
commands,
|
||||||
|
writes,
|
||||||
|
logs,
|
||||||
|
getPackageJsonText: () => packageJsonText,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('release bump parsing', () => {
|
||||||
|
test('defaults to patch when no bump argument is provided', () => {
|
||||||
|
expect(parseReleaseBump()).toBe('patch');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects unsupported bump arguments', () => {
|
||||||
|
expect(() => parseReleaseBump('prerelease')).toThrow(
|
||||||
|
'Unsupported release bump "prerelease". Use patch, minor, or major.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('version incrementing', () => {
|
||||||
|
test('supports patch, minor, and major bumps', () => {
|
||||||
|
expect(incrementVersion('0.0.26', 'patch')).toBe('0.0.27');
|
||||||
|
expect(incrementVersion('0.0.26', 'minor')).toBe('0.1.0');
|
||||||
|
expect(incrementVersion('0.0.26', 'major')).toBe('1.0.0');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('release workflow', () => {
|
||||||
|
test('bumps package.json, commits, tags, and pushes the tracked branch', async () => {
|
||||||
|
const { dependencies, commands, writes, logs, getPackageJsonText } = createReleaseDependencies({
|
||||||
|
gitResults: [
|
||||||
|
gitSuccess(),
|
||||||
|
gitSuccess('main\n'),
|
||||||
|
gitSuccess('origin\n'),
|
||||||
|
gitSuccess('refs/heads/main\n'),
|
||||||
|
gitSuccess(),
|
||||||
|
gitSuccess(),
|
||||||
|
gitSuccess(),
|
||||||
|
gitSuccess(),
|
||||||
|
gitSuccess(),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await runReleaseWorkflow(
|
||||||
|
{
|
||||||
|
repositoryRoot: testRepositoryRoot,
|
||||||
|
packageJsonPath: testPackageJsonPath,
|
||||||
|
},
|
||||||
|
dependencies,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
bump: 'patch',
|
||||||
|
currentVersion: '0.0.26',
|
||||||
|
nextVersion: '0.0.27',
|
||||||
|
tagName: 'v0.0.27',
|
||||||
|
localBranch: 'main',
|
||||||
|
remote: 'origin',
|
||||||
|
upstreamBranch: 'main',
|
||||||
|
});
|
||||||
|
expect(writes).toHaveLength(1);
|
||||||
|
expect(getPackageJsonText()).toContain('"version": "0.0.27"');
|
||||||
|
expect(commands).toEqual([
|
||||||
|
['status', '--porcelain'],
|
||||||
|
['symbolic-ref', '--quiet', '--short', 'HEAD'],
|
||||||
|
['config', '--get', 'branch.main.remote'],
|
||||||
|
['config', '--get', 'branch.main.merge'],
|
||||||
|
['tag', '--list', 'v0.0.27'],
|
||||||
|
['add', 'package.json'],
|
||||||
|
['commit', '-m', 'chore: release v0.0.27'],
|
||||||
|
['tag', '-a', 'v0.0.27', '-m', 'Release v0.0.27'],
|
||||||
|
['push', '--follow-tags', 'origin', 'HEAD:main'],
|
||||||
|
]);
|
||||||
|
expect(logs).toEqual(['Released v0.0.27 from main to origin/main.']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fails before writing package.json when the worktree is dirty', async () => {
|
||||||
|
const { dependencies, commands, writes } = createReleaseDependencies({
|
||||||
|
gitResults: [gitSuccess(' M README.md\n')],
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
runReleaseWorkflow(
|
||||||
|
{
|
||||||
|
repositoryRoot: testRepositoryRoot,
|
||||||
|
packageJsonPath: testPackageJsonPath,
|
||||||
|
},
|
||||||
|
dependencies,
|
||||||
|
),
|
||||||
|
).rejects.toThrow('Release requires a clean git worktree. Commit, stash, or discard changes first.');
|
||||||
|
|
||||||
|
expect(writes).toHaveLength(0);
|
||||||
|
expect(commands).toEqual([['status', '--porcelain']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fails before writing package.json when the next release tag already exists', async () => {
|
||||||
|
const { dependencies, commands, writes } = createReleaseDependencies({
|
||||||
|
gitResults: [
|
||||||
|
gitSuccess(),
|
||||||
|
gitSuccess('main\n'),
|
||||||
|
gitSuccess('origin\n'),
|
||||||
|
gitSuccess('refs/heads/main\n'),
|
||||||
|
gitSuccess('v0.1.0\n'),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
runReleaseWorkflow(
|
||||||
|
{
|
||||||
|
repositoryRoot: testRepositoryRoot,
|
||||||
|
packageJsonPath: testPackageJsonPath,
|
||||||
|
bumpArg: 'minor',
|
||||||
|
},
|
||||||
|
dependencies,
|
||||||
|
),
|
||||||
|
).rejects.toThrow('Tag v0.1.0 already exists. Choose a different release version.');
|
||||||
|
|
||||||
|
expect(writes).toHaveLength(0);
|
||||||
|
expect(commands).toEqual([
|
||||||
|
['status', '--porcelain'],
|
||||||
|
['symbolic-ref', '--quiet', '--short', 'HEAD'],
|
||||||
|
['config', '--get', 'branch.main.remote'],
|
||||||
|
['config', '--get', 'branch.main.merge'],
|
||||||
|
['tag', '--list', 'v0.1.0'],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fails when the current branch does not have an upstream', async () => {
|
||||||
|
const { dependencies, commands, writes } = createReleaseDependencies({
|
||||||
|
gitResults: [
|
||||||
|
gitSuccess(),
|
||||||
|
gitSuccess('release\n'),
|
||||||
|
gitFailure(),
|
||||||
|
gitFailure(),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
runReleaseWorkflow(
|
||||||
|
{
|
||||||
|
repositoryRoot: testRepositoryRoot,
|
||||||
|
packageJsonPath: testPackageJsonPath,
|
||||||
|
},
|
||||||
|
dependencies,
|
||||||
|
),
|
||||||
|
).rejects.toThrow('Release requires an upstream branch for release. Configure tracking before running the release helper.');
|
||||||
|
|
||||||
|
expect(writes).toHaveLength(0);
|
||||||
|
expect(commands).toEqual([
|
||||||
|
['status', '--porcelain'],
|
||||||
|
['symbolic-ref', '--quiet', '--short', 'HEAD'],
|
||||||
|
['config', '--get', 'branch.release.remote'],
|
||||||
|
['config', '--get', 'branch.release.merge'],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
normalizeSessionApprovalSettings,
|
normalizeSessionApprovalSettings,
|
||||||
pruneSessionApprovalSettings,
|
pruneSessionApprovalSettings,
|
||||||
resolveApprovalToolKey,
|
resolveApprovalToolKey,
|
||||||
|
getPendingApprovalToolKey,
|
||||||
dequeuePendingApprovalState,
|
dequeuePendingApprovalState,
|
||||||
enqueuePendingApprovalState,
|
enqueuePendingApprovalState,
|
||||||
listPendingApprovals,
|
listPendingApprovals,
|
||||||
@@ -261,4 +262,48 @@ describe('approval helpers', () => {
|
|||||||
expect(resolveApprovalToolKey(undefined, undefined)).toBeUndefined();
|
expect(resolveApprovalToolKey(undefined, undefined)).toBeUndefined();
|
||||||
expect(resolveApprovalToolKey(undefined, 'mcp')).toBeUndefined();
|
expect(resolveApprovalToolKey(undefined, 'mcp')).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('getPendingApprovalToolKey prefers the explicit approval tool key from the sidecar', () => {
|
||||||
|
expect(
|
||||||
|
getPendingApprovalToolKey({
|
||||||
|
approvalToolKey: 'write',
|
||||||
|
toolName: 'apply_patch',
|
||||||
|
permissionKind: 'hook',
|
||||||
|
}),
|
||||||
|
).toBe('write');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
getPendingApprovalToolKey({
|
||||||
|
approvalToolKey: 'web_fetch',
|
||||||
|
toolName: 'web_search',
|
||||||
|
permissionKind: 'hook',
|
||||||
|
}),
|
||||||
|
).toBe('web_fetch');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
getPendingApprovalToolKey({
|
||||||
|
approvalToolKey: 'mcp_server:icm-mcp',
|
||||||
|
toolName: 'icm-mcp-get_schedule',
|
||||||
|
permissionKind: 'mcp',
|
||||||
|
}),
|
||||||
|
).toBe('mcp_server:icm-mcp');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getPendingApprovalToolKey falls back to derivation for legacy approvals without the explicit key', () => {
|
||||||
|
expect(
|
||||||
|
getPendingApprovalToolKey({
|
||||||
|
toolName: 'view',
|
||||||
|
permissionKind: 'read',
|
||||||
|
}),
|
||||||
|
).toBe('read');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
getPendingApprovalToolKey({
|
||||||
|
toolName: 'git.status',
|
||||||
|
permissionKind: 'mcp',
|
||||||
|
}),
|
||||||
|
).toBe('git.status');
|
||||||
|
|
||||||
|
expect(getPendingApprovalToolKey({})).toBeUndefined();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -26,17 +26,34 @@ describe('streaming text merge', () => {
|
|||||||
expect(mergeStreamingText(current, incoming)).toBe(incoming);
|
expect(mergeStreamingText(current, incoming)).toBe(incoming);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('inserts whitespace when snapshot-like updates would otherwise glue words together', () => {
|
test.each([
|
||||||
expect(mergeStreamingText('How about', 'The **Ashen Crown** feels')).toBe(
|
['requires all wr', 'itable fields', 'requires all writable fields'],
|
||||||
|
['becomes frag', 'ile for clients', 'becomes fragile for clients'],
|
||||||
|
['Endpoint (domain) uniqu', 'eness across tenants', 'Endpoint (domain) uniqueness across tenants'],
|
||||||
|
['The doc says "wildc', 'ards are allowed"', 'The doc says "wildcards are allowed"'],
|
||||||
|
[
|
||||||
|
'What wildcard syntax supported (*.cont',
|
||||||
|
'oso.com? contoso.* ?)',
|
||||||
|
'What wildcard syntax supported (*.contoso.com? contoso.* ?)',
|
||||||
|
],
|
||||||
|
['How does Pur', 'view match traffic', 'How does Purview match traffic'],
|
||||||
|
['more M', 'DA properties', 'more MDA properties'],
|
||||||
|
['does UA', 'G normalize them?', 'does UAG normalize them?'],
|
||||||
|
])('does not inject spaces into split words: %s + %s', (current, incoming, expected) => {
|
||||||
|
expect(mergeStreamingText(current, incoming)).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('preserves whitespace already present in delta', () => {
|
||||||
|
expect(mergeStreamingText('How about', ' The **Ashen Crown** feels')).toBe(
|
||||||
'How about The **Ashen Crown** feels',
|
'How about The **Ashen Crown** feels',
|
||||||
);
|
);
|
||||||
expect(mergeStreamingText('The **Ashen Crown** feels', 'classic and timeless.')).toBe(
|
expect(mergeStreamingText('The **Ashen Crown** feels', ' classic and timeless.')).toBe(
|
||||||
'The **Ashen Crown** feels classic and timeless.',
|
'The **Ashen Crown** feels classic and timeless.',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('inserts a newline before streamed markdown block markers', () => {
|
test('preserves newline already present in delta', () => {
|
||||||
expect(mergeStreamingText('If you want, I can also give you', '- darker titles')).toBe(
|
expect(mergeStreamingText('If you want, I can also give you', '\n- darker titles')).toBe(
|
||||||
'If you want, I can also give you\n- darker titles',
|
'If you want, I can also give you\n- darker titles',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,12 +6,14 @@ import {
|
|||||||
groupApprovalToolsByProvider,
|
groupApprovalToolsByProvider,
|
||||||
listApprovalToolDefinitions,
|
listApprovalToolDefinitions,
|
||||||
listApprovalToolNames,
|
listApprovalToolNames,
|
||||||
|
normalizeOpenTelemetrySettings,
|
||||||
normalizeWorkspaceSettings,
|
normalizeWorkspaceSettings,
|
||||||
resolveProjectToolingSettings,
|
resolveProjectToolingSettings,
|
||||||
resolveToolLabel,
|
resolveToolLabel,
|
||||||
resolveWorkspaceToolingSettings,
|
resolveWorkspaceToolingSettings,
|
||||||
validateLspProfileDefinition,
|
validateLspProfileDefinition,
|
||||||
validateMcpServerDefinition,
|
validateMcpServerDefinition,
|
||||||
|
DEFAULT_OTEL_ENDPOINT,
|
||||||
type LspProfileDefinition,
|
type LspProfileDefinition,
|
||||||
type McpServerDefinition,
|
type McpServerDefinition,
|
||||||
type WorkspaceToolingSettings,
|
type WorkspaceToolingSettings,
|
||||||
@@ -118,6 +120,40 @@ describe('tooling settings helpers', () => {
|
|||||||
expect(normalizeWorkspaceSettings({ terminalHeight: Number.NaN }).terminalHeight).toBeUndefined();
|
expect(normalizeWorkspaceSettings({ terminalHeight: Number.NaN }).terminalHeight).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('normalizes OpenTelemetry settings with defaults', () => {
|
||||||
|
const otel = normalizeOpenTelemetrySettings();
|
||||||
|
expect(otel.enabled).toBe(false);
|
||||||
|
expect(otel.endpoint).toBe(DEFAULT_OTEL_ENDPOINT);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('preserves valid OpenTelemetry settings', () => {
|
||||||
|
const otel = normalizeOpenTelemetrySettings({ enabled: true, endpoint: 'http://custom:4317' });
|
||||||
|
expect(otel.enabled).toBe(true);
|
||||||
|
expect(otel.endpoint).toBe('http://custom:4317');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('trims whitespace from OpenTelemetry endpoint', () => {
|
||||||
|
const otel = normalizeOpenTelemetrySettings({ enabled: true, endpoint: ' http://localhost:4317 ' });
|
||||||
|
expect(otel.endpoint).toBe('http://localhost:4317');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to default endpoint when blank', () => {
|
||||||
|
const otel = normalizeOpenTelemetrySettings({ enabled: true, endpoint: ' ' });
|
||||||
|
expect(otel.endpoint).toBe(DEFAULT_OTEL_ENDPOINT);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normalizeWorkspaceSettings preserves OpenTelemetry when present', () => {
|
||||||
|
const settings = normalizeWorkspaceSettings({
|
||||||
|
openTelemetry: { enabled: true, endpoint: 'http://jaeger:4317' },
|
||||||
|
});
|
||||||
|
expect(settings.openTelemetry).toEqual({ enabled: true, endpoint: 'http://jaeger:4317' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('normalizeWorkspaceSettings omits OpenTelemetry when absent', () => {
|
||||||
|
const settings = normalizeWorkspaceSettings({});
|
||||||
|
expect(settings.openTelemetry).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
test('validates required MCP transport settings', () => {
|
test('validates required MCP transport settings', () => {
|
||||||
const localServer: McpServerDefinition = {
|
const localServer: McpServerDefinition = {
|
||||||
id: 'mcp-local',
|
id: 'mcp-local',
|
||||||
|
|||||||
@@ -354,6 +354,16 @@ import Base from '../layouts/Base.astro';
|
|||||||
<p class="mt-0.5 text-xs leading-relaxed text-warm-400">Minimize to tray, quick-launch scratchpads, see running session count.</p>
|
<p class="mt-0.5 text-xs leading-relaxed text-warm-400">Minimize to tray, quick-launch scratchpads, see running session count.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- Quick Prompt -->
|
||||||
|
<div class="group flex gap-3.5 rounded-xl px-3 py-2.5 transition hover:bg-card/60" data-reveal data-reveal-d="6">
|
||||||
|
<div class="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg bg-accent/[0.07] text-accent transition group-hover:bg-accent/[0.12]">
|
||||||
|
<svg class="size-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4 class="text-sm font-medium text-warm-50">Quick Prompt</h4>
|
||||||
|
<p class="mt-0.5 text-xs leading-relaxed text-warm-400">Global hotkey summons a floating AI prompt from any app. Discard, close, or continue in Aryx.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<!-- Desktop Notifications -->
|
<!-- Desktop Notifications -->
|
||||||
<div class="group flex gap-3.5 rounded-xl px-3 py-2.5 transition hover:bg-card/60" data-reveal data-reveal-d="7">
|
<div class="group flex gap-3.5 rounded-xl px-3 py-2.5 transition hover:bg-card/60" data-reveal data-reveal-d="7">
|
||||||
<div class="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg bg-brand/[0.07] text-brand transition group-hover:bg-brand/[0.12]">
|
<div class="mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-lg bg-brand/[0.07] text-brand transition group-hover:bg-brand/[0.12]">
|
||||||
|
|||||||
Reference in New Issue
Block a user