mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-06-18 06:12:08 +08:00
Compare commits
4 Commits
fix/codex-
...
chore/add-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21b0f14e7a | ||
|
|
f12af8a61b | ||
|
|
f549bd99e7 | ||
|
|
bc34085af9 |
@@ -164,6 +164,14 @@ CloudCLI verfügt über ein Plugin-System, mit dem benutzerdefinierte Tabs mit e
|
|||||||
| Plugin | Beschreibung |
|
| Plugin | Beschreibung |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Zeigt Dateianzahl, Codezeilen, Dateityp-Aufschlüsselung, größte Dateien und zuletzt geänderte Dateien des aktuellen Projekts |
|
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Zeigt Dateianzahl, Codezeilen, Dateityp-Aufschlüsselung, größte Dateien und zuletzt geänderte Dateien des aktuellen Projekts |
|
||||||
|
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | Vollwertiges xterm.js-Terminal mit Multi-Tab-Unterstützung |
|
||||||
|
| **[Claude Watch](https://github.com/satsuki19980613/cloudcli-claude-watch)** | Überwacht lange laufende Claude-Code-Sitzungen auf Hänger und stellt Prozesssteuerungen bereit |
|
||||||
|
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | Erstellt arbeitsbereichsbezogene geplante Prompts und führt sie über eine lokale CLI wie Codex, Claude Code oder Gemini CLI aus |
|
||||||
|
| **[PRISM CloudCLI](https://github.com/jakeefr/cloudcli-plugin-prism)** | Sitzungsintelligenz für Claude Code in CloudCLI, inklusive Sichtbarkeit des Token-Verbrauchs |
|
||||||
|
| **[Sessions](https://github.com/strykereye2/cloudcli-plugin-session-manager)** | Aktive Claude-Code-Sitzungen anzeigen, verwalten und beenden |
|
||||||
|
| **[Token Cost Calculator](https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator)** | API-Kosten anhand von Modellpreisen und Token-Nutzung berechnen, mit Unterstützung für Preisvorlagen |
|
||||||
|
| **[Task Queue](https://github.com/TadMSTR/cloudcli-plugin-task-queue)** | Task-Queue-Dashboard zum Anzeigen, Filtern und Starten von Agent-Aufgaben |
|
||||||
|
| **[GitHub Issues Board](https://github.com/szmidtpiotr/claude-github-issue)** | Kanban-Board für GitHub Issues mit bidirektionaler TaskMaster-Synchronisierung und automatischer Installation des /github-task CLI-Skills |
|
||||||
|
|
||||||
### Eigenes Plugin erstellen
|
### Eigenes Plugin erstellen
|
||||||
|
|
||||||
|
|||||||
@@ -158,6 +158,14 @@ CloudCLI にはプラグインシステムがあり、独自のフロントエ
|
|||||||
| プラグイン | 説明 |
|
| プラグイン | 説明 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 現在のプロジェクトについて、ファイル数、コード行数、ファイル種別の内訳、最大ファイル、最近変更されたファイルを表示 |
|
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 現在のプロジェクトについて、ファイル数、コード行数、ファイル種別の内訳、最大ファイル、最近変更されたファイルを表示 |
|
||||||
|
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | 複数タブに対応した本格的な xterm.js ターミナル |
|
||||||
|
| **[Claude Watch](https://github.com/satsuki19980613/cloudcli-claude-watch)** | 長時間実行中の Claude Code セッションのハングを監視し、プロセス操作を提供 |
|
||||||
|
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | ワークスペース単位のスケジュール済みプロンプトを作成し、Codex、Claude Code、Gemini CLI などのローカル CLI で実行 |
|
||||||
|
| **[PRISM CloudCLI](https://github.com/jakeefr/cloudcli-plugin-prism)** | CloudCLI 内で Claude Code のセッション分析を行い、トークン消費の可視化も提供 |
|
||||||
|
| **[Sessions](https://github.com/strykereye2/cloudcli-plugin-session-manager)** | アクティブな Claude Code セッションを表示、管理、終了 |
|
||||||
|
| **[Token Cost Calculator](https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator)** | モデル価格とトークン使用量から API コストを計算し、モデル価格プリセットにも対応 |
|
||||||
|
| **[Task Queue](https://github.com/TadMSTR/cloudcli-plugin-task-queue)** | エージェントタスクを表示、フィルタリング、起動するためのタスクキューダッシュボード |
|
||||||
|
| **[GitHub Issues Board](https://github.com/szmidtpiotr/claude-github-issue)** | GitHub Issues 用の Kanban ボード。TaskMaster との双方向同期と /github-task CLI スキルの自動インストールに対応 |
|
||||||
|
|
||||||
### 自作する
|
### 自作する
|
||||||
|
|
||||||
|
|||||||
@@ -158,6 +158,14 @@ CloudCLI는 커스텀 탭과 선택적 Node.js 백엔드가 포함된 플러그
|
|||||||
| 플러그인 | 설명 |
|
| 플러그인 | 설명 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 현재 프로젝트의 파일 수, 코드 줄 수, 파일 유형 분포, 가장 큰 파일, 최근 수정 파일을 표시 |
|
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 현재 프로젝트의 파일 수, 코드 줄 수, 파일 유형 분포, 가장 큰 파일, 최근 수정 파일을 표시 |
|
||||||
|
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | 다중 탭을 지원하는 전체 xterm.js 터미널 |
|
||||||
|
| **[Claude Watch](https://github.com/satsuki19980613/cloudcli-claude-watch)** | 장시간 실행 중인 Claude Code 세션의 중단 상태를 감시하고 프로세스 제어를 제공 |
|
||||||
|
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | 워크스페이스 범위 예약 프롬프트를 만들고 Codex, Claude Code, Gemini CLI 같은 로컬 CLI로 실행 |
|
||||||
|
| **[PRISM CloudCLI](https://github.com/jakeefr/cloudcli-plugin-prism)** | CloudCLI 안에서 Claude Code 세션 인텔리전스와 토큰 소모 가시성을 제공 |
|
||||||
|
| **[Sessions](https://github.com/strykereye2/cloudcli-plugin-session-manager)** | 활성 Claude Code 세션을 보고, 관리하고, 종료 |
|
||||||
|
| **[Token Cost Calculator](https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator)** | 모델 가격과 토큰 사용량으로 API 비용을 계산하고 모델 가격 프리셋을 지원 |
|
||||||
|
| **[Task Queue](https://github.com/TadMSTR/cloudcli-plugin-task-queue)** | 에이전트 작업을 보고, 필터링하고, 실행하는 작업 큐 대시보드 |
|
||||||
|
| **[GitHub Issues Board](https://github.com/szmidtpiotr/claude-github-issue)** | GitHub Issues용 Kanban 보드. TaskMaster 양방향 동기화와 /github-task CLI 스킬 자동 설치 지원 |
|
||||||
|
|
||||||
### 직접 만들기
|
### 직접 만들기
|
||||||
|
|
||||||
|
|||||||
11
README.md
11
README.md
@@ -163,8 +163,15 @@ CloudCLI has a plugin system that lets you add custom tabs with their own fronte
|
|||||||
| Plugin | Description |
|
| Plugin | Description |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Shows file counts, lines of code, file-type breakdown, largest files, and recently modified files for your current project |
|
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Shows file counts, lines of code, file-type breakdown, largest files, and recently modified files for your current project |
|
||||||
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | Full xterm.js terminal with multi-tab support|
|
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | Full xterm.js terminal with multi-tab support |
|
||||||
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | Create workspace-scoped scheduled prompts and execute them through a local CLI such as Codex, Claude Code, or Gemini CLI|
|
| **[Claude Watch](https://github.com/satsuki19980613/cloudcli-claude-watch)** | Watches long-running Claude Code sessions for hangs and exposes process controls |
|
||||||
|
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | Create workspace-scoped scheduled prompts and execute them through a local CLI such as Codex, Claude Code, or Gemini CLI |
|
||||||
|
| **[PRISM CloudCLI](https://github.com/jakeefr/cloudcli-plugin-prism)** | Session intelligence for Claude Code inside CloudCLI, including token burn visibility |
|
||||||
|
| **[Sessions](https://github.com/strykereye2/cloudcli-plugin-session-manager)** | View, manage, and kill active Claude Code sessions |
|
||||||
|
| **[Token Cost Calculator](https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator)** | Calculate API costs from model prices and token usage, with preset model pricing support |
|
||||||
|
| **[Task Queue](https://github.com/TadMSTR/cloudcli-plugin-task-queue)** | Task queue dashboard to view, filter, and launch agent tasks |
|
||||||
|
| **[GitHub Issues Board](https://github.com/szmidtpiotr/claude-github-issue)** | Kanban board for GitHub Issues with bidirectional TaskMaster sync and /github-task CLI skill auto-install |
|
||||||
|
|
||||||
### Build Your Own
|
### Build Your Own
|
||||||
|
|
||||||
**[Plugin Starter Template →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** — fork this repo to create your own plugin. It includes a working example with frontend rendering, live context updates, and RPC communication to a backend server.
|
**[Plugin Starter Template →](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** — fork this repo to create your own plugin. It includes a working example with frontend rendering, live context updates, and RPC communication to a backend server.
|
||||||
|
|||||||
@@ -164,6 +164,14 @@ CloudCLI UI — это open source UI-слой, на котором постро
|
|||||||
| Плагин | Описание |
|
| Плагин | Описание |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Показывает количество файлов, строки кода, разбивку по типам файлов, самые большие файлы и недавно изменённые файлы для текущего проекта |
|
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Показывает количество файлов, строки кода, разбивку по типам файлов, самые большие файлы и недавно изменённые файлы для текущего проекта |
|
||||||
|
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | Полноценный терминал xterm.js с поддержкой нескольких вкладок |
|
||||||
|
| **[Claude Watch](https://github.com/satsuki19980613/cloudcli-claude-watch)** | Отслеживает зависания долгих сессий Claude Code и предоставляет управление процессами |
|
||||||
|
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | Создаёт запланированные промпты для рабочей области и запускает их через локальную CLI, например Codex, Claude Code или Gemini CLI |
|
||||||
|
| **[PRISM CloudCLI](https://github.com/jakeefr/cloudcli-plugin-prism)** | Аналитика сессий Claude Code внутри CloudCLI, включая видимость расхода токенов |
|
||||||
|
| **[Sessions](https://github.com/strykereye2/cloudcli-plugin-session-manager)** | Просмотр, управление и завершение активных сессий Claude Code |
|
||||||
|
| **[Token Cost Calculator](https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator)** | Расчёт стоимости API по ценам моделей и использованию токенов, с поддержкой пресетов цен |
|
||||||
|
| **[Task Queue](https://github.com/TadMSTR/cloudcli-plugin-task-queue)** | Дашборд очереди задач для просмотра, фильтрации и запуска агентских задач |
|
||||||
|
| **[GitHub Issues Board](https://github.com/szmidtpiotr/claude-github-issue)** | Kanban-доска для GitHub Issues с двусторонней синхронизацией TaskMaster и автоустановкой CLI-навыка /github-task |
|
||||||
|
|
||||||
### Создать свой
|
### Создать свой
|
||||||
|
|
||||||
|
|||||||
@@ -164,6 +164,13 @@ CloudCLI, kendi frontend UI'sı ve isteğe bağlı Node.js arka ucu olan özel s
|
|||||||
|---|---|
|
|---|---|
|
||||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Mevcut projen için dosya sayıları, kod satırları, dosya türü dağılımı, en büyük dosyalar ve son değiştirilen dosyaları gösterir |
|
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | Mevcut projen için dosya sayıları, kod satırları, dosya türü dağılımı, en büyük dosyalar ve son değiştirilen dosyaları gösterir |
|
||||||
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | Çoklu sekme destekli tam xterm.js terminali |
|
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | Çoklu sekme destekli tam xterm.js terminali |
|
||||||
|
| **[Claude Watch](https://github.com/satsuki19980613/cloudcli-claude-watch)** | Uzun süren Claude Code oturumlarını takılmalara karşı izler ve süreç kontrolleri sunar |
|
||||||
|
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | Çalışma alanı kapsamlı zamanlanmış prompt'lar oluşturur ve bunları Codex, Claude Code veya Gemini CLI gibi yerel CLI'larla çalıştırır |
|
||||||
|
| **[PRISM CloudCLI](https://github.com/jakeefr/cloudcli-plugin-prism)** | CloudCLI içinde Claude Code oturum zekası ve token tüketimi görünürlüğü sağlar |
|
||||||
|
| **[Sessions](https://github.com/strykereye2/cloudcli-plugin-session-manager)** | Aktif Claude Code oturumlarını görüntülemeni, yönetmeni ve sonlandırmanı sağlar |
|
||||||
|
| **[Token Cost Calculator](https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator)** | Model fiyatları ve token kullanımından API maliyetlerini hesaplar; model fiyatı hazır ayarlarını destekler |
|
||||||
|
| **[Task Queue](https://github.com/TadMSTR/cloudcli-plugin-task-queue)** | Ajan görevlerini görüntülemek, filtrelemek ve başlatmak için görev kuyruğu paneli |
|
||||||
|
| **[GitHub Issues Board](https://github.com/szmidtpiotr/claude-github-issue)** | GitHub Issues için Kanban panosu; çift yönlü TaskMaster senkronizasyonu ve /github-task CLI becerisi otomatik kurulumu içerir |
|
||||||
|
|
||||||
### Kendi Eklentini Yaz
|
### Kendi Eklentini Yaz
|
||||||
|
|
||||||
|
|||||||
@@ -158,6 +158,14 @@ CloudCLI 配备插件系统,允许你添加带自定义前端 UI 和可选 Nod
|
|||||||
| 插件 | 描述 |
|
| 插件 | 描述 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 展示当前项目的文件数、代码行数、文件类型分布、最大文件以及最近修改的文件 |
|
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 展示当前项目的文件数、代码行数、文件类型分布、最大文件以及最近修改的文件 |
|
||||||
|
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | 支持多标签页的完整 xterm.js 终端 |
|
||||||
|
| **[Claude Watch](https://github.com/satsuki19980613/cloudcli-claude-watch)** | 监控长时间运行的 Claude Code 会话是否卡住,并提供进程控制 |
|
||||||
|
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | 创建工作区范围的定时提示词,并通过 Codex、Claude Code 或 Gemini CLI 等本地 CLI 执行 |
|
||||||
|
| **[PRISM CloudCLI](https://github.com/jakeefr/cloudcli-plugin-prism)** | 在 CloudCLI 中提供 Claude Code 会话智能分析,包括 token 消耗可视化 |
|
||||||
|
| **[Sessions](https://github.com/strykereye2/cloudcli-plugin-session-manager)** | 查看、管理并终止活动的 Claude Code 会话 |
|
||||||
|
| **[Token Cost Calculator](https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator)** | 根据模型价格和 token 用量计算 API 成本,并支持模型价格预设 |
|
||||||
|
| **[Task Queue](https://github.com/TadMSTR/cloudcli-plugin-task-queue)** | 用于查看、筛选和启动代理任务的任务队列仪表板 |
|
||||||
|
| **[GitHub Issues Board](https://github.com/szmidtpiotr/claude-github-issue)** | 用于 GitHub Issues 的看板,支持 TaskMaster 双向同步和 /github-task CLI 技能自动安装 |
|
||||||
|
|
||||||
### 自行构建
|
### 自行构建
|
||||||
|
|
||||||
|
|||||||
@@ -158,6 +158,14 @@ CloudCLI 配備外掛系統,允許你新增帶有自訂前端 UI 和選用 Nod
|
|||||||
| 外掛 | 描述 |
|
| 外掛 | 描述 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 展示目前專案的檔案數、程式碼行數、檔案類型分佈、最大檔案以及最近修改的檔案 |
|
| **[Project Stats](https://github.com/cloudcli-ai/cloudcli-plugin-starter)** | 展示目前專案的檔案數、程式碼行數、檔案類型分佈、最大檔案以及最近修改的檔案 |
|
||||||
|
| **[Web Terminal](https://github.com/cloudcli-ai/cloudcli-plugin-terminal)** | 支援多分頁的完整 xterm.js 終端機 |
|
||||||
|
| **[Claude Watch](https://github.com/satsuki19980613/cloudcli-claude-watch)** | 監控長時間執行的 Claude Code 工作階段是否卡住,並提供程序控制 |
|
||||||
|
| **[CloudCLI Scheduler](https://github.com/grostim/cloudcli-cron)** | 建立工作區範圍的排程提示詞,並透過 Codex、Claude Code 或 Gemini CLI 等本機 CLI 執行 |
|
||||||
|
| **[PRISM CloudCLI](https://github.com/jakeefr/cloudcli-plugin-prism)** | 在 CloudCLI 中提供 Claude Code 工作階段智慧分析,包括 token 消耗可視化 |
|
||||||
|
| **[Sessions](https://github.com/strykereye2/cloudcli-plugin-session-manager)** | 檢視、管理並終止作用中的 Claude Code 工作階段 |
|
||||||
|
| **[Token Cost Calculator](https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator)** | 根據模型價格與 token 用量計算 API 成本,並支援模型價格預設 |
|
||||||
|
| **[Task Queue](https://github.com/TadMSTR/cloudcli-plugin-task-queue)** | 用於檢視、篩選和啟動代理任務的任務佇列儀表板 |
|
||||||
|
| **[GitHub Issues Board](https://github.com/szmidtpiotr/claude-github-issue)** | 用於 GitHub Issues 的看板,支援 TaskMaster 雙向同步和 /github-task CLI 技能自動安裝 |
|
||||||
|
|
||||||
### 自行建構
|
### 自行建構
|
||||||
|
|
||||||
|
|||||||
@@ -161,8 +161,6 @@ export default tseslint.config(
|
|||||||
"server/shared/utils.{js,ts}",
|
"server/shared/utils.{js,ts}",
|
||||||
"server/shared/frontmatter.ts",
|
"server/shared/frontmatter.ts",
|
||||||
"server/shared/claude-cli-path.ts",
|
"server/shared/claude-cli-path.ts",
|
||||||
"server/shared/cli-runtime-env.ts",
|
|
||||||
"server/shared/codex-cli-runtime.ts",
|
|
||||||
], // classify shared utility files so modules can depend on them explicitly
|
], // classify shared utility files so modules can depend on them explicitly
|
||||||
mode: "file",
|
mode: "file",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -28,14 +28,10 @@ import {
|
|||||||
} from './services/notification-orchestrator.js';
|
} from './services/notification-orchestrator.js';
|
||||||
import { sessionsService } from './modules/providers/services/sessions.service.js';
|
import { sessionsService } from './modules/providers/services/sessions.service.js';
|
||||||
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
||||||
import { createCompleteMessage, createNormalizedMessage } from './shared/utils.js';
|
import { createNormalizedMessage } from './shared/utils.js';
|
||||||
|
|
||||||
const activeSessions = new Map();
|
const activeSessions = new Map();
|
||||||
const pendingToolApprovals = new Map();
|
const pendingToolApprovals = new Map();
|
||||||
// Sessions cancelled via abort-session. The abort handler already sent the
|
|
||||||
// terminal `complete` (aborted: true) to the client, so the run loop must not
|
|
||||||
// emit a second one when its generator winds down.
|
|
||||||
const abortedSessionIds = new Set();
|
|
||||||
|
|
||||||
const TOOL_APPROVAL_TIMEOUT_MS = parseInt(process.env.CLAUDE_TOOL_APPROVAL_TIMEOUT_MS, 10) || 55000;
|
const TOOL_APPROVAL_TIMEOUT_MS = parseInt(process.env.CLAUDE_TOOL_APPROVAL_TIMEOUT_MS, 10) || 55000;
|
||||||
|
|
||||||
@@ -735,18 +731,14 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
|||||||
// Clean up temporary image files
|
// Clean up temporary image files
|
||||||
await cleanupTempFiles(tempImagePaths, tempDir);
|
await cleanupTempFiles(tempImagePaths, tempDir);
|
||||||
|
|
||||||
// Send the terminal completion event — skipped for aborted runs, whose
|
// Send completion event
|
||||||
// terminal `complete` (aborted: true) was already sent by abort-session.
|
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: 0, isNewSession: !sessionId && !!command, sessionId: capturedSessionId, provider: 'claude' }));
|
||||||
const wasAborted = capturedSessionId ? abortedSessionIds.delete(capturedSessionId) : false;
|
|
||||||
if (!wasAborted) {
|
|
||||||
ws.send(createCompleteMessage({ provider: 'claude', sessionId: capturedSessionId || sessionId || null, exitCode: 0 }));
|
|
||||||
}
|
|
||||||
notifyRunStopped({
|
notifyRunStopped({
|
||||||
userId: ws?.userId || null,
|
userId: ws?.userId || null,
|
||||||
provider: 'claude',
|
provider: 'claude',
|
||||||
sessionId: capturedSessionId || sessionId || null,
|
sessionId: capturedSessionId || sessionId || null,
|
||||||
sessionName: sessionSummary,
|
sessionName: sessionSummary,
|
||||||
stopReason: wasAborted ? 'aborted' : 'completed'
|
stopReason: 'completed'
|
||||||
});
|
});
|
||||||
// Complete
|
// Complete
|
||||||
|
|
||||||
@@ -761,22 +753,14 @@ async function queryClaudeSDK(command, options = {}, ws) {
|
|||||||
// Clean up temporary image files on error
|
// Clean up temporary image files on error
|
||||||
await cleanupTempFiles(tempImagePaths, tempDir);
|
await cleanupTempFiles(tempImagePaths, tempDir);
|
||||||
|
|
||||||
const wasAborted = capturedSessionId ? abortedSessionIds.delete(capturedSessionId) : false;
|
|
||||||
if (wasAborted) {
|
|
||||||
// The abort already produced the terminal complete; a generator throw
|
|
||||||
// caused by interrupt() is expected noise, not a user-facing error.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if Claude CLI is installed for a clearer error message
|
// Check if Claude CLI is installed for a clearer error message
|
||||||
const installed = await providerAuthService.isProviderInstalled('claude');
|
const installed = await providerAuthService.isProviderInstalled('claude');
|
||||||
const errorContent = !installed
|
const errorContent = !installed
|
||||||
? 'Claude Code is not installed. Please install it first: https://docs.anthropic.com/en/docs/claude-code'
|
? 'Claude Code is not installed. Please install it first: https://docs.anthropic.com/en/docs/claude-code'
|
||||||
: error.message;
|
: error.message;
|
||||||
|
|
||||||
// Send error to WebSocket, then the terminal complete
|
// Send error to WebSocket
|
||||||
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
|
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
|
||||||
ws.send(createCompleteMessage({ provider: 'claude', sessionId: capturedSessionId || sessionId || null, exitCode: 1 }));
|
|
||||||
notifyRunFailed({
|
notifyRunFailed({
|
||||||
userId: ws?.userId || null,
|
userId: ws?.userId || null,
|
||||||
provider: 'claude',
|
provider: 'claude',
|
||||||
@@ -803,10 +787,6 @@ async function abortClaudeSDKSession(sessionId) {
|
|||||||
try {
|
try {
|
||||||
console.log(`Aborting SDK session: ${sessionId}`);
|
console.log(`Aborting SDK session: ${sessionId}`);
|
||||||
|
|
||||||
// Mark before interrupting so the run loop knows not to emit its own
|
|
||||||
// terminal complete (the abort handler sends the aborted one).
|
|
||||||
abortedSessionIds.add(sessionId);
|
|
||||||
|
|
||||||
// Call interrupt() on the query instance
|
// Call interrupt() on the query instance
|
||||||
await session.instance.interrupt();
|
await session.instance.interrupt();
|
||||||
|
|
||||||
@@ -822,8 +802,6 @@ async function abortClaudeSDKSession(sessionId) {
|
|||||||
return true;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Error aborting session ${sessionId}:`, error);
|
console.error(`Error aborting session ${sessionId}:`, error);
|
||||||
// The run keeps going; let it emit its own terminal complete.
|
|
||||||
abortedSessionIds.delete(sessionId);
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { notifyRunFailed, notifyRunStopped } from './services/notification-orche
|
|||||||
import { sessionsService } from './modules/providers/services/sessions.service.js';
|
import { sessionsService } from './modules/providers/services/sessions.service.js';
|
||||||
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
||||||
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
|
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
|
||||||
import { createCompleteMessage, createNormalizedMessage } from './shared/utils.js';
|
import { createNormalizedMessage } from './shared/utils.js';
|
||||||
|
|
||||||
// Use cross-spawn on Windows for better command execution
|
// Use cross-spawn on Windows for better command execution
|
||||||
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
||||||
@@ -34,10 +34,6 @@ async function spawnCursor(command, options = {}, ws) {
|
|||||||
let sessionCreatedSent = false; // Track if we've already sent session-created event
|
let sessionCreatedSent = false; // Track if we've already sent session-created event
|
||||||
let hasRetriedWithTrust = false;
|
let hasRetriedWithTrust = false;
|
||||||
let settled = false;
|
let settled = false;
|
||||||
// The unified lifecycle contract requires exactly one terminal `complete`
|
|
||||||
// per run. Cursor surfaces completion twice (the `result` JSON line and
|
|
||||||
// the process close), so the first emission wins.
|
|
||||||
let completeSent = false;
|
|
||||||
|
|
||||||
// Use tools settings passed from frontend, or defaults
|
// Use tools settings passed from frontend, or defaults
|
||||||
const settings = toolsSettings || {
|
const settings = toolsSettings || {
|
||||||
@@ -201,15 +197,15 @@ async function spawnCursor(command, options = {}, ws) {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case 'result': {
|
case 'result': {
|
||||||
// Session complete — terminal lifecycle event for this run
|
// Session complete — send stream end + lifecycle complete with result payload
|
||||||
if (!completeSent) {
|
const resultText = typeof response.result === 'string' ? response.result : '';
|
||||||
completeSent = true;
|
ws.send(createNormalizedMessage({
|
||||||
ws.send(createCompleteMessage({
|
kind: 'complete',
|
||||||
provider: 'cursor',
|
exitCode: response.subtype === 'success' ? 0 : 1,
|
||||||
sessionId: capturedSessionId || sessionId || null,
|
resultText,
|
||||||
exitCode: response.subtype === 'success' ? 0 : 1,
|
isError: response.subtype !== 'success',
|
||||||
}));
|
sessionId: capturedSessionId || sessionId, provider: 'cursor',
|
||||||
}
|
}));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,12 +271,7 @@ async function spawnCursor(command, options = {}, ws) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Terminal complete — unless the `result` line already sent it, or the
|
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'cursor' }));
|
||||||
// run was aborted (abort-session sent the aborted complete).
|
|
||||||
if (!completeSent && !cursorProcess.aborted) {
|
|
||||||
completeSent = true;
|
|
||||||
ws.send(createCompleteMessage({ provider: 'cursor', sessionId: finalSessionId, exitCode: code }));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (code === 0) {
|
if (code === 0) {
|
||||||
notifyTerminalState({ code });
|
notifyTerminalState({ code });
|
||||||
@@ -306,10 +297,6 @@ async function spawnCursor(command, options = {}, ws) {
|
|||||||
: error.message;
|
: error.message;
|
||||||
|
|
||||||
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'cursor' }));
|
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'cursor' }));
|
||||||
if (!completeSent && !cursorProcess.aborted) {
|
|
||||||
completeSent = true;
|
|
||||||
ws.send(createCompleteMessage({ provider: 'cursor', sessionId: capturedSessionId || sessionId || null, exitCode: 1 }));
|
|
||||||
}
|
|
||||||
notifyTerminalState({ error });
|
notifyTerminalState({ error });
|
||||||
|
|
||||||
settleOnce(() => reject(error));
|
settleOnce(() => reject(error));
|
||||||
@@ -327,9 +314,6 @@ function abortCursorSession(sessionId) {
|
|||||||
const process = activeCursorProcesses.get(sessionId);
|
const process = activeCursorProcesses.get(sessionId);
|
||||||
if (process) {
|
if (process) {
|
||||||
console.log(`Aborting Cursor session: ${sessionId}`);
|
console.log(`Aborting Cursor session: ${sessionId}`);
|
||||||
// The abort handler sends the terminal complete (aborted: true); flag the
|
|
||||||
// process so its close handler does not emit a second one.
|
|
||||||
process.aborted = true;
|
|
||||||
process.kill('SIGTERM');
|
process.kill('SIGTERM');
|
||||||
activeCursorProcesses.delete(sessionId);
|
activeCursorProcesses.delete(sessionId);
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import GeminiResponseHandler from './gemini-response-handler.js';
|
|||||||
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
||||||
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
||||||
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
|
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
|
||||||
import { createCompleteMessage, createNormalizedMessage } from './shared/utils.js';
|
import { createNormalizedMessage } from './shared/utils.js';
|
||||||
|
|
||||||
// Use cross-spawn on Windows for correct .cmd resolution (same pattern as cursor-cli.js)
|
// Use cross-spawn on Windows for correct .cmd resolution (same pattern as cursor-cli.js)
|
||||||
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
||||||
@@ -129,9 +129,6 @@ async function spawnGemini(command, options = {}, ws) {
|
|||||||
let capturedSessionId = sessionId; // Track session ID throughout the process
|
let capturedSessionId = sessionId; // Track session ID throughout the process
|
||||||
let sessionCreatedSent = false; // Track if we've already sent session-created event
|
let sessionCreatedSent = false; // Track if we've already sent session-created event
|
||||||
let assistantBlocks = []; // Accumulate the full response blocks including tools
|
let assistantBlocks = []; // Accumulate the full response blocks including tools
|
||||||
// Unified lifecycle contract: exactly one terminal `complete` per run
|
|
||||||
// (close and error handlers can both fire for spawn failures).
|
|
||||||
let completeSent = false;
|
|
||||||
|
|
||||||
// Use tools settings passed from frontend, or defaults
|
// Use tools settings passed from frontend, or defaults
|
||||||
const settings = toolsSettings || {
|
const settings = toolsSettings || {
|
||||||
@@ -489,12 +486,7 @@ async function spawnGemini(command, options = {}, ws) {
|
|||||||
sessionManager.addMessage(finalSessionId, 'assistant', assistantBlocks);
|
sessionManager.addMessage(finalSessionId, 'assistant', assistantBlocks);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Terminal complete — skipped for aborted runs (abort-session
|
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'gemini' }));
|
||||||
// already sent the aborted complete on this run's behalf).
|
|
||||||
if (!completeSent && !geminiProcess.aborted) {
|
|
||||||
completeSent = true;
|
|
||||||
ws.send(createCompleteMessage({ provider: 'gemini', sessionId: finalSessionId, exitCode: code }));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up temporary image files if any
|
// Clean up temporary image files if any
|
||||||
if (geminiProcess.tempImagePaths && geminiProcess.tempImagePaths.length > 0) {
|
if (geminiProcess.tempImagePaths && geminiProcess.tempImagePaths.length > 0) {
|
||||||
@@ -574,10 +566,6 @@ async function spawnGemini(command, options = {}, ws) {
|
|||||||
|
|
||||||
const errorSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
const errorSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
||||||
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: errorSessionId, provider: 'gemini' }));
|
ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: errorSessionId, provider: 'gemini' }));
|
||||||
if (!completeSent && !geminiProcess.aborted) {
|
|
||||||
completeSent = true;
|
|
||||||
ws.send(createCompleteMessage({ provider: 'gemini', sessionId: errorSessionId, exitCode: 1 }));
|
|
||||||
}
|
|
||||||
notifyTerminalState({ error });
|
notifyTerminalState({ error });
|
||||||
|
|
||||||
reject(error);
|
reject(error);
|
||||||
@@ -602,9 +590,6 @@ function abortGeminiSession(sessionId) {
|
|||||||
|
|
||||||
if (geminiProc) {
|
if (geminiProc) {
|
||||||
try {
|
try {
|
||||||
// The abort handler sends the terminal complete (aborted: true);
|
|
||||||
// flag the process so its close handler does not emit a second one.
|
|
||||||
geminiProc.aborted = true;
|
|
||||||
geminiProc.kill('SIGTERM');
|
geminiProc.kill('SIGTERM');
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (activeGeminiProcesses.has(processKey)) {
|
if (activeGeminiProcesses.has(processKey)) {
|
||||||
|
|||||||
@@ -22,24 +22,35 @@ import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
|
|||||||
import {
|
import {
|
||||||
queryClaudeSDK,
|
queryClaudeSDK,
|
||||||
abortClaudeSDKSession,
|
abortClaudeSDKSession,
|
||||||
|
isClaudeSDKSessionActive,
|
||||||
|
getActiveClaudeSDKSessions,
|
||||||
resolveToolApproval,
|
resolveToolApproval,
|
||||||
getPendingApprovalsForSession,
|
getPendingApprovalsForSession,
|
||||||
|
reconnectSessionWriter,
|
||||||
} from './claude-sdk.js';
|
} from './claude-sdk.js';
|
||||||
import {
|
import {
|
||||||
spawnCursor,
|
spawnCursor,
|
||||||
abortCursorSession,
|
abortCursorSession,
|
||||||
|
isCursorSessionActive,
|
||||||
|
getActiveCursorSessions,
|
||||||
} from './cursor-cli.js';
|
} from './cursor-cli.js';
|
||||||
import {
|
import {
|
||||||
queryCodex,
|
queryCodex,
|
||||||
abortCodexSession,
|
abortCodexSession,
|
||||||
|
isCodexSessionActive,
|
||||||
|
getActiveCodexSessions,
|
||||||
} from './openai-codex.js';
|
} from './openai-codex.js';
|
||||||
import {
|
import {
|
||||||
spawnGemini,
|
spawnGemini,
|
||||||
abortGeminiSession,
|
abortGeminiSession,
|
||||||
|
isGeminiSessionActive,
|
||||||
|
getActiveGeminiSessions,
|
||||||
} from './gemini-cli.js';
|
} from './gemini-cli.js';
|
||||||
import {
|
import {
|
||||||
spawnOpenCode,
|
spawnOpenCode,
|
||||||
abortOpenCodeSession,
|
abortOpenCodeSession,
|
||||||
|
isOpenCodeSessionActive,
|
||||||
|
getActiveOpenCodeSessions,
|
||||||
} from './opencode-cli.js';
|
} from './opencode-cli.js';
|
||||||
import sessionManager from './sessionManager.js';
|
import sessionManager from './sessionManager.js';
|
||||||
import {
|
import {
|
||||||
@@ -94,35 +105,32 @@ const wss = createWebSocketServer(server, {
|
|||||||
authenticateWebSocket,
|
authenticateWebSocket,
|
||||||
},
|
},
|
||||||
chat: {
|
chat: {
|
||||||
spawnFns: {
|
queryClaudeSDK,
|
||||||
claude: queryClaudeSDK,
|
spawnCursor,
|
||||||
cursor: spawnCursor,
|
queryCodex,
|
||||||
codex: queryCodex,
|
spawnGemini,
|
||||||
gemini: spawnGemini,
|
spawnOpenCode,
|
||||||
opencode: spawnOpenCode,
|
abortClaudeSDKSession,
|
||||||
},
|
abortCursorSession,
|
||||||
abortFns: {
|
abortCodexSession,
|
||||||
claude: abortClaudeSDKSession,
|
abortGeminiSession,
|
||||||
cursor: abortCursorSession,
|
abortOpenCodeSession,
|
||||||
codex: abortCodexSession,
|
|
||||||
gemini: abortGeminiSession,
|
|
||||||
opencode: abortOpenCodeSession,
|
|
||||||
},
|
|
||||||
resolveToolApproval,
|
resolveToolApproval,
|
||||||
|
isClaudeSDKSessionActive,
|
||||||
|
isCursorSessionActive,
|
||||||
|
isCodexSessionActive,
|
||||||
|
isGeminiSessionActive,
|
||||||
|
isOpenCodeSessionActive,
|
||||||
|
reconnectSessionWriter,
|
||||||
getPendingApprovalsForSession,
|
getPendingApprovalsForSession,
|
||||||
|
getActiveClaudeSDKSessions,
|
||||||
|
getActiveCursorSessions,
|
||||||
|
getActiveCodexSessions,
|
||||||
|
getActiveGeminiSessions,
|
||||||
|
getActiveOpenCodeSessions,
|
||||||
},
|
},
|
||||||
shell: {
|
shell: {
|
||||||
resolveProviderSessionId: (sessionId, provider) => {
|
getSessionById: (sessionId) => sessionManager.getSession(sessionId),
|
||||||
const dbSession = sessionsDb.getSessionById(sessionId);
|
|
||||||
const legacyGeminiSession =
|
|
||||||
provider === 'gemini' ? sessionManager.getSession(sessionId) : null;
|
|
||||||
|
|
||||||
if (dbSession) {
|
|
||||||
return dbSession.provider_session_id ?? legacyGeminiSession?.cliSessionId ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return legacyGeminiSession?.cliSessionId;
|
|
||||||
},
|
|
||||||
stripAnsiSequences,
|
stripAnsiSequences,
|
||||||
normalizeDetectedUrl,
|
normalizeDetectedUrl,
|
||||||
extractUrlsFromText,
|
extractUrlsFromText,
|
||||||
@@ -1135,6 +1143,7 @@ app.post('/api/projects/:projectId/upload-images', authenticateToken, async (req
|
|||||||
app.get('/api/projects/:projectId/sessions/:sessionId/token-usage', authenticateToken, async (req, res) => {
|
app.get('/api/projects/:projectId/sessions/:sessionId/token-usage', authenticateToken, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { projectId, sessionId } = req.params;
|
const { projectId, sessionId } = req.params;
|
||||||
|
const { provider = 'claude' } = req.query;
|
||||||
const homeDir = os.homedir();
|
const homeDir = os.homedir();
|
||||||
|
|
||||||
// Allow only safe characters in sessionId
|
// Allow only safe characters in sessionId
|
||||||
@@ -1143,18 +1152,6 @@ app.get('/api/projects/:projectId/sessions/:sessionId/token-usage', authenticate
|
|||||||
return res.status(400).json({ error: 'Invalid sessionId' });
|
return res.status(400).json({ error: 'Invalid sessionId' });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Provider artifacts on disk (JSONL file names, OpenCode sqlite rows)
|
|
||||||
// are keyed by the provider-native session id, while the caller sends
|
|
||||||
// the app-facing id. Resolve provider and id mapping from the indexed
|
|
||||||
// session row so the frontend does not choose provider-specific paths.
|
|
||||||
const sessionRow = sessionsDb.getSessionById(safeSessionId);
|
|
||||||
if (!sessionRow) {
|
|
||||||
return res.status(404).json({ error: 'Session not found', sessionId: safeSessionId });
|
|
||||||
}
|
|
||||||
|
|
||||||
const provider = sessionRow.provider || 'claude';
|
|
||||||
const providerNativeSessionId = sessionRow?.provider_session_id || safeSessionId;
|
|
||||||
|
|
||||||
// Handle Cursor sessions - they use SQLite and don't have token usage info
|
// Handle Cursor sessions - they use SQLite and don't have token usage info
|
||||||
if (provider === 'cursor') {
|
if (provider === 'cursor') {
|
||||||
return res.json({
|
return res.json({
|
||||||
@@ -1255,7 +1252,7 @@ app.get('/api/projects/:projectId/sessions/:sessionId/token-usage', authenticate
|
|||||||
tokens_cache_write AS cacheWriteTokens
|
tokens_cache_write AS cacheWriteTokens
|
||||||
FROM session
|
FROM session
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
`).get(providerNativeSessionId);
|
`).get(safeSessionId);
|
||||||
|
|
||||||
if (!row) {
|
if (!row) {
|
||||||
return res.status(404).json({ error: 'OpenCode session not found', sessionId: safeSessionId });
|
return res.status(404).json({ error: 'OpenCode session not found', sessionId: safeSessionId });
|
||||||
@@ -1296,7 +1293,7 @@ app.get('/api/projects/:projectId/sessions/:sessionId/token-usage', authenticate
|
|||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
const found = await findSessionFile(fullPath);
|
const found = await findSessionFile(fullPath);
|
||||||
if (found) return found;
|
if (found) return found;
|
||||||
} else if (entry.name.includes(providerNativeSessionId) && entry.name.endsWith('.jsonl')) {
|
} else if (entry.name.includes(safeSessionId) && entry.name.endsWith('.jsonl')) {
|
||||||
return fullPath;
|
return fullPath;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1380,19 +1377,12 @@ app.get('/api/projects/:projectId/sessions/:sessionId/token-usage', authenticate
|
|||||||
const encodedPath = projectPath.replace(/[^a-zA-Z0-9-]/g, '-');
|
const encodedPath = projectPath.replace(/[^a-zA-Z0-9-]/g, '-');
|
||||||
const projectDir = path.join(homeDir, '.claude', 'projects', encodedPath);
|
const projectDir = path.join(homeDir, '.claude', 'projects', encodedPath);
|
||||||
|
|
||||||
// Prefer the indexed transcript path (already produced by the trusted
|
const jsonlPath = path.join(projectDir, `${safeSessionId}.jsonl`);
|
||||||
// session synchronizer); fall back to the conventional location
|
|
||||||
// derived from the provider-native session id.
|
|
||||||
let jsonlPath = sessionRow?.jsonl_path;
|
|
||||||
if (!jsonlPath) {
|
|
||||||
jsonlPath = path.join(projectDir, `${providerNativeSessionId}.jsonl`);
|
|
||||||
|
|
||||||
// Constrain the constructed path to projectDir (the id is
|
// Constrain to projectDir
|
||||||
// caller-influenced in this fallback branch).
|
const rel = path.relative(path.resolve(projectDir), path.resolve(jsonlPath));
|
||||||
const rel = path.relative(path.resolve(projectDir), path.resolve(jsonlPath));
|
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
||||||
if (rel.startsWith('..') || path.isAbsolute(rel)) {
|
return res.status(400).json({ error: 'Invalid path' });
|
||||||
return res.status(400).json({ error: 'Invalid path' });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read and parse the JSONL file
|
// Read and parse the JSONL file
|
||||||
|
|||||||
@@ -382,25 +382,6 @@ const rebuildSessionsTableWithProjectSchema = (db: Database): void => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds the `provider_session_id` mapping column used by the session gateway.
|
|
||||||
*
|
|
||||||
* Rows that existed before this migration were always keyed directly by the
|
|
||||||
* provider-native session id, so backfilling `provider_session_id` with
|
|
||||||
* `session_id` keeps every legacy row resolvable through the new mapping.
|
|
||||||
*/
|
|
||||||
const addProviderSessionIdMapping = (db: Database): void => {
|
|
||||||
const sessionsTableInfo = getTableInfo(db, 'sessions');
|
|
||||||
const columnNames = sessionsTableInfo.map((column) => column.name);
|
|
||||||
|
|
||||||
addColumnToTableIfNotExists(db, 'sessions', columnNames, 'provider_session_id', 'TEXT');
|
|
||||||
db.exec(`
|
|
||||||
UPDATE sessions
|
|
||||||
SET provider_session_id = session_id
|
|
||||||
WHERE provider_session_id IS NULL
|
|
||||||
`);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ensureProjectsForSessionPaths = (db: Database): void => {
|
const ensureProjectsForSessionPaths = (db: Database): void => {
|
||||||
if (!tableExists(db, 'sessions')) {
|
if (!tableExists(db, 'sessions')) {
|
||||||
return;
|
return;
|
||||||
@@ -447,11 +428,9 @@ export const runMigrations = (db: Database) => {
|
|||||||
migrateLegacyWorkspaceTableIntoProjects(db);
|
migrateLegacyWorkspaceTableIntoProjects(db);
|
||||||
rebuildSessionsTableWithProjectSchema(db);
|
rebuildSessionsTableWithProjectSchema(db);
|
||||||
migrateLegacySessionNames(db);
|
migrateLegacySessionNames(db);
|
||||||
addProviderSessionIdMapping(db);
|
|
||||||
ensureProjectsForSessionPaths(db);
|
ensureProjectsForSessionPaths(db);
|
||||||
|
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_session_ids_lookup ON sessions(session_id)');
|
db.exec('CREATE INDEX IF NOT EXISTS idx_session_ids_lookup ON sessions(session_id)');
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_sessions_provider_session_id ON sessions(provider_session_id)');
|
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_sessions_project_path ON sessions(project_path)');
|
db.exec('CREATE INDEX IF NOT EXISTS idx_sessions_project_path ON sessions(project_path)');
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_sessions_is_archived ON sessions(isArchived)');
|
db.exec('CREATE INDEX IF NOT EXISTS idx_sessions_is_archived ON sessions(isArchived)');
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_projects_is_starred ON projects(isStarred)');
|
db.exec('CREATE INDEX IF NOT EXISTS idx_projects_is_starred ON projects(isStarred)');
|
||||||
|
|||||||
@@ -70,15 +70,3 @@ test('createSession reactivates archived rows when the session becomes active ag
|
|||||||
assert.equal(restoredSession?.isArchived, 0);
|
assert.equal(restoredSession?.isArchived, 0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test('repository reads normalize SQLite UTC timestamps to ISO strings', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('session-timezone', 'claude', '/workspace/demo-project');
|
|
||||||
|
|
||||||
const row = sessionsDb.getSessionById('session-timezone');
|
|
||||||
assert.ok(row?.created_at.endsWith('Z'));
|
|
||||||
assert.ok(row?.updated_at.endsWith('Z'));
|
|
||||||
assert.match(row?.created_at ?? '', /^\d{4}-\d{2}-\d{2}T/);
|
|
||||||
assert.match(row?.updated_at ?? '', /^\d{4}-\d{2}-\d{2}T/);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { normalizeProjectPath } from '@/shared/utils.js';
|
|||||||
type SessionRow = {
|
type SessionRow = {
|
||||||
session_id: string;
|
session_id: string;
|
||||||
provider: string;
|
provider: string;
|
||||||
provider_session_id: string | null;
|
|
||||||
project_path: string | null;
|
project_path: string | null;
|
||||||
jsonl_path: string | null;
|
jsonl_path: string | null;
|
||||||
custom_name: string | null;
|
custom_name: string | null;
|
||||||
@@ -14,22 +13,15 @@ type SessionRow = {
|
|||||||
updated_at: string;
|
updated_at: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const SESSION_ROW_COLUMNS =
|
type SessionMetadataLookupRow = Pick<
|
||||||
'session_id, provider, provider_session_id, project_path, jsonl_path, custom_name, isArchived, created_at, updated_at';
|
SessionRow,
|
||||||
|
'session_id' | 'provider' | 'project_path' | 'jsonl_path' | 'custom_name' | 'isArchived' | 'created_at' | 'updated_at'
|
||||||
const SQLITE_UTC_TIMESTAMP_REGEX = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
>;
|
||||||
|
|
||||||
function normalizeTimestamp(value?: string): string | null {
|
function normalizeTimestamp(value?: string): string | null {
|
||||||
if (!value) return null;
|
if (!value) return null;
|
||||||
|
|
||||||
// SQLite CURRENT_TIMESTAMP is stored as UTC without a timezone suffix.
|
const parsed = new Date(value);
|
||||||
// Normalize it here so every session reader returns canonical ISO strings
|
|
||||||
// and the sidebar never interprets fresh rows as local-time "hours old".
|
|
||||||
const normalizedValue = SQLITE_UTC_TIMESTAMP_REGEX.test(value)
|
|
||||||
? `${value.replace(' ', 'T')}Z`
|
|
||||||
: value;
|
|
||||||
|
|
||||||
const parsed = new Date(normalizedValue);
|
|
||||||
if (Number.isNaN(parsed.getTime())) {
|
if (Number.isNaN(parsed.getTime())) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -37,38 +29,14 @@ function normalizeTimestamp(value?: string): string | null {
|
|||||||
return parsed.toISOString();
|
return parsed.toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
function normalizeSessionRow<T extends SessionRow | null | undefined>(row: T): T {
|
|
||||||
if (!row) {
|
|
||||||
return row;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...row,
|
|
||||||
created_at: normalizeTimestamp(row.created_at) ?? row.created_at,
|
|
||||||
updated_at: normalizeTimestamp(row.updated_at) ?? row.updated_at,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeSessionRows(rows: SessionRow[]): SessionRow[] {
|
|
||||||
return rows.map((row) => normalizeSessionRow(row) as SessionRow);
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeProjectPathForProvider(provider: string, projectPath: string): string {
|
function normalizeProjectPathForProvider(provider: string, projectPath: string): string {
|
||||||
void provider;
|
void provider;
|
||||||
return normalizeProjectPath(projectPath);
|
return normalizeProjectPath(projectPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const sessionsDb = {
|
export const sessionsDb = {
|
||||||
/**
|
|
||||||
* Upserts one session row discovered on disk by a provider synchronizer.
|
|
||||||
*
|
|
||||||
* The given id is the provider-native session id. Rows are keyed by
|
|
||||||
* `provider_session_id` so a session that was first created by the app
|
|
||||||
* (with an app-allocated `session_id`) is updated in place once its
|
|
||||||
* transcript shows up on disk, instead of producing a duplicate row.
|
|
||||||
*/
|
|
||||||
createSession(
|
createSession(
|
||||||
providerSessionId: string,
|
sessionId: string,
|
||||||
provider: string,
|
provider: string,
|
||||||
projectPath: string,
|
projectPath: string,
|
||||||
customName?: string,
|
customName?: string,
|
||||||
@@ -85,54 +53,19 @@ export const sessionsDb = {
|
|||||||
// since it's a foreign key in the sessions table.
|
// since it's a foreign key in the sessions table.
|
||||||
projectsDb.createProjectPath(normalizedProjectPath);
|
projectsDb.createProjectPath(normalizedProjectPath);
|
||||||
|
|
||||||
const existing = db
|
|
||||||
.prepare(
|
|
||||||
`SELECT session_id FROM sessions
|
|
||||||
WHERE provider_session_id = ? AND provider = ?
|
|
||||||
LIMIT 1`
|
|
||||||
)
|
|
||||||
.get(providerSessionId, provider) as { session_id: string } | undefined;
|
|
||||||
|
|
||||||
if (existing) {
|
|
||||||
db.prepare(
|
|
||||||
`UPDATE sessions SET
|
|
||||||
provider = ?,
|
|
||||||
updated_at = COALESCE(?, CURRENT_TIMESTAMP),
|
|
||||||
project_path = ?,
|
|
||||||
jsonl_path = ?,
|
|
||||||
isArchived = 0,
|
|
||||||
custom_name = COALESCE(?, custom_name)
|
|
||||||
WHERE session_id = ?`
|
|
||||||
).run(
|
|
||||||
provider,
|
|
||||||
updatedAtValue,
|
|
||||||
normalizedProjectPath,
|
|
||||||
jsonlPath ?? null,
|
|
||||||
customName ?? null,
|
|
||||||
existing.session_id
|
|
||||||
);
|
|
||||||
|
|
||||||
return existing.session_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sessions created outside the app (directly via the provider CLI) are
|
|
||||||
// keyed by the provider-native id for both columns. The ON CONFLICT path
|
|
||||||
// covers legacy rows that predate the provider_session_id mapping.
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`INSERT INTO sessions (session_id, provider, provider_session_id, custom_name, project_path, jsonl_path, isArchived, created_at, updated_at)
|
`INSERT INTO sessions (session_id, provider, custom_name, project_path, jsonl_path, isArchived, created_at, updated_at)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, 0, COALESCE(?, CURRENT_TIMESTAMP), COALESCE(?, CURRENT_TIMESTAMP))
|
VALUES (?, ?, ?, ?, ?, 0, COALESCE(?, CURRENT_TIMESTAMP), COALESCE(?, CURRENT_TIMESTAMP))
|
||||||
ON CONFLICT(session_id) DO UPDATE SET
|
ON CONFLICT(session_id) DO UPDATE SET
|
||||||
provider = excluded.provider,
|
provider = excluded.provider,
|
||||||
provider_session_id = excluded.provider_session_id,
|
|
||||||
updated_at = excluded.updated_at,
|
updated_at = excluded.updated_at,
|
||||||
project_path = excluded.project_path,
|
project_path = excluded.project_path,
|
||||||
jsonl_path = excluded.jsonl_path,
|
jsonl_path = excluded.jsonl_path,
|
||||||
isArchived = 0,
|
isArchived = 0,
|
||||||
custom_name = COALESCE(excluded.custom_name, sessions.custom_name)`
|
custom_name = COALESCE(excluded.custom_name, sessions.custom_name)`
|
||||||
).run(
|
).run(
|
||||||
providerSessionId,
|
sessionId,
|
||||||
provider,
|
provider,
|
||||||
providerSessionId,
|
|
||||||
customName ?? null,
|
customName ?? null,
|
||||||
normalizedProjectPath,
|
normalizedProjectPath,
|
||||||
jsonlPath ?? null,
|
jsonlPath ?? null,
|
||||||
@@ -140,77 +73,9 @@ export const sessionsDb = {
|
|||||||
updatedAtValue
|
updatedAtValue
|
||||||
);
|
);
|
||||||
|
|
||||||
return providerSessionId;
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Inserts one app-allocated session row before any provider run happens.
|
|
||||||
*
|
|
||||||
* The session gateway uses this when the frontend starts a brand-new chat:
|
|
||||||
* `session_id` is the stable app-facing id, while `provider_session_id`
|
|
||||||
* stays NULL until the provider runtime announces its own id and
|
|
||||||
* `assignProviderSessionId` records the mapping.
|
|
||||||
*/
|
|
||||||
createAppSession(sessionId: string, provider: string, projectPath: string): string {
|
|
||||||
const db = getConnection();
|
|
||||||
const normalizedProjectPath = normalizeProjectPathForProvider(provider, projectPath);
|
|
||||||
|
|
||||||
projectsDb.createProjectPath(normalizedProjectPath);
|
|
||||||
|
|
||||||
db.prepare(
|
|
||||||
`INSERT INTO sessions (session_id, provider, provider_session_id, custom_name, project_path, jsonl_path, isArchived, created_at, updated_at)
|
|
||||||
VALUES (?, ?, NULL, NULL, ?, NULL, 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`
|
|
||||||
).run(sessionId, provider, normalizedProjectPath);
|
|
||||||
|
|
||||||
return sessionId;
|
return sessionId;
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
|
||||||
* Records the provider-native session id for one app-allocated session.
|
|
||||||
*
|
|
||||||
* If the filesystem watcher indexed the provider transcript before this
|
|
||||||
* mapping was recorded (a duplicate row keyed by the provider id exists),
|
|
||||||
* the duplicate is merged into the app row: its transcript path and name
|
|
||||||
* are adopted and the duplicate row is removed. Runs in a transaction so
|
|
||||||
* the sidebar can never observe both rows at once.
|
|
||||||
*/
|
|
||||||
assignProviderSessionId(sessionId: string, providerSessionId: string): void {
|
|
||||||
const db = getConnection();
|
|
||||||
|
|
||||||
const merge = db.transaction(() => {
|
|
||||||
const duplicate = db
|
|
||||||
.prepare(
|
|
||||||
`SELECT ${SESSION_ROW_COLUMNS} FROM sessions
|
|
||||||
WHERE (session_id = ? OR provider_session_id = ?)
|
|
||||||
AND session_id <> ?
|
|
||||||
LIMIT 1`
|
|
||||||
)
|
|
||||||
.get(providerSessionId, providerSessionId, sessionId) as SessionRow | undefined;
|
|
||||||
|
|
||||||
if (duplicate) {
|
|
||||||
db.prepare('DELETE FROM sessions WHERE session_id = ?').run(duplicate.session_id);
|
|
||||||
db.prepare(
|
|
||||||
`UPDATE sessions SET
|
|
||||||
provider_session_id = ?,
|
|
||||||
jsonl_path = COALESCE(jsonl_path, ?),
|
|
||||||
custom_name = COALESCE(custom_name, ?),
|
|
||||||
updated_at = CURRENT_TIMESTAMP
|
|
||||||
WHERE session_id = ?`
|
|
||||||
).run(providerSessionId, duplicate.jsonl_path, duplicate.custom_name, sessionId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
db.prepare(
|
|
||||||
`UPDATE sessions SET
|
|
||||||
provider_session_id = ?,
|
|
||||||
updated_at = CURRENT_TIMESTAMP
|
|
||||||
WHERE session_id = ?`
|
|
||||||
).run(providerSessionId, sessionId);
|
|
||||||
});
|
|
||||||
|
|
||||||
merge();
|
|
||||||
},
|
|
||||||
|
|
||||||
updateSessionCustomName(sessionId: string, customName: string): void {
|
updateSessionCustomName(sessionId: string, customName: string): void {
|
||||||
const db = getConnection();
|
const db = getConnection();
|
||||||
db.prepare(
|
db.prepare(
|
||||||
@@ -220,91 +85,30 @@ export const sessionsDb = {
|
|||||||
).run(customName, sessionId);
|
).run(customName, sessionId);
|
||||||
},
|
},
|
||||||
|
|
||||||
getSessionById(sessionId: string): SessionRow | null {
|
getSessionById(sessionId: string): SessionMetadataLookupRow | null {
|
||||||
const db = getConnection();
|
const db = getConnection();
|
||||||
const row = db
|
const row = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT ${SESSION_ROW_COLUMNS}
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, isArchived, created_at, updated_at
|
||||||
FROM sessions
|
FROM sessions
|
||||||
WHERE session_id = ?
|
WHERE session_id = ?
|
||||||
ORDER BY updated_at DESC
|
ORDER BY updated_at DESC
|
||||||
LIMIT 1`
|
LIMIT 1`
|
||||||
)
|
)
|
||||||
.get(sessionId) as SessionRow | undefined;
|
.get(sessionId) as SessionMetadataLookupRow | undefined;
|
||||||
|
|
||||||
return normalizeSessionRow(row) ?? null;
|
return row ?? null;
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves one session row through the provider-native id.
|
|
||||||
*
|
|
||||||
* The filesystem watcher only knows provider ids (they come from transcript
|
|
||||||
* file names), so it uses this lookup to translate disk artifacts back to
|
|
||||||
* the app-facing session row before broadcasting sidebar updates.
|
|
||||||
*/
|
|
||||||
getSessionByProviderSessionId(providerSessionId: string): SessionRow | null {
|
|
||||||
const db = getConnection();
|
|
||||||
const row = db
|
|
||||||
.prepare(
|
|
||||||
`SELECT ${SESSION_ROW_COLUMNS}
|
|
||||||
FROM sessions
|
|
||||||
WHERE provider_session_id = ?
|
|
||||||
ORDER BY updated_at DESC
|
|
||||||
LIMIT 1`
|
|
||||||
)
|
|
||||||
.get(providerSessionId) as SessionRow | undefined;
|
|
||||||
|
|
||||||
return normalizeSessionRow(row) ?? null;
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Finds the newest app-created session for a project that is still waiting
|
|
||||||
* for its provider-native id to be recorded.
|
|
||||||
*
|
|
||||||
* Primary intention: OpenCode can expose a new session in its shared
|
|
||||||
* `opencode.db` before the websocket runtime reports that same provider id
|
|
||||||
* back to our app. At that moment the sidebar already has an optimistic
|
|
||||||
* app-owned session row, but the watcher only knows the provider-native id.
|
|
||||||
*
|
|
||||||
* Without this lookup, the synchronizer would insert a second row keyed by
|
|
||||||
* the provider id, then `assignProviderSessionId()` would merge it a moment
|
|
||||||
* later. That eventually self-heals, but on slow networks the user can still
|
|
||||||
* briefly see two sidebar sessions for the same conversation.
|
|
||||||
*
|
|
||||||
* This helper lets the synchronizer claim the pending app row first, so the
|
|
||||||
* provider id is attached before any watcher-created row exists. The result
|
|
||||||
* is simpler than frontend dedupe and keeps the race resolved at the source.
|
|
||||||
*/
|
|
||||||
findLatestPendingAppSession(provider: string, projectPath: string): SessionRow | null {
|
|
||||||
const db = getConnection();
|
|
||||||
const normalizedProjectPath = normalizeProjectPathForProvider(provider, projectPath);
|
|
||||||
const row = db
|
|
||||||
.prepare(
|
|
||||||
`SELECT ${SESSION_ROW_COLUMNS}
|
|
||||||
FROM sessions
|
|
||||||
WHERE provider = ?
|
|
||||||
AND project_path = ?
|
|
||||||
AND provider_session_id IS NULL
|
|
||||||
AND isArchived = 0
|
|
||||||
ORDER BY datetime(COALESCE(updated_at, created_at)) DESC, session_id DESC
|
|
||||||
LIMIT 1`
|
|
||||||
)
|
|
||||||
.get(provider, normalizedProjectPath) as SessionRow | undefined;
|
|
||||||
|
|
||||||
return normalizeSessionRow(row) ?? null;
|
|
||||||
},
|
},
|
||||||
|
|
||||||
getAllSessions(): SessionRow[] {
|
getAllSessions(): SessionRow[] {
|
||||||
const db = getConnection();
|
const db = getConnection();
|
||||||
const rows = db
|
return db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT ${SESSION_ROW_COLUMNS}
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, isArchived, created_at, updated_at
|
||||||
FROM sessions
|
FROM sessions
|
||||||
WHERE isArchived = 0`
|
WHERE isArchived = 0`
|
||||||
)
|
)
|
||||||
.all() as SessionRow[];
|
.all() as SessionRow[];
|
||||||
|
|
||||||
return normalizeSessionRows(rows);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -313,31 +117,27 @@ export const sessionsDb = {
|
|||||||
*/
|
*/
|
||||||
getArchivedSessions(): SessionRow[] {
|
getArchivedSessions(): SessionRow[] {
|
||||||
const db = getConnection();
|
const db = getConnection();
|
||||||
const rows = db
|
return db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT ${SESSION_ROW_COLUMNS}
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, isArchived, created_at, updated_at
|
||||||
FROM sessions
|
FROM sessions
|
||||||
WHERE isArchived = 1
|
WHERE isArchived = 1
|
||||||
ORDER BY datetime(COALESCE(updated_at, created_at)) DESC, session_id DESC`
|
ORDER BY datetime(COALESCE(updated_at, created_at)) DESC, session_id DESC`
|
||||||
)
|
)
|
||||||
.all() as SessionRow[];
|
.all() as SessionRow[];
|
||||||
|
|
||||||
return normalizeSessionRows(rows);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
getSessionsByProjectPath(projectPath: string): SessionRow[] {
|
getSessionsByProjectPath(projectPath: string): SessionRow[] {
|
||||||
const db = getConnection();
|
const db = getConnection();
|
||||||
const normalizedProjectPath = normalizeProjectPath(projectPath);
|
const normalizedProjectPath = normalizeProjectPath(projectPath);
|
||||||
const rows = db
|
return db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT ${SESSION_ROW_COLUMNS}
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, isArchived, created_at, updated_at
|
||||||
FROM sessions
|
FROM sessions
|
||||||
WHERE project_path = ?
|
WHERE project_path = ?
|
||||||
AND isArchived = 0`
|
AND isArchived = 0`
|
||||||
)
|
)
|
||||||
.all(normalizedProjectPath) as SessionRow[];
|
.all(normalizedProjectPath) as SessionRow[];
|
||||||
|
|
||||||
return normalizeSessionRows(rows);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -347,23 +147,21 @@ export const sessionsDb = {
|
|||||||
getSessionsByProjectPathIncludingArchived(projectPath: string): SessionRow[] {
|
getSessionsByProjectPathIncludingArchived(projectPath: string): SessionRow[] {
|
||||||
const db = getConnection();
|
const db = getConnection();
|
||||||
const normalizedProjectPath = normalizeProjectPath(projectPath);
|
const normalizedProjectPath = normalizeProjectPath(projectPath);
|
||||||
const rows = db
|
return db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT ${SESSION_ROW_COLUMNS}
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, isArchived, created_at, updated_at
|
||||||
FROM sessions
|
FROM sessions
|
||||||
WHERE project_path = ?`
|
WHERE project_path = ?`
|
||||||
)
|
)
|
||||||
.all(normalizedProjectPath) as SessionRow[];
|
.all(normalizedProjectPath) as SessionRow[];
|
||||||
|
|
||||||
return normalizeSessionRows(rows);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
getSessionsByProjectPathPage(projectPath: string, limit: number, offset: number): SessionRow[] {
|
getSessionsByProjectPathPage(projectPath: string, limit: number, offset: number): SessionRow[] {
|
||||||
const db = getConnection();
|
const db = getConnection();
|
||||||
const normalizedProjectPath = normalizeProjectPath(projectPath);
|
const normalizedProjectPath = normalizeProjectPath(projectPath);
|
||||||
const rows = db
|
return db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT ${SESSION_ROW_COLUMNS}
|
`SELECT session_id, provider, project_path, jsonl_path, custom_name, isArchived, created_at, updated_at
|
||||||
FROM sessions
|
FROM sessions
|
||||||
WHERE project_path = ?
|
WHERE project_path = ?
|
||||||
AND isArchived = 0
|
AND isArchived = 0
|
||||||
@@ -371,8 +169,6 @@ export const sessionsDb = {
|
|||||||
LIMIT ? OFFSET ?`
|
LIMIT ? OFFSET ?`
|
||||||
)
|
)
|
||||||
.all(normalizedProjectPath, limit, offset) as SessionRow[];
|
.all(normalizedProjectPath, limit, offset) as SessionRow[];
|
||||||
|
|
||||||
return normalizeSessionRows(rows);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
countSessionsByProjectPath(projectPath: string): number {
|
countSessionsByProjectPath(projectPath: string): number {
|
||||||
|
|||||||
@@ -83,12 +83,6 @@ export const SESSIONS_TABLE_SCHEMA_SQL = `
|
|||||||
CREATE TABLE IF NOT EXISTS sessions (
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
session_id TEXT NOT NULL,
|
session_id TEXT NOT NULL,
|
||||||
provider TEXT NOT NULL DEFAULT 'claude',
|
provider TEXT NOT NULL DEFAULT 'claude',
|
||||||
-- The session id used by the provider CLI/SDK on disk (JSONL file name,
|
|
||||||
-- store.db folder, sqlite row id, ...). \`session_id\` is the stable
|
|
||||||
-- app-facing id that the frontend uses for the whole session lifetime;
|
|
||||||
-- \`provider_session_id\` is filled in once the provider announces its own
|
|
||||||
-- id mid-run, or equals \`session_id\` for sessions discovered on disk.
|
|
||||||
provider_session_id TEXT,
|
|
||||||
custom_name TEXT,
|
custom_name TEXT,
|
||||||
project_path TEXT,
|
project_path TEXT,
|
||||||
jsonl_path TEXT,
|
jsonl_path TEXT,
|
||||||
|
|||||||
@@ -1,108 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import { mkdtemp, rm } from 'node:fs/promises';
|
|
||||||
import { tmpdir } from 'node:os';
|
|
||||||
import path from 'node:path';
|
|
||||||
import test from 'node:test';
|
|
||||||
|
|
||||||
import { closeConnection } from '@/modules/database/connection.js';
|
|
||||||
import { initializeDatabase } from '@/modules/database/init-db.js';
|
|
||||||
import { sessionsDb } from '@/modules/database/repositories/sessions.db.js';
|
|
||||||
|
|
||||||
async function withIsolatedDatabase(runTest: () => void | Promise<void>): Promise<void> {
|
|
||||||
const previousDatabasePath = process.env.DATABASE_PATH;
|
|
||||||
const tempDirectory = await mkdtemp(path.join(tmpdir(), 'sessions-mapping-'));
|
|
||||||
const databasePath = path.join(tempDirectory, 'auth.db');
|
|
||||||
|
|
||||||
closeConnection();
|
|
||||||
process.env.DATABASE_PATH = databasePath;
|
|
||||||
await initializeDatabase();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await runTest();
|
|
||||||
} finally {
|
|
||||||
closeConnection();
|
|
||||||
if (previousDatabasePath === undefined) {
|
|
||||||
delete process.env.DATABASE_PATH;
|
|
||||||
} else {
|
|
||||||
process.env.DATABASE_PATH = previousDatabasePath;
|
|
||||||
}
|
|
||||||
await rm(tempDirectory, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test('disk-discovered sessions are keyed by the provider id for both columns', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createSession('provider-abc', 'claude', '/workspace/demo', 'From Disk');
|
|
||||||
|
|
||||||
const row = sessionsDb.getSessionById('provider-abc');
|
|
||||||
assert.equal(row?.session_id, 'provider-abc');
|
|
||||||
assert.equal(row?.provider_session_id, 'provider-abc');
|
|
||||||
|
|
||||||
const byProviderId = sessionsDb.getSessionByProviderSessionId('provider-abc');
|
|
||||||
assert.equal(byProviderId?.session_id, 'provider-abc');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('app sessions get the provider id assigned without creating a duplicate row', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-id-1', 'claude', '/workspace/demo');
|
|
||||||
sessionsDb.assignProviderSessionId('app-id-1', 'provider-xyz');
|
|
||||||
|
|
||||||
// A later synchronizer pass that discovers the transcript on disk must
|
|
||||||
// update the app row in place instead of inserting a provider-keyed row.
|
|
||||||
const returnedId = sessionsDb.createSession(
|
|
||||||
'provider-xyz',
|
|
||||||
'claude',
|
|
||||||
'/workspace/demo',
|
|
||||||
'Synced Name',
|
|
||||||
undefined,
|
|
||||||
undefined,
|
|
||||||
'/fake/path/provider-xyz.jsonl',
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.equal(returnedId, 'app-id-1');
|
|
||||||
assert.equal(sessionsDb.getAllSessions().length, 1);
|
|
||||||
|
|
||||||
const row = sessionsDb.getSessionById('app-id-1');
|
|
||||||
assert.equal(row?.provider_session_id, 'provider-xyz');
|
|
||||||
assert.equal(row?.jsonl_path, '/fake/path/provider-xyz.jsonl');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('assignProviderSessionId merges a watcher-created duplicate into the app row', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-id-2', 'codex', '/workspace/demo');
|
|
||||||
|
|
||||||
// Simulate the race: the filesystem watcher indexed the provider
|
|
||||||
// transcript before the runtime announced its session id to the gateway.
|
|
||||||
sessionsDb.createSession(
|
|
||||||
'provider-race',
|
|
||||||
'codex',
|
|
||||||
'/workspace/demo',
|
|
||||||
'Watcher Name',
|
|
||||||
undefined,
|
|
||||||
undefined,
|
|
||||||
'/fake/provider-race.jsonl',
|
|
||||||
);
|
|
||||||
assert.equal(sessionsDb.getAllSessions().length, 2);
|
|
||||||
|
|
||||||
sessionsDb.assignProviderSessionId('app-id-2', 'provider-race');
|
|
||||||
|
|
||||||
const rows = sessionsDb.getAllSessions();
|
|
||||||
assert.equal(rows.length, 1);
|
|
||||||
assert.equal(rows[0]?.session_id, 'app-id-2');
|
|
||||||
assert.equal(rows[0]?.provider_session_id, 'provider-race');
|
|
||||||
// Transcript path and name from the duplicate are adopted.
|
|
||||||
assert.equal(rows[0]?.jsonl_path, '/fake/provider-race.jsonl');
|
|
||||||
assert.equal(rows[0]?.custom_name, 'Watcher Name');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('legacy provider-keyed rows stay resolvable through both lookups', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createSession('legacy-1', 'gemini', '/workspace/demo');
|
|
||||||
|
|
||||||
assert.equal(sessionsDb.getSessionById('legacy-1')?.provider, 'gemini');
|
|
||||||
assert.equal(sessionsDb.getSessionByProviderSessionId('legacy-1')?.session_id, 'legacy-1');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -30,6 +30,10 @@ type ProjectApiView = {
|
|||||||
isArchived: boolean;
|
isArchived: boolean;
|
||||||
isStarred: boolean;
|
isStarred: boolean;
|
||||||
sessions: [];
|
sessions: [];
|
||||||
|
cursorSessions: [];
|
||||||
|
codexSessions: [];
|
||||||
|
geminiSessions: [];
|
||||||
|
opencodeSessions: [];
|
||||||
sessionMeta: {
|
sessionMeta: {
|
||||||
hasMore: false;
|
hasMore: false;
|
||||||
total: 0;
|
total: 0;
|
||||||
@@ -78,6 +82,10 @@ function mapProjectRowToApiView(projectRow: ProjectRepositoryRow): ProjectApiVie
|
|||||||
isArchived: Boolean(projectRow.isArchived),
|
isArchived: Boolean(projectRow.isArchived),
|
||||||
isStarred: Boolean(projectRow.isStarred),
|
isStarred: Boolean(projectRow.isStarred),
|
||||||
sessions: [],
|
sessions: [],
|
||||||
|
cursorSessions: [],
|
||||||
|
codexSessions: [],
|
||||||
|
geminiSessions: [],
|
||||||
|
opencodeSessions: [],
|
||||||
sessionMeta: {
|
sessionMeta: {
|
||||||
hasMore: false,
|
hasMore: false,
|
||||||
total: 0,
|
total: 0,
|
||||||
|
|||||||
@@ -9,12 +9,13 @@ import { AppError } from '@/shared/utils.js';
|
|||||||
|
|
||||||
type SessionSummary = {
|
type SessionSummary = {
|
||||||
id: string;
|
id: string;
|
||||||
provider: string;
|
|
||||||
summary: string;
|
summary: string;
|
||||||
messageCount: number;
|
messageCount: number;
|
||||||
lastActivity: string;
|
lastActivity: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type SessionsByProvider = Record<'claude' | 'cursor' | 'codex' | 'gemini' | 'opencode', SessionSummary[]>;
|
||||||
|
|
||||||
type SessionRepositoryRow = {
|
type SessionRepositoryRow = {
|
||||||
provider: string;
|
provider: string;
|
||||||
session_id: string;
|
session_id: string;
|
||||||
@@ -30,6 +31,10 @@ export type ProjectListItem = {
|
|||||||
fullPath: string;
|
fullPath: string;
|
||||||
isStarred: boolean;
|
isStarred: boolean;
|
||||||
sessions: SessionSummary[];
|
sessions: SessionSummary[];
|
||||||
|
cursorSessions: SessionSummary[];
|
||||||
|
codexSessions: SessionSummary[];
|
||||||
|
geminiSessions: SessionSummary[];
|
||||||
|
opencodeSessions: SessionSummary[];
|
||||||
sessionMeta: {
|
sessionMeta: {
|
||||||
hasMore: boolean;
|
hasMore: boolean;
|
||||||
total: number;
|
total: number;
|
||||||
@@ -59,7 +64,7 @@ type SessionPaginationOptions = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
type ProjectSessionsPageResult = {
|
type ProjectSessionsPageResult = {
|
||||||
sessions: SessionSummary[];
|
sessionsByProvider: SessionsByProvider;
|
||||||
total: number;
|
total: number;
|
||||||
hasMore: boolean;
|
hasMore: boolean;
|
||||||
};
|
};
|
||||||
@@ -67,6 +72,10 @@ type ProjectSessionsPageResult = {
|
|||||||
export type ProjectSessionsPageApiView = {
|
export type ProjectSessionsPageApiView = {
|
||||||
projectId: string;
|
projectId: string;
|
||||||
sessions: SessionSummary[];
|
sessions: SessionSummary[];
|
||||||
|
cursorSessions: SessionSummary[];
|
||||||
|
codexSessions: SessionSummary[];
|
||||||
|
geminiSessions: SessionSummary[];
|
||||||
|
opencodeSessions: SessionSummary[];
|
||||||
sessionMeta: {
|
sessionMeta: {
|
||||||
hasMore: boolean;
|
hasMore: boolean;
|
||||||
total: number;
|
total: number;
|
||||||
@@ -120,18 +129,39 @@ function normalizeSessionPagination(options: SessionPaginationOptions = {}): { l
|
|||||||
function mapSessionRowToSummary(row: SessionRepositoryRow): SessionSummary {
|
function mapSessionRowToSummary(row: SessionRepositoryRow): SessionSummary {
|
||||||
return {
|
return {
|
||||||
id: row.session_id,
|
id: row.session_id,
|
||||||
provider: row.provider,
|
|
||||||
summary: row.custom_name || '',
|
summary: row.custom_name || '',
|
||||||
messageCount: 0,
|
messageCount: 0,
|
||||||
lastActivity: row.updated_at ?? row.created_at ?? new Date().toISOString(),
|
lastActivity: row.updated_at ?? row.created_at ?? new Date().toISOString(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function bucketSessionRowsByProvider(rows: SessionRepositoryRow[]): SessionsByProvider {
|
||||||
|
const byProvider: SessionsByProvider = {
|
||||||
|
claude: [],
|
||||||
|
cursor: [],
|
||||||
|
codex: [],
|
||||||
|
gemini: [],
|
||||||
|
opencode: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const provider = row.provider as keyof SessionsByProvider;
|
||||||
|
const bucket = byProvider[provider];
|
||||||
|
if (!bucket) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bucket.push(mapSessionRowToSummary(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
return byProvider;
|
||||||
|
}
|
||||||
|
|
||||||
function readProjectSessionsIncludingArchived(projectPath: string): ProjectSessionsPageResult {
|
function readProjectSessionsIncludingArchived(projectPath: string): ProjectSessionsPageResult {
|
||||||
const rows = sessionsDb.getSessionsByProjectPathIncludingArchived(projectPath) as SessionRepositoryRow[];
|
const rows = sessionsDb.getSessionsByProjectPathIncludingArchived(projectPath) as SessionRepositoryRow[];
|
||||||
|
|
||||||
return {
|
return {
|
||||||
sessions: rows.map(mapSessionRowToSummary),
|
sessionsByProvider: bucketSessionRowsByProvider(rows),
|
||||||
total: rows.length,
|
total: rows.length,
|
||||||
hasMore: false,
|
hasMore: false,
|
||||||
};
|
};
|
||||||
@@ -153,17 +183,16 @@ function readProjectSessionsPageByPath(
|
|||||||
const total = sessionsDb.countSessionsByProjectPath(projectPath);
|
const total = sessionsDb.countSessionsByProjectPath(projectPath);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
sessions: rows.map(mapSessionRowToSummary),
|
sessionsByProvider: bucketSessionRowsByProvider(rows),
|
||||||
total,
|
total,
|
||||||
hasMore: pagination.offset + rows.length < total,
|
hasMore: pagination.offset + rows.length < total,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Broadcast progress to all connected WebSocket clients.
|
// Broadcast progress to all connected WebSocket clients
|
||||||
// Uses the unified `kind` envelope like every other websocket frame.
|
|
||||||
function broadcastProgress(progress: ProgressUpdate) {
|
function broadcastProgress(progress: ProgressUpdate) {
|
||||||
const message = JSON.stringify({
|
const message = JSON.stringify({
|
||||||
kind: 'loading_progress',
|
type: 'loading_progress',
|
||||||
...progress,
|
...progress,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -175,7 +204,7 @@ function broadcastProgress(progress: ProgressUpdate) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reads all projects from DB and returns normalized session summaries.
|
* Reads all projects from DB and returns provider-bucketed session summaries.
|
||||||
*/
|
*/
|
||||||
export async function getProjectsWithSessions(
|
export async function getProjectsWithSessions(
|
||||||
options: GetProjectsWithSessionsOptions = {}
|
options: GetProjectsWithSessionsOptions = {}
|
||||||
@@ -223,7 +252,11 @@ export async function getProjectsWithSessions(
|
|||||||
displayName,
|
displayName,
|
||||||
fullPath: projectPath,
|
fullPath: projectPath,
|
||||||
isStarred: Boolean(row.isStarred),
|
isStarred: Boolean(row.isStarred),
|
||||||
sessions: sessionsPage.sessions,
|
sessions: sessionsPage.sessionsByProvider.claude,
|
||||||
|
cursorSessions: sessionsPage.sessionsByProvider.cursor,
|
||||||
|
codexSessions: sessionsPage.sessionsByProvider.codex,
|
||||||
|
geminiSessions: sessionsPage.sessionsByProvider.gemini,
|
||||||
|
opencodeSessions: sessionsPage.sessionsByProvider.opencode,
|
||||||
sessionMeta: {
|
sessionMeta: {
|
||||||
hasMore: sessionsPage.hasMore,
|
hasMore: sessionsPage.hasMore,
|
||||||
total: sessionsPage.total,
|
total: sessionsPage.total,
|
||||||
@@ -276,7 +309,11 @@ export async function getArchivedProjectsWithSessions(
|
|||||||
fullPath: row.project_path,
|
fullPath: row.project_path,
|
||||||
isStarred: Boolean(row.isStarred),
|
isStarred: Boolean(row.isStarred),
|
||||||
isArchived: true,
|
isArchived: true,
|
||||||
sessions: sessionsPage.sessions,
|
sessions: sessionsPage.sessionsByProvider.claude,
|
||||||
|
cursorSessions: sessionsPage.sessionsByProvider.cursor,
|
||||||
|
codexSessions: sessionsPage.sessionsByProvider.codex,
|
||||||
|
geminiSessions: sessionsPage.sessionsByProvider.gemini,
|
||||||
|
opencodeSessions: sessionsPage.sessionsByProvider.opencode,
|
||||||
sessionMeta: {
|
sessionMeta: {
|
||||||
hasMore: sessionsPage.hasMore,
|
hasMore: sessionsPage.hasMore,
|
||||||
total: sessionsPage.total,
|
total: sessionsPage.total,
|
||||||
@@ -305,7 +342,11 @@ export async function getProjectSessionsPage(
|
|||||||
const sessionsPage = readProjectSessionsPageByPath(projectRow.project_path, options);
|
const sessionsPage = readProjectSessionsPageByPath(projectRow.project_path, options);
|
||||||
return {
|
return {
|
||||||
projectId: projectRow.project_id,
|
projectId: projectRow.project_id,
|
||||||
sessions: sessionsPage.sessions,
|
sessions: sessionsPage.sessionsByProvider.claude,
|
||||||
|
cursorSessions: sessionsPage.sessionsByProvider.cursor,
|
||||||
|
codexSessions: sessionsPage.sessionsByProvider.codex,
|
||||||
|
geminiSessions: sessionsPage.sessionsByProvider.gemini,
|
||||||
|
opencodeSessions: sessionsPage.sessionsByProvider.opencode,
|
||||||
sessionMeta: {
|
sessionMeta: {
|
||||||
hasMore: sessionsPage.hasMore,
|
hasMore: sessionsPage.hasMore,
|
||||||
total: sessionsPage.total,
|
total: sessionsPage.total,
|
||||||
|
|||||||
@@ -111,10 +111,7 @@ export class ClaudeSessionSynchronizer implements IProviderSessionSynchronizer {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// App-created sessions are keyed by an app id, so disk-discovered provider
|
const existingSession = sessionsDb.getSessionById(parsed.sessionId);
|
||||||
// ids must be resolved through the provider-id mapping first.
|
|
||||||
const existingSession = sessionsDb.getSessionByProviderSessionId(parsed.sessionId)
|
|
||||||
?? sessionsDb.getSessionById(parsed.sessionId);
|
|
||||||
const existingSessionName = existingSession?.custom_name;
|
const existingSessionName = existingSession?.custom_name;
|
||||||
if (existingSessionName && existingSessionName !== 'Untitled Claude Session') {
|
if (existingSessionName && existingSessionName !== 'Untitled Claude Session') {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import readline from 'node:readline';
|
|||||||
|
|
||||||
import type { IProviderSessions } from '@/shared/interfaces.js';
|
import type { IProviderSessions } from '@/shared/interfaces.js';
|
||||||
import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
|
import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
|
||||||
import { createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage } from '@/shared/utils.js';
|
import { createNormalizedMessage, generateMessageId, readObjectRecord } from '@/shared/utils.js';
|
||||||
import { sessionsDb } from '@/modules/database/index.js';
|
import { sessionsDb } from '@/modules/database/index.js';
|
||||||
|
|
||||||
const PROVIDER = 'claude';
|
const PROVIDER = 'claude';
|
||||||
@@ -103,13 +103,10 @@ async function parseAgentTools(filePath: string): Promise<AnyRecord[]> {
|
|||||||
|
|
||||||
async function getSessionMessages(
|
async function getSessionMessages(
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
providerSessionId: string,
|
|
||||||
limit: number | null,
|
limit: number | null,
|
||||||
offset: number,
|
offset: number,
|
||||||
): Promise<ClaudeHistoryMessagesResult> {
|
): Promise<ClaudeHistoryMessagesResult> {
|
||||||
try {
|
try {
|
||||||
// The DB row is keyed by the app-facing session id, while the JSONL rows
|
|
||||||
// on disk carry the provider-native id — both ids are needed here.
|
|
||||||
const jsonLPath = sessionsDb.getSessionById(sessionId)?.jsonl_path;
|
const jsonLPath = sessionsDb.getSessionById(sessionId)?.jsonl_path;
|
||||||
|
|
||||||
if (!jsonLPath) {
|
if (!jsonLPath) {
|
||||||
@@ -136,7 +133,7 @@ async function getSessionMessages(
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const entry = JSON.parse(line) as AnyRecord;
|
const entry = JSON.parse(line) as AnyRecord;
|
||||||
if (entry.sessionId === providerSessionId) {
|
if (entry.sessionId === sessionId) {
|
||||||
messages.push(entry);
|
messages.push(entry);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -556,13 +553,12 @@ export class ClaudeSessionsProvider implements IProviderSessions {
|
|||||||
options: FetchHistoryOptions = {},
|
options: FetchHistoryOptions = {},
|
||||||
): Promise<FetchHistoryResult> {
|
): Promise<FetchHistoryResult> {
|
||||||
const { limit = null, offset = 0 } = options;
|
const { limit = null, offset = 0 } = options;
|
||||||
const providerSessionId = options.providerSessionId ?? sessionId;
|
|
||||||
|
|
||||||
let result: ClaudeHistoryResult;
|
let result: ClaudeHistoryResult;
|
||||||
try {
|
try {
|
||||||
// Load full history first so `total` reflects frontend-normalized messages,
|
// Load full history first so `total` reflects frontend-normalized messages,
|
||||||
// not raw JSONL records.
|
// not raw JSONL records.
|
||||||
result = await getSessionMessages(sessionId, providerSessionId, null, 0);
|
result = await getSessionMessages(sessionId, null, 0);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
console.warn(`[ClaudeProvider] Failed to load session ${sessionId}:`, message);
|
console.warn(`[ClaudeProvider] Failed to load session ${sessionId}:`, message);
|
||||||
@@ -610,6 +606,7 @@ export class ClaudeSessionsProvider implements IProviderSessions {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const totalNormalized = normalized.length;
|
||||||
let total = 0;
|
let total = 0;
|
||||||
for (const msg of normalized) {
|
for (const msg of normalized) {
|
||||||
if (msg.kind !== 'tool_result') {
|
if (msg.kind !== 'tool_result') {
|
||||||
@@ -618,10 +615,18 @@ export class ClaudeSessionsProvider implements IProviderSessions {
|
|||||||
}
|
}
|
||||||
const normalizedOffset = Math.max(0, offset);
|
const normalizedOffset = Math.max(0, offset);
|
||||||
const normalizedLimit = limit === null ? null : Math.max(0, limit);
|
const normalizedLimit = limit === null ? null : Math.max(0, limit);
|
||||||
const { page, hasMore } = sliceTailPage(normalized, normalizedLimit, normalizedOffset);
|
const messages = normalizedLimit === null
|
||||||
|
? normalized
|
||||||
|
: normalized.slice(
|
||||||
|
Math.max(0, totalNormalized - normalizedOffset - normalizedLimit),
|
||||||
|
Math.max(0, totalNormalized - normalizedOffset),
|
||||||
|
);
|
||||||
|
const hasMore = normalizedLimit === null
|
||||||
|
? false
|
||||||
|
: Math.max(0, totalNormalized - normalizedOffset - normalizedLimit) > 0;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages: page,
|
messages,
|
||||||
total,
|
total,
|
||||||
hasMore,
|
hasMore,
|
||||||
offset: normalizedOffset,
|
offset: normalizedOffset,
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import spawn from 'cross-spawn';
|
|||||||
|
|
||||||
import type { IProviderAuth } from '@/shared/interfaces.js';
|
import type { IProviderAuth } from '@/shared/interfaces.js';
|
||||||
import type { ProviderAuthStatus } from '@/shared/types.js';
|
import type { ProviderAuthStatus } from '@/shared/types.js';
|
||||||
import { createCodexRuntimeEnv, resolveCodexExecutablePath } from '@/shared/codex-cli-runtime.js';
|
|
||||||
import { readObjectRecord, readOptionalString } from '@/shared/utils.js';
|
import { readObjectRecord, readOptionalString } from '@/shared/utils.js';
|
||||||
|
|
||||||
type CodexCredentialsStatus = {
|
type CodexCredentialsStatus = {
|
||||||
@@ -22,12 +21,8 @@ export class CodexProviderAuth implements IProviderAuth {
|
|||||||
*/
|
*/
|
||||||
private checkInstalled(): boolean {
|
private checkInstalled(): boolean {
|
||||||
try {
|
try {
|
||||||
const result = spawn.sync(resolveCodexExecutablePath(), ['--version'], {
|
spawn.sync('codex', ['--version'], { stdio: 'ignore', timeout: 5000 });
|
||||||
env: createCodexRuntimeEnv(),
|
return true;
|
||||||
stdio: 'ignore',
|
|
||||||
timeout: 5000,
|
|
||||||
});
|
|
||||||
return !result.error && result.status === 0;
|
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,12 +43,11 @@ export class CodexSessionSynchronizer implements IProviderSessionSynchronizer {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const existingSession = sessionsDb.getSessionByProviderSessionId(parsed.sessionId)
|
const existingSession = sessionsDb.getSessionById(parsed.sessionId);
|
||||||
?? sessionsDb.getSessionById(parsed.sessionId);
|
|
||||||
if (existingSession) {
|
if (existingSession) {
|
||||||
// If session name is untitled and we now have a name, update it
|
// If session name is untitled and we now have a name, update it
|
||||||
if (existingSession.custom_name === 'Untitled Codex Session' && parsed.sessionName && parsed.sessionName !== 'Untitled Codex Session') {
|
if (existingSession.custom_name === 'Untitled Codex Session' && parsed.sessionName && parsed.sessionName !== 'Untitled Codex Session') {
|
||||||
sessionsDb.updateSessionCustomName(existingSession.session_id, parsed.sessionName);
|
sessionsDb.updateSessionCustomName(parsed.sessionId, parsed.sessionName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,10 +120,7 @@ export class CodexSessionSynchronizer implements IProviderSessionSynchronizer {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// App-created sessions are keyed by an app id, so disk-discovered provider
|
const existingSession = sessionsDb.getSessionById(parsed.sessionId);
|
||||||
// ids must be resolved through the provider-id mapping first.
|
|
||||||
const existingSession = sessionsDb.getSessionByProviderSessionId(parsed.sessionId)
|
|
||||||
?? sessionsDb.getSessionById(parsed.sessionId);
|
|
||||||
const existingSessionName = existingSession?.custom_name;
|
const existingSessionName = existingSession?.custom_name;
|
||||||
if (existingSessionName && existingSessionName !== 'Untitled Codex Session') {
|
if (existingSessionName && existingSessionName !== 'Untitled Codex Session') {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import readline from 'node:readline';
|
|||||||
import { sessionsDb } from '@/modules/database/index.js';
|
import { sessionsDb } from '@/modules/database/index.js';
|
||||||
import type { IProviderSessions } from '@/shared/interfaces.js';
|
import type { IProviderSessions } from '@/shared/interfaces.js';
|
||||||
import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
|
import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
|
||||||
import { createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage } from '@/shared/utils.js';
|
import { createNormalizedMessage, generateMessageId, readObjectRecord } from '@/shared/utils.js';
|
||||||
|
|
||||||
const PROVIDER = 'codex';
|
const PROVIDER = 'codex';
|
||||||
|
|
||||||
@@ -552,6 +552,7 @@ export class CodexSessionsProvider implements IProviderSessions {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const totalNormalized = normalized.length;
|
||||||
let total = 0;
|
let total = 0;
|
||||||
for (const msg of normalized) {
|
for (const msg of normalized) {
|
||||||
if (msg.kind !== 'tool_result') {
|
if (msg.kind !== 'tool_result') {
|
||||||
@@ -560,10 +561,18 @@ export class CodexSessionsProvider implements IProviderSessions {
|
|||||||
}
|
}
|
||||||
const normalizedOffset = Math.max(0, offset);
|
const normalizedOffset = Math.max(0, offset);
|
||||||
const normalizedLimit = limit === null ? null : Math.max(0, limit);
|
const normalizedLimit = limit === null ? null : Math.max(0, limit);
|
||||||
const { page, hasMore } = sliceTailPage(normalized, normalizedLimit, normalizedOffset);
|
const messages = normalizedLimit === null
|
||||||
|
? normalized
|
||||||
|
: normalized.slice(
|
||||||
|
Math.max(0, totalNormalized - normalizedOffset - normalizedLimit),
|
||||||
|
Math.max(0, totalNormalized - normalizedOffset),
|
||||||
|
);
|
||||||
|
const hasMore = normalizedLimit === null
|
||||||
|
? false
|
||||||
|
: Math.max(0, totalNormalized - normalizedOffset - normalizedLimit) > 0;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages: page,
|
messages,
|
||||||
total,
|
total,
|
||||||
hasMore,
|
hasMore,
|
||||||
offset: normalizedOffset,
|
offset: normalizedOffset,
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
generateMessageId,
|
generateMessageId,
|
||||||
readObjectRecord,
|
readObjectRecord,
|
||||||
sanitizeLeafDirectoryName,
|
sanitizeLeafDirectoryName,
|
||||||
sliceTailPage,
|
|
||||||
} from '@/shared/utils.js';
|
} from '@/shared/utils.js';
|
||||||
|
|
||||||
const PROVIDER = 'cursor';
|
const PROVIDER = 'cursor';
|
||||||
@@ -364,32 +363,42 @@ export class CursorSessionsProvider implements IProviderSessions {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetches and paginates Cursor session history from its project-scoped store.db.
|
* Fetches and paginates Cursor session history from its project-scoped store.db.
|
||||||
*
|
|
||||||
* Pagination follows the shared tail contract (`sliceTailPage`): offset 0 is
|
|
||||||
* the most recent page, matching every other provider.
|
|
||||||
*/
|
*/
|
||||||
async fetchHistory(
|
async fetchHistory(
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
options: FetchHistoryOptions = {},
|
options: FetchHistoryOptions = {},
|
||||||
): Promise<FetchHistoryResult> {
|
): Promise<FetchHistoryResult> {
|
||||||
const { projectPath = '', limit = null, offset = 0 } = options;
|
const { projectPath = '', limit = null, offset = 0 } = options;
|
||||||
// The store.db folder on disk is named after the provider-native id, not
|
|
||||||
// the app-facing session id this method is addressed with.
|
|
||||||
const providerSessionId = options.providerSessionId ?? sessionId;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const blobs = await this.loadCursorBlobs(providerSessionId, projectPath);
|
const blobs = await this.loadCursorBlobs(sessionId, projectPath);
|
||||||
const allNormalized = this.normalizeCursorBlobs(blobs, sessionId);
|
const allNormalized = this.normalizeCursorBlobs(blobs, sessionId);
|
||||||
const renderableMessages = allNormalized.filter((msg) => msg.kind !== 'tool_result');
|
const renderableMessages = allNormalized.filter((msg) => msg.kind !== 'tool_result');
|
||||||
const total = renderableMessages.length;
|
const total = renderableMessages.length;
|
||||||
const { page, hasMore } = sliceTailPage(renderableMessages, limit, offset);
|
|
||||||
|
if (limit !== null) {
|
||||||
|
const start = offset;
|
||||||
|
const page = limit === 0
|
||||||
|
? []
|
||||||
|
: renderableMessages.slice(start, start + limit);
|
||||||
|
const hasMore = limit === 0
|
||||||
|
? start < total
|
||||||
|
: start + limit < total;
|
||||||
|
return {
|
||||||
|
messages: page,
|
||||||
|
total,
|
||||||
|
hasMore,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages: page,
|
messages: renderableMessages,
|
||||||
total,
|
total,
|
||||||
hasMore,
|
hasMore: false,
|
||||||
offset,
|
offset: 0,
|
||||||
limit,
|
limit: null,
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
|
|||||||
@@ -12,14 +12,17 @@ import {
|
|||||||
|
|
||||||
export const GEMINI_FALLBACK_MODELS: ProviderModelsDefinition = {
|
export const GEMINI_FALLBACK_MODELS: ProviderModelsDefinition = {
|
||||||
OPTIONS: [
|
OPTIONS: [
|
||||||
|
{ value: 'gemini-3.1-pro-preview', label: 'Gemini 3.1 Pro Preview' },
|
||||||
|
{ value: 'gemini-3-pro-preview', label: 'Gemini 3 Pro Preview' },
|
||||||
{ value: 'gemini-3-flash-preview', label: 'Gemini 3 Flash Preview' },
|
{ value: 'gemini-3-flash-preview', label: 'Gemini 3 Flash Preview' },
|
||||||
{ value: 'gemini-3.1-flash-lite-preview', label: 'Gemini 3.1 Flash Lite Preview' },
|
|
||||||
{ value: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
|
{ value: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' },
|
||||||
{ value: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' },
|
{ value: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' },
|
||||||
{ value: 'gemma-4-31b-it', label: 'Gemma 4 31B IT' },
|
{ value: 'gemini-2.0-flash-lite', label: 'Gemini 2.0 Flash Lite' },
|
||||||
{ value: 'gemma-4-26b-a4b-it', label: 'Gemma 4 26B A4B IT' },
|
{ value: 'gemini-2.0-flash', label: 'Gemini 2.0 Flash' },
|
||||||
|
{ value: 'gemini-2.0-pro-exp', label: 'Gemini 2.0 Pro Experimental' },
|
||||||
|
{ value: 'gemini-2.0-flash-thinking-exp', label: 'Gemini 2.0 Flash Thinking' },
|
||||||
],
|
],
|
||||||
DEFAULT: 'gemini-3-flash-preview',
|
DEFAULT: 'gemini-3.1-pro-preview',
|
||||||
};
|
};
|
||||||
|
|
||||||
export class GeminiProviderModels implements IProviderModels {
|
export class GeminiProviderModels implements IProviderModels {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import readline from 'node:readline';
|
|||||||
import { sessionsDb } from '@/modules/database/index.js';
|
import { sessionsDb } from '@/modules/database/index.js';
|
||||||
import type { IProviderSessions } from '@/shared/interfaces.js';
|
import type { IProviderSessions } from '@/shared/interfaces.js';
|
||||||
import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
|
import type { AnyRecord, FetchHistoryOptions, FetchHistoryResult, NormalizedMessage } from '@/shared/types.js';
|
||||||
import { createNormalizedMessage, generateMessageId, readObjectRecord, sliceTailPage } from '@/shared/utils.js';
|
import { createNormalizedMessage, generateMessageId, readObjectRecord } from '@/shared/utils.js';
|
||||||
|
|
||||||
const PROVIDER = 'gemini';
|
const PROVIDER = 'gemini';
|
||||||
|
|
||||||
@@ -518,9 +518,9 @@ export class GeminiSessionsProvider implements IProviderSessions {
|
|||||||
|
|
||||||
const start = Math.max(0, offset);
|
const start = Math.max(0, offset);
|
||||||
const pageLimit = limit === null ? null : Math.max(0, limit);
|
const pageLimit = limit === null ? null : Math.max(0, limit);
|
||||||
// Tail pagination via the shared contract: offset 0 returns the most
|
const messages = pageLimit === null
|
||||||
// recent page, matching every other provider.
|
? normalized.slice(start)
|
||||||
const { page, hasMore } = sliceTailPage(normalized, pageLimit, start);
|
: normalized.slice(start, start + pageLimit);
|
||||||
let total = 0;
|
let total = 0;
|
||||||
for (const msg of normalized) {
|
for (const msg of normalized) {
|
||||||
if (msg.kind !== 'tool_result') {
|
if (msg.kind !== 'tool_result') {
|
||||||
@@ -529,9 +529,9 @@ export class GeminiSessionsProvider implements IProviderSessions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages: page,
|
messages,
|
||||||
total,
|
total,
|
||||||
hasMore,
|
hasMore: pageLimit === null ? false : start + pageLimit < normalized.length,
|
||||||
offset: start,
|
offset: start,
|
||||||
limit: pageLimit,
|
limit: pageLimit,
|
||||||
tokenUsage: result.tokenUsage,
|
tokenUsage: result.tokenUsage,
|
||||||
|
|||||||
@@ -112,21 +112,7 @@ export class OpenCodeSessionSynchronizer implements IProviderSessionSynchronizer
|
|||||||
}
|
}
|
||||||
|
|
||||||
const fallbackTitle = 'Untitled OpenCode Session';
|
const fallbackTitle = 'Untitled OpenCode Session';
|
||||||
const pendingAppSession = sessionsDb.getSessionByProviderSessionId(sessionId)
|
const existingSession = sessionsDb.getSessionById(sessionId);
|
||||||
?? sessionsDb.getSessionById(sessionId)
|
|
||||||
?? sessionsDb.findLatestPendingAppSession(this.provider, projectPath);
|
|
||||||
if (pendingAppSession && !pendingAppSession.provider_session_id) {
|
|
||||||
// Slow networks can let the sqlite watcher index opencode.db before the
|
|
||||||
// runtime reports its provider id back through the websocket mapping.
|
|
||||||
// Bind that id to the fresh app row first so the watcher does not create
|
|
||||||
// a temporary provider-id sidebar entry for the same session.
|
|
||||||
sessionsDb.assignProviderSessionId(pendingAppSession.session_id, sessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
// App-created sessions are keyed by an app id, so disk-discovered provider
|
|
||||||
// ids must be resolved through the provider-id mapping first.
|
|
||||||
const existingSession = sessionsDb.getSessionByProviderSessionId(sessionId)
|
|
||||||
?? sessionsDb.getSessionById(sessionId);
|
|
||||||
const existingName = existingSession?.custom_name;
|
const existingName = existingSession?.custom_name;
|
||||||
const nextName = existingName && existingName !== fallbackTitle
|
const nextName = existingName && existingName !== fallbackTitle
|
||||||
? existingName
|
? existingName
|
||||||
@@ -134,9 +120,7 @@ export class OpenCodeSessionSynchronizer implements IProviderSessionSynchronizer
|
|||||||
|
|
||||||
// OpenCode stores every session in one shared sqlite database, so jsonl_path
|
// OpenCode stores every session in one shared sqlite database, so jsonl_path
|
||||||
// must stay null to avoid deleting opencode.db when one app session is removed.
|
// must stay null to avoid deleting opencode.db when one app session is removed.
|
||||||
// Return the canonical stored row id so watcher-triggered sidebar updates
|
sessionsDb.createSession(
|
||||||
// stay on the app session once provider_session_id has already been mapped.
|
|
||||||
return sessionsDb.createSession(
|
|
||||||
sessionId,
|
sessionId,
|
||||||
this.provider,
|
this.provider,
|
||||||
projectPath,
|
projectPath,
|
||||||
@@ -145,6 +129,8 @@ export class OpenCodeSessionSynchronizer implements IProviderSessionSynchronizer
|
|||||||
normalizeProviderTimestamp(row.time_updated ?? row.time_created),
|
normalizeProviderTimestamp(row.time_updated ?? row.time_created),
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
return sessionId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private readFirstUserText(db: Database.Database, sessionId: string): string | undefined {
|
private readFirstUserText(db: Database.Database, sessionId: string): string | undefined {
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
readObjectRecord,
|
readObjectRecord,
|
||||||
readJsonRecord,
|
readJsonRecord,
|
||||||
readOptionalString,
|
readOptionalString,
|
||||||
sliceTailPage,
|
|
||||||
} from '@/shared/utils.js';
|
} from '@/shared/utils.js';
|
||||||
|
|
||||||
const PROVIDER = 'opencode';
|
const PROVIDER = 'opencode';
|
||||||
@@ -326,9 +325,6 @@ export class OpenCodeSessionsProvider implements IProviderSessions {
|
|||||||
options: FetchHistoryOptions = {},
|
options: FetchHistoryOptions = {},
|
||||||
): Promise<FetchHistoryResult> {
|
): Promise<FetchHistoryResult> {
|
||||||
const { limit = null, offset = 0 } = options;
|
const { limit = null, offset = 0 } = options;
|
||||||
// OpenCode's shared sqlite database keys messages by the provider-native
|
|
||||||
// session id, not the app-facing id this method is addressed with.
|
|
||||||
const providerSessionId = options.providerSessionId ?? sessionId;
|
|
||||||
const db = openOpenCodeDatabase();
|
const db = openOpenCodeDatabase();
|
||||||
if (!db) {
|
if (!db) {
|
||||||
return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
|
return { messages: [], total: 0, hasMore: false, offset: 0, limit: null };
|
||||||
@@ -353,20 +349,27 @@ export class OpenCodeSessionsProvider implements IProviderSessions {
|
|||||||
m.id,
|
m.id,
|
||||||
COALESCE(p.time_created, 0),
|
COALESCE(p.time_created, 0),
|
||||||
p.id
|
p.id
|
||||||
`).all(providerSessionId) as OpenCodeHistoryRow[];
|
`).all(sessionId) as OpenCodeHistoryRow[];
|
||||||
|
|
||||||
const normalized = this.normalizeHistoryRows(rows, sessionId);
|
const normalized = this.normalizeHistoryRows(rows, sessionId);
|
||||||
const tokenUsage = aggregateOpenCodeSessionTokenUsage(db, providerSessionId);
|
const tokenUsage = aggregateOpenCodeSessionTokenUsage(db, sessionId);
|
||||||
|
|
||||||
const normalizedOffset = Math.max(0, offset);
|
const normalizedOffset = Math.max(0, offset);
|
||||||
const normalizedLimit = limit === null ? null : Math.max(0, limit);
|
const normalizedLimit = limit === null ? null : Math.max(0, limit);
|
||||||
const total = normalized.length;
|
const total = normalized.length;
|
||||||
const { page, hasMore } = sliceTailPage(normalized, normalizedLimit, normalizedOffset);
|
const messages = normalizedLimit === null
|
||||||
|
? normalized
|
||||||
|
: normalized.slice(
|
||||||
|
Math.max(0, total - normalizedOffset - normalizedLimit),
|
||||||
|
Math.max(0, total - normalizedOffset),
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
messages: page,
|
messages,
|
||||||
total,
|
total,
|
||||||
hasMore,
|
hasMore: normalizedLimit === null
|
||||||
|
? false
|
||||||
|
: Math.max(0, total - normalizedOffset - normalizedLimit) > 0,
|
||||||
offset: normalizedOffset,
|
offset: normalizedOffset,
|
||||||
limit: normalizedLimit,
|
limit: normalizedLimit,
|
||||||
tokenUsage,
|
tokenUsage,
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import express, { type Request, type Response } from 'express';
|
import express, { type Request, type Response } from 'express';
|
||||||
|
|
||||||
import { providerAuthService } from '@/modules/providers/services/provider-auth.service.js';
|
import { providerAuthService } from '@/modules/providers/services/provider-auth.service.js';
|
||||||
import { providerCapabilitiesService } from '@/modules/providers/services/provider-capabilities.service.js';
|
|
||||||
import { providerMcpService } from '@/modules/providers/services/mcp.service.js';
|
import { providerMcpService } from '@/modules/providers/services/mcp.service.js';
|
||||||
import { providerModelsService } from '@/modules/providers/services/provider-models.service.js';
|
import { providerModelsService } from '@/modules/providers/services/provider-models.service.js';
|
||||||
import { providerSkillsService } from '@/modules/providers/services/skills.service.js';
|
import { providerSkillsService } from '@/modules/providers/services/skills.service.js';
|
||||||
@@ -383,51 +382,7 @@ router.post(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
router.get(
|
|
||||||
'/capabilities',
|
|
||||||
asyncHandler(async (_req: Request, res: Response) => {
|
|
||||||
res.json(createApiSuccessResponse({
|
|
||||||
providers: providerCapabilitiesService.listAllProviderCapabilities(),
|
|
||||||
}));
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
router.get(
|
|
||||||
'/:provider/capabilities',
|
|
||||||
asyncHandler(async (req: Request, res: Response) => {
|
|
||||||
const provider = parseProvider(req.params.provider);
|
|
||||||
res.json(createApiSuccessResponse(
|
|
||||||
providerCapabilitiesService.getProviderCapabilities(provider),
|
|
||||||
));
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
// ----------------- Session routes -----------------
|
// ----------------- Session routes -----------------
|
||||||
/**
|
|
||||||
* Session gateway entry point: allocates the stable app-facing session id for
|
|
||||||
* a brand-new chat. The frontend must call this before the first `chat.send`
|
|
||||||
* so the session id in the URL, the store, and the websocket all agree from
|
|
||||||
* the very first message — there is no client-visible session-id handoff.
|
|
||||||
*/
|
|
||||||
router.post(
|
|
||||||
'/sessions',
|
|
||||||
asyncHandler(async (req: Request, res: Response) => {
|
|
||||||
const body = (req.body ?? {}) as Record<string, unknown>;
|
|
||||||
const provider = parseProvider(body.provider);
|
|
||||||
const projectPath = typeof body.projectPath === 'string' ? body.projectPath : '';
|
|
||||||
const result = sessionsService.createAppSession(provider, projectPath);
|
|
||||||
res.status(201).json(createApiSuccessResponse(result));
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
router.get(
|
|
||||||
'/sessions/running',
|
|
||||||
asyncHandler(async (_req: Request, res: Response) => {
|
|
||||||
const sessions = sessionsService.listRunningSessions();
|
|
||||||
res.json(createApiSuccessResponse({ sessions }));
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
router.get(
|
router.get(
|
||||||
'/sessions/archived',
|
'/sessions/archived',
|
||||||
asyncHandler(async (_req: Request, res: Response) => {
|
asyncHandler(async (_req: Request, res: Response) => {
|
||||||
@@ -504,7 +459,7 @@ router.get(
|
|||||||
limit,
|
limit,
|
||||||
offset,
|
offset,
|
||||||
});
|
});
|
||||||
res.json(createApiSuccessResponse(result));
|
res.json(result);
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,91 +0,0 @@
|
|||||||
import type { LLMProvider } from '@/shared/types.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Static, backend-owned description of what one provider integration supports.
|
|
||||||
*
|
|
||||||
* The frontend renders its composer UI (permission mode picker, image upload,
|
|
||||||
* abort button, ...) purely from this shape, which is what keeps the frontend
|
|
||||||
* free of per-provider conditionals. New provider features should be exposed
|
|
||||||
* here instead of branching on the provider id in React components.
|
|
||||||
*/
|
|
||||||
type ProviderCapabilities = {
|
|
||||||
provider: LLMProvider;
|
|
||||||
/** Permission modes the provider runtime understands, in cycle order. */
|
|
||||||
permissionModes: string[];
|
|
||||||
defaultPermissionMode: string;
|
|
||||||
/** Whether image attachments can be included in a chat.send. */
|
|
||||||
supportsImages: boolean;
|
|
||||||
/** Whether an in-flight run can be cancelled via chat.abort. */
|
|
||||||
supportsAbort: boolean;
|
|
||||||
/** Whether interactive tool permission prompts can reach the UI. */
|
|
||||||
supportsPermissionRequests: boolean;
|
|
||||||
/** Whether the token-usage endpoint has data for this provider. */
|
|
||||||
supportsTokenUsage: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The capability matrix mirrors what each runtime actually implements today:
|
|
||||||
* - permission modes match the option sets accepted by each CLI/SDK.
|
|
||||||
* - only the Claude SDK integration surfaces interactive permission requests.
|
|
||||||
* - Cursor has no token usage endpoint support (its store.db has no usage rows).
|
|
||||||
*/
|
|
||||||
const PROVIDER_CAPABILITIES: Record<LLMProvider, ProviderCapabilities> = {
|
|
||||||
claude: {
|
|
||||||
provider: 'claude',
|
|
||||||
permissionModes: ['default', 'auto', 'acceptEdits', 'bypassPermissions', 'plan'],
|
|
||||||
defaultPermissionMode: 'default',
|
|
||||||
supportsImages: true,
|
|
||||||
supportsAbort: true,
|
|
||||||
supportsPermissionRequests: true,
|
|
||||||
supportsTokenUsage: true,
|
|
||||||
},
|
|
||||||
cursor: {
|
|
||||||
provider: 'cursor',
|
|
||||||
permissionModes: ['default', 'acceptEdits', 'bypassPermissions', 'plan'],
|
|
||||||
defaultPermissionMode: 'default',
|
|
||||||
supportsImages: false,
|
|
||||||
supportsAbort: true,
|
|
||||||
supportsPermissionRequests: false,
|
|
||||||
supportsTokenUsage: false,
|
|
||||||
},
|
|
||||||
codex: {
|
|
||||||
provider: 'codex',
|
|
||||||
permissionModes: ['default', 'acceptEdits', 'bypassPermissions'],
|
|
||||||
defaultPermissionMode: 'default',
|
|
||||||
supportsImages: false,
|
|
||||||
supportsAbort: true,
|
|
||||||
supportsPermissionRequests: false,
|
|
||||||
supportsTokenUsage: true,
|
|
||||||
},
|
|
||||||
gemini: {
|
|
||||||
provider: 'gemini',
|
|
||||||
permissionModes: ['default', 'acceptEdits', 'bypassPermissions', 'plan'],
|
|
||||||
defaultPermissionMode: 'default',
|
|
||||||
supportsImages: false,
|
|
||||||
supportsAbort: true,
|
|
||||||
supportsPermissionRequests: false,
|
|
||||||
supportsTokenUsage: true,
|
|
||||||
},
|
|
||||||
opencode: {
|
|
||||||
provider: 'opencode',
|
|
||||||
permissionModes: ['default'],
|
|
||||||
defaultPermissionMode: 'default',
|
|
||||||
supportsImages: false,
|
|
||||||
supportsAbort: true,
|
|
||||||
supportsPermissionRequests: false,
|
|
||||||
supportsTokenUsage: true,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Application service exposing the provider capability matrix.
|
|
||||||
*/
|
|
||||||
export const providerCapabilitiesService = {
|
|
||||||
getProviderCapabilities(provider: LLMProvider): ProviderCapabilities {
|
|
||||||
return PROVIDER_CAPABILITIES[provider];
|
|
||||||
},
|
|
||||||
|
|
||||||
listAllProviderCapabilities(): ProviderCapabilities[] {
|
|
||||||
return Object.values(PROVIDER_CAPABILITIES);
|
|
||||||
},
|
|
||||||
};
|
|
||||||
@@ -17,7 +17,7 @@ import { readProviderSessionActiveModelChange } from '@/shared/utils.js';
|
|||||||
|
|
||||||
export const PROVIDER_MODELS_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1000;
|
export const PROVIDER_MODELS_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1000;
|
||||||
const PROVIDER_MODELS_CACHE_VERSION = 1;
|
const PROVIDER_MODELS_CACHE_VERSION = 1;
|
||||||
const UNCACHED_PROVIDERS = new Set<LLMProvider>(['claude', 'gemini']);
|
const UNCACHED_PROVIDERS = new Set<LLMProvider>(['claude']);
|
||||||
|
|
||||||
type ProviderModelsServiceDependencies = {
|
type ProviderModelsServiceDependencies = {
|
||||||
resolveProvider?: (provider: LLMProvider) => Pick<IProvider, 'models'>;
|
resolveProvider?: (provider: LLMProvider) => Pick<IProvider, 'models'>;
|
||||||
|
|||||||
@@ -4,11 +4,10 @@ import { promises as fsPromises } from 'node:fs';
|
|||||||
|
|
||||||
import chokidar, { type FSWatcher } from 'chokidar';
|
import chokidar, { type FSWatcher } from 'chokidar';
|
||||||
|
|
||||||
import { projectsDb, sessionsDb } from '@/modules/database/index.js';
|
|
||||||
import { sessionSynchronizerService } from '@/modules/providers/services/session-synchronizer.service.js';
|
import { sessionSynchronizerService } from '@/modules/providers/services/session-synchronizer.service.js';
|
||||||
import { WS_OPEN_STATE, connectedClients } from '@/modules/websocket/index.js';
|
import { WS_OPEN_STATE, connectedClients } from '@/modules/websocket/index.js';
|
||||||
import type { LLMProvider } from '@/shared/types.js';
|
import type { LLMProvider } from '@/shared/types.js';
|
||||||
import { generateDisplayName } from '@/modules/projects/index.js';
|
import { getProjectsWithSessions } from '@/modules/projects/index.js';
|
||||||
|
|
||||||
type WatcherEventType = 'add' | 'change';
|
type WatcherEventType = 'add' | 'change';
|
||||||
|
|
||||||
@@ -59,11 +58,6 @@ const watchers: FSWatcher[] = [];
|
|||||||
type PendingWatcherUpdate = {
|
type PendingWatcherUpdate = {
|
||||||
providers: Set<LLMProvider>;
|
providers: Set<LLMProvider>;
|
||||||
changeTypes: Set<WatcherEventType>;
|
changeTypes: Set<WatcherEventType>;
|
||||||
/**
|
|
||||||
* Provider-native session ids reported by the synchronizers. They are
|
|
||||||
* translated back to app-facing session rows at flush time, because the
|
|
||||||
* transcript file names on disk only ever contain provider ids.
|
|
||||||
*/
|
|
||||||
updatedSessionIds: Set<string>;
|
updatedSessionIds: Set<string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -137,50 +131,6 @@ function queuePendingWatcherUpdate(
|
|||||||
schedulePendingWatcherFlush();
|
schedulePendingWatcherFlush();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Builds one `session_upserted` delta event for a provider-native session id.
|
|
||||||
*
|
|
||||||
* The event carries everything a sidebar needs to upsert the session in place
|
|
||||||
* (session summary plus owning-project metadata), so clients never need a full
|
|
||||||
* project-list refetch when a transcript file changes on disk. Returns `null`
|
|
||||||
* when the id cannot be resolved to an indexed session row.
|
|
||||||
*/
|
|
||||||
async function buildSessionUpsertedEvent(updatedProviderSessionId: string): Promise<string | null> {
|
|
||||||
const row = sessionsDb.getSessionByProviderSessionId(updatedProviderSessionId)
|
|
||||||
?? sessionsDb.getSessionById(updatedProviderSessionId);
|
|
||||||
if (!row || row.isArchived) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const projectPath = row.project_path;
|
|
||||||
const project = projectPath ? projectsDb.getProjectPath(projectPath) : null;
|
|
||||||
const displayName = project?.custom_project_name?.trim()
|
|
||||||
? project.custom_project_name
|
|
||||||
: await generateDisplayName(path.basename(projectPath ?? '') || (projectPath ?? ''), projectPath);
|
|
||||||
|
|
||||||
return JSON.stringify({
|
|
||||||
kind: 'session_upserted',
|
|
||||||
sessionId: row.session_id,
|
|
||||||
provider: row.provider,
|
|
||||||
session: {
|
|
||||||
id: row.session_id,
|
|
||||||
summary: row.custom_name || '',
|
|
||||||
messageCount: 0,
|
|
||||||
lastActivity: row.updated_at ?? row.created_at ?? new Date().toISOString(),
|
|
||||||
},
|
|
||||||
project: project
|
|
||||||
? {
|
|
||||||
projectId: project.project_id,
|
|
||||||
path: project.project_path,
|
|
||||||
fullPath: project.project_path,
|
|
||||||
displayName,
|
|
||||||
isStarred: Boolean(project.isStarred),
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function flushPendingWatcherUpdate(): Promise<void> {
|
async function flushPendingWatcherUpdate(): Promise<void> {
|
||||||
clearPendingWatcherFlushTimer();
|
clearPendingWatcherFlushTimer();
|
||||||
|
|
||||||
@@ -199,29 +149,33 @@ async function flushPendingWatcherUpdate(): Promise<void> {
|
|||||||
watcherRefreshInFlight = true;
|
watcherRefreshInFlight = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Per-session deltas instead of full project snapshots: an upsert of one
|
const updatedProjects = await getProjectsWithSessions({ skipSynchronization: true });
|
||||||
// session can never clobber unrelated client state, so the frontend needs
|
const changeTypes = Array.from(queuedUpdate.changeTypes);
|
||||||
// no "suppress updates while a run is active" protection logic.
|
const watchProviders = Array.from(queuedUpdate.providers);
|
||||||
const events: string[] = [];
|
const updatedSessionIds = Array.from(queuedUpdate.updatedSessionIds);
|
||||||
for (const updatedSessionId of queuedUpdate.updatedSessionIds) {
|
|
||||||
const event = await buildSessionUpsertedEvent(updatedSessionId);
|
|
||||||
if (event) {
|
|
||||||
events.push(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (events.length > 0) {
|
// Backward-compatible fields stay populated with the first queued values.
|
||||||
connectedClients.forEach(client => {
|
const updateMessage = JSON.stringify({
|
||||||
if (client.readyState === WS_OPEN_STATE) {
|
type: 'projects_updated',
|
||||||
for (const event of events) {
|
projects: updatedProjects,
|
||||||
client.send(event);
|
timestamp: new Date().toISOString(),
|
||||||
}
|
changeType: changeTypes[0] ?? 'change',
|
||||||
}
|
updatedSessionId: updatedSessionIds[0] ?? undefined,
|
||||||
});
|
watchProvider: watchProviders[0] ?? undefined,
|
||||||
}
|
changeTypes,
|
||||||
|
updatedSessionIds,
|
||||||
|
watchProviders,
|
||||||
|
batched: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
connectedClients.forEach(client => {
|
||||||
|
if (client.readyState === WS_OPEN_STATE) {
|
||||||
|
client.send(updateMessage);
|
||||||
|
}
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
console.error('Session watcher refresh failed while broadcasting session_upserted', { error: message });
|
console.error('Session watcher refresh failed while broadcasting projects_updated', { error: message });
|
||||||
} finally {
|
} finally {
|
||||||
watcherRefreshInFlight = false;
|
watcherRefreshInFlight = false;
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import { randomUUID } from 'node:crypto';
|
|
||||||
import fsp from 'node:fs/promises';
|
import fsp from 'node:fs/promises';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
|
||||||
import { projectsDb, sessionsDb } from '@/modules/database/index.js';
|
import { projectsDb, sessionsDb } from '@/modules/database/index.js';
|
||||||
import { chatRunRegistry } from '@/modules/websocket/index.js';
|
|
||||||
import { providerRegistry } from '@/modules/providers/provider.registry.js';
|
import { providerRegistry } from '@/modules/providers/provider.registry.js';
|
||||||
import type {
|
import type {
|
||||||
FetchHistoryOptions,
|
FetchHistoryOptions,
|
||||||
@@ -13,12 +11,6 @@ import type {
|
|||||||
} from '@/shared/types.js';
|
} from '@/shared/types.js';
|
||||||
import { AppError } from '@/shared/utils.js';
|
import { AppError } from '@/shared/utils.js';
|
||||||
|
|
||||||
type CreateAppSessionResult = {
|
|
||||||
sessionId: string;
|
|
||||||
provider: LLMProvider;
|
|
||||||
projectPath: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ArchivedSessionListItem = {
|
type ArchivedSessionListItem = {
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
provider: LLMProvider;
|
provider: LLMProvider;
|
||||||
@@ -85,21 +77,6 @@ export const sessionsService = {
|
|||||||
return providerRegistry.listProviders().map((provider) => provider.id);
|
return providerRegistry.listProviders().map((provider) => provider.id);
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns app-facing ids for provider runs that are currently processing.
|
|
||||||
*
|
|
||||||
* This is intentionally status-only: callers that only need sidebar activity
|
|
||||||
* indicators should not attach to chat streams or request replayed messages.
|
|
||||||
*/
|
|
||||||
listRunningSessions(): Array<{
|
|
||||||
sessionId: string;
|
|
||||||
provider: LLMProvider;
|
|
||||||
startedAt: number;
|
|
||||||
lastSeq: number;
|
|
||||||
}> {
|
|
||||||
return chatRunRegistry.listRunningRuns();
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalizes one provider-native event into frontend session message events.
|
* Normalizes one provider-native event into frontend session message events.
|
||||||
*/
|
*/
|
||||||
@@ -112,43 +89,12 @@ export const sessionsService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Allocates a stable app-facing session id before any provider run happens.
|
* Fetches persisted history by session id.
|
||||||
*
|
|
||||||
* This is the entry point of the session gateway: the frontend calls this
|
|
||||||
* (via `POST /api/providers/sessions`) when the user starts a brand-new
|
|
||||||
* chat, navigates to the returned id immediately, and the id never changes
|
|
||||||
* for the lifetime of the conversation. The provider-native id is mapped to
|
|
||||||
* this row later, when the provider runtime announces it mid-run.
|
|
||||||
*/
|
|
||||||
createAppSession(provider: LLMProvider, projectPath: string): CreateAppSessionResult {
|
|
||||||
const normalizedProjectPath = projectPath.trim();
|
|
||||||
if (!normalizedProjectPath) {
|
|
||||||
throw new AppError('projectPath is required.', {
|
|
||||||
code: 'PROJECT_PATH_REQUIRED',
|
|
||||||
statusCode: 400,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const sessionId = randomUUID();
|
|
||||||
sessionsDb.createAppSession(sessionId, provider, normalizedProjectPath);
|
|
||||||
|
|
||||||
return {
|
|
||||||
sessionId,
|
|
||||||
provider,
|
|
||||||
projectPath: normalizedProjectPath,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetches persisted history by app session id.
|
|
||||||
*
|
*
|
||||||
* Provider and provider-specific lookup hints are resolved from the indexed
|
* Provider and provider-specific lookup hints are resolved from the indexed
|
||||||
* session metadata in the database. The provider adapter receives the
|
* session metadata in the database.
|
||||||
* provider-native session id (the one written into transcripts on disk),
|
|
||||||
* and every returned message is remapped back to the app session id so
|
|
||||||
* provider ids never reach the frontend.
|
|
||||||
*/
|
*/
|
||||||
async fetchHistory(
|
fetchHistory(
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
options: Pick<FetchHistoryOptions, 'limit' | 'offset'> = {},
|
options: Pick<FetchHistoryOptions, 'limit' | 'offset'> = {},
|
||||||
): Promise<FetchHistoryResult> {
|
): Promise<FetchHistoryResult> {
|
||||||
@@ -160,33 +106,12 @@ export const sessionsService = {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// App-created sessions that never produced a provider transcript yet
|
|
||||||
// (e.g. first message still streaming) simply have no history.
|
|
||||||
if (!session.provider_session_id) {
|
|
||||||
return {
|
|
||||||
messages: [],
|
|
||||||
total: 0,
|
|
||||||
hasMore: false,
|
|
||||||
offset: options.offset ?? 0,
|
|
||||||
limit: options.limit ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const provider = session.provider as LLMProvider;
|
const provider = session.provider as LLMProvider;
|
||||||
const result = await providerRegistry.resolveProvider(provider).sessions.fetchHistory(sessionId, {
|
return providerRegistry.resolveProvider(provider).sessions.fetchHistory(sessionId, {
|
||||||
limit: options.limit ?? null,
|
limit: options.limit ?? null,
|
||||||
offset: options.offset ?? 0,
|
offset: options.offset ?? 0,
|
||||||
projectPath: session.project_path ?? '',
|
projectPath: session.project_path ?? '',
|
||||||
providerSessionId: session.provider_session_id,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
|
||||||
...result,
|
|
||||||
messages: result.messages.map((message) => ({
|
|
||||||
...message,
|
|
||||||
sessionId,
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -272,55 +272,6 @@ test('OpenCode session synchronizer indexes sqlite sessions without deletable tr
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('OpenCode session synchronizer returns the app session id once provider mapping exists', { concurrency: false }, async () => {
|
|
||||||
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'opencode-session-sync-mapped-'));
|
|
||||||
const workspacePath = path.join(tempRoot, 'workspace');
|
|
||||||
await mkdir(workspacePath, { recursive: true });
|
|
||||||
const restoreHomeDir = patchHomeDir(tempRoot);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await createOpenCodeDatabase(tempRoot, workspacePath);
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-session-1', 'opencode', workspacePath);
|
|
||||||
sessionsDb.assignProviderSessionId('app-session-1', 'open-session-1');
|
|
||||||
|
|
||||||
const synchronizer = new OpenCodeSessionSynchronizer();
|
|
||||||
return synchronizer.synchronizeFile(path.join(tempRoot, '.local', 'share', 'opencode', 'opencode.db')).then((sessionId) => {
|
|
||||||
assert.equal(sessionId, 'app-session-1');
|
|
||||||
assert.equal(sessionsDb.getAllSessions().length, 1);
|
|
||||||
assert.equal(sessionsDb.getSessionById('app-session-1')?.provider_session_id, 'open-session-1');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
restoreHomeDir();
|
|
||||||
await rm(tempRoot, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('OpenCode session synchronizer adopts the pending app session before watcher sync creates a duplicate', { concurrency: false }, async () => {
|
|
||||||
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'opencode-session-sync-race-'));
|
|
||||||
const workspacePath = path.join(tempRoot, 'workspace');
|
|
||||||
await mkdir(workspacePath, { recursive: true });
|
|
||||||
const restoreHomeDir = patchHomeDir(tempRoot);
|
|
||||||
|
|
||||||
try {
|
|
||||||
await createOpenCodeDatabase(tempRoot, workspacePath);
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-session-race', 'opencode', workspacePath);
|
|
||||||
|
|
||||||
const synchronizer = new OpenCodeSessionSynchronizer();
|
|
||||||
return synchronizer.synchronizeFile(path.join(tempRoot, '.local', 'share', 'opencode', 'opencode.db')).then((sessionId) => {
|
|
||||||
assert.equal(sessionId, 'app-session-race');
|
|
||||||
assert.equal(sessionsDb.getAllSessions().length, 1);
|
|
||||||
assert.equal(sessionsDb.getSessionById('app-session-race')?.provider_session_id, 'open-session-1');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
restoreHomeDir();
|
|
||||||
await rm(tempRoot, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test('OpenCode sessions provider normalizes quoted live text and skips user echoes', () => {
|
test('OpenCode sessions provider normalizes quoted live text and skips user echoes', () => {
|
||||||
const provider = new OpenCodeSessionsProvider();
|
const provider = new OpenCodeSessionsProvider();
|
||||||
const normalized = provider.normalizeMessage({
|
const normalized = provider.normalizeMessage({
|
||||||
|
|||||||
@@ -33,12 +33,10 @@ Benefits:
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `services/websocket-server.service.ts` | Creates `WebSocketServer`, binds `verifyClient`, routes connection by pathname |
|
| `services/websocket-server.service.ts` | Creates `WebSocketServer`, binds `verifyClient`, routes connection by pathname |
|
||||||
| `services/websocket-auth.service.ts` | Authenticates upgrade requests and attaches `request.user` |
|
| `services/websocket-auth.service.ts` | Authenticates upgrade requests and attaches `request.user` |
|
||||||
| `services/chat-websocket.service.ts` | Handles the `/ws` chat protocol (`chat.send` / `chat.abort` / `chat.subscribe` / `chat.permission-response`) |
|
| `services/chat-websocket.service.ts` | Handles `/ws` chat protocol and provider command/session control messages |
|
||||||
| `services/chat-run-registry.service.ts` | Tracks live provider runs per app session id: seq numbering, event replay buffer, provider-id mapping, completion state |
|
|
||||||
| `services/chat-session-writer.service.ts` | Gateway writer handed to provider runtimes: remaps provider session ids to app ids, swallows `session_created`, assigns `seq` |
|
|
||||||
| `services/shell-websocket.service.ts` | Handles `/shell` PTY lifecycle, reconnect buffering, auth URL detection |
|
| `services/shell-websocket.service.ts` | Handles `/shell` PTY lifecycle, reconnect buffering, auth URL detection |
|
||||||
| `services/plugin-websocket-proxy.service.ts` | Bridges client socket to plugin socket |
|
| `services/plugin-websocket-proxy.service.ts` | Bridges client socket to plugin socket |
|
||||||
| `services/websocket-writer.service.ts` | Adapts raw WebSocket to writer interface (`send`, `setSessionId`, `getSessionId`) for non-chat writer consumers |
|
| `services/websocket-writer.service.ts` | Adapts raw WebSocket to writer interface (`send`, `setSessionId`, `getSessionId`) |
|
||||||
| `services/websocket-state.service.ts` | Holds shared chat client set and open-state constant |
|
| `services/websocket-state.service.ts` | Holds shared chat client set and open-state constant |
|
||||||
|
|
||||||
## High-Level Architecture
|
## High-Level Architecture
|
||||||
@@ -54,12 +52,12 @@ flowchart LR
|
|||||||
D -->|other| H[close()]
|
D -->|other| H[close()]
|
||||||
|
|
||||||
E --> I[connectedClients Set]
|
E --> I[connectedClients Set]
|
||||||
E --> J[chatRunRegistry + ChatSessionWriter]
|
E --> J[WebSocketWriter]
|
||||||
F --> K[ptySessionsMap]
|
F --> K[ptySessionsMap]
|
||||||
G --> L[Upstream Plugin ws://127.0.0.1:port/ws]
|
G --> L[Upstream Plugin ws://127.0.0.1:port/ws]
|
||||||
|
|
||||||
I --> M[projects.service loading_progress]
|
I --> M[projects.service broadcastProgress]
|
||||||
I --> N[sessions-watcher.service session_upserted]
|
I --> N[sessions-watcher.service projects_updated]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Connection Handshake + Routing
|
## Connection Handshake + Routing
|
||||||
@@ -107,41 +105,37 @@ sequenceDiagram
|
|||||||
When a chat socket connects:
|
When a chat socket connects:
|
||||||
|
|
||||||
1. Add socket to `connectedClients`.
|
1. Add socket to `connectedClients`.
|
||||||
2. Parse each incoming message with `parseIncomingJsonObject`.
|
2. Build `WebSocketWriter` (captures `userId` from authenticated request).
|
||||||
3. Dispatch by `data.type` (four message types, none provider-specific).
|
3. Parse each incoming message with `parseIncomingJsonObject`.
|
||||||
4. On close, remove socket from `connectedClients`.
|
4. Dispatch by `data.type`.
|
||||||
|
5. On close, remove socket from `connectedClients`.
|
||||||
### Session identity model
|
|
||||||
|
|
||||||
The frontend only ever knows the **app session id** (allocated by
|
|
||||||
`POST /api/providers/sessions` or discovered via the session index). The
|
|
||||||
provider-native id (JSONL file name, CLI resume id) stays inside the backend:
|
|
||||||
|
|
||||||
1. `chat.send` resolves the app id to `{ provider, provider_session_id, project_path }` from the sessions DB.
|
|
||||||
2. The provider runtime receives the provider-native id for resume.
|
|
||||||
3. The `ChatSessionWriter` remaps every outbound event back to the app id, and turns `session_created` announcements into a DB mapping update instead of forwarding them.
|
|
||||||
|
|
||||||
### Chat Message Dispatch
|
### Chat Message Dispatch
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
A[Incoming WS message] --> B[parseIncomingJsonObject]
|
A[Incoming WS message] --> B[parseIncomingJsonObject]
|
||||||
B -->|invalid| C[send kind:protocol_error]
|
B -->|invalid| C[send {type:error}]
|
||||||
B -->|ok| D{data.type}
|
B -->|ok| D{data.type}
|
||||||
|
|
||||||
D -->|chat.send| E[resolve session row -> startRun -> spawnFns provider]
|
D -->|claude-command| E[queryClaudeSDK]
|
||||||
D -->|chat.abort| F[abortFns provider + synthetic complete]
|
D -->|cursor-command| F[spawnCursor]
|
||||||
D -->|chat.subscribe| G[chat_subscribed ack + attach socket + replay events seq > lastSeq]
|
D -->|codex-command| G[queryCodex]
|
||||||
D -->|chat.permission-response| H[resolveToolApproval]
|
D -->|gemini-command| H[spawnGemini]
|
||||||
D -->|other| I[send kind:protocol_error]
|
D -->|cursor-resume| I[spawnCursor resume]
|
||||||
|
D -->|abort-session| J[abort by provider]
|
||||||
|
D -->|claude-permission-response| K[resolveToolApproval]
|
||||||
|
D -->|cursor-abort| L[abortCursorSession]
|
||||||
|
D -->|check-session-status| M[is*SessionActive + optional reconnectSessionWriter]
|
||||||
|
D -->|get-pending-permissions| N[getPendingApprovalsForSession]
|
||||||
|
D -->|get-active-sessions| O[getActive*Sessions]
|
||||||
```
|
```
|
||||||
|
|
||||||
### Chat Notes
|
### Chat Notes
|
||||||
|
|
||||||
1. **Unified envelope**: every server-to-client frame carries a `kind` — either a provider `NormalizedMessage` kind or a gateway kind (`chat_subscribed`, `session_upserted`, `loading_progress`, `protocol_error`). There is no second `type`-based protocol.
|
1. `abort-session` returns a normalized `complete` message with `aborted: true`.
|
||||||
2. **Unified terminal lifecycle**: every provider run ends with exactly one `complete` message built by `createCompleteMessage()` (`server/shared/utils.ts`): `{ kind: "complete", sessionId, actualSessionId, exitCode, success, aborted }`. The chat handler emits a synthetic `complete` for runs that crash or get aborted, and the run registry drops duplicate completes.
|
2. `check-session-status` returns `{ type: "session-status", isProcessing }`.
|
||||||
3. **Per-run event log**: every live event gets a monotonically increasing `seq`. `chat.subscribe { sessions: [{ sessionId, lastSeq }] }` re-attaches the live stream to the requesting socket (any provider, not just Claude) and replays events with `seq > lastSeq`. If the buffer no longer covers `lastSeq`, the client refreshes over REST.
|
3. Claude status checks can reconnect output stream to the new socket via `reconnectSessionWriter`.
|
||||||
4. `chat_subscribed` includes `isProcessing` (replaces `check-session-status`) and `pendingPermissions` (replaces `get-pending-permissions`).
|
|
||||||
|
|
||||||
## `/shell` Terminal Flow
|
## `/shell` Terminal Flow
|
||||||
|
|
||||||
@@ -229,9 +223,9 @@ Only chat sockets (`/ws`) are tracked in `connectedClients`.
|
|||||||
That shared set is consumed by:
|
That shared set is consumed by:
|
||||||
|
|
||||||
1. `modules/projects/services/projects-with-sessions-fetch.service.ts`
|
1. `modules/projects/services/projects-with-sessions-fetch.service.ts`
|
||||||
Broadcasts `kind: loading_progress` while project snapshots are being built.
|
Broadcasts `loading_progress` while project snapshots are being built.
|
||||||
2. `modules/providers/services/sessions-watcher.service.ts`
|
2. `modules/providers/services/sessions-watcher.service.ts`
|
||||||
Broadcasts per-session `kind: session_upserted` deltas when provider session artifacts change (no full project snapshots).
|
Broadcasts `projects_updated` when provider session artifacts change.
|
||||||
|
|
||||||
This design centralizes cross-module realtime fanout without requiring route-local references to WebSocket internals.
|
This design centralizes cross-module realtime fanout without requiring route-local references to WebSocket internals.
|
||||||
|
|
||||||
@@ -258,7 +252,7 @@ Current explicit close codes in this module:
|
|||||||
|
|
||||||
Other errors:
|
Other errors:
|
||||||
|
|
||||||
1. Chat handler catches and emits `{ kind: "protocol_error", code, error }`.
|
1. Chat handler catches and emits `{ type: "error", error }`.
|
||||||
2. Shell handler catches and writes terminal-visible error output.
|
2. Shell handler catches and writes terminal-visible error output.
|
||||||
3. Unknown websocket paths are closed immediately.
|
3. Unknown websocket paths are closed immediately.
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,2 @@
|
|||||||
export { WS_OPEN_STATE, connectedClients } from './services/websocket-state.service.js';
|
export { WS_OPEN_STATE, connectedClients } from './services/websocket-state.service.js';
|
||||||
export { createWebSocketServer } from './services/websocket-server.service.js';
|
export { createWebSocketServer } from './services/websocket-server.service.js';
|
||||||
export { chatRunRegistry } from './services/chat-run-registry.service.js';
|
|
||||||
|
|||||||
@@ -1,327 +0,0 @@
|
|||||||
import path from 'node:path';
|
|
||||||
|
|
||||||
import { projectsDb, sessionsDb } from '@/modules/database/index.js';
|
|
||||||
import { generateDisplayName } from '@/modules/projects/index.js';
|
|
||||||
import { ChatSessionWriter } from '@/modules/websocket/services/chat-session-writer.service.js';
|
|
||||||
import { connectedClients, WS_OPEN_STATE } from '@/modules/websocket/services/websocket-state.service.js';
|
|
||||||
import type {
|
|
||||||
LLMProvider,
|
|
||||||
NormalizedMessage,
|
|
||||||
RealtimeClientConnection,
|
|
||||||
} from '@/shared/types.js';
|
|
||||||
|
|
||||||
type ChatRunStatus = 'running' | 'completed';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* One live (or recently finished) provider run for a single app session.
|
|
||||||
*
|
|
||||||
* State notes — why each mutable field is essential:
|
|
||||||
* - `providerSessionId`: the provider-native id captured mid-run. The abort
|
|
||||||
* handler needs it to address the provider runtime, and the DB mapping is
|
|
||||||
* written from it so history/resume work after the run.
|
|
||||||
* - `status`: drives `chat_subscribed.isProcessing`, prevents double sends
|
|
||||||
* into the same session, and guards the synthetic-complete fallback in the
|
|
||||||
* chat handler (only emitted when a runtime died without completing).
|
|
||||||
* - `lastSeq` / `events`: the per-run event log. Every live event gets a
|
|
||||||
* monotonically increasing `seq` and is buffered so a reconnecting client
|
|
||||||
* can replay exactly the events it missed via `chat.subscribe`.
|
|
||||||
*/
|
|
||||||
type ChatRun = {
|
|
||||||
appSessionId: string;
|
|
||||||
provider: LLMProvider;
|
|
||||||
providerSessionId: string | null;
|
|
||||||
status: ChatRunStatus;
|
|
||||||
lastSeq: number;
|
|
||||||
events: NormalizedMessage[];
|
|
||||||
writer: ChatSessionWriter;
|
|
||||||
startedAt: number;
|
|
||||||
completedAt: number | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* How long a completed run stays available for replay. Covers the window
|
|
||||||
* between a run finishing and the client refreshing history over REST (for
|
|
||||||
* example when the browser tab was asleep while the run completed).
|
|
||||||
*/
|
|
||||||
const COMPLETED_RUN_RETENTION_MS = 5 * 60 * 1000;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Upper bound on buffered events per run so a very long tool-heavy run cannot
|
|
||||||
* grow memory unbounded. When exceeded, the oldest events are dropped —
|
|
||||||
* a reconnecting client whose `lastSeq` predates the buffer falls back to a
|
|
||||||
* REST history refresh, which is always the authoritative source.
|
|
||||||
*/
|
|
||||||
const MAX_BUFFERED_EVENTS_PER_RUN = 5000;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Active and recently-completed runs keyed by app session id.
|
|
||||||
*
|
|
||||||
* This map is the single in-memory source of truth for "is something running
|
|
||||||
* for this session" — the chat websocket handler, abort path, and subscribe
|
|
||||||
* path all consult it instead of asking each provider runtime individually.
|
|
||||||
*/
|
|
||||||
const runs = new Map<string, ChatRun>();
|
|
||||||
|
|
||||||
async function broadcastCanonicalSessionUpsert(appSessionId: string): Promise<void> {
|
|
||||||
const row = sessionsDb.getSessionById(appSessionId);
|
|
||||||
if (!row || row.isArchived) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const projectPath = row.project_path;
|
|
||||||
const project = projectPath ? projectsDb.getProjectPath(projectPath) : null;
|
|
||||||
const displayName = project?.custom_project_name?.trim()
|
|
||||||
? project.custom_project_name
|
|
||||||
: await generateDisplayName(path.basename(projectPath ?? '') || (projectPath ?? ''), projectPath);
|
|
||||||
|
|
||||||
const payload = JSON.stringify({
|
|
||||||
kind: 'session_upserted',
|
|
||||||
sessionId: row.session_id,
|
|
||||||
providerSessionId: row.provider_session_id,
|
|
||||||
provider: row.provider,
|
|
||||||
session: {
|
|
||||||
id: row.session_id,
|
|
||||||
summary: row.custom_name || '',
|
|
||||||
messageCount: 0,
|
|
||||||
lastActivity: row.updated_at ?? row.created_at ?? new Date().toISOString(),
|
|
||||||
},
|
|
||||||
project: project
|
|
||||||
? {
|
|
||||||
projectId: project.project_id,
|
|
||||||
path: project.project_path,
|
|
||||||
fullPath: project.project_path,
|
|
||||||
displayName,
|
|
||||||
isStarred: Boolean(project.isStarred),
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
});
|
|
||||||
|
|
||||||
connectedClients.forEach((client) => {
|
|
||||||
if (client.readyState === WS_OPEN_STATE) {
|
|
||||||
client.send(payload);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function evictRunLater(appSessionId: string): void {
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
const run = runs.get(appSessionId);
|
|
||||||
if (run && run.status === 'completed') {
|
|
||||||
runs.delete(appSessionId);
|
|
||||||
}
|
|
||||||
}, COMPLETED_RUN_RETENTION_MS);
|
|
||||||
|
|
||||||
// Never keep the process alive just to evict a buffered run.
|
|
||||||
timer.unref?.();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Decorates one outbound live event for a run and records it in the event log.
|
|
||||||
*
|
|
||||||
* Responsibilities:
|
|
||||||
* 1. Remap `sessionId` (and `actualSessionId` on `complete`) to the stable
|
|
||||||
* app session id — provider-native ids never leave the backend.
|
|
||||||
* 2. Assign the next `seq` so clients can detect/replay gaps.
|
|
||||||
* 3. Buffer the event for `chat.subscribe` replay.
|
|
||||||
* 4. Flip the run to `completed` when the terminal `complete` event passes by.
|
|
||||||
*/
|
|
||||||
function decorateAndRecordEvent(run: ChatRun, message: NormalizedMessage): NormalizedMessage | null {
|
|
||||||
// Exactly-one-complete contract: when a run is aborted the chat handler
|
|
||||||
// emits the terminal `complete` immediately, but the killed runtime may
|
|
||||||
// still emit its own `complete` from its exit handler moments later.
|
|
||||||
// Whichever arrives first wins; the duplicate is dropped here.
|
|
||||||
if (message.kind === 'complete' && run.status === 'completed') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
run.lastSeq += 1;
|
|
||||||
|
|
||||||
const outbound: NormalizedMessage = {
|
|
||||||
...message,
|
|
||||||
sessionId: run.appSessionId,
|
|
||||||
seq: run.lastSeq,
|
|
||||||
};
|
|
||||||
|
|
||||||
if (message.kind === 'complete') {
|
|
||||||
// The provider may report its own id here; the frontend only ever knows
|
|
||||||
// the app id, so the "actual" id is by definition the app id as well.
|
|
||||||
outbound.actualSessionId = run.appSessionId;
|
|
||||||
run.status = 'completed';
|
|
||||||
run.completedAt = Date.now();
|
|
||||||
evictRunLater(run.appSessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
run.events.push(outbound);
|
|
||||||
if (run.events.length > MAX_BUFFERED_EVENTS_PER_RUN) {
|
|
||||||
run.events.splice(0, run.events.length - MAX_BUFFERED_EVENTS_PER_RUN);
|
|
||||||
}
|
|
||||||
|
|
||||||
return outbound;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Records the provider-native session id for a run and persists the
|
|
||||||
* app-id-to-provider-id mapping so history fetches and future resumes can
|
|
||||||
* address the provider transcript.
|
|
||||||
*
|
|
||||||
* Called from the gateway writer when the runtime either calls
|
|
||||||
* `setSessionId(...)` or emits its `session_created` event — whichever
|
|
||||||
* happens first wins; later calls with the same id are no-ops.
|
|
||||||
*/
|
|
||||||
function recordProviderSessionId(run: ChatRun, providerSessionId: string): void {
|
|
||||||
if (!providerSessionId || run.providerSessionId === providerSessionId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
run.providerSessionId = providerSessionId;
|
|
||||||
|
|
||||||
try {
|
|
||||||
sessionsDb.assignProviderSessionId(run.appSessionId, providerSessionId);
|
|
||||||
void broadcastCanonicalSessionUpsert(run.appSessionId).catch((error) => {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
console.error('[ChatRunRegistry] Failed to broadcast canonical session mapping', {
|
|
||||||
appSessionId: run.appSessionId,
|
|
||||||
providerSessionId,
|
|
||||||
error: message,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
console.error('[ChatRunRegistry] Failed to persist provider session id mapping', {
|
|
||||||
appSessionId: run.appSessionId,
|
|
||||||
providerSessionId,
|
|
||||||
error: message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Registry of live provider runs keyed by the stable app session id.
|
|
||||||
*
|
|
||||||
* The registry is what makes the websocket protocol provider-independent:
|
|
||||||
* every run gets a `ChatSessionWriter` that remaps provider-native session
|
|
||||||
* ids to the app id, assigns `seq` numbers, and buffers events for replay —
|
|
||||||
* regardless of which provider runtime produced them.
|
|
||||||
*/
|
|
||||||
export const chatRunRegistry = {
|
|
||||||
/**
|
|
||||||
* Starts tracking a run and returns it, or `null` when a run is already in
|
|
||||||
* progress for the session (callers must reject the duplicate send).
|
|
||||||
*/
|
|
||||||
startRun(input: {
|
|
||||||
appSessionId: string;
|
|
||||||
provider: LLMProvider;
|
|
||||||
providerSessionId: string | null;
|
|
||||||
connection: RealtimeClientConnection;
|
|
||||||
userId: string | number | null;
|
|
||||||
}): ChatRun | null {
|
|
||||||
const existing = runs.get(input.appSessionId);
|
|
||||||
if (existing && existing.status === 'running') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const run: ChatRun = {
|
|
||||||
appSessionId: input.appSessionId,
|
|
||||||
provider: input.provider,
|
|
||||||
providerSessionId: input.providerSessionId,
|
|
||||||
status: 'running',
|
|
||||||
lastSeq: 0,
|
|
||||||
events: [],
|
|
||||||
writer: null as unknown as ChatSessionWriter,
|
|
||||||
startedAt: Date.now(),
|
|
||||||
completedAt: null,
|
|
||||||
};
|
|
||||||
|
|
||||||
run.writer = new ChatSessionWriter({
|
|
||||||
connection: input.connection,
|
|
||||||
userId: input.userId,
|
|
||||||
provider: input.provider,
|
|
||||||
providerSessionId: input.providerSessionId,
|
|
||||||
onProviderSessionId: (providerSessionId) => {
|
|
||||||
recordProviderSessionId(run, providerSessionId);
|
|
||||||
},
|
|
||||||
decorateOutboundEvent: (message) => decorateAndRecordEvent(run, message),
|
|
||||||
});
|
|
||||||
|
|
||||||
runs.set(input.appSessionId, run);
|
|
||||||
return run;
|
|
||||||
},
|
|
||||||
|
|
||||||
getRun(appSessionId: string): ChatRun | undefined {
|
|
||||||
return runs.get(appSessionId);
|
|
||||||
},
|
|
||||||
|
|
||||||
isProcessing(appSessionId: string): boolean {
|
|
||||||
return runs.get(appSessionId)?.status === 'running';
|
|
||||||
},
|
|
||||||
|
|
||||||
listRunningRuns(): Array<{
|
|
||||||
sessionId: string;
|
|
||||||
provider: LLMProvider;
|
|
||||||
startedAt: number;
|
|
||||||
lastSeq: number;
|
|
||||||
}> {
|
|
||||||
return Array.from(runs.values())
|
|
||||||
.filter((run) => run.status === 'running')
|
|
||||||
.map((run) => ({
|
|
||||||
sessionId: run.appSessionId,
|
|
||||||
provider: run.provider,
|
|
||||||
startedAt: run.startedAt,
|
|
||||||
lastSeq: run.lastSeq,
|
|
||||||
}));
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Re-attaches a run's outbound stream to a (new) websocket connection.
|
|
||||||
*
|
|
||||||
* This is the generic replacement for the Claude-only writer reconnect:
|
|
||||||
* after a page refresh the new socket subscribes and immediately starts
|
|
||||||
* receiving the still-running stream, for every provider.
|
|
||||||
*/
|
|
||||||
attachConnection(appSessionId: string, connection: RealtimeClientConnection): boolean {
|
|
||||||
const run = runs.get(appSessionId);
|
|
||||||
if (!run) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
run.writer.updateWebSocket(connection);
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns buffered events with `seq` greater than `afterSeq` for replay.
|
|
||||||
*
|
|
||||||
* An empty array with `run.lastSeq > afterSeq` not covered by the buffer
|
|
||||||
* means the buffer was truncated; the client should refresh over REST.
|
|
||||||
*/
|
|
||||||
replayEvents(appSessionId: string, afterSeq: number): NormalizedMessage[] {
|
|
||||||
const run = runs.get(appSessionId);
|
|
||||||
if (!run) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return run.events.filter((event) => typeof event.seq === 'number' && event.seq > afterSeq);
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Emits a synthetic terminal `complete` if (and only if) the run is still
|
|
||||||
* marked running. Used when a provider runtime throws or resolves without
|
|
||||||
* having produced its own terminal event, and by the abort path.
|
|
||||||
*/
|
|
||||||
completeRun(appSessionId: string, opts: { exitCode: number; aborted?: boolean }): void {
|
|
||||||
const run = runs.get(appSessionId);
|
|
||||||
if (!run || run.status !== 'running') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
run.writer.sendComplete(opts);
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test-only escape hatch: clears every tracked run.
|
|
||||||
*/
|
|
||||||
clearAll(): void {
|
|
||||||
runs.clear();
|
|
||||||
},
|
|
||||||
};
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
import { WS_OPEN_STATE } from '@/modules/websocket/services/websocket-state.service.js';
|
|
||||||
import type {
|
|
||||||
LLMProvider,
|
|
||||||
NormalizedMessage,
|
|
||||||
RealtimeClientConnection,
|
|
||||||
} from '@/shared/types.js';
|
|
||||||
import { createCompleteMessage, readObjectRecord } from '@/shared/utils.js';
|
|
||||||
|
|
||||||
type ChatSessionWriterOptions = {
|
|
||||||
connection: RealtimeClientConnection;
|
|
||||||
userId: string | number | null;
|
|
||||||
provider: LLMProvider;
|
|
||||||
/** Provider-native id when resuming an existing session, otherwise null. */
|
|
||||||
providerSessionId: string | null;
|
|
||||||
/**
|
|
||||||
* Invoked the moment the provider runtime reveals its native session id
|
|
||||||
* (either via `setSessionId` or a `session_created` event). The registry
|
|
||||||
* persists the app-id-to-provider-id mapping from this callback.
|
|
||||||
*/
|
|
||||||
onProviderSessionId: (providerSessionId: string) => void;
|
|
||||||
/**
|
|
||||||
* Remaps/sequences/buffers one outbound live event. Implemented by the chat
|
|
||||||
* run registry; the writer never forwards a provider event untouched.
|
|
||||||
* Returns `null` when the event must be dropped (duplicate terminal
|
|
||||||
* `complete` after an abort already completed the run).
|
|
||||||
*/
|
|
||||||
decorateOutboundEvent: (message: NormalizedMessage) => NormalizedMessage | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gateway writer handed to provider runtimes instead of a raw websocket writer.
|
|
||||||
*
|
|
||||||
* It exposes the exact same surface as `WebSocketWriter` (`send`,
|
|
||||||
* `setSessionId`, `getSessionId`, `updateWebSocket`, `userId`,
|
|
||||||
* `isWebSocketWriter`) so the provider runtimes (`claude-sdk.js`,
|
|
||||||
* `cursor-cli.js`, ...) need zero changes — but everything that flows through
|
|
||||||
* it is translated from the provider's world into the app's protocol:
|
|
||||||
*
|
|
||||||
* - `session_created` events are swallowed and turned into a provider-id
|
|
||||||
* mapping; the frontend never learns provider-native ids.
|
|
||||||
* - every other event gets `sessionId` remapped to the app session id and a
|
|
||||||
* per-run `seq` assigned before being forwarded.
|
|
||||||
* - `setSessionId(...)` calls (used by runtimes to label captured ids) are
|
|
||||||
* intercepted and recorded as the provider-id mapping as well.
|
|
||||||
*/
|
|
||||||
export class ChatSessionWriter {
|
|
||||||
ws: RealtimeClientConnection;
|
|
||||||
userId: string | number | null;
|
|
||||||
/**
|
|
||||||
* Some runtimes feature-detect their writer with this flag; keep it so the
|
|
||||||
* gateway writer is a drop-in replacement for `WebSocketWriter`.
|
|
||||||
*/
|
|
||||||
isWebSocketWriter = true;
|
|
||||||
|
|
||||||
private readonly options: ChatSessionWriterOptions;
|
|
||||||
/**
|
|
||||||
* The provider-native session id as the runtime knows it. Kept locally
|
|
||||||
* (besides the registry) because runtimes read it back via `getSessionId()`
|
|
||||||
* to label their own outgoing events — those labels are remapped on send
|
|
||||||
* anyway, but the runtime-visible value must stay provider-native.
|
|
||||||
*/
|
|
||||||
private providerSessionId: string | null;
|
|
||||||
|
|
||||||
constructor(options: ChatSessionWriterOptions) {
|
|
||||||
this.options = options;
|
|
||||||
this.ws = options.connection;
|
|
||||||
this.userId = options.userId;
|
|
||||||
this.providerSessionId = options.providerSessionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
send(data: unknown): void {
|
|
||||||
const record = readObjectRecord(data);
|
|
||||||
if (!record || typeof record.kind !== 'string') {
|
|
||||||
// Provider runtimes only emit kind-based normalized messages. Anything
|
|
||||||
// else indicates a programming error; drop it rather than leaking an
|
|
||||||
// un-remapped payload to the client.
|
|
||||||
console.error('[ChatSessionWriter] Dropping non-normalized outbound payload', data);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const message = record as NormalizedMessage;
|
|
||||||
|
|
||||||
if (message.kind === 'session_created') {
|
|
||||||
const announcedId =
|
|
||||||
typeof message.newSessionId === 'string' && message.newSessionId
|
|
||||||
? message.newSessionId
|
|
||||||
: message.sessionId;
|
|
||||||
if (announcedId) {
|
|
||||||
this.captureProviderSessionId(announcedId);
|
|
||||||
}
|
|
||||||
// Swallowed on purpose: the frontend already has the stable app session
|
|
||||||
// id, so there is no client-side handoff to perform anymore.
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const outbound = this.options.decorateOutboundEvent(message);
|
|
||||||
if (outbound) {
|
|
||||||
this.forward(outbound);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Emits the synthetic terminal `complete` for runs that ended without one
|
|
||||||
* (runtime crash before completing, or user abort).
|
|
||||||
*/
|
|
||||||
sendComplete(opts: { exitCode: number; aborted?: boolean }): void {
|
|
||||||
const message = createCompleteMessage({
|
|
||||||
provider: this.options.provider,
|
|
||||||
sessionId: this.providerSessionId,
|
|
||||||
exitCode: opts.exitCode,
|
|
||||||
aborted: opts.aborted,
|
|
||||||
});
|
|
||||||
const outbound = this.options.decorateOutboundEvent(message);
|
|
||||||
if (outbound) {
|
|
||||||
this.forward(outbound);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
updateWebSocket(newConnection: RealtimeClientConnection): void {
|
|
||||||
this.ws = newConnection;
|
|
||||||
}
|
|
||||||
|
|
||||||
setSessionId(sessionId: string): void {
|
|
||||||
this.captureProviderSessionId(sessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
getSessionId(): string | null {
|
|
||||||
return this.providerSessionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
private captureProviderSessionId(providerSessionId: string): void {
|
|
||||||
if (!providerSessionId || this.providerSessionId === providerSessionId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.providerSessionId = providerSessionId;
|
|
||||||
this.options.onProviderSessionId(providerSessionId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private forward(message: NormalizedMessage): void {
|
|
||||||
if (this.ws.readyState === WS_OPEN_STATE) {
|
|
||||||
this.ws.send(JSON.stringify(message));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +1,40 @@
|
|||||||
import type { WebSocket } from 'ws';
|
import type { WebSocket } from 'ws';
|
||||||
|
|
||||||
import { sessionsDb } from '@/modules/database/index.js';
|
import { connectedClients } from '@/modules/websocket/services/websocket-state.service.js';
|
||||||
import { chatRunRegistry } from '@/modules/websocket/services/chat-run-registry.service.js';
|
import { WebSocketWriter } from '@/modules/websocket/services/websocket-writer.service.js';
|
||||||
import { connectedClients, WS_OPEN_STATE } from '@/modules/websocket/services/websocket-state.service.js';
|
|
||||||
import type {
|
import type {
|
||||||
AnyRecord,
|
AnyRecord,
|
||||||
AuthenticatedWebSocketRequest,
|
AuthenticatedWebSocketRequest,
|
||||||
LLMProvider,
|
LLMProvider,
|
||||||
} from '@/shared/types.js';
|
} from '@/shared/types.js';
|
||||||
import { parseIncomingJsonObject } from '@/shared/utils.js';
|
import { createNormalizedMessage, parseIncomingJsonObject } from '@/shared/utils.js';
|
||||||
|
|
||||||
/**
|
type ChatIncomingMessage = AnyRecord & {
|
||||||
* One provider runtime entry point. All five runtimes share this signature,
|
type?: string;
|
||||||
* which lets the chat handler dispatch through a provider-keyed map instead
|
command?: string;
|
||||||
* of provider-specific branches.
|
options?: AnyRecord;
|
||||||
*/
|
provider?: string;
|
||||||
type ProviderSpawnFn = (
|
sessionId?: string;
|
||||||
command: string,
|
requestId?: string;
|
||||||
options: AnyRecord,
|
allow?: unknown;
|
||||||
writer: unknown
|
updatedInput?: unknown;
|
||||||
) => Promise<unknown>;
|
message?: unknown;
|
||||||
|
rememberEntry?: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_PROVIDER: LLMProvider = 'claude';
|
||||||
|
|
||||||
type ChatWebSocketDependencies = {
|
type ChatWebSocketDependencies = {
|
||||||
/** Provider runtimes keyed by provider id. */
|
queryClaudeSDK: (command: string, options: unknown, writer: WebSocketWriter) => Promise<unknown>;
|
||||||
spawnFns: Record<LLMProvider, ProviderSpawnFn>;
|
spawnCursor: (command: string, options: unknown, writer: WebSocketWriter) => Promise<unknown>;
|
||||||
/**
|
queryCodex: (command: string, options: unknown, writer: WebSocketWriter) => Promise<unknown>;
|
||||||
* Abort functions keyed by provider id. They are addressed with the
|
spawnGemini: (command: string, options: unknown, writer: WebSocketWriter) => Promise<unknown>;
|
||||||
* provider-native session id (that is how runtimes key their process maps).
|
spawnOpenCode: (command: string, options: unknown, writer: WebSocketWriter) => Promise<unknown>;
|
||||||
* The Claude abort is async; the rest are sync — both shapes are accepted.
|
abortClaudeSDKSession: (sessionId: string) => Promise<boolean>;
|
||||||
*/
|
abortCursorSession: (sessionId: string) => boolean;
|
||||||
abortFns: Record<LLMProvider, (providerSessionId: string) => boolean | Promise<boolean>>;
|
abortCodexSession: (sessionId: string) => boolean;
|
||||||
|
abortGeminiSession: (sessionId: string) => boolean;
|
||||||
|
abortOpenCodeSession: (sessionId: string) => boolean;
|
||||||
resolveToolApproval: (
|
resolveToolApproval: (
|
||||||
requestId: string,
|
requestId: string,
|
||||||
payload: {
|
payload: {
|
||||||
@@ -39,10 +44,31 @@ type ChatWebSocketDependencies = {
|
|||||||
rememberEntry?: unknown;
|
rememberEntry?: unknown;
|
||||||
}
|
}
|
||||||
) => void;
|
) => void;
|
||||||
/** Claude-only today: pending tool approvals included in `chat_subscribed`. */
|
isClaudeSDKSessionActive: (sessionId: string) => boolean;
|
||||||
getPendingApprovalsForSession: (providerSessionId: string) => unknown[];
|
isCursorSessionActive: (sessionId: string) => boolean;
|
||||||
|
isCodexSessionActive: (sessionId: string) => boolean;
|
||||||
|
isGeminiSessionActive: (sessionId: string) => boolean;
|
||||||
|
isOpenCodeSessionActive: (sessionId: string) => boolean;
|
||||||
|
reconnectSessionWriter: (sessionId: string, ws: WebSocket) => boolean;
|
||||||
|
getPendingApprovalsForSession: (sessionId: string) => unknown[];
|
||||||
|
getActiveClaudeSDKSessions: () => unknown;
|
||||||
|
getActiveCursorSessions: () => unknown;
|
||||||
|
getActiveCodexSessions: () => unknown;
|
||||||
|
getActiveGeminiSessions: () => unknown;
|
||||||
|
getActiveOpenCodeSessions: () => unknown;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalizes potentially invalid provider names coming from websocket payloads.
|
||||||
|
*/
|
||||||
|
function readProvider(value: unknown): LLMProvider {
|
||||||
|
if (value === 'claude' || value === 'cursor' || value === 'codex' || value === 'gemini' || value === 'opencode') {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return DEFAULT_PROVIDER;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extracts the authenticated request user id in the formats currently produced
|
* Extracts the authenticated request user id in the formats currently produced
|
||||||
* by platform and OSS auth code paths.
|
* by platform and OSS auth code paths.
|
||||||
@@ -66,258 +92,8 @@ function readRequestUserId(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function sendJson(ws: WebSocket, payload: unknown): void {
|
|
||||||
if (ws.readyState === WS_OPEN_STATE) {
|
|
||||||
ws.send(JSON.stringify(payload));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reports a protocol-level failure to the requesting client.
|
|
||||||
*
|
|
||||||
* Protocol errors deliberately use their own `kind` (instead of the provider
|
|
||||||
* `error` message kind) so the frontend can distinguish "your request was
|
|
||||||
* invalid" from "the model run produced an error" without inspecting text.
|
|
||||||
*/
|
|
||||||
function sendProtocolError(
|
|
||||||
ws: WebSocket,
|
|
||||||
code: string,
|
|
||||||
error: string,
|
|
||||||
sessionId?: string
|
|
||||||
): void {
|
|
||||||
sendJson(ws, {
|
|
||||||
kind: 'protocol_error',
|
|
||||||
code,
|
|
||||||
error,
|
|
||||||
sessionId: sessionId ?? null,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function readRequiredSessionId(data: AnyRecord): string | null {
|
|
||||||
const sessionId = typeof data.sessionId === 'string' ? data.sessionId.trim() : '';
|
|
||||||
return sessionId.length > 0 ? sessionId : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handles `chat.send`: resolves the session row (provider, project path, and
|
|
||||||
* provider-native id all come from the database — never from the client),
|
|
||||||
* registers the run, and dispatches to the provider runtime.
|
|
||||||
*/
|
|
||||||
async function handleChatSend(
|
|
||||||
ws: WebSocket,
|
|
||||||
userId: string | number | null,
|
|
||||||
data: AnyRecord,
|
|
||||||
dependencies: ChatWebSocketDependencies
|
|
||||||
): Promise<void> {
|
|
||||||
const sessionId = readRequiredSessionId(data);
|
|
||||||
if (!sessionId) {
|
|
||||||
sendProtocolError(ws, 'SESSION_ID_REQUIRED', 'chat.send requires a sessionId.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const session = sessionsDb.getSessionById(sessionId);
|
|
||||||
if (!session) {
|
|
||||||
sendProtocolError(
|
|
||||||
ws,
|
|
||||||
'SESSION_NOT_FOUND',
|
|
||||||
`Session "${sessionId}" was not found. Create it via POST /api/providers/sessions first.`,
|
|
||||||
sessionId
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const provider = session.provider as LLMProvider;
|
|
||||||
const spawnFn = dependencies.spawnFns[provider];
|
|
||||||
if (!spawnFn) {
|
|
||||||
sendProtocolError(ws, 'UNSUPPORTED_PROVIDER', `Provider "${provider}" is not available.`, sessionId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const run = chatRunRegistry.startRun({
|
|
||||||
appSessionId: sessionId,
|
|
||||||
provider,
|
|
||||||
providerSessionId: session.provider_session_id,
|
|
||||||
connection: ws,
|
|
||||||
userId,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!run) {
|
|
||||||
sendProtocolError(
|
|
||||||
ws,
|
|
||||||
'RUN_IN_PROGRESS',
|
|
||||||
`Session "${sessionId}" already has a run in progress.`,
|
|
||||||
sessionId
|
|
||||||
);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const clientOptions = (data.options ?? {}) as AnyRecord;
|
|
||||||
const command = typeof data.content === 'string' ? data.content : '';
|
|
||||||
|
|
||||||
// The provider runtimes receive the provider-native session id (that is the
|
|
||||||
// id their CLI/SDK understands for resume). Brand-new sessions have no
|
|
||||||
// provider id yet, so the runtime starts fresh and announces one, which the
|
|
||||||
// gateway writer captures and maps back to the app session id.
|
|
||||||
const runtimeOptions: AnyRecord = {
|
|
||||||
...clientOptions,
|
|
||||||
sessionId: session.provider_session_id ?? undefined,
|
|
||||||
resume: Boolean(session.provider_session_id),
|
|
||||||
cwd: clientOptions.cwd ?? session.project_path ?? undefined,
|
|
||||||
projectPath: session.project_path ?? clientOptions.projectPath,
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
await spawnFn(command, runtimeOptions, run.writer);
|
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
|
||||||
console.error(`[Chat] Provider runtime "${provider}" failed`, { sessionId, error: message });
|
|
||||||
} finally {
|
|
||||||
// Safety net: a runtime that crashed (or resolved) without emitting its
|
|
||||||
// terminal `complete` would otherwise leave the session stuck in
|
|
||||||
// "processing" forever on every connected client.
|
|
||||||
chatRunRegistry.completeRun(sessionId, { exitCode: 1 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handles `chat.abort`: cancels the run for one app session and emits the
|
|
||||||
* terminal `complete` on its behalf (runtimes skip their own complete for
|
|
||||||
* aborted runs, and the registry drops any duplicate).
|
|
||||||
*/
|
|
||||||
async function handleChatAbort(
|
|
||||||
ws: WebSocket,
|
|
||||||
data: AnyRecord,
|
|
||||||
dependencies: ChatWebSocketDependencies
|
|
||||||
): Promise<void> {
|
|
||||||
const sessionId = readRequiredSessionId(data);
|
|
||||||
if (!sessionId) {
|
|
||||||
sendProtocolError(ws, 'SESSION_ID_REQUIRED', 'chat.abort requires a sessionId.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const run = chatRunRegistry.getRun(sessionId);
|
|
||||||
if (!run || run.status !== 'running') {
|
|
||||||
sendProtocolError(ws, 'NO_ACTIVE_RUN', `Session "${sessionId}" has no active run.`, sessionId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const abortFn = dependencies.abortFns[run.provider];
|
|
||||||
let success = false;
|
|
||||||
if (abortFn && run.providerSessionId) {
|
|
||||||
success = Boolean(await abortFn(run.providerSessionId));
|
|
||||||
}
|
|
||||||
|
|
||||||
chatRunRegistry.completeRun(sessionId, {
|
|
||||||
exitCode: success ? 0 : 1,
|
|
||||||
aborted: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handles `chat.subscribe`: for each requested session, reports whether a run
|
|
||||||
* is processing, re-attaches the live stream to this socket, replays missed
|
|
||||||
* events (seq > lastSeq), and includes pending permission requests.
|
|
||||||
*
|
|
||||||
* This single message replaces the old `check-session-status`,
|
|
||||||
* `get-pending-permissions`, and Claude-only writer reconnect flows.
|
|
||||||
*/
|
|
||||||
function handleChatSubscribe(
|
|
||||||
ws: WebSocket,
|
|
||||||
data: AnyRecord,
|
|
||||||
dependencies: ChatWebSocketDependencies
|
|
||||||
): void {
|
|
||||||
const targets = Array.isArray(data.sessions) ? data.sessions : [];
|
|
||||||
|
|
||||||
for (const target of targets) {
|
|
||||||
if (!target || typeof target !== 'object') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const sessionId = typeof (target as AnyRecord).sessionId === 'string'
|
|
||||||
? ((target as AnyRecord).sessionId as string).trim()
|
|
||||||
: '';
|
|
||||||
if (!sessionId) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lastSeqRaw = (target as AnyRecord).lastSeq;
|
|
||||||
const lastSeq = typeof lastSeqRaw === 'number' && Number.isFinite(lastSeqRaw)
|
|
||||||
? Math.max(0, Math.floor(lastSeqRaw))
|
|
||||||
: 0;
|
|
||||||
|
|
||||||
const run = chatRunRegistry.getRun(sessionId);
|
|
||||||
const isProcessing = chatRunRegistry.isProcessing(sessionId);
|
|
||||||
|
|
||||||
// Future live events for this run should land on the socket that asked —
|
|
||||||
// this is what makes mid-stream page refreshes work for all providers.
|
|
||||||
if (isProcessing) {
|
|
||||||
chatRunRegistry.attachConnection(sessionId, ws);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pending approvals are tracked under the provider-native id inside the
|
|
||||||
// Claude runtime; remap their sessionId so the client only sees app ids.
|
|
||||||
const pendingPermissions = (run?.providerSessionId
|
|
||||||
? dependencies.getPendingApprovalsForSession(run.providerSessionId)
|
|
||||||
: []
|
|
||||||
).map((approval) =>
|
|
||||||
approval && typeof approval === 'object'
|
|
||||||
? { ...(approval as AnyRecord), sessionId }
|
|
||||||
: approval,
|
|
||||||
);
|
|
||||||
|
|
||||||
sendJson(ws, {
|
|
||||||
kind: 'chat_subscribed',
|
|
||||||
sessionId,
|
|
||||||
isProcessing,
|
|
||||||
lastSeq: run?.lastSeq ?? 0,
|
|
||||||
pendingPermissions,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Replay only for RUNNING runs, strictly after the ack. Completed runs
|
|
||||||
// are fully persisted to the provider transcript and served over REST —
|
|
||||||
// replaying them (e.g. after a page reload where the client's lastSeq is
|
|
||||||
// 0) would duplicate messages the history fetch already returned.
|
|
||||||
if (isProcessing) {
|
|
||||||
for (const event of chatRunRegistry.replayEvents(sessionId, lastSeq)) {
|
|
||||||
sendJson(ws, event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handles `chat.permission-response`: forwards a tool-approval decision to the
|
|
||||||
* pending approval resolver (Claude is the only provider with interactive
|
|
||||||
* approvals today, but the message is intentionally provider-neutral).
|
|
||||||
*/
|
|
||||||
function handlePermissionResponse(data: AnyRecord, dependencies: ChatWebSocketDependencies): void {
|
|
||||||
if (typeof data.requestId !== 'string' || data.requestId.length === 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies.resolveToolApproval(data.requestId, {
|
|
||||||
allow: Boolean(data.allow),
|
|
||||||
updatedInput: data.updatedInput,
|
|
||||||
message: typeof data.message === 'string' ? data.message : undefined,
|
|
||||||
rememberEntry: data.rememberEntry,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles authenticated chat websocket messages used by the main chat panel.
|
* Handles authenticated chat websocket messages used by the main chat panel.
|
||||||
*
|
|
||||||
* Inbound protocol (client to server):
|
|
||||||
* - `chat.send` { sessionId, content, options? }
|
|
||||||
* - `chat.abort` { sessionId }
|
|
||||||
* - `chat.subscribe` { sessions: [{ sessionId, lastSeq? }] }
|
|
||||||
* - `chat.permission-response` { requestId, allow, updatedInput?, message?, rememberEntry? }
|
|
||||||
*
|
|
||||||
* Outbound protocol (server to client): every frame is `kind`-based — either
|
|
||||||
* a provider `NormalizedMessage` (with `seq`) or a gateway event
|
|
||||||
* (`chat_subscribed`, `session_upserted`, `loading_progress`,
|
|
||||||
* `protocol_error`).
|
|
||||||
*/
|
*/
|
||||||
export function handleChatConnection(
|
export function handleChatConnection(
|
||||||
ws: WebSocket,
|
ws: WebSocket,
|
||||||
@@ -327,7 +103,7 @@ export function handleChatConnection(
|
|||||||
console.log('[INFO] Chat WebSocket connected');
|
console.log('[INFO] Chat WebSocket connected');
|
||||||
connectedClients.add(ws);
|
connectedClients.add(ws);
|
||||||
|
|
||||||
const userId = readRequestUserId(request);
|
const writer = new WebSocketWriter(ws, readRequestUserId(request));
|
||||||
|
|
||||||
ws.on('message', async (rawMessage) => {
|
ws.on('message', async (rawMessage) => {
|
||||||
try {
|
try {
|
||||||
@@ -336,30 +112,169 @@ export function handleChatConnection(
|
|||||||
throw new Error('Invalid websocket payload');
|
throw new Error('Invalid websocket payload');
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = parsed as AnyRecord;
|
const data = parsed as ChatIncomingMessage;
|
||||||
const messageType = typeof data.type === 'string' ? data.type : '';
|
const messageType = data.type;
|
||||||
|
if (!messageType) {
|
||||||
|
throw new Error('Message type is required');
|
||||||
|
}
|
||||||
|
|
||||||
switch (messageType) {
|
if (messageType === 'claude-command') {
|
||||||
case 'chat.send':
|
await dependencies.queryClaudeSDK(data.command ?? '', data.options, writer);
|
||||||
await handleChatSend(ws, userId, data, dependencies);
|
return;
|
||||||
return;
|
}
|
||||||
case 'chat.abort':
|
|
||||||
await handleChatAbort(ws, data, dependencies);
|
if (messageType === 'cursor-command') {
|
||||||
return;
|
await dependencies.spawnCursor(data.command ?? '', data.options, writer);
|
||||||
case 'chat.subscribe':
|
return;
|
||||||
handleChatSubscribe(ws, data, dependencies);
|
}
|
||||||
return;
|
|
||||||
case 'chat.permission-response':
|
if (messageType === 'codex-command') {
|
||||||
handlePermissionResponse(data, dependencies);
|
await dependencies.queryCodex(data.command ?? '', data.options, writer);
|
||||||
return;
|
return;
|
||||||
default:
|
}
|
||||||
sendProtocolError(ws, 'UNKNOWN_MESSAGE_TYPE', `Unknown message type "${messageType}".`);
|
|
||||||
return;
|
if (messageType === 'gemini-command') {
|
||||||
|
await dependencies.spawnGemini(data.command ?? '', data.options, writer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'opencode-command') {
|
||||||
|
await dependencies.spawnOpenCode(data.command ?? '', data.options, writer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'cursor-resume') {
|
||||||
|
await dependencies.spawnCursor(
|
||||||
|
'',
|
||||||
|
{
|
||||||
|
sessionId: data.sessionId,
|
||||||
|
resume: true,
|
||||||
|
cwd: data.options?.cwd,
|
||||||
|
},
|
||||||
|
writer
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'abort-session') {
|
||||||
|
const provider = readProvider(data.provider);
|
||||||
|
const sessionId = typeof data.sessionId === 'string' ? data.sessionId : '';
|
||||||
|
let success = false;
|
||||||
|
|
||||||
|
if (provider === 'cursor') {
|
||||||
|
success = dependencies.abortCursorSession(sessionId);
|
||||||
|
} else if (provider === 'codex') {
|
||||||
|
success = dependencies.abortCodexSession(sessionId);
|
||||||
|
} else if (provider === 'gemini') {
|
||||||
|
success = dependencies.abortGeminiSession(sessionId);
|
||||||
|
} else if (provider === 'opencode') {
|
||||||
|
success = dependencies.abortOpenCodeSession(sessionId);
|
||||||
|
} else {
|
||||||
|
success = await dependencies.abortClaudeSDKSession(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.send(
|
||||||
|
createNormalizedMessage({
|
||||||
|
kind: 'complete',
|
||||||
|
exitCode: success ? 0 : 1,
|
||||||
|
aborted: true,
|
||||||
|
success,
|
||||||
|
sessionId,
|
||||||
|
provider,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'claude-permission-response') {
|
||||||
|
if (typeof data.requestId === 'string' && data.requestId.length > 0) {
|
||||||
|
dependencies.resolveToolApproval(data.requestId, {
|
||||||
|
allow: Boolean(data.allow),
|
||||||
|
updatedInput: data.updatedInput,
|
||||||
|
message: typeof data.message === 'string' ? data.message : undefined,
|
||||||
|
rememberEntry: data.rememberEntry,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'cursor-abort') {
|
||||||
|
const sessionId = typeof data.sessionId === 'string' ? data.sessionId : '';
|
||||||
|
const success = dependencies.abortCursorSession(sessionId);
|
||||||
|
writer.send(
|
||||||
|
createNormalizedMessage({
|
||||||
|
kind: 'complete',
|
||||||
|
exitCode: success ? 0 : 1,
|
||||||
|
aborted: true,
|
||||||
|
success,
|
||||||
|
sessionId,
|
||||||
|
provider: 'cursor',
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'check-session-status') {
|
||||||
|
const provider = readProvider(data.provider);
|
||||||
|
const sessionId = typeof data.sessionId === 'string' ? data.sessionId : '';
|
||||||
|
let isActive = false;
|
||||||
|
|
||||||
|
if (provider === 'cursor') {
|
||||||
|
isActive = dependencies.isCursorSessionActive(sessionId);
|
||||||
|
} else if (provider === 'codex') {
|
||||||
|
isActive = dependencies.isCodexSessionActive(sessionId);
|
||||||
|
} else if (provider === 'gemini') {
|
||||||
|
isActive = dependencies.isGeminiSessionActive(sessionId);
|
||||||
|
} else if (provider === 'opencode') {
|
||||||
|
isActive = dependencies.isOpenCodeSessionActive(sessionId);
|
||||||
|
} else {
|
||||||
|
isActive = dependencies.isClaudeSDKSessionActive(sessionId);
|
||||||
|
if (isActive) {
|
||||||
|
dependencies.reconnectSessionWriter(sessionId, ws);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.send({
|
||||||
|
type: 'session-status',
|
||||||
|
sessionId,
|
||||||
|
provider,
|
||||||
|
isProcessing: isActive,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'get-pending-permissions') {
|
||||||
|
const sessionId = typeof data.sessionId === 'string' ? data.sessionId : '';
|
||||||
|
if (sessionId && dependencies.isClaudeSDKSessionActive(sessionId)) {
|
||||||
|
const pending = dependencies.getPendingApprovalsForSession(sessionId);
|
||||||
|
writer.send({
|
||||||
|
type: 'pending-permissions-response',
|
||||||
|
sessionId,
|
||||||
|
data: pending,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (messageType === 'get-active-sessions') {
|
||||||
|
writer.send({
|
||||||
|
type: 'active-sessions',
|
||||||
|
sessions: {
|
||||||
|
claude: dependencies.getActiveClaudeSDKSessions(),
|
||||||
|
cursor: dependencies.getActiveCursorSessions(),
|
||||||
|
codex: dependencies.getActiveCodexSessions(),
|
||||||
|
gemini: dependencies.getActiveGeminiSessions(),
|
||||||
|
opencode: dependencies.getActiveOpenCodeSessions(),
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const message = error instanceof Error ? error.message : String(error);
|
const message = error instanceof Error ? error.message : String(error);
|
||||||
console.error('[ERROR] Chat WebSocket error:', message);
|
console.error('[ERROR] Chat WebSocket error:', message);
|
||||||
sendProtocolError(ws, 'INTERNAL_ERROR', message);
|
writer.send({
|
||||||
|
type: 'error',
|
||||||
|
error: message,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import path from 'node:path';
|
|||||||
import pty, { type IPty } from 'node-pty';
|
import pty, { type IPty } from 'node-pty';
|
||||||
import { WebSocket, type RawData } from 'ws';
|
import { WebSocket, type RawData } from 'ws';
|
||||||
|
|
||||||
import { createUserShellRuntimeEnv } from '@/shared/cli-runtime-env.js';
|
|
||||||
import { getCodexShellCommand } from '@/shared/codex-cli-runtime.js';
|
|
||||||
import { parseIncomingJsonObject } from '@/shared/utils.js';
|
import { parseIncomingJsonObject } from '@/shared/utils.js';
|
||||||
|
|
||||||
type ShellIncomingMessage = {
|
type ShellIncomingMessage = {
|
||||||
@@ -37,10 +35,7 @@ const PTY_SESSION_TIMEOUT = 30 * 60 * 1000;
|
|||||||
const SHELL_URL_PARSE_BUFFER_LIMIT = 32768;
|
const SHELL_URL_PARSE_BUFFER_LIMIT = 32768;
|
||||||
|
|
||||||
type ShellWebSocketDependencies = {
|
type ShellWebSocketDependencies = {
|
||||||
resolveProviderSessionId: (
|
getSessionById: (sessionId: string) => { cliSessionId?: string } | null | undefined;
|
||||||
sessionId: string,
|
|
||||||
provider: string,
|
|
||||||
) => string | null | undefined;
|
|
||||||
stripAnsiSequences: (content: string) => string;
|
stripAnsiSequences: (content: string) => string;
|
||||||
normalizeDetectedUrl: (url: string) => string | null;
|
normalizeDetectedUrl: (url: string) => string | null;
|
||||||
extractUrlsFromText: (content: string) => string[];
|
extractUrlsFromText: (content: string) => string[];
|
||||||
@@ -81,36 +76,6 @@ function parseShellMessage(rawMessage: RawData): ShellIncomingMessage | null {
|
|||||||
return payload as ShellIncomingMessage;
|
return payload as ShellIncomingMessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
const SAFE_SESSION_ID_PATTERN = /^[a-zA-Z0-9_.\-:]+$/;
|
|
||||||
|
|
||||||
function resolveResumeSessionId(
|
|
||||||
message: ShellIncomingMessage,
|
|
||||||
dependencies: ShellWebSocketDependencies
|
|
||||||
): string {
|
|
||||||
const hasSession = readBoolean(message.hasSession);
|
|
||||||
const sessionId = readString(message.sessionId);
|
|
||||||
const provider = readString(message.provider, 'claude');
|
|
||||||
|
|
||||||
if (!hasSession || !sessionId) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
let resumeSessionId: string | null | undefined;
|
|
||||||
try {
|
|
||||||
resumeSessionId = dependencies.resolveProviderSessionId(sessionId, provider);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to resolve provider session ID:', error);
|
|
||||||
resumeSessionId = undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolvedSessionId = resumeSessionId === undefined ? sessionId : resumeSessionId;
|
|
||||||
if (!resolvedSessionId || !SAFE_SESSION_ID_PATTERN.test(resolvedSessionId)) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
return resolvedSessionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolves provider command line for plain shell and agent-backed shell modes.
|
* Resolves provider command line for plain shell and agent-backed shell modes.
|
||||||
*/
|
*/
|
||||||
@@ -119,9 +84,10 @@ function buildShellCommand(
|
|||||||
dependencies: ShellWebSocketDependencies
|
dependencies: ShellWebSocketDependencies
|
||||||
): string {
|
): string {
|
||||||
const hasSession = readBoolean(message.hasSession);
|
const hasSession = readBoolean(message.hasSession);
|
||||||
|
const sessionId = readString(message.sessionId);
|
||||||
const initialCommand = readString(message.initialCommand);
|
const initialCommand = readString(message.initialCommand);
|
||||||
const provider = readString(message.provider, 'claude');
|
const provider = readString(message.provider, 'claude');
|
||||||
const resumeSessionId = resolveResumeSessionId(message, dependencies);
|
const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
|
||||||
const isPlainShell =
|
const isPlainShell =
|
||||||
readBoolean(message.isPlainShell) ||
|
readBoolean(message.isPlainShell) ||
|
||||||
(!!initialCommand && !hasSession) ||
|
(!!initialCommand && !hasSession) ||
|
||||||
@@ -132,44 +98,58 @@ function buildShellCommand(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (provider === 'cursor') {
|
if (provider === 'cursor') {
|
||||||
if (resumeSessionId) {
|
if (hasSession && sessionId) {
|
||||||
return `cursor-agent --resume="${resumeSessionId}"`;
|
return `cursor-agent --resume="${sessionId}"`;
|
||||||
}
|
}
|
||||||
return 'cursor-agent';
|
return 'cursor-agent';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (provider === 'codex') {
|
if (provider === 'codex') {
|
||||||
const codexCommand = getCodexShellCommand();
|
if (hasSession && sessionId) {
|
||||||
if (resumeSessionId) {
|
|
||||||
if (os.platform() === 'win32') {
|
if (os.platform() === 'win32') {
|
||||||
return `${codexCommand} resume "${resumeSessionId}"; if ($LASTEXITCODE -ne 0) { ${codexCommand} }`;
|
return `codex resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { codex }`;
|
||||||
}
|
}
|
||||||
return `${codexCommand} resume "${resumeSessionId}" || ${codexCommand}`;
|
return `codex resume "${sessionId}" || codex`;
|
||||||
}
|
}
|
||||||
return codexCommand;
|
return 'codex';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (provider === 'gemini') {
|
if (provider === 'gemini') {
|
||||||
const command = initialCommand || 'gemini';
|
const command = initialCommand || 'gemini';
|
||||||
if (resumeSessionId) {
|
let resumeId = sessionId;
|
||||||
return `${command} --resume "${resumeSessionId}"`;
|
if (hasSession && sessionId) {
|
||||||
|
try {
|
||||||
|
const existingSession = dependencies.getSessionById(sessionId);
|
||||||
|
if (existingSession && existingSession.cliSessionId) {
|
||||||
|
resumeId = existingSession.cliSessionId;
|
||||||
|
if (!safeSessionIdPattern.test(resumeId)) {
|
||||||
|
resumeId = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to get Gemini CLI session ID:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasSession && resumeId) {
|
||||||
|
return `${command} --resume "${resumeId}"`;
|
||||||
}
|
}
|
||||||
return command;
|
return command;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (provider === 'opencode') {
|
if (provider === 'opencode') {
|
||||||
if (resumeSessionId) {
|
if (hasSession && sessionId) {
|
||||||
return `opencode --session "${resumeSessionId}"`;
|
return `opencode --session "${sessionId}"`;
|
||||||
}
|
}
|
||||||
return initialCommand || 'opencode';
|
return initialCommand || 'opencode';
|
||||||
}
|
}
|
||||||
|
|
||||||
const command = initialCommand || 'claude';
|
const command = initialCommand || 'claude';
|
||||||
if (resumeSessionId) {
|
if (hasSession && sessionId) {
|
||||||
if (os.platform() === 'win32') {
|
if (os.platform() === 'win32') {
|
||||||
return `claude --resume "${resumeSessionId}"; if ($LASTEXITCODE -ne 0) { claude }`;
|
return `claude --resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { claude }`;
|
||||||
}
|
}
|
||||||
return `claude --resume "${resumeSessionId}" || claude`;
|
return `claude --resume "${sessionId}" || claude`;
|
||||||
}
|
}
|
||||||
return command;
|
return command;
|
||||||
}
|
}
|
||||||
@@ -281,16 +261,11 @@ export function handleShellConnection(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const shellCommand = buildShellCommand(data, dependencies);
|
const shellCommand = buildShellCommand(data, dependencies);
|
||||||
const resumeSessionId = resolveResumeSessionId(data, dependencies);
|
|
||||||
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
|
const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
|
||||||
const shellArgs =
|
const shellArgs =
|
||||||
os.platform() === 'win32' ? ['-Command', shellCommand] : ['-c', shellCommand];
|
os.platform() === 'win32' ? ['-Command', shellCommand] : ['-c', shellCommand];
|
||||||
const termCols = readNumber(data.cols, 80);
|
const termCols = readNumber(data.cols, 80);
|
||||||
const termRows = readNumber(data.rows, 24);
|
const termRows = readNumber(data.rows, 24);
|
||||||
// Plain terminals inherit the server process PATH, which npm can prefix with
|
|
||||||
// /opt/claudecodeui/node_modules/.bin. Put user CLI bins first so shell
|
|
||||||
// commands resolve like the user's login shell instead of the app install.
|
|
||||||
const ptyEnv = createUserShellRuntimeEnv();
|
|
||||||
|
|
||||||
shellProcess = pty.spawn(shell, shellArgs, {
|
shellProcess = pty.spawn(shell, shellArgs, {
|
||||||
name: 'xterm-256color',
|
name: 'xterm-256color',
|
||||||
@@ -298,7 +273,7 @@ export function handleShellConnection(
|
|||||||
rows: termRows,
|
rows: termRows,
|
||||||
cwd: resolvedProjectPath,
|
cwd: resolvedProjectPath,
|
||||||
env: {
|
env: {
|
||||||
...ptyEnv,
|
...process.env,
|
||||||
TERM: 'xterm-256color',
|
TERM: 'xterm-256color',
|
||||||
COLORTERM: 'truecolor',
|
COLORTERM: 'truecolor',
|
||||||
FORCE_COLOR: '3',
|
FORCE_COLOR: '3',
|
||||||
@@ -431,8 +406,8 @@ export function handleShellConnection(
|
|||||||
: provider === 'opencode'
|
: provider === 'opencode'
|
||||||
? 'OpenCode'
|
? 'OpenCode'
|
||||||
: 'Claude';
|
: 'Claude';
|
||||||
welcomeMsg = hasSession && resumeSessionId
|
welcomeMsg = hasSession
|
||||||
? `\x1b[36mResuming ${providerName} session ${resumeSessionId} in: ${projectPath}\x1b[0m\r\n`
|
? `\x1b[36mResuming ${providerName} session ${sessionId} in: ${projectPath}\x1b[0m\r\n`
|
||||||
: `\x1b[36mStarting new ${providerName} session in: ${projectPath}\x1b[0m\r\n`;
|
: `\x1b[36mStarting new ${providerName} session in: ${projectPath}\x1b[0m\r\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,244 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import { mkdtemp, rm } from 'node:fs/promises';
|
|
||||||
import { tmpdir } from 'node:os';
|
|
||||||
import path from 'node:path';
|
|
||||||
import test from 'node:test';
|
|
||||||
|
|
||||||
import { closeConnection, initializeDatabase, sessionsDb } from '@/modules/database/index.js';
|
|
||||||
import { chatRunRegistry } from '@/modules/websocket/services/chat-run-registry.service.js';
|
|
||||||
import { connectedClients } from '@/modules/websocket/services/websocket-state.service.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Minimal stand-in for a websocket connection: collects every JSON frame the
|
|
||||||
* gateway writer forwards so assertions can inspect the outbound protocol.
|
|
||||||
*/
|
|
||||||
class FakeConnection {
|
|
||||||
readyState = 1; // WS_OPEN_STATE
|
|
||||||
frames: Array<Record<string, unknown>> = [];
|
|
||||||
|
|
||||||
send(data: string): void {
|
|
||||||
this.frames.push(JSON.parse(data) as Record<string, unknown>);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function withIsolatedDatabase(runTest: () => void | Promise<void>): Promise<void> {
|
|
||||||
const previousDatabasePath = process.env.DATABASE_PATH;
|
|
||||||
const tempDirectory = await mkdtemp(path.join(tmpdir(), 'chat-run-registry-'));
|
|
||||||
const databasePath = path.join(tempDirectory, 'auth.db');
|
|
||||||
|
|
||||||
closeConnection();
|
|
||||||
process.env.DATABASE_PATH = databasePath;
|
|
||||||
await initializeDatabase();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await runTest();
|
|
||||||
} finally {
|
|
||||||
connectedClients.clear();
|
|
||||||
chatRunRegistry.clearAll();
|
|
||||||
closeConnection();
|
|
||||||
if (previousDatabasePath === undefined) {
|
|
||||||
delete process.env.DATABASE_PATH;
|
|
||||||
} else {
|
|
||||||
process.env.DATABASE_PATH = previousDatabasePath;
|
|
||||||
}
|
|
||||||
await rm(tempDirectory, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test('live events are remapped to the app session id and sequenced', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-run-1', 'claude', '/workspace/demo');
|
|
||||||
const connection = new FakeConnection();
|
|
||||||
const run = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-1',
|
|
||||||
provider: 'claude',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: 'user-1',
|
|
||||||
});
|
|
||||||
assert.ok(run);
|
|
||||||
|
|
||||||
run.writer.send({ kind: 'stream_delta', provider: 'claude', sessionId: 'provider-id-9', content: 'hello' });
|
|
||||||
run.writer.send({ kind: 'text', provider: 'claude', sessionId: 'provider-id-9', content: 'hello world' });
|
|
||||||
|
|
||||||
assert.equal(connection.frames.length, 2);
|
|
||||||
assert.equal(connection.frames[0]?.sessionId, 'app-run-1');
|
|
||||||
assert.equal(connection.frames[0]?.seq, 1);
|
|
||||||
assert.equal(connection.frames[1]?.sessionId, 'app-run-1');
|
|
||||||
assert.equal(connection.frames[1]?.seq, 2);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('session_created is swallowed and persisted as the provider-id mapping', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-run-2', 'cursor', '/workspace/demo');
|
|
||||||
const connection = new FakeConnection();
|
|
||||||
connectedClients.add(connection as never);
|
|
||||||
const run = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-2',
|
|
||||||
provider: 'cursor',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.ok(run);
|
|
||||||
|
|
||||||
run.writer.send({
|
|
||||||
kind: 'session_created',
|
|
||||||
provider: 'cursor',
|
|
||||||
sessionId: 'cursor-native-7',
|
|
||||||
newSessionId: 'cursor-native-7',
|
|
||||||
});
|
|
||||||
|
|
||||||
// The provider-native event itself is never forwarded...
|
|
||||||
const sessionUpserts = connection.frames.filter((frame) => frame.kind === 'session_upserted');
|
|
||||||
assert.equal(sessionUpserts.length, 1);
|
|
||||||
assert.equal(sessionUpserts[0]?.sessionId, 'app-run-2');
|
|
||||||
assert.equal(sessionUpserts[0]?.providerSessionId, 'cursor-native-7');
|
|
||||||
// ...but the canonical mapping is recorded and persisted in the database.
|
|
||||||
assert.equal(run.providerSessionId, 'cursor-native-7');
|
|
||||||
assert.equal(sessionsDb.getSessionById('app-run-2')?.provider_session_id, 'cursor-native-7');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('complete marks the run finished and duplicate completes are dropped', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-run-3', 'codex', '/workspace/demo');
|
|
||||||
const connection = new FakeConnection();
|
|
||||||
const run = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-3',
|
|
||||||
provider: 'codex',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.ok(run);
|
|
||||||
|
|
||||||
run.writer.send({ kind: 'complete', provider: 'codex', sessionId: 'native-3', exitCode: 0 });
|
|
||||||
// Late duplicate from a killed runtime's exit handler.
|
|
||||||
run.writer.send({ kind: 'complete', provider: 'codex', sessionId: 'native-3', exitCode: 1 });
|
|
||||||
|
|
||||||
const completes = connection.frames.filter((frame) => frame.kind === 'complete');
|
|
||||||
assert.equal(completes.length, 1);
|
|
||||||
assert.equal(completes[0]?.actualSessionId, 'app-run-3');
|
|
||||||
assert.equal(chatRunRegistry.isProcessing('app-run-3'), false);
|
|
||||||
|
|
||||||
// completeRun is also a no-op once the run already completed.
|
|
||||||
chatRunRegistry.completeRun('app-run-3', { exitCode: 1 });
|
|
||||||
assert.equal(connection.frames.filter((frame) => frame.kind === 'complete').length, 1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('listRunningRuns returns only currently running app sessions', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-run-7', 'claude', '/workspace/demo');
|
|
||||||
sessionsDb.createAppSession('app-run-8', 'codex', '/workspace/demo');
|
|
||||||
const connection = new FakeConnection();
|
|
||||||
|
|
||||||
const completedRun = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-7',
|
|
||||||
provider: 'claude',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.ok(completedRun);
|
|
||||||
|
|
||||||
const runningRun = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-8',
|
|
||||||
provider: 'codex',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.ok(runningRun);
|
|
||||||
|
|
||||||
chatRunRegistry.completeRun('app-run-7', { exitCode: 0 });
|
|
||||||
|
|
||||||
const runningSessions = chatRunRegistry.listRunningRuns();
|
|
||||||
assert.deepEqual(runningSessions.map((session) => session.sessionId), ['app-run-8']);
|
|
||||||
assert.equal(runningSessions[0]?.provider, 'codex');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('replayEvents returns only events after the requested seq', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-run-4', 'claude', '/workspace/demo');
|
|
||||||
const connection = new FakeConnection();
|
|
||||||
const run = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-4',
|
|
||||||
provider: 'claude',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.ok(run);
|
|
||||||
|
|
||||||
run.writer.send({ kind: 'stream_delta', provider: 'claude', sessionId: 'x', content: 'a' });
|
|
||||||
run.writer.send({ kind: 'stream_delta', provider: 'claude', sessionId: 'x', content: 'b' });
|
|
||||||
run.writer.send({ kind: 'stream_delta', provider: 'claude', sessionId: 'x', content: 'c' });
|
|
||||||
|
|
||||||
const replayed = chatRunRegistry.replayEvents('app-run-4', 1);
|
|
||||||
assert.deepEqual(replayed.map((event) => event.content), ['b', 'c']);
|
|
||||||
assert.deepEqual(replayed.map((event) => event.seq), [2, 3]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('attachConnection reroutes the live stream to a new socket', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-run-5', 'gemini', '/workspace/demo');
|
|
||||||
const firstConnection = new FakeConnection();
|
|
||||||
const run = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-5',
|
|
||||||
provider: 'gemini',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection: firstConnection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.ok(run);
|
|
||||||
|
|
||||||
run.writer.send({ kind: 'stream_delta', provider: 'gemini', sessionId: 'g', content: 'before' });
|
|
||||||
|
|
||||||
const secondConnection = new FakeConnection();
|
|
||||||
assert.equal(chatRunRegistry.attachConnection('app-run-5', secondConnection), true);
|
|
||||||
run.writer.send({ kind: 'stream_delta', provider: 'gemini', sessionId: 'g', content: 'after' });
|
|
||||||
|
|
||||||
assert.deepEqual(firstConnection.frames.map((frame) => frame.content), ['before']);
|
|
||||||
assert.deepEqual(secondConnection.frames.map((frame) => frame.content), ['after']);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('startRun rejects a second concurrent run for the same session', async () => {
|
|
||||||
await withIsolatedDatabase(() => {
|
|
||||||
sessionsDb.createAppSession('app-run-6', 'opencode', '/workspace/demo');
|
|
||||||
const connection = new FakeConnection();
|
|
||||||
const first = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-6',
|
|
||||||
provider: 'opencode',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.ok(first);
|
|
||||||
|
|
||||||
const second = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-6',
|
|
||||||
provider: 'opencode',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.equal(second, null);
|
|
||||||
|
|
||||||
// After the run finishes a new one is allowed again.
|
|
||||||
chatRunRegistry.completeRun('app-run-6', { exitCode: 0 });
|
|
||||||
const third = chatRunRegistry.startRun({
|
|
||||||
appSessionId: 'app-run-6',
|
|
||||||
provider: 'opencode',
|
|
||||||
providerSessionId: null,
|
|
||||||
connection,
|
|
||||||
userId: null,
|
|
||||||
});
|
|
||||||
assert.ok(third);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -14,13 +14,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { Codex } from '@openai/codex-sdk';
|
import { Codex } from '@openai/codex-sdk';
|
||||||
|
|
||||||
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
||||||
import { sessionsService } from './modules/providers/services/sessions.service.js';
|
import { sessionsService } from './modules/providers/services/sessions.service.js';
|
||||||
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
||||||
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
|
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
|
||||||
import { createCodexRuntimeEnv, resolveCodexExecutablePath } from './shared/codex-cli-runtime.js';
|
import { createNormalizedMessage } from './shared/utils.js';
|
||||||
import { createCompleteMessage, createNormalizedMessage } from './shared/utils.js';
|
|
||||||
|
|
||||||
// Track active sessions
|
// Track active sessions
|
||||||
const activeCodexSessions = new Map();
|
const activeCodexSessions = new Map();
|
||||||
@@ -250,11 +248,8 @@ export async function queryCodex(command, options = {}, ws) {
|
|||||||
const abortController = new AbortController();
|
const abortController = new AbortController();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Initialize Codex SDK against the same user/global Codex runtime used by shell terminals.
|
// Initialize Codex SDK
|
||||||
codex = new Codex({
|
codex = new Codex();
|
||||||
codexPathOverride: resolveCodexExecutablePath(),
|
|
||||||
env: createCodexRuntimeEnv(),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Thread options with sandbox and approval settings
|
// Thread options with sandbox and approval settings
|
||||||
const threadOptions = {
|
const threadOptions = {
|
||||||
@@ -357,26 +352,21 @@ export async function queryCodex(command, options = {}, ws) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send the terminal completion event — skipped for aborted runs, whose
|
// Send completion event
|
||||||
// terminal `complete` (aborted: true) was already sent by abort-session.
|
if (!terminalFailure) {
|
||||||
const runSession = capturedSessionId ? activeCodexSessions.get(capturedSessionId) : null;
|
sendMessage(ws, createNormalizedMessage({
|
||||||
const runAborted = runSession?.status === 'aborted' || abortController.signal.aborted;
|
kind: 'complete',
|
||||||
if (!runAborted) {
|
actualSessionId: capturedSessionId || thread.id || sessionId || null,
|
||||||
sendMessage(ws, createCompleteMessage({
|
sessionId: capturedSessionId || sessionId || null,
|
||||||
|
provider: 'codex'
|
||||||
|
}));
|
||||||
|
notifyRunStopped({
|
||||||
|
userId: ws?.userId || null,
|
||||||
provider: 'codex',
|
provider: 'codex',
|
||||||
sessionId: capturedSessionId || sessionId || null,
|
sessionId: capturedSessionId || sessionId || null,
|
||||||
actualSessionId: capturedSessionId || thread.id || sessionId || null,
|
sessionName: sessionSummary,
|
||||||
exitCode: terminalFailure ? 1 : 0,
|
stopReason: 'completed'
|
||||||
}));
|
});
|
||||||
if (!terminalFailure) {
|
|
||||||
notifyRunStopped({
|
|
||||||
userId: ws?.userId || null,
|
|
||||||
provider: 'codex',
|
|
||||||
sessionId: capturedSessionId || sessionId || null,
|
|
||||||
sessionName: sessionSummary,
|
|
||||||
stopReason: 'completed'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -396,11 +386,6 @@ export async function queryCodex(command, options = {}, ws) {
|
|||||||
: error.message;
|
: error.message;
|
||||||
|
|
||||||
sendMessage(ws, createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'codex' }));
|
sendMessage(ws, createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'codex' }));
|
||||||
sendMessage(ws, createCompleteMessage({
|
|
||||||
provider: 'codex',
|
|
||||||
sessionId: capturedSessionId || sessionId || null,
|
|
||||||
exitCode: 1,
|
|
||||||
}));
|
|
||||||
if (!terminalFailure) {
|
if (!terminalFailure) {
|
||||||
notifyRunFailed({
|
notifyRunFailed({
|
||||||
userId: ws?.userId || null,
|
userId: ws?.userId || null,
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { sessionsService } from './modules/providers/services/sessions.service.j
|
|||||||
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
|
||||||
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
|
import { providerModelsService } from './modules/providers/services/provider-models.service.js';
|
||||||
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
|
||||||
import { createCompleteMessage, createNormalizedMessage, getOpenCodeDatabasePath } from './shared/utils.js';
|
import { createNormalizedMessage, getOpenCodeDatabasePath } from './shared/utils.js';
|
||||||
|
|
||||||
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
|
||||||
|
|
||||||
@@ -92,9 +92,6 @@ async function spawnOpenCode(command, options = {}, ws) {
|
|||||||
let stdoutLineBuffer = '';
|
let stdoutLineBuffer = '';
|
||||||
let terminalNotificationSent = false;
|
let terminalNotificationSent = false;
|
||||||
let opencodeProcess = null;
|
let opencodeProcess = null;
|
||||||
// Unified lifecycle contract: exactly one terminal `complete` per run
|
|
||||||
// (close and error handlers can both fire for spawn failures).
|
|
||||||
let completeSent = false;
|
|
||||||
|
|
||||||
const notifyTerminalState = ({ code = null, error = null } = {}) => {
|
const notifyTerminalState = ({ code = null, error = null } = {}) => {
|
||||||
if (terminalNotificationSent) {
|
if (terminalNotificationSent) {
|
||||||
@@ -194,10 +191,6 @@ async function spawnOpenCode(command, options = {}, ws) {
|
|||||||
|
|
||||||
void providerModelsService.resolveResumeModel('opencode', sessionId, model).then((resolvedModel) => {
|
void providerModelsService.resolveResumeModel('opencode', sessionId, model).then((resolvedModel) => {
|
||||||
const args = ['run', '--format', 'json'];
|
const args = ['run', '--format', 'json'];
|
||||||
// OpenCode's `run` command owns workspace selection through `--dir`.
|
|
||||||
// Relying on the child-process cwd alone is not enough on Linux, where
|
|
||||||
// the CLI can still resolve the session under the server install dir.
|
|
||||||
args.push('--dir', workingDir);
|
|
||||||
if (sessionId) {
|
if (sessionId) {
|
||||||
args.push('--session', sessionId);
|
args.push('--session', sessionId);
|
||||||
}
|
}
|
||||||
@@ -263,12 +256,13 @@ async function spawnOpenCode(command, options = {}, ws) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Terminal complete — skipped for aborted runs (abort-session
|
ws.send(createNormalizedMessage({
|
||||||
// already sent the aborted complete on this run's behalf).
|
kind: 'complete',
|
||||||
if (!completeSent && !opencodeProcess.aborted) {
|
exitCode: code,
|
||||||
completeSent = true;
|
isNewSession: !sessionId && !!command,
|
||||||
ws.send(createCompleteMessage({ provider: 'opencode', sessionId: finalSessionId, exitCode: code }));
|
sessionId: finalSessionId,
|
||||||
}
|
provider: 'opencode',
|
||||||
|
}));
|
||||||
|
|
||||||
if (code === 0) {
|
if (code === 0) {
|
||||||
notifyTerminalState({ code });
|
notifyTerminalState({ code });
|
||||||
@@ -308,10 +302,6 @@ async function spawnOpenCode(command, options = {}, ws) {
|
|||||||
sessionId: finalSessionId,
|
sessionId: finalSessionId,
|
||||||
provider: 'opencode',
|
provider: 'opencode',
|
||||||
}));
|
}));
|
||||||
if (!completeSent && !opencodeProcess.aborted) {
|
|
||||||
completeSent = true;
|
|
||||||
ws.send(createCompleteMessage({ provider: 'opencode', sessionId: finalSessionId, exitCode: 1 }));
|
|
||||||
}
|
|
||||||
notifyTerminalState({ error });
|
notifyTerminalState({ error });
|
||||||
reject(error);
|
reject(error);
|
||||||
});
|
});
|
||||||
@@ -325,9 +315,6 @@ function abortOpenCodeSession(sessionId) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The abort handler sends the terminal complete (aborted: true); flag the
|
|
||||||
// process so its close handler does not emit a second one.
|
|
||||||
process.aborted = true;
|
|
||||||
process.kill('SIGTERM');
|
process.kill('SIGTERM');
|
||||||
activeOpenCodeProcesses.delete(sessionId);
|
activeOpenCodeProcesses.delete(sessionId);
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
@@ -12,11 +12,6 @@ const findEnvKey = (name) =>
|
|||||||
async function createFakeOpenCodeExecutable(binDir) {
|
async function createFakeOpenCodeExecutable(binDir) {
|
||||||
const scriptPath = path.join(binDir, 'opencode.js');
|
const scriptPath = path.join(binDir, 'opencode.js');
|
||||||
await writeFile(scriptPath, `
|
await writeFile(scriptPath, `
|
||||||
const capturePath = process.env.OPENCODE_ARGS_CAPTURE;
|
|
||||||
if (capturePath) {
|
|
||||||
require('node:fs').writeFileSync(capturePath, JSON.stringify(process.argv.slice(2)));
|
|
||||||
}
|
|
||||||
|
|
||||||
const events = [
|
const events = [
|
||||||
{ type: 'text', sessionID: 'open-live-1', text: 'assistant response' },
|
{ type: 'text', sessionID: 'open-live-1', text: 'assistant response' },
|
||||||
{ type: 'step_finish', sessionID: 'open-live-1' },
|
{ type: 'step_finish', sessionID: 'open-live-1' },
|
||||||
@@ -40,12 +35,10 @@ for (const event of events) {
|
|||||||
|
|
||||||
test('spawnOpenCode emits session_created before normalized live messages for new sessions', async () => {
|
test('spawnOpenCode emits session_created before normalized live messages for new sessions', async () => {
|
||||||
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'opencode-cli-live-'));
|
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'opencode-cli-live-'));
|
||||||
const argsCapturePath = path.join(tempRoot, 'opencode-args.json');
|
|
||||||
const pathKey = findEnvKey('PATH');
|
const pathKey = findEnvKey('PATH');
|
||||||
const pathExtKey = findEnvKey('PATHEXT');
|
const pathExtKey = findEnvKey('PATHEXT');
|
||||||
const previousPath = process.env[pathKey];
|
const previousPath = process.env[pathKey];
|
||||||
const previousPathExt = process.env[pathExtKey];
|
const previousPathExt = process.env[pathExtKey];
|
||||||
const previousArgsCapture = process.env.OPENCODE_ARGS_CAPTURE;
|
|
||||||
const messages = [];
|
const messages = [];
|
||||||
const writer = {
|
const writer = {
|
||||||
userId: null,
|
userId: null,
|
||||||
@@ -61,7 +54,6 @@ test('spawnOpenCode emits session_created before normalized live messages for ne
|
|||||||
try {
|
try {
|
||||||
await createFakeOpenCodeExecutable(tempRoot);
|
await createFakeOpenCodeExecutable(tempRoot);
|
||||||
process.env[pathKey] = `${tempRoot}${path.delimiter}${previousPath || ''}`;
|
process.env[pathKey] = `${tempRoot}${path.delimiter}${previousPath || ''}`;
|
||||||
process.env.OPENCODE_ARGS_CAPTURE = argsCapturePath;
|
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
process.env[pathExtKey] = previousPathExt?.toUpperCase().includes('.CMD')
|
process.env[pathExtKey] = previousPathExt?.toUpperCase().includes('.CMD')
|
||||||
? previousPathExt
|
? previousPathExt
|
||||||
@@ -85,11 +77,6 @@ test('spawnOpenCode emits session_created before normalized live messages for ne
|
|||||||
assert.equal(streamEnd?.sessionId, 'open-live-1');
|
assert.equal(streamEnd?.sessionId, 'open-live-1');
|
||||||
assert.equal(complete?.sessionId, 'open-live-1');
|
assert.equal(complete?.sessionId, 'open-live-1');
|
||||||
assert.equal(messages.some((message) => message.kind === 'error'), false);
|
assert.equal(messages.some((message) => message.kind === 'error'), false);
|
||||||
|
|
||||||
const launchedArgs = JSON.parse(await readFile(argsCapturePath, 'utf8'));
|
|
||||||
assert.ok(Array.isArray(launchedArgs));
|
|
||||||
assert.deepEqual(launchedArgs.slice(0, 4), ['run', '--format', 'json', '--dir']);
|
|
||||||
assert.equal(launchedArgs[4], tempRoot);
|
|
||||||
} finally {
|
} finally {
|
||||||
if (previousPath === undefined) {
|
if (previousPath === undefined) {
|
||||||
delete process.env[pathKey];
|
delete process.env[pathKey];
|
||||||
@@ -103,12 +90,6 @@ test('spawnOpenCode emits session_created before normalized live messages for ne
|
|||||||
process.env[pathExtKey] = previousPathExt;
|
process.env[pathExtKey] = previousPathExt;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (previousArgsCapture === undefined) {
|
|
||||||
delete process.env.OPENCODE_ARGS_CAPTURE;
|
|
||||||
} else {
|
|
||||||
process.env.OPENCODE_ARGS_CAPTURE = previousArgsCapture;
|
|
||||||
}
|
|
||||||
|
|
||||||
await rm(tempRoot, { recursive: true, force: true });
|
await rm(tempRoot, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -98,44 +98,6 @@ function normalizeSessionName(sessionName) {
|
|||||||
return normalized.length > 80 ? `${normalized.slice(0, 77)}...` : normalized;
|
return normalized.length > 80 ? `${normalized.slice(0, 77)}...` : normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
function rowMatchesProvider(row, provider) {
|
|
||||||
return row && (!provider || row.provider === provider);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveSessionRow(sessionId, provider) {
|
|
||||||
if (!sessionId) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const appSessionRow = sessionsDb.getSessionById(sessionId);
|
|
||||||
if (rowMatchesProvider(appSessionRow, provider)) {
|
|
||||||
return appSessionRow;
|
|
||||||
}
|
|
||||||
|
|
||||||
const providerSessionRow = sessionsDb.getSessionByProviderSessionId(sessionId);
|
|
||||||
if (rowMatchesProvider(providerSessionRow, provider)) {
|
|
||||||
return providerSessionRow;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeNotificationSession(event) {
|
|
||||||
if (!event?.sessionId || !event.provider || event.provider === 'system') {
|
|
||||||
return event;
|
|
||||||
}
|
|
||||||
|
|
||||||
const row = resolveSessionRow(event.sessionId, event.provider);
|
|
||||||
if (!row || row.session_id === event.sessionId) {
|
|
||||||
return event;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...event,
|
|
||||||
sessionId: row.session_id
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveSessionName(event) {
|
function resolveSessionName(event) {
|
||||||
const explicitSessionName = normalizeSessionName(event.meta?.sessionName);
|
const explicitSessionName = normalizeSessionName(event.meta?.sessionName);
|
||||||
if (explicitSessionName) {
|
if (explicitSessionName) {
|
||||||
@@ -150,29 +112,28 @@ function resolveSessionName(event) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildPushBody(event) {
|
function buildPushBody(event) {
|
||||||
const normalizedEvent = normalizeNotificationSession(event);
|
|
||||||
const CODE_MAP = {
|
const CODE_MAP = {
|
||||||
'permission.required': normalizedEvent.meta?.toolName
|
'permission.required': event.meta?.toolName
|
||||||
? `Action Required: Tool "${normalizedEvent.meta.toolName}" needs approval`
|
? `Action Required: Tool "${event.meta.toolName}" needs approval`
|
||||||
: 'Action Required: A tool needs your approval',
|
: 'Action Required: A tool needs your approval',
|
||||||
'run.stopped': normalizedEvent.meta?.stopReason || 'Run Stopped: The run has stopped',
|
'run.stopped': event.meta?.stopReason || 'Run Stopped: The run has stopped',
|
||||||
'run.failed': normalizedEvent.meta?.error ? `Run Failed: ${normalizedEvent.meta.error}` : 'Run Failed: The run encountered an error',
|
'run.failed': event.meta?.error ? `Run Failed: ${event.meta.error}` : 'Run Failed: The run encountered an error',
|
||||||
'agent.notification': normalizedEvent.meta?.message ? String(normalizedEvent.meta.message) : 'You have a new notification',
|
'agent.notification': event.meta?.message ? String(event.meta.message) : 'You have a new notification',
|
||||||
'push.enabled': 'Push notifications are now enabled!'
|
'push.enabled': 'Push notifications are now enabled!'
|
||||||
};
|
};
|
||||||
const providerLabel = PROVIDER_LABELS[normalizedEvent.provider] || 'Assistant';
|
const providerLabel = PROVIDER_LABELS[event.provider] || 'Assistant';
|
||||||
const sessionName = resolveSessionName(normalizedEvent);
|
const sessionName = resolveSessionName(event);
|
||||||
const message = CODE_MAP[normalizedEvent.code] || 'You have a new notification';
|
const message = CODE_MAP[event.code] || 'You have a new notification';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
title: sessionName || 'CloudCLI',
|
title: sessionName || 'CloudCLI',
|
||||||
body: `${providerLabel}: ${message}`,
|
body: `${providerLabel}: ${message}`,
|
||||||
data: {
|
data: {
|
||||||
sessionId: normalizedEvent.sessionId || null,
|
sessionId: event.sessionId || null,
|
||||||
code: normalizedEvent.code,
|
code: event.code,
|
||||||
provider: normalizedEvent.provider || null,
|
provider: event.provider || null,
|
||||||
sessionName,
|
sessionName,
|
||||||
tag: `${normalizedEvent.provider || 'assistant'}:${normalizedEvent.sessionId || 'none'}:${normalizedEvent.code}`
|
tag: `${event.provider || 'assistant'}:${event.sessionId || 'none'}:${event.code}`
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -214,16 +175,15 @@ function notifyUserIfEnabled({ userId, event }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const normalizedEvent = normalizeNotificationSession(event);
|
|
||||||
const preferences = notificationPreferencesDb.getPreferences(userId);
|
const preferences = notificationPreferencesDb.getPreferences(userId);
|
||||||
if (!shouldSendPush(preferences, normalizedEvent)) {
|
if (!shouldSendPush(preferences, event)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (isDuplicate(normalizedEvent)) {
|
if (isDuplicate(event)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
sendWebPush(userId, normalizedEvent).catch((err) => {
|
sendWebPush(userId, event).catch((err) => {
|
||||||
console.error('Web push send error:', err);
|
console.error('Web push send error:', err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import { mkdtemp, rm } from 'node:fs/promises';
|
|
||||||
import { tmpdir } from 'node:os';
|
|
||||||
import path from 'node:path';
|
|
||||||
import test from 'node:test';
|
|
||||||
|
|
||||||
import webPush from 'web-push';
|
|
||||||
|
|
||||||
import {
|
|
||||||
closeConnection,
|
|
||||||
initializeDatabase,
|
|
||||||
notificationPreferencesDb,
|
|
||||||
pushSubscriptionsDb,
|
|
||||||
sessionsDb,
|
|
||||||
userDb,
|
|
||||||
} from '../modules/database/index.js';
|
|
||||||
|
|
||||||
import { notifyRunStopped } from './notification-orchestrator.js';
|
|
||||||
|
|
||||||
async function withIsolatedDatabase(runTest) {
|
|
||||||
const previousDatabasePath = process.env.DATABASE_PATH;
|
|
||||||
const tempDirectory = await mkdtemp(path.join(tmpdir(), 'notification-orchestrator-'));
|
|
||||||
const databasePath = path.join(tempDirectory, 'auth.db');
|
|
||||||
|
|
||||||
closeConnection();
|
|
||||||
process.env.DATABASE_PATH = databasePath;
|
|
||||||
await initializeDatabase();
|
|
||||||
|
|
||||||
try {
|
|
||||||
await runTest();
|
|
||||||
} finally {
|
|
||||||
closeConnection();
|
|
||||||
if (previousDatabasePath === undefined) {
|
|
||||||
delete process.env.DATABASE_PATH;
|
|
||||||
} else {
|
|
||||||
process.env.DATABASE_PATH = previousDatabasePath;
|
|
||||||
}
|
|
||||||
await rm(tempDirectory, { recursive: true, force: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test('push payload uses the app session id when notified with a provider session id', async () => {
|
|
||||||
const originalSendNotification = webPush.sendNotification;
|
|
||||||
const sentPayloads = [];
|
|
||||||
|
|
||||||
webPush.sendNotification = async (_subscription, payload) => {
|
|
||||||
sentPayloads.push(JSON.parse(payload));
|
|
||||||
return {};
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
await withIsolatedDatabase(async () => {
|
|
||||||
const user = userDb.createUser('notify-user', 'hash');
|
|
||||||
const userId = Number(user.id);
|
|
||||||
|
|
||||||
notificationPreferencesDb.updatePreferences(userId, {
|
|
||||||
channels: { webPush: true },
|
|
||||||
events: { actionRequired: true, stop: true, error: true },
|
|
||||||
});
|
|
||||||
pushSubscriptionsDb.saveSubscription(userId, 'https://example.test/push', 'p256dh', 'auth');
|
|
||||||
sessionsDb.createAppSession('app-session-1', 'claude', '/workspace/demo');
|
|
||||||
sessionsDb.assignProviderSessionId('app-session-1', 'claude-native-1');
|
|
||||||
|
|
||||||
notifyRunStopped({
|
|
||||||
userId,
|
|
||||||
provider: 'claude',
|
|
||||||
sessionId: 'claude-native-1',
|
|
||||||
stopReason: 'completed',
|
|
||||||
});
|
|
||||||
|
|
||||||
await new Promise((resolve) => setImmediate(resolve));
|
|
||||||
|
|
||||||
assert.equal(sentPayloads.length, 1);
|
|
||||||
assert.equal(sentPayloads[0]?.data?.sessionId, 'app-session-1');
|
|
||||||
assert.match(sentPayloads[0]?.data?.tag, /app-session-1/);
|
|
||||||
});
|
|
||||||
} finally {
|
|
||||||
webPush.sendNotification = originalSendNotification;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
|
|
||||||
import { createUserShellRuntimeEnv } from '@/shared/cli-runtime-env.js';
|
|
||||||
|
|
||||||
const POSIX_PATH_DELIMITER = ':';
|
|
||||||
|
|
||||||
test('createUserShellRuntimeEnv prepends user CLI bins before app-local npm bins', () => {
|
|
||||||
const runtimeEnv = createUserShellRuntimeEnv(
|
|
||||||
{
|
|
||||||
NPM_CONFIG_PREFIX: '/home/devuser/.npm-global',
|
|
||||||
PATH: `/opt/claudecodeui/node_modules/.bin${POSIX_PATH_DELIMITER}/usr/bin`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
homedir: () => '/home/devuser',
|
|
||||||
platform: 'linux',
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.equal(
|
|
||||||
runtimeEnv.PATH,
|
|
||||||
[
|
|
||||||
'/home/devuser/.npm-global/bin',
|
|
||||||
'/home/devuser/.local/bin',
|
|
||||||
'/opt/claudecodeui/node_modules/.bin',
|
|
||||||
'/usr/bin',
|
|
||||||
].join(POSIX_PATH_DELIMITER)
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('createUserShellRuntimeEnv does not duplicate existing user CLI path entries', () => {
|
|
||||||
const runtimeEnv = createUserShellRuntimeEnv(
|
|
||||||
{
|
|
||||||
PATH: [
|
|
||||||
'/home/devuser/.npm-global/bin',
|
|
||||||
'/opt/claudecodeui/node_modules/.bin',
|
|
||||||
'/usr/bin',
|
|
||||||
].join(POSIX_PATH_DELIMITER),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
homedir: () => '/home/devuser',
|
|
||||||
platform: 'linux',
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.equal(
|
|
||||||
runtimeEnv.PATH,
|
|
||||||
[
|
|
||||||
'/home/devuser/.local/bin',
|
|
||||||
'/home/devuser/.npm-global/bin',
|
|
||||||
'/opt/claudecodeui/node_modules/.bin',
|
|
||||||
'/usr/bin',
|
|
||||||
].join(POSIX_PATH_DELIMITER)
|
|
||||||
);
|
|
||||||
});
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
import os from 'node:os';
|
|
||||||
import path from 'node:path';
|
|
||||||
|
|
||||||
export type EnvRecord = Record<string, string | undefined>;
|
|
||||||
|
|
||||||
export type CliRuntimeEnvDependencies = {
|
|
||||||
env?: EnvRecord;
|
|
||||||
homedir?: typeof os.homedir;
|
|
||||||
platform?: NodeJS.Platform;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the path implementation that matches the target runtime platform.
|
|
||||||
*/
|
|
||||||
function getPathApi(platform: NodeJS.Platform) {
|
|
||||||
return platform === 'win32' ? path.win32 : path.posix;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the PATH delimiter used by the target runtime platform.
|
|
||||||
*/
|
|
||||||
function getPathDelimiter(platform: NodeJS.Platform): string {
|
|
||||||
return platform === 'win32' ? ';' : ':';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Finds the environment key that represents PATH, preserving Windows case variants.
|
|
||||||
*/
|
|
||||||
function getPathEnvKey(env: EnvRecord, platform: NodeJS.Platform): string {
|
|
||||||
if (platform !== 'win32') {
|
|
||||||
return 'PATH';
|
|
||||||
}
|
|
||||||
|
|
||||||
return Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'Path';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Deduplicates non-empty string values while preserving their original order.
|
|
||||||
*/
|
|
||||||
function unique(values: string[]): string[] {
|
|
||||||
return Array.from(new Set(values.filter(Boolean)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts a process-style environment object into a string-only environment for child processes.
|
|
||||||
*/
|
|
||||||
export function toStringEnv(env: EnvRecord): Record<string, string> {
|
|
||||||
return Object.fromEntries(
|
|
||||||
Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Builds user/global CLI bin directories that should rank ahead of app-local npm bins.
|
|
||||||
*/
|
|
||||||
export function getPreferredUserCliBinDirectories(
|
|
||||||
dependencies: Required<CliRuntimeEnvDependencies>
|
|
||||||
): string[] {
|
|
||||||
const pathApi = getPathApi(dependencies.platform);
|
|
||||||
const homeDir = dependencies.homedir();
|
|
||||||
const candidates: string[] = [];
|
|
||||||
const npmPrefix = dependencies.env.NPM_CONFIG_PREFIX?.trim();
|
|
||||||
|
|
||||||
if (npmPrefix) {
|
|
||||||
candidates.push(pathApi.join(npmPrefix, dependencies.platform === 'win32' ? '' : 'bin'));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dependencies.platform === 'win32') {
|
|
||||||
const appData = dependencies.env.APPDATA?.trim();
|
|
||||||
if (appData) {
|
|
||||||
candidates.push(appData, pathApi.join(appData, 'npm'));
|
|
||||||
}
|
|
||||||
candidates.push(pathApi.join(homeDir, 'AppData', 'Roaming', 'npm'));
|
|
||||||
} else {
|
|
||||||
candidates.push(
|
|
||||||
pathApi.join(homeDir, '.npm-global', 'bin'),
|
|
||||||
pathApi.join(homeDir, '.local', 'bin'),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return unique(candidates);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a provider-neutral shell environment that prefers user/global CLI bins over app-local bins.
|
|
||||||
*/
|
|
||||||
export function createUserShellRuntimeEnv(
|
|
||||||
env: EnvRecord = process.env,
|
|
||||||
dependencies: CliRuntimeEnvDependencies = {}
|
|
||||||
): Record<string, string> {
|
|
||||||
const deps: Required<CliRuntimeEnvDependencies> = {
|
|
||||||
env,
|
|
||||||
homedir: dependencies.homedir ?? os.homedir,
|
|
||||||
platform: dependencies.platform ?? process.platform,
|
|
||||||
};
|
|
||||||
const pathKey = getPathEnvKey(env, deps.platform);
|
|
||||||
const delimiter = getPathDelimiter(deps.platform);
|
|
||||||
const currentPathEntries = (env[pathKey] ?? '').split(delimiter).filter(Boolean);
|
|
||||||
const preferredEntries = getPreferredUserCliBinDirectories(deps).filter(
|
|
||||||
(entry) => !currentPathEntries.includes(entry)
|
|
||||||
);
|
|
||||||
const nextEnv: EnvRecord = { ...env };
|
|
||||||
|
|
||||||
if (preferredEntries.length > 0) {
|
|
||||||
nextEnv[pathKey] = [...preferredEntries, ...currentPathEntries].join(delimiter);
|
|
||||||
}
|
|
||||||
|
|
||||||
return toStringEnv(nextEnv);
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
|
|
||||||
import {
|
|
||||||
createCodexRuntimeEnv,
|
|
||||||
getCodexShellCommand,
|
|
||||||
resolveCodexExecutablePath,
|
|
||||||
type ResolveCodexExecutablePathDependencies,
|
|
||||||
} from '@/shared/codex-cli-runtime.js';
|
|
||||||
|
|
||||||
const POSIX_PATH_DELIMITER = ':';
|
|
||||||
|
|
||||||
function createExistsSync(paths: string[]): ResolveCodexExecutablePathDependencies['existsSync'] {
|
|
||||||
const existing = new Set(paths);
|
|
||||||
return ((candidate: string) => existing.has(candidate)) as ResolveCodexExecutablePathDependencies['existsSync'];
|
|
||||||
}
|
|
||||||
|
|
||||||
test('resolveCodexExecutablePath prefers the user npm-global install over app-local PATH entries', () => {
|
|
||||||
const globalCodexPath = '/home/devuser/.npm-global/bin/codex';
|
|
||||||
const localCodexPath = '/opt/claudecodeui/node_modules/.bin/codex';
|
|
||||||
|
|
||||||
const resolved = resolveCodexExecutablePath(undefined, {
|
|
||||||
env: {
|
|
||||||
NPM_CONFIG_PREFIX: '/home/devuser/.npm-global',
|
|
||||||
PATH: `/opt/claudecodeui/node_modules/.bin${POSIX_PATH_DELIMITER}/usr/bin`,
|
|
||||||
},
|
|
||||||
existsSync: createExistsSync([globalCodexPath, localCodexPath]),
|
|
||||||
homedir: () => '/home/devuser',
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(resolved, globalCodexPath);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('resolveCodexExecutablePath skips node_modules bin when a non-local PATH codex exists', () => {
|
|
||||||
const localCodexPath = '/opt/claudecodeui/node_modules/.bin/codex';
|
|
||||||
const pathCodexPath = '/usr/local/bin/codex';
|
|
||||||
|
|
||||||
const resolved = resolveCodexExecutablePath(undefined, {
|
|
||||||
env: {
|
|
||||||
PATH: `/opt/claudecodeui/node_modules/.bin${POSIX_PATH_DELIMITER}/usr/local/bin`,
|
|
||||||
},
|
|
||||||
existsSync: createExistsSync([localCodexPath, pathCodexPath]),
|
|
||||||
homedir: () => '/home/devuser',
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(resolved, pathCodexPath);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('resolveCodexExecutablePath falls back to app-local codex when it is the only install', () => {
|
|
||||||
const localCodexPath = '/opt/claudecodeui/node_modules/.bin/codex';
|
|
||||||
|
|
||||||
const resolved = resolveCodexExecutablePath(undefined, {
|
|
||||||
env: {
|
|
||||||
PATH: `/opt/claudecodeui/node_modules/.bin${POSIX_PATH_DELIMITER}/usr/bin`,
|
|
||||||
},
|
|
||||||
existsSync: createExistsSync([localCodexPath]),
|
|
||||||
homedir: () => '/home/devuser',
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(resolved, localCodexPath);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('createCodexRuntimeEnv prepends the selected Codex directory to PATH', () => {
|
|
||||||
const runtimeEnv = createCodexRuntimeEnv(
|
|
||||||
{
|
|
||||||
NPM_CONFIG_PREFIX: '/home/devuser/.npm-global',
|
|
||||||
PATH: `/opt/claudecodeui/node_modules/.bin${POSIX_PATH_DELIMITER}/usr/bin`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
existsSync: createExistsSync(['/home/devuser/.npm-global/bin/codex']),
|
|
||||||
homedir: () => '/home/devuser',
|
|
||||||
platform: 'linux',
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
assert.equal(
|
|
||||||
runtimeEnv.PATH,
|
|
||||||
`/home/devuser/.npm-global/bin${POSIX_PATH_DELIMITER}/opt/claudecodeui/node_modules/.bin${POSIX_PATH_DELIMITER}/usr/bin`
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('getCodexShellCommand quotes explicit executable paths for shell launches', () => {
|
|
||||||
const command = getCodexShellCommand({
|
|
||||||
env: {
|
|
||||||
CODEX_CLI_PATH: "/home/devuser/bin/codex with space",
|
|
||||||
},
|
|
||||||
existsSync: createExistsSync([]),
|
|
||||||
homedir: () => '/home/devuser',
|
|
||||||
platform: 'linux',
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(command, "'/home/devuser/bin/codex with space'");
|
|
||||||
});
|
|
||||||
@@ -1,288 +0,0 @@
|
|||||||
import fs from 'node:fs';
|
|
||||||
import os from 'node:os';
|
|
||||||
import path from 'node:path';
|
|
||||||
|
|
||||||
const DEFAULT_CODEX_COMMAND = 'codex';
|
|
||||||
const CODEX_CLI_PATH_ENV_KEYS = ['CODEX_CLI_PATH', 'CLOUDCLI_CODEX_CLI_PATH'] as const;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Codex runtime precedence:
|
|
||||||
* 1. Explicit CODEX_CLI_PATH or CLOUDCLI_CODEX_CLI_PATH.
|
|
||||||
* 2. User/global installs such as NPM_CONFIG_PREFIX/bin, ~/.npm-global/bin, or ~/.local/bin.
|
|
||||||
* 3. Non-local PATH entries.
|
|
||||||
* 4. App-local node_modules/.bin as the final fallback.
|
|
||||||
*/
|
|
||||||
type EnvRecord = Record<string, string | undefined>;
|
|
||||||
|
|
||||||
export type ResolveCodexExecutablePathDependencies = {
|
|
||||||
env?: EnvRecord;
|
|
||||||
existsSync?: typeof fs.existsSync;
|
|
||||||
homedir?: typeof os.homedir;
|
|
||||||
platform?: NodeJS.Platform;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the path implementation that matches the target runtime platform.
|
|
||||||
*/
|
|
||||||
function getPathApi(platform: NodeJS.Platform) {
|
|
||||||
return platform === 'win32' ? path.win32 : path.posix;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the PATH delimiter used by the target runtime platform.
|
|
||||||
*/
|
|
||||||
function getPathDelimiter(platform: NodeJS.Platform): string {
|
|
||||||
return platform === 'win32' ? ';' : ':';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes one matching pair of surrounding quotes from a configured path value.
|
|
||||||
*/
|
|
||||||
function stripWrappingQuotes(value: string): string {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (
|
|
||||||
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
|
|
||||||
(trimmed.startsWith("'") && trimmed.endsWith("'"))
|
|
||||||
) {
|
|
||||||
return trimmed.slice(1, -1);
|
|
||||||
}
|
|
||||||
return trimmed;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks whether a command value looks like a filesystem path instead of a bare command name.
|
|
||||||
*/
|
|
||||||
function isPathLike(value: string, platform: NodeJS.Platform): boolean {
|
|
||||||
return value.includes('/') || value.includes('\\') || getPathApi(platform).isAbsolute(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Finds the environment key that represents PATH, preserving Windows case variants.
|
|
||||||
*/
|
|
||||||
function getPathEnvKey(env: EnvRecord, platform: NodeJS.Platform): string {
|
|
||||||
if (platform !== 'win32') {
|
|
||||||
return 'PATH';
|
|
||||||
}
|
|
||||||
|
|
||||||
return Object.keys(env).find((key) => key.toLowerCase() === 'path') ?? 'Path';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the Codex executable filenames to probe for the target platform.
|
|
||||||
*/
|
|
||||||
function getExecutableNames(platform: NodeJS.Platform): string[] {
|
|
||||||
if (platform !== 'win32') {
|
|
||||||
return [DEFAULT_CODEX_COMMAND];
|
|
||||||
}
|
|
||||||
|
|
||||||
return ['codex.exe', 'codex.cmd', 'codex.bat', 'codex.ps1', DEFAULT_CODEX_COMMAND];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Deduplicates non-empty string values while preserving their original order.
|
|
||||||
*/
|
|
||||||
function unique(values: string[]): string[] {
|
|
||||||
return Array.from(new Set(values.filter(Boolean)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Detects app-local npm bin directories so they can be treated as a fallback.
|
|
||||||
*/
|
|
||||||
function isNodeModulesBinPath(directoryPath: string, platform: NodeJS.Platform): boolean {
|
|
||||||
const pathApi = getPathApi(platform);
|
|
||||||
const normalized = directoryPath.replace(/[\\/]+$/, '');
|
|
||||||
return (
|
|
||||||
pathApi.basename(normalized).toLowerCase() === '.bin' &&
|
|
||||||
pathApi.basename(pathApi.dirname(normalized)).toLowerCase() === 'node_modules'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves the first Codex executable that exists inside one directory.
|
|
||||||
*/
|
|
||||||
function resolveExecutableInDirectory(
|
|
||||||
directoryPath: string,
|
|
||||||
deps: Required<ResolveCodexExecutablePathDependencies>
|
|
||||||
): string | null {
|
|
||||||
const pathApi = getPathApi(deps.platform);
|
|
||||||
for (const executableName of getExecutableNames(deps.platform)) {
|
|
||||||
const candidate = pathApi.join(directoryPath, executableName);
|
|
||||||
if (deps.existsSync(candidate)) {
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reads an explicit Codex executable override from supported environment variables.
|
|
||||||
*/
|
|
||||||
function getConfiguredCodexPath(env: EnvRecord): string | null {
|
|
||||||
for (const key of CODEX_CLI_PATH_ENV_KEYS) {
|
|
||||||
const value = env[key]?.trim();
|
|
||||||
if (value) {
|
|
||||||
return stripWrappingQuotes(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Builds user/global Codex install candidates that rank ahead of PATH and app-local installs:
|
|
||||||
* NPM_CONFIG_PREFIX/bin, ~/.npm-global/bin, ~/.local/bin, or the Windows npm user folders.
|
|
||||||
*/
|
|
||||||
function getPreferredUserInstallCandidates(
|
|
||||||
deps: Required<ResolveCodexExecutablePathDependencies>
|
|
||||||
): string[] {
|
|
||||||
const pathApi = getPathApi(deps.platform);
|
|
||||||
const homeDir = deps.homedir();
|
|
||||||
const candidates: string[] = [];
|
|
||||||
const npmPrefix = deps.env.NPM_CONFIG_PREFIX?.trim();
|
|
||||||
|
|
||||||
if (npmPrefix) {
|
|
||||||
candidates.push(pathApi.join(npmPrefix, deps.platform === 'win32' ? '' : 'bin'));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (deps.platform === 'win32') {
|
|
||||||
const appData = deps.env.APPDATA?.trim();
|
|
||||||
if (appData) {
|
|
||||||
candidates.push(appData, pathApi.join(appData, 'npm'));
|
|
||||||
}
|
|
||||||
candidates.push(pathApi.join(homeDir, 'AppData', 'Roaming', 'npm'));
|
|
||||||
} else {
|
|
||||||
candidates.push(
|
|
||||||
pathApi.join(homeDir, '.npm-global', 'bin'),
|
|
||||||
pathApi.join(homeDir, '.local', 'bin'),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return unique(candidates);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Searches PATH for Codex after user/global candidates, keeping node_modules/.bin as the last fallback.
|
|
||||||
*/
|
|
||||||
function resolveFromPath(
|
|
||||||
deps: Required<ResolveCodexExecutablePathDependencies>
|
|
||||||
): string | null {
|
|
||||||
const pathKey = getPathEnvKey(deps.env, deps.platform);
|
|
||||||
const pathValue = deps.env[pathKey] ?? '';
|
|
||||||
const directories = unique(pathValue.split(getPathDelimiter(deps.platform)).filter(Boolean));
|
|
||||||
let nodeModulesFallback: string | null = null;
|
|
||||||
|
|
||||||
for (const directory of directories) {
|
|
||||||
const candidate = resolveExecutableInDirectory(directory, deps);
|
|
||||||
if (!candidate) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isNodeModulesBinPath(directory, deps.platform)) {
|
|
||||||
nodeModulesFallback ??= candidate;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
|
|
||||||
return nodeModulesFallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts a process-style environment object into a string-only environment for child processes.
|
|
||||||
*/
|
|
||||||
function toStringEnv(env: EnvRecord): Record<string, string> {
|
|
||||||
return Object.fromEntries(
|
|
||||||
Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolves the Codex executable path for all backend entry points in this order:
|
|
||||||
* explicit CODEX_CLI_PATH/CLOUDCLI_CODEX_CLI_PATH, user/global installs, non-local PATH, app-local PATH.
|
|
||||||
*/
|
|
||||||
export function resolveCodexExecutablePath(
|
|
||||||
configuredPath: string | undefined = undefined,
|
|
||||||
dependencies: ResolveCodexExecutablePathDependencies = {}
|
|
||||||
): string {
|
|
||||||
const deps: Required<ResolveCodexExecutablePathDependencies> = {
|
|
||||||
env: dependencies.env ?? process.env,
|
|
||||||
existsSync: dependencies.existsSync ?? fs.existsSync,
|
|
||||||
homedir: dependencies.homedir ?? os.homedir,
|
|
||||||
platform: dependencies.platform ?? process.platform,
|
|
||||||
};
|
|
||||||
|
|
||||||
const normalizedConfiguredPath = stripWrappingQuotes(
|
|
||||||
configuredPath?.trim() || getConfiguredCodexPath(deps.env) || ''
|
|
||||||
);
|
|
||||||
if (normalizedConfiguredPath) {
|
|
||||||
if (!isPathLike(normalizedConfiguredPath, deps.platform)) {
|
|
||||||
return resolveFromPath(deps) ?? normalizedConfiguredPath;
|
|
||||||
}
|
|
||||||
return normalizedConfiguredPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const candidateDirectory of getPreferredUserInstallCandidates(deps)) {
|
|
||||||
const candidate = resolveExecutableInDirectory(candidateDirectory, deps);
|
|
||||||
if (candidate) {
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return resolveFromPath(deps) ?? DEFAULT_CODEX_COMMAND;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a Codex child-process environment with the selected runtime directory first on PATH,
|
|
||||||
* preserving the same source precedence as resolveCodexExecutablePath.
|
|
||||||
*/
|
|
||||||
export function createCodexRuntimeEnv(
|
|
||||||
env: EnvRecord = process.env,
|
|
||||||
dependencies: ResolveCodexExecutablePathDependencies = {}
|
|
||||||
): Record<string, string> {
|
|
||||||
const platform = dependencies.platform ?? process.platform;
|
|
||||||
const pathApi = getPathApi(platform);
|
|
||||||
const resolvedCodexPath = resolveCodexExecutablePath(undefined, {
|
|
||||||
...dependencies,
|
|
||||||
env,
|
|
||||||
platform,
|
|
||||||
});
|
|
||||||
const pathKey = getPathEnvKey(env, platform);
|
|
||||||
const currentPath = env[pathKey] ?? '';
|
|
||||||
const resolvedDirectory = isPathLike(resolvedCodexPath, platform)
|
|
||||||
? pathApi.dirname(resolvedCodexPath)
|
|
||||||
: '';
|
|
||||||
const nextEnv: EnvRecord = { ...env };
|
|
||||||
|
|
||||||
if (resolvedDirectory) {
|
|
||||||
const delimiter = getPathDelimiter(platform);
|
|
||||||
const pathEntries = currentPath.split(delimiter).filter(Boolean);
|
|
||||||
if (!pathEntries.includes(resolvedDirectory)) {
|
|
||||||
nextEnv[pathKey] = currentPath
|
|
||||||
? `${resolvedDirectory}${delimiter}${currentPath}`
|
|
||||||
: resolvedDirectory;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return toStringEnv(nextEnv);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the shell-safe Codex command used by interactive PTY launches.
|
|
||||||
*/
|
|
||||||
export function getCodexShellCommand(
|
|
||||||
dependencies: ResolveCodexExecutablePathDependencies = {}
|
|
||||||
): string {
|
|
||||||
const platform = dependencies.platform ?? process.platform;
|
|
||||||
const resolvedCodexPath = resolveCodexExecutablePath(undefined, dependencies);
|
|
||||||
if (!isPathLike(resolvedCodexPath, platform)) {
|
|
||||||
return resolvedCodexPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (platform === 'win32') {
|
|
||||||
return `& '${resolvedCodexPath.replace(/'/g, "''")}'`;
|
|
||||||
}
|
|
||||||
|
|
||||||
return `'${resolvedCodexPath.replace(/'/g, "'\\''")}'`;
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
import assert from 'node:assert/strict';
|
|
||||||
import test from 'node:test';
|
|
||||||
|
|
||||||
import { sliceTailPage } from '@/shared/utils.js';
|
|
||||||
|
|
||||||
const ITEMS = ['a', 'b', 'c', 'd', 'e'];
|
|
||||||
|
|
||||||
test('offset 0 returns the most recent page', () => {
|
|
||||||
const { page, hasMore } = sliceTailPage(ITEMS, 2, 0);
|
|
||||||
assert.deepEqual(page, ['d', 'e']);
|
|
||||||
assert.equal(hasMore, true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('increasing offsets walk backwards in time', () => {
|
|
||||||
const { page, hasMore } = sliceTailPage(ITEMS, 2, 2);
|
|
||||||
assert.deepEqual(page, ['b', 'c']);
|
|
||||||
assert.equal(hasMore, true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('the oldest page reports hasMore false', () => {
|
|
||||||
const { page, hasMore } = sliceTailPage(ITEMS, 2, 4);
|
|
||||||
assert.deepEqual(page, ['a']);
|
|
||||||
assert.equal(hasMore, false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('null limit returns everything', () => {
|
|
||||||
const { page, hasMore } = sliceTailPage(ITEMS, null, 0);
|
|
||||||
assert.deepEqual(page, ITEMS);
|
|
||||||
assert.equal(hasMore, false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('offsets past the start return an empty page', () => {
|
|
||||||
const { page, hasMore } = sliceTailPage(ITEMS, 3, 10);
|
|
||||||
assert.deepEqual(page, []);
|
|
||||||
assert.equal(hasMore, false);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('zero limit returns an empty page but keeps hasMore accurate', () => {
|
|
||||||
const { page, hasMore } = sliceTailPage(ITEMS, 0, 0);
|
|
||||||
assert.deepEqual(page, []);
|
|
||||||
assert.equal(hasMore, true);
|
|
||||||
});
|
|
||||||
@@ -175,30 +175,6 @@ export type MessageKind =
|
|||||||
| 'interactive_prompt'
|
| 'interactive_prompt'
|
||||||
| 'task_notification';
|
| 'task_notification';
|
||||||
|
|
||||||
/**
|
|
||||||
* Event kinds added by the chat gateway layer on top of provider message kinds.
|
|
||||||
*
|
|
||||||
* These are app-level realtime events (subscription acks, sidebar deltas,
|
|
||||||
* project loading progress, protocol failures) that are not produced by any
|
|
||||||
* provider adapter. Together with `MessageKind` they form the complete set of
|
|
||||||
* `kind` values a websocket client can receive, so the frontend only ever
|
|
||||||
* needs one kind-based switch.
|
|
||||||
*/
|
|
||||||
export type GatewayEventKind =
|
|
||||||
| 'chat_subscribed'
|
|
||||||
| 'session_upserted'
|
|
||||||
| 'loading_progress'
|
|
||||||
| 'protocol_error';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Complete set of `kind` values emitted to websocket clients.
|
|
||||||
*
|
|
||||||
* Every server-to-client websocket frame carries a `kind` from this union.
|
|
||||||
* Provider runtimes emit `MessageKind` values; gateway services emit
|
|
||||||
* `GatewayEventKind` values.
|
|
||||||
*/
|
|
||||||
export type ServerEventKind = MessageKind | GatewayEventKind;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Provider-neutral message envelope used in REST responses and realtime channels.
|
* Provider-neutral message envelope used in REST responses and realtime channels.
|
||||||
*
|
*
|
||||||
@@ -211,13 +187,6 @@ export type NormalizedMessage = {
|
|||||||
timestamp: string;
|
timestamp: string;
|
||||||
provider: LLMProvider;
|
provider: LLMProvider;
|
||||||
kind: MessageKind;
|
kind: MessageKind;
|
||||||
/**
|
|
||||||
* Monotonic per-run sequence number assigned by the chat run registry when a
|
|
||||||
* live event is forwarded to the websocket. History messages loaded over
|
|
||||||
* REST do not carry it. Clients use it with `chat.subscribe` to replay only
|
|
||||||
* the live events they missed across websocket reconnects.
|
|
||||||
*/
|
|
||||||
seq?: number;
|
|
||||||
role?: 'user' | 'assistant';
|
role?: 'user' | 'assistant';
|
||||||
content?: string;
|
content?: string;
|
||||||
/**
|
/**
|
||||||
@@ -268,18 +237,11 @@ export type NormalizedMessage = {
|
|||||||
*
|
*
|
||||||
* Consumers should pass provider-specific lookup hints (`projectPath`) only
|
* Consumers should pass provider-specific lookup hints (`projectPath`) only
|
||||||
* when the selected provider requires them.
|
* when the selected provider requires them.
|
||||||
*
|
|
||||||
* `providerSessionId` is the provider-native session id from the sessions
|
|
||||||
* index (transcript file name / provider database key). Provider adapters
|
|
||||||
* must use it — never the app-facing session id they were called with — when
|
|
||||||
* matching transcript rows on disk, because app-created sessions use an
|
|
||||||
* app-allocated id that the provider has never seen.
|
|
||||||
*/
|
*/
|
||||||
export type FetchHistoryOptions = {
|
export type FetchHistoryOptions = {
|
||||||
projectPath?: string;
|
projectPath?: string;
|
||||||
limit?: number | null;
|
limit?: number | null;
|
||||||
offset?: number;
|
offset?: number;
|
||||||
providerSessionId?: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -346,84 +346,6 @@ export function createNormalizedMessage(fields: NormalizedMessageInput): Normali
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Build the unified terminal `complete` lifecycle message.
|
|
||||||
*
|
|
||||||
* Contract: every provider run ends with exactly one `complete` (the
|
|
||||||
* abort-session handler emits it on behalf of cancelled runs, so aborted runs
|
|
||||||
* must NOT emit their own). The frontend treats `complete` as the only
|
|
||||||
* terminal signal and never needs provider-specific handling:
|
|
||||||
*
|
|
||||||
* - `sessionId` — the id the client knows this run by ('' if never discovered)
|
|
||||||
* - `actualSessionId` — canonical id after the run; equals `sessionId` unless
|
|
||||||
* the provider rewrote it mid-run
|
|
||||||
* - `exitCode` — 0 on success; a missing/null code (e.g. killed process)
|
|
||||||
* is reported as failure
|
|
||||||
* - `success` — exitCode === 0 and not aborted
|
|
||||||
* - `aborted` — run was cancelled by the user
|
|
||||||
*/
|
|
||||||
export function createCompleteMessage(opts: {
|
|
||||||
provider: NormalizedMessage['provider'];
|
|
||||||
sessionId?: string | null;
|
|
||||||
actualSessionId?: string | null;
|
|
||||||
exitCode?: number | null;
|
|
||||||
aborted?: boolean;
|
|
||||||
}): NormalizedMessage {
|
|
||||||
const exitCode = typeof opts.exitCode === 'number' ? opts.exitCode : 1;
|
|
||||||
const aborted = Boolean(opts.aborted);
|
|
||||||
|
|
||||||
return createNormalizedMessage({
|
|
||||||
kind: 'complete',
|
|
||||||
provider: opts.provider,
|
|
||||||
sessionId: opts.sessionId || null,
|
|
||||||
actualSessionId: opts.actualSessionId || opts.sessionId || null,
|
|
||||||
exitCode,
|
|
||||||
success: exitCode === 0 && !aborted,
|
|
||||||
aborted,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------
|
|
||||||
//----------------- CONVERSATION HISTORY PAGINATION UTILITIES ------------
|
|
||||||
/**
|
|
||||||
* Slices one page from the END of a chronologically ordered message list.
|
|
||||||
*
|
|
||||||
* This is the single pagination contract for conversation history across all
|
|
||||||
* providers: `offset = 0` returns the most recent `limit` items, increasing
|
|
||||||
* offsets walk backwards in time (for "scroll up to load older" UIs), and a
|
|
||||||
* `null` limit returns everything. Items must already be sorted oldest-first;
|
|
||||||
* the returned page preserves that order.
|
|
||||||
*
|
|
||||||
* Every provider history reader must use this helper instead of slicing
|
|
||||||
* manually so `offset`/`limit` query params behave identically regardless of
|
|
||||||
* which provider produced the session.
|
|
||||||
*/
|
|
||||||
export function sliceTailPage<T>(
|
|
||||||
items: T[],
|
|
||||||
limit: number | null,
|
|
||||||
offset: number,
|
|
||||||
): { page: T[]; hasMore: boolean } {
|
|
||||||
const total = items.length;
|
|
||||||
const normalizedOffset = Math.max(0, offset);
|
|
||||||
|
|
||||||
if (limit === null) {
|
|
||||||
// A null limit returns the full list; offset still trims newest entries
|
|
||||||
// so "everything before the page I already have" stays expressible.
|
|
||||||
const end = Math.max(0, total - normalizedOffset);
|
|
||||||
return {
|
|
||||||
page: items.slice(0, end),
|
|
||||||
hasMore: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const end = Math.max(0, total - normalizedOffset);
|
|
||||||
const start = Math.max(0, end - Math.max(0, limit));
|
|
||||||
return {
|
|
||||||
page: items.slice(start, end),
|
|
||||||
hasMore: start > 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------
|
// ---------------------------
|
||||||
//----------------- MCP CONFIG PARSING UTILITIES ------------
|
//----------------- MCP CONFIG PARSING UTILITIES ------------
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useEffect } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { useNavigate, useParams } from 'react-router-dom';
|
import { useNavigate, useParams } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
@@ -10,33 +10,6 @@ import { PaletteOpsProvider, usePaletteOpsRegister } from '../../contexts/Palett
|
|||||||
import { useDeviceSettings } from '../../hooks/useDeviceSettings';
|
import { useDeviceSettings } from '../../hooks/useDeviceSettings';
|
||||||
import { useSessionProtection } from '../../hooks/useSessionProtection';
|
import { useSessionProtection } from '../../hooks/useSessionProtection';
|
||||||
import { useProjectsState } from '../../hooks/useProjectsState';
|
import { useProjectsState } from '../../hooks/useProjectsState';
|
||||||
import { api } from '../../utils/api';
|
|
||||||
|
|
||||||
type RunningSessionApiItem = {
|
|
||||||
sessionId?: unknown;
|
|
||||||
startedAt?: unknown;
|
|
||||||
statusText?: unknown;
|
|
||||||
canInterrupt?: unknown;
|
|
||||||
};
|
|
||||||
|
|
||||||
type RunningSessionsApiPayload = {
|
|
||||||
data?: {
|
|
||||||
sessions?: RunningSessionApiItem[];
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
const parseStartedAt = (value: unknown): number | undefined => {
|
|
||||||
if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof value !== 'string') {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parsed = Date.parse(value);
|
|
||||||
return Number.isFinite(parsed) ? parsed : undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function AppContent() {
|
export default function AppContent() {
|
||||||
return (
|
return (
|
||||||
@@ -51,13 +24,16 @@ function AppContentInner() {
|
|||||||
const { sessionId } = useParams<{ sessionId?: string }>();
|
const { sessionId } = useParams<{ sessionId?: string }>();
|
||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
const { isMobile } = useDeviceSettings({ trackPWA: false });
|
const { isMobile } = useDeviceSettings({ trackPWA: false });
|
||||||
const { ws, sendMessage, subscribe } = useWebSocket();
|
const { ws, sendMessage, latestMessage, isConnected } = useWebSocket();
|
||||||
|
const wasConnectedRef = useRef(false);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
activeSessions,
|
||||||
processingSessions,
|
processingSessions,
|
||||||
markSessionProcessing,
|
markSessionAsActive,
|
||||||
markSessionIdle,
|
markSessionAsInactive,
|
||||||
syncProcessingSessions,
|
markSessionAsProcessing,
|
||||||
|
markSessionAsNotProcessing,
|
||||||
} = useSessionProtection();
|
} = useSessionProtection();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@@ -74,64 +50,16 @@ function AppContentInner() {
|
|||||||
setShowSettings,
|
setShowSettings,
|
||||||
openSettings,
|
openSettings,
|
||||||
refreshProjectsSilently,
|
refreshProjectsSilently,
|
||||||
registerOptimisticSession,
|
|
||||||
sidebarSharedProps,
|
sidebarSharedProps,
|
||||||
handleNewSession,
|
handleNewSession,
|
||||||
} = useProjectsState({
|
} = useProjectsState({
|
||||||
sessionId,
|
sessionId,
|
||||||
navigate,
|
navigate,
|
||||||
subscribe,
|
latestMessage,
|
||||||
isMobile,
|
isMobile,
|
||||||
activeSessions: processingSessions,
|
activeSessions,
|
||||||
});
|
});
|
||||||
|
|
||||||
const refreshRunningSessions = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
const response = await api.runningSessions();
|
|
||||||
if (!response.ok) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = (await response.json()) as RunningSessionsApiPayload;
|
|
||||||
const sessions = Array.isArray(payload.data?.sessions) ? payload.data.sessions : [];
|
|
||||||
|
|
||||||
syncProcessingSessions(
|
|
||||||
sessions
|
|
||||||
.map((session) => {
|
|
||||||
if (typeof session.sessionId !== 'string' || !session.sessionId) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
sessionId: session.sessionId,
|
|
||||||
startedAt: parseStartedAt(session.startedAt),
|
|
||||||
statusText: typeof session.statusText === 'string' ? session.statusText : undefined,
|
|
||||||
canInterrupt: typeof session.canInterrupt === 'boolean' ? session.canInterrupt : undefined,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.filter((session): session is NonNullable<typeof session> => Boolean(session)),
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[AppContent] Failed to sync running sessions:', error);
|
|
||||||
}
|
|
||||||
}, [syncProcessingSessions]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
void refreshRunningSessions();
|
|
||||||
}, [refreshRunningSessions]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (processingSessions.size === 0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const interval = window.setInterval(() => {
|
|
||||||
void refreshRunningSessions();
|
|
||||||
}, 5000);
|
|
||||||
|
|
||||||
return () => window.clearInterval(interval);
|
|
||||||
}, [processingSessions.size, refreshRunningSessions]);
|
|
||||||
|
|
||||||
usePaletteOpsRegister({
|
usePaletteOpsRegister({
|
||||||
openSettings,
|
openSettings,
|
||||||
refreshProjects: refreshProjectsSilently,
|
refreshProjects: refreshProjectsSilently,
|
||||||
@@ -171,9 +99,23 @@ function AppContentInner() {
|
|||||||
};
|
};
|
||||||
}, [navigate, refreshProjectsSilently, setActiveTab, setSidebarOpen]);
|
}, [navigate, refreshProjectsSilently, setActiveTab, setSidebarOpen]);
|
||||||
|
|
||||||
// Pending tool permissions are recovered through the `chat.subscribe` flow:
|
// Permission recovery: query pending permissions on WebSocket reconnect or session change
|
||||||
// the `chat_subscribed` ack carries them on session open and on reconnect,
|
useEffect(() => {
|
||||||
// so no separate permission-recovery message is needed here.
|
const isReconnect = isConnected && !wasConnectedRef.current;
|
||||||
|
|
||||||
|
if (isReconnect) {
|
||||||
|
wasConnectedRef.current = true;
|
||||||
|
} else if (!isConnected) {
|
||||||
|
wasConnectedRef.current = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isConnected && selectedSession?.id) {
|
||||||
|
sendMessage({
|
||||||
|
type: 'get-pending-permissions',
|
||||||
|
sessionId: selectedSession.id
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [isConnected, selectedSession?.id, sendMessage]);
|
||||||
|
|
||||||
// Adjust the app container to stay above the virtual keyboard on iOS Safari.
|
// Adjust the app container to stay above the virtual keyboard on iOS Safari.
|
||||||
// On Chrome for Android the layout viewport already shrinks when the keyboard opens,
|
// On Chrome for Android the layout viewport already shrinks when the keyboard opens,
|
||||||
@@ -238,19 +180,19 @@ function AppContentInner() {
|
|||||||
setActiveTab={setActiveTab}
|
setActiveTab={setActiveTab}
|
||||||
ws={ws}
|
ws={ws}
|
||||||
sendMessage={sendMessage}
|
sendMessage={sendMessage}
|
||||||
|
latestMessage={latestMessage}
|
||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
onMenuClick={() => setSidebarOpen(true)}
|
onMenuClick={() => setSidebarOpen(true)}
|
||||||
isLoading={isLoadingProjects}
|
isLoading={isLoadingProjects}
|
||||||
onInputFocusChange={setIsInputFocused}
|
onInputFocusChange={setIsInputFocused}
|
||||||
onSessionProcessing={markSessionProcessing}
|
onSessionActive={markSessionAsActive}
|
||||||
onSessionIdle={markSessionIdle}
|
onSessionInactive={markSessionAsInactive}
|
||||||
|
onSessionProcessing={markSessionAsProcessing}
|
||||||
|
onSessionNotProcessing={markSessionAsNotProcessing}
|
||||||
processingSessions={processingSessions}
|
processingSessions={processingSessions}
|
||||||
onNavigateToSession={(targetSessionId: string, options) =>
|
onNavigateToSession={(targetSessionId: string, options) =>
|
||||||
navigate(`/session/${targetSessionId}`, { replace: Boolean(options?.replace) })
|
navigate(`/session/${targetSessionId}`, { replace: Boolean(options?.replace) })
|
||||||
}
|
}
|
||||||
onSessionEstablished={(targetSessionId, context) =>
|
|
||||||
registerOptimisticSession({ sessionId: targetSessionId, ...context })
|
|
||||||
}
|
|
||||||
onShowSettings={() => setShowSettings(true)}
|
onShowSettings={() => setShowSettings(true)}
|
||||||
externalMessageUpdate={externalMessageUpdate}
|
externalMessageUpdate={externalMessageUpdate}
|
||||||
newSessionTrigger={newSessionTrigger}
|
newSessionTrigger={newSessionTrigger}
|
||||||
|
|||||||
@@ -12,14 +12,12 @@ import type {
|
|||||||
import { useDropzone } from 'react-dropzone';
|
import { useDropzone } from 'react-dropzone';
|
||||||
|
|
||||||
import { authenticatedFetch } from '../../../utils/api';
|
import { authenticatedFetch } from '../../../utils/api';
|
||||||
import type { MarkSessionProcessing } from '../../../hooks/useSessionProtection';
|
|
||||||
import { grantClaudeToolPermission } from '../utils/chatPermissions';
|
import { grantClaudeToolPermission } from '../utils/chatPermissions';
|
||||||
import { safeLocalStorage } from '../utils/chatStorage';
|
import { safeLocalStorage } from '../utils/chatStorage';
|
||||||
import type {
|
import type {
|
||||||
ChatMessage,
|
ChatMessage,
|
||||||
PendingPermissionRequest,
|
PendingPermissionRequest,
|
||||||
PermissionMode,
|
PermissionMode,
|
||||||
SessionEstablishedContext,
|
|
||||||
} from '../types/types';
|
} from '../types/types';
|
||||||
import type { Project, ProjectSession, LLMProvider, ProviderModelsCacheInfo } from '../../../types/app';
|
import type { Project, ProjectSession, LLMProvider, ProviderModelsCacheInfo } from '../../../types/app';
|
||||||
import { escapeRegExp } from '../utils/chatFormatting';
|
import { escapeRegExp } from '../utils/chatFormatting';
|
||||||
@@ -27,6 +25,10 @@ import { escapeRegExp } from '../utils/chatFormatting';
|
|||||||
import { useFileMentions } from './useFileMentions';
|
import { useFileMentions } from './useFileMentions';
|
||||||
import { type SlashCommand, useSlashCommands } from './useSlashCommands';
|
import { type SlashCommand, useSlashCommands } from './useSlashCommands';
|
||||||
|
|
||||||
|
type PendingViewSession = {
|
||||||
|
startedAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
interface UseChatComposerStateArgs {
|
interface UseChatComposerStateArgs {
|
||||||
selectedProject: Project | null;
|
selectedProject: Project | null;
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
@@ -44,20 +46,17 @@ interface UseChatComposerStateArgs {
|
|||||||
tokenBudget: Record<string, unknown> | null;
|
tokenBudget: Record<string, unknown> | null;
|
||||||
sendMessage: (message: unknown) => void;
|
sendMessage: (message: unknown) => void;
|
||||||
sendByCtrlEnter?: boolean;
|
sendByCtrlEnter?: boolean;
|
||||||
onSessionProcessing?: MarkSessionProcessing;
|
onSessionActive?: (sessionId?: string | null) => void;
|
||||||
/**
|
onSessionProcessing?: (sessionId?: string | null) => void;
|
||||||
* Invoked with the freshly allocated session id when the user sends the
|
|
||||||
* first message of a brand-new conversation. The backend allocates the id
|
|
||||||
* via POST /api/providers/sessions BEFORE the websocket send, so the id is
|
|
||||||
* stable for the conversation's whole lifetime — the consumer navigates to
|
|
||||||
* /session/:id and records it as the current session.
|
|
||||||
*/
|
|
||||||
onSessionEstablished?: (sessionId: string, context: SessionEstablishedContext) => void;
|
|
||||||
onInputFocusChange?: (focused: boolean) => void;
|
onInputFocusChange?: (focused: boolean) => void;
|
||||||
onFileOpen?: (filePath: string, diffInfo?: unknown) => void;
|
onFileOpen?: (filePath: string, diffInfo?: unknown) => void;
|
||||||
onShowSettings?: () => void;
|
onShowSettings?: () => void;
|
||||||
|
pendingViewSessionRef: { current: PendingViewSession | null };
|
||||||
scrollToBottom: () => void;
|
scrollToBottom: () => void;
|
||||||
addMessage: (msg: ChatMessage) => void;
|
addMessage: (msg: ChatMessage) => void;
|
||||||
|
setIsLoading: (loading: boolean) => void;
|
||||||
|
setCanAbortSession: (canAbort: boolean) => void;
|
||||||
|
setClaudeStatus: (status: { text: string; tokens: number; can_interrupt: boolean } | null) => void;
|
||||||
setIsUserScrolledUp: (isScrolledUp: boolean) => void;
|
setIsUserScrolledUp: (isScrolledUp: boolean) => void;
|
||||||
setPendingPermissionRequests: Dispatch<SetStateAction<PendingPermissionRequest[]>>;
|
setPendingPermissionRequests: Dispatch<SetStateAction<PendingPermissionRequest[]>>;
|
||||||
}
|
}
|
||||||
@@ -178,13 +177,17 @@ export function useChatComposerState({
|
|||||||
tokenBudget,
|
tokenBudget,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
sendByCtrlEnter,
|
sendByCtrlEnter,
|
||||||
|
onSessionActive,
|
||||||
onSessionProcessing,
|
onSessionProcessing,
|
||||||
onSessionEstablished,
|
|
||||||
onInputFocusChange,
|
onInputFocusChange,
|
||||||
onFileOpen,
|
onFileOpen,
|
||||||
onShowSettings,
|
onShowSettings,
|
||||||
|
pendingViewSessionRef,
|
||||||
scrollToBottom,
|
scrollToBottom,
|
||||||
addMessage,
|
addMessage,
|
||||||
|
setIsLoading,
|
||||||
|
setCanAbortSession,
|
||||||
|
setClaudeStatus,
|
||||||
setIsUserScrolledUp,
|
setIsUserScrolledUp,
|
||||||
setPendingPermissionRequests,
|
setPendingPermissionRequests,
|
||||||
}: UseChatComposerStateArgs) {
|
}: UseChatComposerStateArgs) {
|
||||||
@@ -606,54 +609,8 @@ export function useChatComposerState({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const resolvedProjectPath = selectedProject.fullPath || selectedProject.path || '';
|
const effectiveSessionId =
|
||||||
const sessionSummary = getNotificationSessionSummary(selectedSession, currentInput);
|
currentSessionId || selectedSession?.id || sessionStorage.getItem('cursorSessionId');
|
||||||
|
|
||||||
// The conversation always has a stable backend-allocated session id
|
|
||||||
// BEFORE the first websocket send: brand-new chats allocate one here
|
|
||||||
// via the session gateway. There is no client-visible session-id
|
|
||||||
// handoff later — this id stays valid for the conversation's lifetime.
|
|
||||||
let targetSessionId = selectedSession?.id || currentSessionId || null;
|
|
||||||
if (!targetSessionId) {
|
|
||||||
try {
|
|
||||||
const response = await authenticatedFetch('/api/providers/sessions', {
|
|
||||||
method: 'POST',
|
|
||||||
body: JSON.stringify({
|
|
||||||
provider,
|
|
||||||
projectPath: resolvedProjectPath,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`Failed to create session (${response.status})`);
|
|
||||||
}
|
|
||||||
const body = await response.json();
|
|
||||||
targetSessionId = body?.data?.sessionId || null;
|
|
||||||
} catch (error) {
|
|
||||||
const message = error instanceof Error ? error.message : 'Unknown error';
|
|
||||||
console.error('Session creation failed:', error);
|
|
||||||
addMessage({
|
|
||||||
type: 'error',
|
|
||||||
content: `Failed to start a new session: ${message}`,
|
|
||||||
timestamp: new Date(),
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!targetSessionId) {
|
|
||||||
addMessage({
|
|
||||||
type: 'error',
|
|
||||||
content: 'Failed to start a new session: no session id returned.',
|
|
||||||
timestamp: new Date(),
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
onSessionEstablished?.(targetSessionId, {
|
|
||||||
provider,
|
|
||||||
project: selectedProject,
|
|
||||||
summary: sessionSummary,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const userMessage: ChatMessage = {
|
const userMessage: ChatMessage = {
|
||||||
type: 'user',
|
type: 'user',
|
||||||
@@ -663,17 +620,27 @@ export function useChatComposerState({
|
|||||||
};
|
};
|
||||||
|
|
||||||
addMessage(userMessage);
|
addMessage(userMessage);
|
||||||
// Mark this request as processing in the per-session activity map (the
|
setIsLoading(true); // Processing banner starts
|
||||||
// single source of truth the indicator derives from). The id is always
|
setCanAbortSession(true);
|
||||||
// concrete at this point — no pending placeholder exists anymore.
|
setClaudeStatus({
|
||||||
onSessionProcessing?.(targetSessionId, {
|
text: 'Processing',
|
||||||
statusText: null,
|
tokens: 0,
|
||||||
canInterrupt: true,
|
can_interrupt: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
setIsUserScrolledUp(false);
|
setIsUserScrolledUp(false);
|
||||||
setTimeout(() => scrollToBottom(), 100);
|
setTimeout(() => scrollToBottom(), 100);
|
||||||
|
|
||||||
|
if (!effectiveSessionId && !selectedSession?.id) {
|
||||||
|
// This tracks only that a request is in flight before the provider has
|
||||||
|
// emitted its real session id; routing still waits for session_created.
|
||||||
|
pendingViewSessionRef.current = { startedAt: Date.now() };
|
||||||
|
}
|
||||||
|
if (effectiveSessionId) {
|
||||||
|
onSessionActive?.(effectiveSessionId);
|
||||||
|
onSessionProcessing?.(effectiveSessionId);
|
||||||
|
}
|
||||||
|
|
||||||
const getToolsSettings = () => {
|
const getToolsSettings = () => {
|
||||||
try {
|
try {
|
||||||
const settingsKey =
|
const settingsKey =
|
||||||
@@ -702,35 +669,87 @@ export function useChatComposerState({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const toolsSettings = getToolsSettings();
|
const toolsSettings = getToolsSettings();
|
||||||
const model =
|
const resolvedProjectPath = selectedProject.fullPath || selectedProject.path || '';
|
||||||
provider === 'cursor'
|
const sessionSummary = getNotificationSessionSummary(selectedSession, currentInput);
|
||||||
? cursorModel
|
|
||||||
: provider === 'codex'
|
|
||||||
? codexModel
|
|
||||||
: provider === 'gemini'
|
|
||||||
? geminiModel
|
|
||||||
: provider === 'opencode'
|
|
||||||
? opencodeModel
|
|
||||||
: claudeModel;
|
|
||||||
|
|
||||||
// One message shape for every provider. The backend resolves the
|
if (provider === 'cursor') {
|
||||||
// provider, project path, and provider-native resume id from the
|
sendMessage({
|
||||||
// session row; `options` only carries composer-level preferences.
|
type: 'cursor-command',
|
||||||
sendMessage({
|
command: messageContent,
|
||||||
type: 'chat.send',
|
sessionId: effectiveSessionId,
|
||||||
sessionId: targetSessionId,
|
options: {
|
||||||
content: messageContent,
|
cwd: resolvedProjectPath,
|
||||||
options: {
|
projectPath: resolvedProjectPath,
|
||||||
model,
|
sessionId: effectiveSessionId,
|
||||||
// Codex has no plan mode; downgrade rather than sending an
|
resume: Boolean(effectiveSessionId),
|
||||||
// unsupported value to its runtime.
|
model: cursorModel,
|
||||||
permissionMode: provider === 'codex' && permissionMode === 'plan' ? 'default' : permissionMode,
|
skipPermissions: toolsSettings?.skipPermissions || false,
|
||||||
toolsSettings,
|
sessionSummary,
|
||||||
skipPermissions: toolsSettings?.skipPermissions || false,
|
toolsSettings,
|
||||||
sessionSummary,
|
},
|
||||||
images: uploadedImages,
|
});
|
||||||
},
|
} else if (provider === 'codex') {
|
||||||
});
|
sendMessage({
|
||||||
|
type: 'codex-command',
|
||||||
|
command: messageContent,
|
||||||
|
sessionId: effectiveSessionId,
|
||||||
|
options: {
|
||||||
|
cwd: resolvedProjectPath,
|
||||||
|
projectPath: resolvedProjectPath,
|
||||||
|
sessionId: effectiveSessionId,
|
||||||
|
resume: Boolean(effectiveSessionId),
|
||||||
|
model: codexModel,
|
||||||
|
sessionSummary,
|
||||||
|
permissionMode: permissionMode === 'plan' ? 'default' : permissionMode,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else if (provider === 'gemini') {
|
||||||
|
sendMessage({
|
||||||
|
type: 'gemini-command',
|
||||||
|
command: messageContent,
|
||||||
|
sessionId: effectiveSessionId,
|
||||||
|
options: {
|
||||||
|
cwd: resolvedProjectPath,
|
||||||
|
projectPath: resolvedProjectPath,
|
||||||
|
sessionId: effectiveSessionId,
|
||||||
|
resume: Boolean(effectiveSessionId),
|
||||||
|
model: geminiModel,
|
||||||
|
sessionSummary,
|
||||||
|
permissionMode,
|
||||||
|
toolsSettings,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else if (provider === 'opencode') {
|
||||||
|
sendMessage({
|
||||||
|
type: 'opencode-command',
|
||||||
|
command: messageContent,
|
||||||
|
sessionId: effectiveSessionId,
|
||||||
|
options: {
|
||||||
|
cwd: resolvedProjectPath,
|
||||||
|
projectPath: resolvedProjectPath,
|
||||||
|
sessionId: effectiveSessionId,
|
||||||
|
resume: Boolean(effectiveSessionId),
|
||||||
|
model: opencodeModel,
|
||||||
|
sessionSummary,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
sendMessage({
|
||||||
|
type: 'claude-command',
|
||||||
|
command: messageContent,
|
||||||
|
options: {
|
||||||
|
projectPath: resolvedProjectPath,
|
||||||
|
cwd: resolvedProjectPath,
|
||||||
|
sessionId: effectiveSessionId,
|
||||||
|
resume: Boolean(effectiveSessionId),
|
||||||
|
toolsSettings,
|
||||||
|
permissionMode,
|
||||||
|
model: claudeModel,
|
||||||
|
sessionSummary,
|
||||||
|
images: uploadedImages,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
setInput('');
|
setInput('');
|
||||||
inputValueRef.current = '';
|
inputValueRef.current = '';
|
||||||
@@ -757,15 +776,19 @@ export function useChatComposerState({
|
|||||||
geminiModel,
|
geminiModel,
|
||||||
opencodeModel,
|
opencodeModel,
|
||||||
isLoading,
|
isLoading,
|
||||||
|
onSessionActive,
|
||||||
onSessionProcessing,
|
onSessionProcessing,
|
||||||
onSessionEstablished,
|
pendingViewSessionRef,
|
||||||
permissionMode,
|
permissionMode,
|
||||||
provider,
|
provider,
|
||||||
resetCommandMenuState,
|
resetCommandMenuState,
|
||||||
scrollToBottom,
|
scrollToBottom,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
|
setCanAbortSession,
|
||||||
addMessage,
|
addMessage,
|
||||||
|
setClaudeStatus,
|
||||||
|
setIsLoading,
|
||||||
setIsUserScrolledUp,
|
setIsUserScrolledUp,
|
||||||
slashCommands,
|
slashCommands,
|
||||||
],
|
],
|
||||||
@@ -921,19 +944,29 @@ export function useChatComposerState({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const targetSessionId = selectedSession?.id || currentSessionId || null;
|
const cursorSessionId =
|
||||||
|
typeof window !== 'undefined' ? sessionStorage.getItem('cursorSessionId') : null;
|
||||||
|
|
||||||
|
const candidateSessionIds = [
|
||||||
|
currentSessionId,
|
||||||
|
provider === 'cursor' ? cursorSessionId : null,
|
||||||
|
selectedSession?.id || null,
|
||||||
|
];
|
||||||
|
|
||||||
|
const targetSessionId =
|
||||||
|
candidateSessionIds.find((sessionId) => Boolean(sessionId)) || null;
|
||||||
|
|
||||||
if (!targetSessionId) {
|
if (!targetSessionId) {
|
||||||
console.warn('Abort requested but no session ID is available.');
|
console.warn('Abort requested but no concrete session ID is available yet.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The backend resolves the provider from the session row, so no provider
|
|
||||||
// field is needed here.
|
|
||||||
sendMessage({
|
sendMessage({
|
||||||
type: 'chat.abort',
|
type: 'abort-session',
|
||||||
sessionId: targetSessionId,
|
sessionId: targetSessionId,
|
||||||
|
provider,
|
||||||
});
|
});
|
||||||
}, [canAbortSession, currentSessionId, selectedSession?.id, sendMessage]);
|
}, [canAbortSession, currentSessionId, provider, selectedSession?.id, sendMessage]);
|
||||||
|
|
||||||
const handleGrantToolPermission = useCallback(
|
const handleGrantToolPermission = useCallback(
|
||||||
(suggestion: { entry: string; toolName: string }) => {
|
(suggestion: { entry: string; toolName: string }) => {
|
||||||
@@ -958,7 +991,7 @@ export function useChatComposerState({
|
|||||||
|
|
||||||
validIds.forEach((requestId) => {
|
validIds.forEach((requestId) => {
|
||||||
sendMessage({
|
sendMessage({
|
||||||
type: 'chat.permission-response',
|
type: 'claude-permission-response',
|
||||||
requestId,
|
requestId,
|
||||||
allow: Boolean(decision?.allow),
|
allow: Boolean(decision?.allow),
|
||||||
updatedInput: decision?.updatedInput,
|
updatedInput: decision?.updatedInput,
|
||||||
@@ -967,11 +1000,15 @@ export function useChatComposerState({
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
setPendingPermissionRequests((previous) =>
|
setPendingPermissionRequests((previous) => {
|
||||||
previous.filter((request) => !validIds.includes(request.requestId)),
|
const next = previous.filter((request) => !validIds.includes(request.requestId));
|
||||||
);
|
if (next.length === 0) {
|
||||||
|
setClaudeStatus(null);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
},
|
},
|
||||||
[sendMessage, setPendingPermissionRequests],
|
[sendMessage, setClaudeStatus, setPendingPermissionRequests],
|
||||||
);
|
);
|
||||||
|
|
||||||
const [isInputFocused, setIsInputFocused] = useState(false);
|
const [isInputFocused, setIsInputFocused] = useState(false);
|
||||||
|
|||||||
@@ -17,35 +17,17 @@ const FALLBACK_DEFAULT_MODEL: Record<LLMProvider, string> = {
|
|||||||
opencode: 'anthropic/claude-sonnet-4-5',
|
opencode: 'anthropic/claude-sonnet-4-5',
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
const getPermissionModesForProvider = (provider: LLMProvider): PermissionMode[] => {
|
||||||
* Fallback permission-mode matrix used only until the backend capability
|
if (provider === 'codex') {
|
||||||
* matrix (`GET /api/providers/capabilities`) has loaded. The backend is the
|
return ['default', 'acceptEdits', 'bypassPermissions'];
|
||||||
* source of truth; this mirror exists so the composer renders sensibly on
|
}
|
||||||
* first paint and when the capabilities request fails.
|
if (provider === 'claude') {
|
||||||
*/
|
return ['default', 'auto', 'acceptEdits', 'bypassPermissions', 'plan'];
|
||||||
const FALLBACK_PERMISSION_MODES: Record<LLMProvider, PermissionMode[]> = {
|
}
|
||||||
claude: ['default', 'auto', 'acceptEdits', 'bypassPermissions', 'plan'],
|
if (provider === 'opencode') {
|
||||||
cursor: ['default', 'acceptEdits', 'bypassPermissions', 'plan'],
|
return ['default'];
|
||||||
codex: ['default', 'acceptEdits', 'bypassPermissions'],
|
}
|
||||||
gemini: ['default', 'acceptEdits', 'bypassPermissions', 'plan'],
|
return ['default', 'acceptEdits', 'bypassPermissions', 'plan'];
|
||||||
opencode: ['default'],
|
|
||||||
};
|
|
||||||
|
|
||||||
type ProviderCapabilities = {
|
|
||||||
provider: LLMProvider;
|
|
||||||
permissionModes: string[];
|
|
||||||
defaultPermissionMode: string;
|
|
||||||
supportsImages: boolean;
|
|
||||||
supportsAbort: boolean;
|
|
||||||
supportsPermissionRequests: boolean;
|
|
||||||
supportsTokenUsage: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ProviderCapabilitiesApiResponse = {
|
|
||||||
success?: boolean;
|
|
||||||
data?: {
|
|
||||||
providers?: ProviderCapabilities[];
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
interface UseChatProviderStateArgs {
|
interface UseChatProviderStateArgs {
|
||||||
@@ -94,17 +76,6 @@ export function useChatProviderState({ selectedSession, selectedProject }: UseCh
|
|||||||
return localStorage.getItem('opencode-model') || FALLBACK_DEFAULT_MODEL.opencode;
|
return localStorage.getItem('opencode-model') || FALLBACK_DEFAULT_MODEL.opencode;
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
|
||||||
* Backend-owned capability matrix keyed by provider. Drives the permission
|
|
||||||
* mode picker (and is the extension point for future per-provider UI
|
|
||||||
* differences) so the frontend stays free of hardcoded provider branching.
|
|
||||||
* Null until `/api/providers/capabilities` resolves; the static fallback
|
|
||||||
* map covers that window.
|
|
||||||
*/
|
|
||||||
const [providerCapabilities, setProviderCapabilities] = useState<
|
|
||||||
Partial<Record<LLMProvider, ProviderCapabilities>> | null
|
|
||||||
>(null);
|
|
||||||
|
|
||||||
const [providerModelCatalog, setProviderModelCatalog] = useState<
|
const [providerModelCatalog, setProviderModelCatalog] = useState<
|
||||||
Partial<Record<LLMProvider, ProviderModelsDefinition>>
|
Partial<Record<LLMProvider, ProviderModelsDefinition>>
|
||||||
>({});
|
>({});
|
||||||
@@ -210,41 +181,6 @@ export function useChatProviderState({ selectedSession, selectedProject }: UseCh
|
|||||||
void loadProviderModels();
|
void loadProviderModels();
|
||||||
}, [loadProviderModels]);
|
}, [loadProviderModels]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let cancelled = false;
|
|
||||||
|
|
||||||
const loadCapabilities = async () => {
|
|
||||||
try {
|
|
||||||
const response = await authenticatedFetch('/api/providers/capabilities');
|
|
||||||
const body = (await response.json()) as ProviderCapabilitiesApiResponse;
|
|
||||||
if (cancelled || !body.success || !Array.isArray(body.data?.providers)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const byProvider: Partial<Record<LLMProvider, ProviderCapabilities>> = {};
|
|
||||||
for (const capabilities of body.data.providers) {
|
|
||||||
byProvider[capabilities.provider] = capabilities;
|
|
||||||
}
|
|
||||||
setProviderCapabilities(byProvider);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error loading provider capabilities:', error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
void loadCapabilities();
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const getPermissionModesForProvider = useCallback((targetProvider: LLMProvider): PermissionMode[] => {
|
|
||||||
const capabilityModes = providerCapabilities?.[targetProvider]?.permissionModes;
|
|
||||||
if (capabilityModes && capabilityModes.length > 0) {
|
|
||||||
return capabilityModes as PermissionMode[];
|
|
||||||
}
|
|
||||||
return FALLBACK_PERMISSION_MODES[targetProvider] ?? ['default'];
|
|
||||||
}, [providerCapabilities]);
|
|
||||||
|
|
||||||
const pickStoredOrCurrent = (
|
const pickStoredOrCurrent = (
|
||||||
storageKey: string,
|
storageKey: string,
|
||||||
current: string,
|
current: string,
|
||||||
@@ -333,7 +269,7 @@ export function useChatProviderState({ selectedSession, selectedProject }: UseCh
|
|||||||
const savedMode = localStorage.getItem(`permissionMode-${selectedSession.id}`) as PermissionMode | null;
|
const savedMode = localStorage.getItem(`permissionMode-${selectedSession.id}`) as PermissionMode | null;
|
||||||
const validModes = getPermissionModesForProvider(provider);
|
const validModes = getPermissionModesForProvider(provider);
|
||||||
setPermissionMode(savedMode && validModes.includes(savedMode) ? savedMode : 'default');
|
setPermissionMode(savedMode && validModes.includes(savedMode) ? savedMode : 'default');
|
||||||
}, [selectedSession?.id, provider, getPermissionModesForProvider]);
|
}, [selectedSession?.id, provider]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selectedSession?.__provider || selectedSession.__provider === provider) {
|
if (!selectedSession?.__provider || selectedSession.__provider === provider) {
|
||||||
@@ -391,7 +327,7 @@ export function useChatProviderState({ selectedSession, selectedProject }: UseCh
|
|||||||
if (selectedSession?.id) {
|
if (selectedSession?.id) {
|
||||||
localStorage.setItem(`permissionMode-${selectedSession.id}`, nextMode);
|
localStorage.setItem(`permissionMode-${selectedSession.id}`, nextMode);
|
||||||
}
|
}
|
||||||
}, [permissionMode, provider, selectedSession?.id, getPermissionModesForProvider]);
|
}, [permissionMode, provider, selectedSession?.id]);
|
||||||
|
|
||||||
const selectProviderModel = useCallback(async (
|
const selectProviderModel = useCallback(async (
|
||||||
targetProvider: LLMProvider,
|
targetProvider: LLMProvider,
|
||||||
|
|||||||
@@ -1,34 +1,73 @@
|
|||||||
import { useEffect } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import type { Dispatch, MutableRefObject, SetStateAction } from 'react';
|
import type { Dispatch, MutableRefObject, SetStateAction } from 'react';
|
||||||
|
|
||||||
import type { ServerEvent } from '../../../contexts/WebSocketContext';
|
import { usePaletteOps } from '../../../contexts/PaletteOpsContext';
|
||||||
import { showCompletionTitleIndicator } from '../../../utils/pageTitleNotification';
|
import { showCompletionTitleIndicator } from '../../../utils/pageTitleNotification';
|
||||||
import { playChatCompletionSound } from '../../../utils/notificationSound';
|
import { playChatCompletionSound } from '../../../utils/notificationSound';
|
||||||
import type { MarkSessionIdle, MarkSessionProcessing } from '../../../hooks/useSessionProtection';
|
import type { PendingPermissionRequest, SessionNavigationOptions } from '../types/types';
|
||||||
import type { PendingPermissionRequest } from '../types/types';
|
|
||||||
import type { ProjectSession, LLMProvider } from '../../../types/app';
|
import type { ProjectSession, LLMProvider } from '../../../types/app';
|
||||||
import type { SessionStore, NormalizedMessage } from '../../../stores/useSessionStore';
|
import type { SessionStore, NormalizedMessage } from '../../../stores/useSessionStore';
|
||||||
|
|
||||||
|
type PendingViewSession = {
|
||||||
|
startedAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type LatestChatMessage = {
|
||||||
|
type?: string;
|
||||||
|
kind?: string;
|
||||||
|
data?: any;
|
||||||
|
message?: any;
|
||||||
|
delta?: string;
|
||||||
|
sessionId?: string;
|
||||||
|
session_id?: string;
|
||||||
|
requestId?: string;
|
||||||
|
toolName?: string;
|
||||||
|
input?: unknown;
|
||||||
|
context?: unknown;
|
||||||
|
error?: string;
|
||||||
|
tool?: any;
|
||||||
|
toolId?: string;
|
||||||
|
result?: any;
|
||||||
|
exitCode?: number;
|
||||||
|
isProcessing?: boolean;
|
||||||
|
actualSessionId?: string;
|
||||||
|
event?: string;
|
||||||
|
status?: any;
|
||||||
|
isNewSession?: boolean;
|
||||||
|
resultText?: string;
|
||||||
|
isError?: boolean;
|
||||||
|
success?: boolean;
|
||||||
|
reason?: string;
|
||||||
|
provider?: string;
|
||||||
|
content?: string;
|
||||||
|
text?: string;
|
||||||
|
tokens?: number;
|
||||||
|
canInterrupt?: boolean;
|
||||||
|
tokenBudget?: unknown;
|
||||||
|
newSessionId?: string;
|
||||||
|
aborted?: boolean;
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
|
|
||||||
interface UseChatRealtimeHandlersArgs {
|
interface UseChatRealtimeHandlersArgs {
|
||||||
subscribe: (listener: (event: ServerEvent) => void) => () => void;
|
latestMessage: LatestChatMessage | null;
|
||||||
provider: LLMProvider;
|
provider: LLMProvider;
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
currentSessionId: string | null;
|
currentSessionId: string | null;
|
||||||
|
setCurrentSessionId: (sessionId: string | null) => void;
|
||||||
|
setIsLoading: (loading: boolean) => void;
|
||||||
|
setCanAbortSession: (canAbort: boolean) => void;
|
||||||
|
setClaudeStatus: (status: { text: string; tokens: number; can_interrupt: boolean } | null) => void;
|
||||||
setTokenBudget: (budget: Record<string, unknown> | null) => void;
|
setTokenBudget: (budget: Record<string, unknown> | null) => void;
|
||||||
setPendingPermissionRequests: Dispatch<SetStateAction<PendingPermissionRequest[]>>;
|
setPendingPermissionRequests: Dispatch<SetStateAction<PendingPermissionRequest[]>>;
|
||||||
|
pendingViewSessionRef: MutableRefObject<PendingViewSession | null>;
|
||||||
streamTimerRef: MutableRefObject<number | null>;
|
streamTimerRef: MutableRefObject<number | null>;
|
||||||
accumulatedStreamRef: MutableRefObject<string>;
|
accumulatedStreamRef: MutableRefObject<string>;
|
||||||
/**
|
onSessionInactive?: (sessionId?: string | null) => void;
|
||||||
* Highest live `seq` observed per session. Essential for reconnect catch-up:
|
onSessionActive?: (sessionId?: string | null) => void;
|
||||||
* `chat.subscribe` sends this value as `lastSeq` so the server replays only
|
onSessionProcessing?: (sessionId?: string | null) => void;
|
||||||
* the events this client actually missed. Written here on every sequenced
|
onSessionNotProcessing?: (sessionId?: string | null) => void;
|
||||||
* frame; read wherever a `chat.subscribe` is sent (session open, reconnect).
|
onNavigateToSession?: (sessionId: string, options?: SessionNavigationOptions) => void;
|
||||||
*/
|
|
||||||
lastSeqRef: MutableRefObject<Map<string, number>>;
|
|
||||||
/** When each session's `chat.subscribe` was last sent; guards stale idle acks. */
|
|
||||||
statusCheckSentAtRef: MutableRefObject<Map<string, number>>;
|
|
||||||
onSessionProcessing?: MarkSessionProcessing;
|
|
||||||
onSessionIdle?: MarkSessionIdle;
|
|
||||||
onWebSocketReconnect?: () => void;
|
onWebSocketReconnect?: () => void;
|
||||||
sessionStore: SessionStore;
|
sessionStore: SessionStore;
|
||||||
}
|
}
|
||||||
@@ -37,259 +76,324 @@ interface UseChatRealtimeHandlersArgs {
|
|||||||
/* Hook */
|
/* Hook */
|
||||||
/* ------------------------------------------------------------------ */
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
/**
|
|
||||||
* Routes server events into the session store and processing-state map.
|
|
||||||
*
|
|
||||||
* This is intentionally a thin reducer over the unified `kind`-based
|
|
||||||
* protocol: every frame is keyed by the stable app session id, so there is
|
|
||||||
* no session-id handoff, no provider branching, and no navigation here.
|
|
||||||
* Sidebar events (`session_upserted`, `loading_progress`) are handled by
|
|
||||||
* `useProjectsState`, not in this hook.
|
|
||||||
*/
|
|
||||||
export function useChatRealtimeHandlers({
|
export function useChatRealtimeHandlers({
|
||||||
subscribe,
|
latestMessage,
|
||||||
provider,
|
provider,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
currentSessionId,
|
currentSessionId,
|
||||||
|
setCurrentSessionId,
|
||||||
|
setIsLoading,
|
||||||
|
setCanAbortSession,
|
||||||
|
setClaudeStatus,
|
||||||
setTokenBudget,
|
setTokenBudget,
|
||||||
setPendingPermissionRequests,
|
setPendingPermissionRequests,
|
||||||
|
pendingViewSessionRef,
|
||||||
streamTimerRef,
|
streamTimerRef,
|
||||||
accumulatedStreamRef,
|
accumulatedStreamRef,
|
||||||
lastSeqRef,
|
onSessionInactive,
|
||||||
statusCheckSentAtRef,
|
onSessionActive,
|
||||||
onSessionProcessing,
|
onSessionProcessing,
|
||||||
onSessionIdle,
|
onSessionNotProcessing,
|
||||||
|
onNavigateToSession,
|
||||||
onWebSocketReconnect,
|
onWebSocketReconnect,
|
||||||
sessionStore,
|
sessionStore,
|
||||||
}: UseChatRealtimeHandlersArgs) {
|
}: UseChatRealtimeHandlersArgs) {
|
||||||
|
const paletteOps = usePaletteOps();
|
||||||
|
const lastProcessedMessageRef = useRef<LatestChatMessage | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleEvent = (msg: ServerEvent) => {
|
if (!latestMessage) return;
|
||||||
if (!msg.kind) {
|
if (lastProcessedMessageRef.current === latestMessage) return;
|
||||||
return;
|
lastProcessedMessageRef.current = latestMessage;
|
||||||
}
|
|
||||||
|
|
||||||
const activeViewSessionId = selectedSession?.id || currentSessionId || null;
|
const activeViewSessionId =
|
||||||
const sid = (typeof msg.sessionId === 'string' && msg.sessionId) || activeViewSessionId;
|
selectedSession?.id || currentSessionId || null;
|
||||||
|
|
||||||
// Record replay progress for every sequenced live event.
|
/* ---------------------------------------------------------------- */
|
||||||
if (sid && typeof msg.seq === 'number') {
|
/* Legacy messages (no `kind` field) — handle and return */
|
||||||
const known = lastSeqRef.current.get(sid) ?? 0;
|
/* ---------------------------------------------------------------- */
|
||||||
if (msg.seq > known) {
|
|
||||||
lastSeqRef.current.set(sid, msg.seq);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (msg.kind) {
|
const msg = latestMessage as any;
|
||||||
case 'websocket_reconnected':
|
|
||||||
|
if (!msg.kind) {
|
||||||
|
const messageType = String(msg.type || '');
|
||||||
|
|
||||||
|
switch (messageType) {
|
||||||
|
case 'websocket-reconnected':
|
||||||
onWebSocketReconnect?.();
|
onWebSocketReconnect?.();
|
||||||
return;
|
return;
|
||||||
|
|
||||||
case 'chat_subscribed': {
|
case 'pending-permissions-response': {
|
||||||
// Ack for chat.subscribe: authoritative processing state plus any
|
const permSessionId = msg.sessionId;
|
||||||
// pending tool-permission prompts for the run.
|
const isCurrentPermSession =
|
||||||
if (!sid) return;
|
permSessionId === currentSessionId || (selectedSession && permSessionId === selectedSession.id);
|
||||||
|
if (permSessionId && !isCurrentPermSession) return;
|
||||||
|
setPendingPermissionRequests(msg.data || []);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'session-status': {
|
||||||
|
const statusSessionId = msg.sessionId;
|
||||||
|
if (!statusSessionId) return;
|
||||||
|
|
||||||
|
const status = msg.status;
|
||||||
|
if (status) {
|
||||||
|
const statusInfo = {
|
||||||
|
text: status.text || 'Working...',
|
||||||
|
tokens: status.tokens || 0,
|
||||||
|
can_interrupt: status.can_interrupt !== undefined ? status.can_interrupt : true,
|
||||||
|
};
|
||||||
|
setClaudeStatus(statusInfo);
|
||||||
|
setIsLoading(true);
|
||||||
|
setCanAbortSession(statusInfo.can_interrupt);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy isProcessing format from check-session-status
|
||||||
|
const isCurrentSession =
|
||||||
|
statusSessionId === currentSessionId || (selectedSession && statusSessionId === selectedSession.id);
|
||||||
|
|
||||||
if (msg.isProcessing) {
|
if (msg.isProcessing) {
|
||||||
onSessionProcessing?.(sid);
|
onSessionActive?.(statusSessionId);
|
||||||
} else {
|
onSessionProcessing?.(statusSessionId);
|
||||||
// Idle ack: ignore it if a newer request started after the
|
if (isCurrentSession) { setIsLoading(true); setCanAbortSession(true); }
|
||||||
// subscribe was sent — the ack describes the older state.
|
return;
|
||||||
onSessionIdle?.(sid, {
|
|
||||||
ifStartedBefore: statusCheckSentAtRef.current.get(sid),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const isViewedSession = sid === activeViewSessionId;
|
onSessionInactive?.(statusSessionId);
|
||||||
if (isViewedSession && Array.isArray(msg.pendingPermissions)) {
|
onSessionNotProcessing?.(statusSessionId);
|
||||||
setPendingPermissionRequests(msg.pendingPermissions as PendingPermissionRequest[]);
|
if (isCurrentSession) {
|
||||||
|
setIsLoading(false);
|
||||||
|
setCanAbortSession(false);
|
||||||
|
setClaudeStatus(null);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'protocol_error': {
|
|
||||||
console.error('[Chat] Protocol error:', msg.code, msg.error);
|
|
||||||
if (sid) {
|
|
||||||
// Surface the failure in the conversation and stop the spinner —
|
|
||||||
// the run never started (or was rejected), so no `complete` follows.
|
|
||||||
onSessionIdle?.(sid);
|
|
||||||
sessionStore.appendRealtime(sid, {
|
|
||||||
id: `protocol_error_${Date.now()}`,
|
|
||||||
sessionId: sid,
|
|
||||||
timestamp: new Date().toISOString(),
|
|
||||||
provider,
|
|
||||||
kind: 'error',
|
|
||||||
content: String(msg.error || 'Request failed'),
|
|
||||||
} as NormalizedMessage);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sidebar/global events — owned by useProjectsState.
|
|
||||||
case 'session_upserted':
|
|
||||||
case 'loading_progress':
|
|
||||||
return;
|
|
||||||
|
|
||||||
default:
|
default:
|
||||||
break;
|
// Unknown legacy message type — ignore
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- */
|
||||||
|
/* NormalizedMessage handling (has `kind` field) */
|
||||||
|
/* ---------------------------------------------------------------- */
|
||||||
|
|
||||||
|
const sid = msg.sessionId || activeViewSessionId;
|
||||||
|
|
||||||
|
// --- Streaming: buffer for performance ---
|
||||||
|
if (msg.kind === 'stream_delta') {
|
||||||
|
const text = msg.content || '';
|
||||||
|
if (!text) return;
|
||||||
|
accumulatedStreamRef.current += text;
|
||||||
|
if (!streamTimerRef.current) {
|
||||||
|
streamTimerRef.current = window.setTimeout(() => {
|
||||||
|
streamTimerRef.current = null;
|
||||||
|
if (sid) {
|
||||||
|
sessionStore.updateStreaming(sid, accumulatedStreamRef.current, provider);
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
}
|
||||||
|
// Also route to store for non-active sessions
|
||||||
|
if (sid && sid !== activeViewSessionId) {
|
||||||
|
sessionStore.appendRealtime(sid, msg as NormalizedMessage);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.kind === 'stream_end') {
|
||||||
|
if (streamTimerRef.current) {
|
||||||
|
clearTimeout(streamTimerRef.current);
|
||||||
|
streamTimerRef.current = null;
|
||||||
|
}
|
||||||
|
if (sid) {
|
||||||
|
if (accumulatedStreamRef.current) {
|
||||||
|
sessionStore.updateStreaming(sid, accumulatedStreamRef.current, provider);
|
||||||
|
}
|
||||||
|
sessionStore.finalizeStreaming(sid);
|
||||||
|
}
|
||||||
|
accumulatedStreamRef.current = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- All other messages: route to store ---
|
||||||
|
const shouldPersist =
|
||||||
|
msg.kind !== 'session_created'
|
||||||
|
&& msg.kind !== 'complete'
|
||||||
|
&& msg.kind !== 'status'
|
||||||
|
&& msg.kind !== 'permission_request'
|
||||||
|
&& msg.kind !== 'permission_cancelled';
|
||||||
|
|
||||||
|
if (sid && shouldPersist) {
|
||||||
|
sessionStore.appendRealtime(sid, msg as NormalizedMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- UI side effects for specific kinds ---
|
||||||
|
switch (msg.kind) {
|
||||||
|
case 'session_created': {
|
||||||
|
const newSessionId = msg.newSessionId;
|
||||||
|
if (!newSessionId) break;
|
||||||
|
|
||||||
|
// We no longer synthesize client-side placeholder IDs. Until the provider
|
||||||
|
// announces `session_created`, the active id is expected to be null.
|
||||||
|
if (!currentSessionId) {
|
||||||
|
console.log('Session created with ID:', newSessionId);
|
||||||
|
console.log('Existing session ID:', currentSessionId);
|
||||||
|
setCurrentSessionId(newSessionId);
|
||||||
|
setPendingPermissionRequests((prev) =>
|
||||||
|
prev.map((r) => (r.sessionId ? r : { ...r, sessionId: newSessionId })),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
pendingViewSessionRef.current = null;
|
||||||
|
onSessionActive?.(newSessionId);
|
||||||
|
onSessionProcessing?.(newSessionId);
|
||||||
|
setIsLoading(true);
|
||||||
|
setCanAbortSession(true);
|
||||||
|
setClaudeStatus({
|
||||||
|
text: 'Processing',
|
||||||
|
tokens: 0,
|
||||||
|
can_interrupt: true,
|
||||||
|
});
|
||||||
|
onNavigateToSession?.(newSessionId);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* -------------------------------------------------------------- */
|
case 'complete': {
|
||||||
/* Provider NormalizedMessage handling */
|
// Flush any remaining streaming state
|
||||||
/* -------------------------------------------------------------- */
|
|
||||||
|
|
||||||
// --- Streaming: buffer for performance ---
|
|
||||||
if (msg.kind === 'stream_delta') {
|
|
||||||
const text = (msg.content as string) || '';
|
|
||||||
if (!text) return;
|
|
||||||
accumulatedStreamRef.current += text;
|
|
||||||
if (!streamTimerRef.current) {
|
|
||||||
streamTimerRef.current = window.setTimeout(() => {
|
|
||||||
streamTimerRef.current = null;
|
|
||||||
if (sid) {
|
|
||||||
sessionStore.updateStreaming(sid, accumulatedStreamRef.current, provider);
|
|
||||||
}
|
|
||||||
}, 100);
|
|
||||||
}
|
|
||||||
// Also route to store for non-active sessions
|
|
||||||
if (sid && sid !== activeViewSessionId) {
|
|
||||||
sessionStore.appendRealtime(sid, msg as unknown as NormalizedMessage);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (msg.kind === 'stream_end') {
|
|
||||||
if (streamTimerRef.current) {
|
if (streamTimerRef.current) {
|
||||||
clearTimeout(streamTimerRef.current);
|
clearTimeout(streamTimerRef.current);
|
||||||
streamTimerRef.current = null;
|
streamTimerRef.current = null;
|
||||||
}
|
}
|
||||||
if (sid) {
|
if (sid && accumulatedStreamRef.current) {
|
||||||
if (accumulatedStreamRef.current) {
|
sessionStore.updateStreaming(sid, accumulatedStreamRef.current, provider);
|
||||||
sessionStore.updateStreaming(sid, accumulatedStreamRef.current, provider);
|
|
||||||
}
|
|
||||||
sessionStore.finalizeStreaming(sid);
|
sessionStore.finalizeStreaming(sid);
|
||||||
}
|
}
|
||||||
accumulatedStreamRef.current = '';
|
accumulatedStreamRef.current = '';
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- All other messages: route to store ---
|
setIsLoading(false);
|
||||||
const shouldPersist =
|
setCanAbortSession(false);
|
||||||
msg.kind !== 'complete'
|
setClaudeStatus(null);
|
||||||
&& msg.kind !== 'status'
|
setPendingPermissionRequests([]);
|
||||||
&& msg.kind !== 'permission_request'
|
onSessionInactive?.(sid);
|
||||||
&& msg.kind !== 'permission_cancelled';
|
onSessionNotProcessing?.(sid);
|
||||||
|
pendingViewSessionRef.current = null;
|
||||||
if (sid && shouldPersist) {
|
|
||||||
sessionStore.appendRealtime(sid, msg as unknown as NormalizedMessage);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- UI side effects for specific kinds ---
|
|
||||||
switch (msg.kind) {
|
|
||||||
case 'complete': {
|
|
||||||
// Flush any remaining streaming state
|
|
||||||
if (streamTimerRef.current) {
|
|
||||||
clearTimeout(streamTimerRef.current);
|
|
||||||
streamTimerRef.current = null;
|
|
||||||
}
|
|
||||||
if (sid && accumulatedStreamRef.current) {
|
|
||||||
sessionStore.updateStreaming(sid, accumulatedStreamRef.current, provider);
|
|
||||||
sessionStore.finalizeStreaming(sid);
|
|
||||||
}
|
|
||||||
accumulatedStreamRef.current = '';
|
|
||||||
|
|
||||||
// `complete` is the unified terminal event — every provider run ends
|
|
||||||
// with exactly one, regardless of success, failure, or abort. The
|
|
||||||
// indicator derives from the processing map, so deleting the entry
|
|
||||||
// hides it immediately and atomically.
|
|
||||||
onSessionIdle?.(sid);
|
|
||||||
setPendingPermissionRequests([]);
|
|
||||||
|
|
||||||
if (msg.aborted) {
|
|
||||||
// Abort was requested — the complete event confirms it. No
|
|
||||||
// further UI action is needed beyond clearing the entry above.
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Celebrate only successful runs (failed runs end with success: false).
|
|
||||||
if (msg.success !== false) {
|
|
||||||
showCompletionTitleIndicator();
|
|
||||||
void playChatCompletionSound();
|
|
||||||
}
|
|
||||||
|
|
||||||
// The session id is stable for the whole conversation (allocated
|
|
||||||
// before the first send), so the only follow-up is syncing the
|
|
||||||
// viewed conversation with the now-persisted transcript.
|
|
||||||
if (sid && sid === activeViewSessionId) {
|
|
||||||
void sessionStore.refreshFromServer(sid);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Handle aborted case
|
||||||
|
if (msg.aborted) {
|
||||||
|
// Abort was requested — the complete event confirms it
|
||||||
|
// No special UI action needed beyond clearing loading state above
|
||||||
|
// The backend already sent any abort-related messages
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 'error' is an informational message row, not a terminal event —
|
showCompletionTitleIndicator();
|
||||||
// providers emit it for mid-run stderr output too. Run teardown is
|
void playChatCompletionSound();
|
||||||
// always signalled by the unified 'complete' that follows.
|
|
||||||
|
|
||||||
case 'permission_request': {
|
const actualSessionId =
|
||||||
if (!msg.requestId) break;
|
typeof msg.actualSessionId === 'string' && msg.actualSessionId.trim().length > 0
|
||||||
setPendingPermissionRequests((prev) => {
|
? msg.actualSessionId
|
||||||
if (prev.some((r: PendingPermissionRequest) => r.requestId === msg.requestId)) return prev;
|
: null;
|
||||||
return [...prev, {
|
const isVisibleSession =
|
||||||
requestId: msg.requestId as string,
|
Boolean(
|
||||||
toolName: (msg.toolName as string) || 'UnknownTool',
|
sid
|
||||||
input: msg.input,
|
&& sid === activeViewSessionId,
|
||||||
context: msg.context,
|
);
|
||||||
sessionId: sid || null,
|
|
||||||
receivedAt: new Date(),
|
if (actualSessionId && sid && actualSessionId !== sid) {
|
||||||
}];
|
sessionStore.replaceSessionId(sid, actualSessionId);
|
||||||
|
|
||||||
|
if (isVisibleSession) {
|
||||||
|
setCurrentSessionId(actualSessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isVisibleSession) {
|
||||||
|
onNavigateToSession?.(actualSessionId, { replace: true });
|
||||||
|
setTimeout(() => { void paletteOps.refreshProjects(); }, 500);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'error': {
|
||||||
|
setIsLoading(false);
|
||||||
|
setCanAbortSession(false);
|
||||||
|
setClaudeStatus(null);
|
||||||
|
onSessionInactive?.(sid);
|
||||||
|
onSessionNotProcessing?.(sid);
|
||||||
|
pendingViewSessionRef.current = null;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'permission_request': {
|
||||||
|
if (!msg.requestId) break;
|
||||||
|
setPendingPermissionRequests((prev) => {
|
||||||
|
if (prev.some((r: PendingPermissionRequest) => r.requestId === msg.requestId)) return prev;
|
||||||
|
return [...prev, {
|
||||||
|
requestId: msg.requestId,
|
||||||
|
toolName: msg.toolName || 'UnknownTool',
|
||||||
|
input: msg.input,
|
||||||
|
context: msg.context,
|
||||||
|
sessionId: sid || null,
|
||||||
|
receivedAt: new Date(),
|
||||||
|
}];
|
||||||
|
});
|
||||||
|
setIsLoading(true);
|
||||||
|
setCanAbortSession(true);
|
||||||
|
setClaudeStatus({ text: 'Waiting for permission', tokens: 0, can_interrupt: true });
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'permission_cancelled': {
|
||||||
|
if (msg.requestId) {
|
||||||
|
setPendingPermissionRequests((prev) => prev.filter((r: PendingPermissionRequest) => r.requestId !== msg.requestId));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'status': {
|
||||||
|
if (msg.text === 'token_budget' && msg.tokenBudget) {
|
||||||
|
setTokenBudget(msg.tokenBudget as Record<string, unknown>);
|
||||||
|
} else if (msg.text) {
|
||||||
|
setClaudeStatus({
|
||||||
|
text: msg.text,
|
||||||
|
tokens: msg.tokens || 0,
|
||||||
|
can_interrupt: msg.canInterrupt !== undefined ? msg.canInterrupt : true,
|
||||||
});
|
});
|
||||||
if (sid) {
|
setIsLoading(true);
|
||||||
onSessionProcessing?.(sid);
|
setCanAbortSession(msg.canInterrupt !== false);
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
break;
|
||||||
case 'permission_cancelled': {
|
|
||||||
if (msg.requestId) {
|
|
||||||
setPendingPermissionRequests((prev) => prev.filter((r: PendingPermissionRequest) => r.requestId !== msg.requestId));
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
case 'status': {
|
|
||||||
if (msg.text === 'token_budget' && msg.tokenBudget) {
|
|
||||||
setTokenBudget(msg.tokenBudget as Record<string, unknown>);
|
|
||||||
} else if (msg.text && sid) {
|
|
||||||
onSessionProcessing?.(sid, {
|
|
||||||
statusText: msg.text as string,
|
|
||||||
canInterrupt: msg.canInterrupt !== false,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// text, tool_use, tool_result, thinking, interactive_prompt, task_notification
|
|
||||||
// → already routed to store above, no UI side effects needed
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
return subscribe(handleEvent);
|
// text, tool_use, tool_result, thinking, interactive_prompt, task_notification
|
||||||
|
// → already routed to store above, no UI side effects needed
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
}, [
|
}, [
|
||||||
subscribe,
|
latestMessage,
|
||||||
provider,
|
provider,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
currentSessionId,
|
currentSessionId,
|
||||||
|
setCurrentSessionId,
|
||||||
|
setIsLoading,
|
||||||
|
setCanAbortSession,
|
||||||
|
setClaudeStatus,
|
||||||
setTokenBudget,
|
setTokenBudget,
|
||||||
setPendingPermissionRequests,
|
setPendingPermissionRequests,
|
||||||
|
pendingViewSessionRef,
|
||||||
streamTimerRef,
|
streamTimerRef,
|
||||||
accumulatedStreamRef,
|
accumulatedStreamRef,
|
||||||
lastSeqRef,
|
onSessionInactive,
|
||||||
statusCheckSentAtRef,
|
onSessionActive,
|
||||||
onSessionProcessing,
|
onSessionProcessing,
|
||||||
onSessionIdle,
|
onSessionNotProcessing,
|
||||||
|
onNavigateToSession,
|
||||||
onWebSocketReconnect,
|
onWebSocketReconnect,
|
||||||
sessionStore,
|
sessionStore,
|
||||||
|
paletteOps,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,9 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
|
|||||||
import type { MutableRefObject } from 'react';
|
import type { MutableRefObject } from 'react';
|
||||||
|
|
||||||
import { authenticatedFetch } from '../../../utils/api';
|
import { authenticatedFetch } from '../../../utils/api';
|
||||||
import type { MarkSessionIdle, SessionActivityMap } from '../../../hooks/useSessionProtection';
|
|
||||||
import type { Project, ProjectSession, LLMProvider } from '../../../types/app';
|
import type { Project, ProjectSession, LLMProvider } from '../../../types/app';
|
||||||
import type { SessionStore, NormalizedMessage } from '../../../stores/useSessionStore';
|
import type { SessionStore, NormalizedMessage } from '../../../stores/useSessionStore';
|
||||||
import type { ChatMessage } from '../types/types';
|
import type { ChatMessage, Provider } from '../types/types';
|
||||||
import { createCachedDiffCalculator, type DiffCalculator } from '../utils/messageTransforms';
|
import { createCachedDiffCalculator, type DiffCalculator } from '../utils/messageTransforms';
|
||||||
|
|
||||||
import { normalizedToChatMessages } from './useChatMessages';
|
import { normalizedToChatMessages } from './useChatMessages';
|
||||||
@@ -13,6 +12,10 @@ import { normalizedToChatMessages } from './useChatMessages';
|
|||||||
const MESSAGES_PER_PAGE = 20;
|
const MESSAGES_PER_PAGE = 20;
|
||||||
const INITIAL_VISIBLE_MESSAGES = 100;
|
const INITIAL_VISIBLE_MESSAGES = 100;
|
||||||
|
|
||||||
|
type PendingViewSession = {
|
||||||
|
startedAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
interface UseChatSessionStateArgs {
|
interface UseChatSessionStateArgs {
|
||||||
selectedProject: Project | null;
|
selectedProject: Project | null;
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
@@ -21,13 +24,9 @@ interface UseChatSessionStateArgs {
|
|||||||
autoScrollToBottom?: boolean;
|
autoScrollToBottom?: boolean;
|
||||||
externalMessageUpdate?: number;
|
externalMessageUpdate?: number;
|
||||||
newSessionTrigger?: number;
|
newSessionTrigger?: number;
|
||||||
processingSessions?: SessionActivityMap;
|
processingSessions?: Set<string>;
|
||||||
onSessionIdle?: MarkSessionIdle;
|
|
||||||
resetStreamingState: () => void;
|
resetStreamingState: () => void;
|
||||||
/** When each session's `chat.subscribe` was last sent; guards stale idle acks. */
|
pendingViewSessionRef: MutableRefObject<PendingViewSession | null>;
|
||||||
statusCheckSentAtRef: MutableRefObject<Map<string, number>>;
|
|
||||||
/** Highest live seq observed per session; sent as `lastSeq` on subscribe. */
|
|
||||||
lastSeqRef: MutableRefObject<Map<string, number>>;
|
|
||||||
sessionStore: SessionStore;
|
sessionStore: SessionStore;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,20 +99,21 @@ export function useChatSessionState({
|
|||||||
externalMessageUpdate,
|
externalMessageUpdate,
|
||||||
newSessionTrigger,
|
newSessionTrigger,
|
||||||
processingSessions,
|
processingSessions,
|
||||||
onSessionIdle,
|
|
||||||
resetStreamingState,
|
resetStreamingState,
|
||||||
statusCheckSentAtRef,
|
pendingViewSessionRef,
|
||||||
lastSeqRef,
|
|
||||||
sessionStore,
|
sessionStore,
|
||||||
}: UseChatSessionStateArgs) {
|
}: UseChatSessionStateArgs) {
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [currentSessionId, setCurrentSessionId] = useState<string | null>(selectedSession?.id || null);
|
const [currentSessionId, setCurrentSessionId] = useState<string | null>(selectedSession?.id || null);
|
||||||
const [isLoadingSessionMessages, setIsLoadingSessionMessages] = useState(false);
|
const [isLoadingSessionMessages, setIsLoadingSessionMessages] = useState(false);
|
||||||
const [isLoadingMoreMessages, setIsLoadingMoreMessages] = useState(false);
|
const [isLoadingMoreMessages, setIsLoadingMoreMessages] = useState(false);
|
||||||
const [hasMoreMessages, setHasMoreMessages] = useState(false);
|
const [hasMoreMessages, setHasMoreMessages] = useState(false);
|
||||||
const [totalMessages, setTotalMessages] = useState(0);
|
const [totalMessages, setTotalMessages] = useState(0);
|
||||||
|
const [canAbortSession, setCanAbortSession] = useState(false);
|
||||||
const [isUserScrolledUp, setIsUserScrolledUp] = useState(false);
|
const [isUserScrolledUp, setIsUserScrolledUp] = useState(false);
|
||||||
const [tokenBudget, setTokenBudget] = useState<Record<string, unknown> | null>(null);
|
const [tokenBudget, setTokenBudget] = useState<Record<string, unknown> | null>(null);
|
||||||
const [visibleMessageCount, setVisibleMessageCount] = useState(INITIAL_VISIBLE_MESSAGES);
|
const [visibleMessageCount, setVisibleMessageCount] = useState(INITIAL_VISIBLE_MESSAGES);
|
||||||
|
const [claudeStatus, setClaudeStatus] = useState<{ text: string; tokens: number; can_interrupt: boolean } | null>(null);
|
||||||
const [allMessagesLoaded, setAllMessagesLoaded] = useState(false);
|
const [allMessagesLoaded, setAllMessagesLoaded] = useState(false);
|
||||||
const [isLoadingAllMessages, setIsLoadingAllMessages] = useState(false);
|
const [isLoadingAllMessages, setIsLoadingAllMessages] = useState(false);
|
||||||
const [loadAllJustFinished, setLoadAllJustFinished] = useState(false);
|
const [loadAllJustFinished, setLoadAllJustFinished] = useState(false);
|
||||||
@@ -170,8 +170,13 @@ export function useChatSessionState({
|
|||||||
* - No coupling to unrelated external update signals.
|
* - No coupling to unrelated external update signals.
|
||||||
*/
|
*/
|
||||||
resetStreamingState();
|
resetStreamingState();
|
||||||
|
pendingViewSessionRef.current = null;
|
||||||
|
setClaudeStatus(null);
|
||||||
|
setCanAbortSession(false);
|
||||||
|
setIsLoading(false);
|
||||||
setCurrentSessionId(null);
|
setCurrentSessionId(null);
|
||||||
setPendingUserMessage(null);
|
setPendingUserMessage(null);
|
||||||
|
sessionStorage.removeItem('cursorSessionId');
|
||||||
messagesOffsetRef.current = 0;
|
messagesOffsetRef.current = 0;
|
||||||
setHasMoreMessages(false);
|
setHasMoreMessages(false);
|
||||||
setTotalMessages(0);
|
setTotalMessages(0);
|
||||||
@@ -199,30 +204,13 @@ export function useChatSessionState({
|
|||||||
clearTimeout(loadAllFinishedTimerRef.current);
|
clearTimeout(loadAllFinishedTimerRef.current);
|
||||||
loadAllFinishedTimerRef.current = null;
|
loadAllFinishedTimerRef.current = null;
|
||||||
}
|
}
|
||||||
}, [newSessionTrigger, onSessionIdle, resetStreamingState]);
|
}, [newSessionTrigger, pendingViewSessionRef, resetStreamingState]);
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- */
|
|
||||||
/* Derive processing state for the viewed session */
|
|
||||||
/* ---------------------------------------------------------------- */
|
|
||||||
|
|
||||||
const activeSessionId = selectedSession?.id || currentSessionId || null;
|
|
||||||
|
|
||||||
// The activity indicator always reflects the latest status of the session
|
|
||||||
// being viewed — never stale local UI state from the last time it was
|
|
||||||
// open. Session ids are concrete before any send, so no pending
|
|
||||||
// placeholder entry exists anymore.
|
|
||||||
const sessionActivity = (activeSessionId && processingSessions?.get(activeSessionId)) || null;
|
|
||||||
const isProcessing = sessionActivity !== null;
|
|
||||||
const canAbortSession = isProcessing && sessionActivity.canInterrupt;
|
|
||||||
|
|
||||||
// Ref mirror so effects can read the latest map without re-running on
|
|
||||||
// every activity transition.
|
|
||||||
const processingSessionsRef = useRef(processingSessions);
|
|
||||||
processingSessionsRef.current = processingSessions;
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- */
|
/* ---------------------------------------------------------------- */
|
||||||
/* Derive chatMessages from the store */
|
/* Derive chatMessages from the store */
|
||||||
/* ---------------------------------------------------------------- */
|
/* ---------------------------------------------------------------- */
|
||||||
|
|
||||||
|
const activeSessionId = selectedSession?.id || currentSessionId || null;
|
||||||
const [pendingUserMessage, setPendingUserMessage] = useState<ChatMessage | null>(null);
|
const [pendingUserMessage, setPendingUserMessage] = useState<ChatMessage | null>(null);
|
||||||
const flushedPendingUserMessageRef = useRef<ChatMessage | null>(null);
|
const flushedPendingUserMessageRef = useRef<ChatMessage | null>(null);
|
||||||
|
|
||||||
@@ -328,12 +316,18 @@ export function useChatSessionState({
|
|||||||
if (allMessagesLoadedRef.current) return false;
|
if (allMessagesLoadedRef.current) return false;
|
||||||
if (!hasMoreMessages || !selectedSession || !selectedProject) return false;
|
if (!hasMoreMessages || !selectedSession || !selectedProject) return false;
|
||||||
|
|
||||||
|
const sessionProvider = selectedSession.__provider || 'claude';
|
||||||
|
|
||||||
isLoadingMoreRef.current = true;
|
isLoadingMoreRef.current = true;
|
||||||
const previousScrollHeight = container.scrollHeight;
|
const previousScrollHeight = container.scrollHeight;
|
||||||
const previousScrollTop = container.scrollTop;
|
const previousScrollTop = container.scrollTop;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const slot = await sessionStore.fetchMore(selectedSession.id, {
|
const slot = await sessionStore.fetchMore(selectedSession.id, {
|
||||||
|
provider: sessionProvider as LLMProvider,
|
||||||
|
// DB-assigned projectId replaces the legacy folder-derived name.
|
||||||
|
projectId: selectedProject.projectId,
|
||||||
|
projectPath: selectedProject.fullPath || selectedProject.path || '',
|
||||||
limit: MESSAGES_PER_PAGE,
|
limit: MESSAGES_PER_PAGE,
|
||||||
});
|
});
|
||||||
if (!slot || slot.serverMessages.length === 0) return false;
|
if (!slot || slot.serverMessages.length === 0) return false;
|
||||||
@@ -435,15 +429,19 @@ export function useChatSessionState({
|
|||||||
// Main session loading effect — store-based
|
// Main session loading effect — store-based
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!selectedSession || !selectedProject) {
|
if (!selectedSession || !selectedProject) {
|
||||||
// A freshly created session can be mid-run before the router has a
|
// A new provider run can be in flight before the router has a canonical
|
||||||
// canonical selectedSession (the URL effect synthesizes one on the
|
// selectedSession. Keep the processing banner alive until complete/error.
|
||||||
// next render). Keep the active view intact instead of wiping it.
|
if (pendingViewSessionRef.current) {
|
||||||
if (currentSessionId && processingSessionsRef.current?.has(currentSessionId)) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
resetStreamingState();
|
resetStreamingState();
|
||||||
|
pendingViewSessionRef.current = null;
|
||||||
|
setClaudeStatus(null);
|
||||||
|
setCanAbortSession(false);
|
||||||
|
setIsLoading(false);
|
||||||
setCurrentSessionId(null);
|
setCurrentSessionId(null);
|
||||||
|
sessionStorage.removeItem('cursorSessionId');
|
||||||
messagesOffsetRef.current = 0;
|
messagesOffsetRef.current = 0;
|
||||||
setHasMoreMessages(false);
|
setHasMoreMessages(false);
|
||||||
setTotalMessages(0);
|
setTotalMessages(0);
|
||||||
@@ -452,7 +450,8 @@ export function useChatSessionState({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const sessionKey = `${selectedSession.id}:${selectedProject.projectId}`;
|
const provider = (selectedSession.__provider || localStorage.getItem('selected-provider') as Provider) || 'claude';
|
||||||
|
const sessionKey = `${selectedSession.id}:${selectedProject.projectId}:${provider}`;
|
||||||
|
|
||||||
// Skip if already loaded and fresh
|
// Skip if already loaded and fresh
|
||||||
if (lastLoadedSessionKeyRef.current === sessionKey && sessionStore.has(selectedSession.id) && !sessionStore.isStale(selectedSession.id)) {
|
if (lastLoadedSessionKeyRef.current === sessionKey && sessionStore.has(selectedSession.id) && !sessionStore.isStale(selectedSession.id)) {
|
||||||
@@ -462,6 +461,9 @@ export function useChatSessionState({
|
|||||||
const sessionChanged = currentSessionId !== null && currentSessionId !== selectedSession.id;
|
const sessionChanged = currentSessionId !== null && currentSessionId !== selectedSession.id;
|
||||||
if (sessionChanged) {
|
if (sessionChanged) {
|
||||||
resetStreamingState();
|
resetStreamingState();
|
||||||
|
pendingViewSessionRef.current = null;
|
||||||
|
setClaudeStatus(null);
|
||||||
|
setCanAbortSession(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset pagination/scroll state
|
// Reset pagination/scroll state
|
||||||
@@ -480,24 +482,17 @@ export function useChatSessionState({
|
|||||||
|
|
||||||
if (sessionChanged) {
|
if (sessionChanged) {
|
||||||
setTokenBudget(null);
|
setTokenBudget(null);
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
setCurrentSessionId(selectedSession.id);
|
setCurrentSessionId(selectedSession.id);
|
||||||
|
if (provider === 'cursor') {
|
||||||
|
sessionStorage.setItem('cursorSessionId', selectedSession.id);
|
||||||
|
}
|
||||||
|
|
||||||
// Subscribe to the session's live run (if any): the ack reconciles the
|
// Check session status
|
||||||
// processing indicator, re-attaches a mid-flight stream to this socket,
|
|
||||||
// and replays any live events missed since `lastSeq`. Recording the send
|
|
||||||
// time lets the ack handler discard idle acks that a newer request has
|
|
||||||
// since outdated.
|
|
||||||
if (ws) {
|
if (ws) {
|
||||||
statusCheckSentAtRef.current.set(selectedSession.id, Date.now());
|
sendMessage({ type: 'check-session-status', sessionId: selectedSession.id, provider });
|
||||||
sendMessage({
|
|
||||||
type: 'chat.subscribe',
|
|
||||||
sessions: [{
|
|
||||||
sessionId: selectedSession.id,
|
|
||||||
lastSeq: lastSeqRef.current.get(selectedSession.id) ?? 0,
|
|
||||||
}],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
lastLoadedSessionKeyRef.current = sessionKey;
|
lastLoadedSessionKeyRef.current = sessionKey;
|
||||||
@@ -505,6 +500,9 @@ export function useChatSessionState({
|
|||||||
// Fetch from server → store updates → chatMessages re-derives automatically
|
// Fetch from server → store updates → chatMessages re-derives automatically
|
||||||
setIsLoadingSessionMessages(true);
|
setIsLoadingSessionMessages(true);
|
||||||
sessionStore.fetchFromServer(selectedSession.id, {
|
sessionStore.fetchFromServer(selectedSession.id, {
|
||||||
|
provider: (selectedSession.__provider || provider) as LLMProvider,
|
||||||
|
projectId: selectedProject.projectId,
|
||||||
|
projectPath: selectedProject.fullPath || selectedProject.path || '',
|
||||||
limit: MESSAGES_PER_PAGE,
|
limit: MESSAGES_PER_PAGE,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
}).then(slot => {
|
}).then(slot => {
|
||||||
@@ -518,12 +516,11 @@ export function useChatSessionState({
|
|||||||
setIsLoadingSessionMessages(false);
|
setIsLoadingSessionMessages(false);
|
||||||
});
|
});
|
||||||
}, [
|
}, [
|
||||||
|
pendingViewSessionRef,
|
||||||
resetStreamingState,
|
resetStreamingState,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
selectedSession?.id,
|
selectedSession?.id,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
statusCheckSentAtRef,
|
|
||||||
lastSeqRef,
|
|
||||||
ws,
|
ws,
|
||||||
sessionStore,
|
sessionStore,
|
||||||
]);
|
]);
|
||||||
@@ -534,9 +531,15 @@ export function useChatSessionState({
|
|||||||
|
|
||||||
const reloadExternalMessages = async () => {
|
const reloadExternalMessages = async () => {
|
||||||
try {
|
try {
|
||||||
|
const provider = (localStorage.getItem('selected-provider') as Provider) || 'claude';
|
||||||
|
|
||||||
// Skip store refresh during active streaming
|
// Skip store refresh during active streaming
|
||||||
if (!isProcessing) {
|
if (!isLoading) {
|
||||||
await sessionStore.refreshFromServer(selectedSession.id);
|
await sessionStore.refreshFromServer(selectedSession.id, {
|
||||||
|
provider: (selectedSession.__provider || provider) as LLMProvider,
|
||||||
|
projectId: selectedProject.projectId,
|
||||||
|
projectPath: selectedProject.fullPath || selectedProject.path || '',
|
||||||
|
});
|
||||||
|
|
||||||
if (Boolean(autoScrollToBottom) && isNearBottom()) {
|
if (Boolean(autoScrollToBottom) && isNearBottom()) {
|
||||||
setTimeout(() => scrollToBottom(), 200);
|
setTimeout(() => scrollToBottom(), 200);
|
||||||
@@ -556,7 +559,7 @@ export function useChatSessionState({
|
|||||||
selectedProject,
|
selectedProject,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
sessionStore,
|
sessionStore,
|
||||||
isProcessing,
|
isLoading,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Search navigation target
|
// Search navigation target
|
||||||
@@ -582,9 +585,13 @@ export function useChatSessionState({
|
|||||||
|
|
||||||
const scrollToTarget = async () => {
|
const scrollToTarget = async () => {
|
||||||
if (!allMessagesLoadedRef.current && selectedSession && selectedProject) {
|
if (!allMessagesLoadedRef.current && selectedSession && selectedProject) {
|
||||||
|
const sessionProvider = selectedSession.__provider || 'claude';
|
||||||
try {
|
try {
|
||||||
// Load all messages into the store for search navigation
|
// Load all messages into the store for search navigation
|
||||||
const slot = await sessionStore.fetchFromServer(selectedSession.id, {
|
const slot = await sessionStore.fetchFromServer(selectedSession.id, {
|
||||||
|
provider: sessionProvider as LLMProvider,
|
||||||
|
projectId: selectedProject.projectId,
|
||||||
|
projectPath: selectedProject.fullPath || selectedProject.path || '',
|
||||||
limit: null,
|
limit: null,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
});
|
});
|
||||||
@@ -658,10 +665,17 @@ export function useChatSessionState({
|
|||||||
setTokenBudget(null);
|
setTokenBudget(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const sessionProvider = selectedSession.__provider || 'claude';
|
||||||
|
if (sessionProvider !== 'claude' && sessionProvider !== 'codex' && sessionProvider !== 'gemini' && sessionProvider !== 'opencode') {
|
||||||
|
setTokenBudget(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const fetchInitialTokenUsage = async () => {
|
const fetchInitialTokenUsage = async () => {
|
||||||
try {
|
try {
|
||||||
// The backend resolves the provider from the indexed session row.
|
// Token usage endpoint is now keyed by the DB projectId.
|
||||||
const url = `/api/projects/${selectedProject.projectId}/sessions/${selectedSession.id}/token-usage`;
|
const params = new URLSearchParams({ provider: sessionProvider });
|
||||||
|
const url = `/api/projects/${selectedProject.projectId}/sessions/${selectedSession.id}/token-usage?${params.toString()}`;
|
||||||
const response = await authenticatedFetch(url);
|
const response = await authenticatedFetch(url);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
setTokenBudget(await response.json());
|
setTokenBudget(await response.json());
|
||||||
@@ -673,7 +687,7 @@ export function useChatSessionState({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
fetchInitialTokenUsage();
|
fetchInitialTokenUsage();
|
||||||
}, [selectedProject, selectedSession?.id]);
|
}, [selectedProject, selectedSession?.id, selectedSession?.__provider]);
|
||||||
|
|
||||||
const visibleMessages = useMemo(() => {
|
const visibleMessages = useMemo(() => {
|
||||||
if (chatMessages.length <= visibleMessageCount) return chatMessages;
|
if (chatMessages.length <= visibleMessageCount) return chatMessages;
|
||||||
@@ -712,6 +726,16 @@ export function useChatSessionState({
|
|||||||
return () => container.removeEventListener('scroll', handleScroll);
|
return () => container.removeEventListener('scroll', handleScroll);
|
||||||
}, [handleScroll]);
|
}, [handleScroll]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const activeViewSessionId = selectedSession?.id || currentSessionId;
|
||||||
|
if (!activeViewSessionId || !processingSessions) return;
|
||||||
|
const shouldBeProcessing = processingSessions.has(activeViewSessionId);
|
||||||
|
if (shouldBeProcessing && !isLoading) {
|
||||||
|
setIsLoading(true);
|
||||||
|
setCanAbortSession(true);
|
||||||
|
}
|
||||||
|
}, [currentSessionId, isLoading, processingSessions, selectedSession?.id]);
|
||||||
|
|
||||||
// "Load all" overlay
|
// "Load all" overlay
|
||||||
const prevLoadingRef = useRef(false);
|
const prevLoadingRef = useRef(false);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -733,6 +757,8 @@ export function useChatSessionState({
|
|||||||
const loadAllMessages = useCallback(async () => {
|
const loadAllMessages = useCallback(async () => {
|
||||||
if (!selectedSession || !selectedProject) return;
|
if (!selectedSession || !selectedProject) return;
|
||||||
if (isLoadingAllMessages) return;
|
if (isLoadingAllMessages) return;
|
||||||
|
const sessionProvider = selectedSession.__provider || 'claude';
|
||||||
|
|
||||||
const requestSessionId = selectedSession.id;
|
const requestSessionId = selectedSession.id;
|
||||||
allMessagesLoadedRef.current = true;
|
allMessagesLoadedRef.current = true;
|
||||||
isLoadingMoreRef.current = true;
|
isLoadingMoreRef.current = true;
|
||||||
@@ -745,6 +771,9 @@ export function useChatSessionState({
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const slot = await sessionStore.fetchFromServer(requestSessionId, {
|
const slot = await sessionStore.fetchFromServer(requestSessionId, {
|
||||||
|
provider: sessionProvider as LLMProvider,
|
||||||
|
projectId: selectedProject.projectId,
|
||||||
|
projectPath: selectedProject.fullPath || selectedProject.path || '',
|
||||||
limit: null,
|
limit: null,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
});
|
});
|
||||||
@@ -788,15 +817,16 @@ export function useChatSessionState({
|
|||||||
addMessage,
|
addMessage,
|
||||||
clearMessages,
|
clearMessages,
|
||||||
rewindMessages,
|
rewindMessages,
|
||||||
sessionActivity,
|
isLoading,
|
||||||
isProcessing,
|
setIsLoading,
|
||||||
canAbortSession,
|
|
||||||
currentSessionId,
|
currentSessionId,
|
||||||
setCurrentSessionId,
|
setCurrentSessionId,
|
||||||
isLoadingSessionMessages,
|
isLoadingSessionMessages,
|
||||||
isLoadingMoreMessages,
|
isLoadingMoreMessages,
|
||||||
hasMoreMessages,
|
hasMoreMessages,
|
||||||
totalMessages,
|
totalMessages,
|
||||||
|
canAbortSession,
|
||||||
|
setCanAbortSession,
|
||||||
isUserScrolledUp,
|
isUserScrolledUp,
|
||||||
setIsUserScrolledUp,
|
setIsUserScrolledUp,
|
||||||
tokenBudget,
|
tokenBudget,
|
||||||
@@ -809,6 +839,8 @@ export function useChatSessionState({
|
|||||||
isLoadingAllMessages,
|
isLoadingAllMessages,
|
||||||
loadAllJustFinished,
|
loadAllJustFinished,
|
||||||
showLoadAllOverlay,
|
showLoadAllOverlay,
|
||||||
|
claudeStatus,
|
||||||
|
setClaudeStatus,
|
||||||
createDiff,
|
createDiff,
|
||||||
scrollContainerRef,
|
scrollContainerRef,
|
||||||
scrollToBottom,
|
scrollToBottom,
|
||||||
|
|||||||
@@ -1,9 +1,4 @@
|
|||||||
import type { Project, ProjectSession, LLMProvider } from '../../../types/app';
|
import type { Project, ProjectSession, LLMProvider } from '../../../types/app';
|
||||||
import type {
|
|
||||||
MarkSessionIdle,
|
|
||||||
MarkSessionProcessing,
|
|
||||||
SessionActivityMap,
|
|
||||||
} from '../../../hooks/useSessionProtection';
|
|
||||||
|
|
||||||
export type Provider = LLMProvider;
|
export type Provider = LLMProvider;
|
||||||
|
|
||||||
@@ -107,24 +102,20 @@ export type SessionNavigationOptions = {
|
|||||||
replace?: boolean;
|
replace?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SessionEstablishedContext = {
|
|
||||||
provider: LLMProvider;
|
|
||||||
project: Project;
|
|
||||||
summary?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface ChatInterfaceProps {
|
export interface ChatInterfaceProps {
|
||||||
selectedProject: Project | null;
|
selectedProject: Project | null;
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
ws: WebSocket | null;
|
ws: WebSocket | null;
|
||||||
sendMessage: (message: unknown) => void;
|
sendMessage: (message: unknown) => void;
|
||||||
|
latestMessage: any;
|
||||||
onFileOpen?: (filePath: string, diffInfo?: any) => void;
|
onFileOpen?: (filePath: string, diffInfo?: any) => void;
|
||||||
onInputFocusChange?: (focused: boolean) => void;
|
onInputFocusChange?: (focused: boolean) => void;
|
||||||
onSessionProcessing?: MarkSessionProcessing;
|
onSessionActive?: (sessionId?: string | null) => void;
|
||||||
onSessionIdle?: MarkSessionIdle;
|
onSessionInactive?: (sessionId?: string | null) => void;
|
||||||
processingSessions?: SessionActivityMap;
|
onSessionProcessing?: (sessionId?: string | null) => void;
|
||||||
|
onSessionNotProcessing?: (sessionId?: string | null) => void;
|
||||||
|
processingSessions?: Set<string>;
|
||||||
onNavigateToSession?: (targetSessionId: string, options?: SessionNavigationOptions) => void;
|
onNavigateToSession?: (targetSessionId: string, options?: SessionNavigationOptions) => void;
|
||||||
onSessionEstablished?: (sessionId: string, context: SessionEstablishedContext) => void;
|
|
||||||
onShowSettings?: () => void;
|
onShowSettings?: () => void;
|
||||||
autoExpandTools?: boolean;
|
autoExpandTools?: boolean;
|
||||||
showRawParameters?: boolean;
|
showRawParameters?: boolean;
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ import React, { useCallback, useEffect, useMemo, useRef } from 'react';
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
import { useTasksSettings } from '../../../contexts/TasksSettingsContext';
|
import { useTasksSettings } from '../../../contexts/TasksSettingsContext';
|
||||||
import { useWebSocket } from '../../../contexts/WebSocketContext';
|
|
||||||
import PermissionContext from '../../../contexts/PermissionContext';
|
import PermissionContext from '../../../contexts/PermissionContext';
|
||||||
import { QuickSettingsPanel } from '../../quick-settings-panel';
|
import { QuickSettingsPanel } from '../../quick-settings-panel';
|
||||||
import type { ChatInterfaceProps, Provider } from '../types/types';
|
import type { ChatInterfaceProps, Provider } from '../types/types';
|
||||||
|
import type { LLMProvider } from '../../../types/app';
|
||||||
import { useChatProviderState } from '../hooks/useChatProviderState';
|
import { useChatProviderState } from '../hooks/useChatProviderState';
|
||||||
import { useChatSessionState } from '../hooks/useChatSessionState';
|
import { useChatSessionState } from '../hooks/useChatSessionState';
|
||||||
import { useChatRealtimeHandlers } from '../hooks/useChatRealtimeHandlers';
|
import { useChatRealtimeHandlers } from '../hooks/useChatRealtimeHandlers';
|
||||||
@@ -17,18 +17,24 @@ import ChatComposer from './subcomponents/ChatComposer';
|
|||||||
import CommandResultModal from './subcomponents/CommandResultModal';
|
import CommandResultModal from './subcomponents/CommandResultModal';
|
||||||
|
|
||||||
|
|
||||||
|
type PendingViewSession = {
|
||||||
|
startedAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
function ChatInterface({
|
function ChatInterface({
|
||||||
selectedProject,
|
selectedProject,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
ws,
|
ws,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
|
latestMessage,
|
||||||
onFileOpen,
|
onFileOpen,
|
||||||
onInputFocusChange,
|
onInputFocusChange,
|
||||||
|
onSessionActive,
|
||||||
|
onSessionInactive,
|
||||||
onSessionProcessing,
|
onSessionProcessing,
|
||||||
onSessionIdle,
|
onSessionNotProcessing,
|
||||||
processingSessions,
|
processingSessions,
|
||||||
onNavigateToSession,
|
onNavigateToSession,
|
||||||
onSessionEstablished,
|
|
||||||
onShowSettings,
|
onShowSettings,
|
||||||
autoExpandTools,
|
autoExpandTools,
|
||||||
showRawParameters,
|
showRawParameters,
|
||||||
@@ -40,19 +46,12 @@ function ChatInterface({
|
|||||||
onShowAllTasks,
|
onShowAllTasks,
|
||||||
}: ChatInterfaceProps) {
|
}: ChatInterfaceProps) {
|
||||||
const { tasksEnabled, isTaskMasterInstalled } = useTasksSettings();
|
const { tasksEnabled, isTaskMasterInstalled } = useTasksSettings();
|
||||||
const { subscribe } = useWebSocket();
|
|
||||||
const { t } = useTranslation('chat');
|
const { t } = useTranslation('chat');
|
||||||
|
|
||||||
const sessionStore = useSessionStore();
|
const sessionStore = useSessionStore();
|
||||||
const streamTimerRef = useRef<number | null>(null);
|
const streamTimerRef = useRef<number | null>(null);
|
||||||
const accumulatedStreamRef = useRef('');
|
const accumulatedStreamRef = useRef('');
|
||||||
// When each session's `chat.subscribe` was last sent; idle acks older than
|
const pendingViewSessionRef = useRef<PendingViewSession | null>(null);
|
||||||
// a later local request are discarded as stale.
|
|
||||||
const statusCheckSentAtRef = useRef(new Map<string, number>());
|
|
||||||
// Highest live `seq` observed per session. Written by the realtime handler
|
|
||||||
// on every sequenced frame, read whenever a `chat.subscribe` is sent so the
|
|
||||||
// server replays only the events this client actually missed.
|
|
||||||
const lastSeqRef = useRef(new Map<string, number>());
|
|
||||||
|
|
||||||
const resetStreamingState = useCallback(() => {
|
const resetStreamingState = useCallback(() => {
|
||||||
if (streamTimerRef.current) {
|
if (streamTimerRef.current) {
|
||||||
@@ -93,15 +92,16 @@ function ChatInterface({
|
|||||||
const {
|
const {
|
||||||
chatMessages,
|
chatMessages,
|
||||||
addMessage,
|
addMessage,
|
||||||
sessionActivity,
|
isLoading,
|
||||||
isProcessing,
|
setIsLoading,
|
||||||
canAbortSession,
|
|
||||||
currentSessionId,
|
currentSessionId,
|
||||||
setCurrentSessionId,
|
setCurrentSessionId,
|
||||||
isLoadingSessionMessages,
|
isLoadingSessionMessages,
|
||||||
isLoadingMoreMessages,
|
isLoadingMoreMessages,
|
||||||
hasMoreMessages,
|
hasMoreMessages,
|
||||||
totalMessages,
|
totalMessages,
|
||||||
|
canAbortSession,
|
||||||
|
setCanAbortSession,
|
||||||
isUserScrolledUp,
|
isUserScrolledUp,
|
||||||
setIsUserScrolledUp,
|
setIsUserScrolledUp,
|
||||||
tokenBudget,
|
tokenBudget,
|
||||||
@@ -114,6 +114,8 @@ function ChatInterface({
|
|||||||
isLoadingAllMessages,
|
isLoadingAllMessages,
|
||||||
loadAllJustFinished,
|
loadAllJustFinished,
|
||||||
showLoadAllOverlay,
|
showLoadAllOverlay,
|
||||||
|
claudeStatus,
|
||||||
|
setClaudeStatus,
|
||||||
createDiff,
|
createDiff,
|
||||||
scrollContainerRef,
|
scrollContainerRef,
|
||||||
scrollToBottom,
|
scrollToBottom,
|
||||||
@@ -128,22 +130,11 @@ function ChatInterface({
|
|||||||
externalMessageUpdate,
|
externalMessageUpdate,
|
||||||
newSessionTrigger,
|
newSessionTrigger,
|
||||||
processingSessions,
|
processingSessions,
|
||||||
onSessionIdle,
|
|
||||||
resetStreamingState,
|
resetStreamingState,
|
||||||
statusCheckSentAtRef,
|
pendingViewSessionRef,
|
||||||
lastSeqRef,
|
|
||||||
sessionStore,
|
sessionStore,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Brand-new conversation: the composer allocated a stable session id via
|
|
||||||
// the session gateway before the first send. Record it locally and put it
|
|
||||||
// in the URL — this id never changes again, so there is no later handoff.
|
|
||||||
const handleSessionEstablished = useCallback<NonNullable<ChatInterfaceProps['onSessionEstablished']>>((sessionId, context) => {
|
|
||||||
setCurrentSessionId(sessionId);
|
|
||||||
onSessionEstablished?.(sessionId, context);
|
|
||||||
onNavigateToSession?.(sessionId);
|
|
||||||
}, [setCurrentSessionId, onSessionEstablished, onNavigateToSession]);
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
input,
|
input,
|
||||||
setInput,
|
setInput,
|
||||||
@@ -200,58 +191,66 @@ function ChatInterface({
|
|||||||
codexModel,
|
codexModel,
|
||||||
geminiModel,
|
geminiModel,
|
||||||
opencodeModel,
|
opencodeModel,
|
||||||
isLoading: isProcessing,
|
isLoading,
|
||||||
canAbortSession,
|
canAbortSession,
|
||||||
tokenBudget,
|
tokenBudget,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
sendByCtrlEnter,
|
sendByCtrlEnter,
|
||||||
|
onSessionActive,
|
||||||
onSessionProcessing,
|
onSessionProcessing,
|
||||||
onSessionEstablished: handleSessionEstablished,
|
|
||||||
onInputFocusChange,
|
onInputFocusChange,
|
||||||
onFileOpen,
|
onFileOpen,
|
||||||
onShowSettings,
|
onShowSettings,
|
||||||
|
pendingViewSessionRef,
|
||||||
scrollToBottom,
|
scrollToBottom,
|
||||||
addMessage,
|
addMessage,
|
||||||
|
setIsLoading,
|
||||||
|
setCanAbortSession,
|
||||||
|
setClaudeStatus,
|
||||||
setIsUserScrolledUp,
|
setIsUserScrolledUp,
|
||||||
setPendingPermissionRequests,
|
setPendingPermissionRequests,
|
||||||
});
|
});
|
||||||
|
|
||||||
// On WebSocket reconnect, re-fetch the current session's messages from the
|
// On WebSocket reconnect, re-fetch the current session's messages from the server
|
||||||
// server so missed streaming events are shown, then re-subscribe — the
|
// so missed streaming events are shown. Also reset isLoading.
|
||||||
// `chat_subscribed` ack restores or clears the activity indicator, replays
|
|
||||||
// missed live events, and re-attaches a still-running stream to this socket.
|
|
||||||
const handleWebSocketReconnect = useCallback(async () => {
|
const handleWebSocketReconnect = useCallback(async () => {
|
||||||
if (!selectedProject || !selectedSession) return;
|
if (!selectedProject || !selectedSession) return;
|
||||||
await sessionStore.refreshFromServer(selectedSession.id);
|
const providerVal = (localStorage.getItem('selected-provider') as LLMProvider) || 'claude';
|
||||||
statusCheckSentAtRef.current.set(selectedSession.id, Date.now());
|
await sessionStore.refreshFromServer(selectedSession.id, {
|
||||||
sendMessage({
|
provider: (selectedSession.__provider || providerVal) as LLMProvider,
|
||||||
type: 'chat.subscribe',
|
// Use DB projectId; legacy folder-derived projectName is no longer accepted here.
|
||||||
sessions: [{
|
projectId: selectedProject.projectId,
|
||||||
sessionId: selectedSession.id,
|
projectPath: selectedProject.fullPath || selectedProject.path || '',
|
||||||
lastSeq: lastSeqRef.current.get(selectedSession.id) ?? 0,
|
|
||||||
}],
|
|
||||||
});
|
});
|
||||||
}, [selectedProject, selectedSession, sendMessage, sessionStore]);
|
setIsLoading(false);
|
||||||
|
setCanAbortSession(false);
|
||||||
|
}, [selectedProject, selectedSession, sessionStore, setIsLoading, setCanAbortSession]);
|
||||||
|
|
||||||
useChatRealtimeHandlers({
|
useChatRealtimeHandlers({
|
||||||
subscribe,
|
latestMessage,
|
||||||
provider,
|
provider,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
currentSessionId,
|
currentSessionId,
|
||||||
|
setCurrentSessionId,
|
||||||
|
setIsLoading,
|
||||||
|
setCanAbortSession,
|
||||||
|
setClaudeStatus,
|
||||||
setTokenBudget,
|
setTokenBudget,
|
||||||
setPendingPermissionRequests,
|
setPendingPermissionRequests,
|
||||||
|
pendingViewSessionRef,
|
||||||
streamTimerRef,
|
streamTimerRef,
|
||||||
accumulatedStreamRef,
|
accumulatedStreamRef,
|
||||||
lastSeqRef,
|
onSessionInactive,
|
||||||
statusCheckSentAtRef,
|
onSessionActive,
|
||||||
onSessionProcessing,
|
onSessionProcessing,
|
||||||
onSessionIdle,
|
onSessionNotProcessing,
|
||||||
|
onNavigateToSession,
|
||||||
onWebSocketReconnect: handleWebSocketReconnect,
|
onWebSocketReconnect: handleWebSocketReconnect,
|
||||||
sessionStore,
|
sessionStore,
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!canAbortSession) {
|
if (!isLoading || !canAbortSession) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,7 +267,7 @@ function ChatInterface({
|
|||||||
return () => {
|
return () => {
|
||||||
document.removeEventListener('keydown', handleGlobalEscape, { capture: true });
|
document.removeEventListener('keydown', handleGlobalEscape, { capture: true });
|
||||||
};
|
};
|
||||||
}, [canAbortSession, handleAbortSession]);
|
}, [canAbortSession, handleAbortSession, isLoading]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
@@ -315,7 +314,6 @@ function ChatInterface({
|
|||||||
onWheel={handleScroll}
|
onWheel={handleScroll}
|
||||||
onTouchMove={handleScroll}
|
onTouchMove={handleScroll}
|
||||||
isLoadingSessionMessages={isLoadingSessionMessages}
|
isLoadingSessionMessages={isLoadingSessionMessages}
|
||||||
isProcessing={isProcessing}
|
|
||||||
chatMessages={chatMessages}
|
chatMessages={chatMessages}
|
||||||
selectedSession={selectedSession}
|
selectedSession={selectedSession}
|
||||||
currentSessionId={currentSessionId}
|
currentSessionId={currentSessionId}
|
||||||
@@ -364,9 +362,10 @@ function ChatInterface({
|
|||||||
pendingPermissionRequests={pendingPermissionRequests}
|
pendingPermissionRequests={pendingPermissionRequests}
|
||||||
handlePermissionDecision={handlePermissionDecision}
|
handlePermissionDecision={handlePermissionDecision}
|
||||||
handleGrantToolPermission={handleGrantToolPermission}
|
handleGrantToolPermission={handleGrantToolPermission}
|
||||||
activity={sessionActivity}
|
claudeStatus={claudeStatus}
|
||||||
isLoading={isProcessing}
|
isLoading={isLoading}
|
||||||
onAbortSession={handleAbortSession}
|
onAbortSession={handleAbortSession}
|
||||||
|
provider={provider}
|
||||||
permissionMode={permissionMode}
|
permissionMode={permissionMode}
|
||||||
onModeSwitch={cyclePermissionMode}
|
onModeSwitch={cyclePermissionMode}
|
||||||
tokenBudget={tokenBudget}
|
tokenBudget={tokenBudget}
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
import { useEffect, useState } from 'react';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
|
||||||
|
|
||||||
import { Shimmer } from '../../../../shared/view/ui';
|
|
||||||
import type { SessionActivity } from '../../../../hooks/useSessionProtection';
|
|
||||||
|
|
||||||
type ActivityIndicatorProps = {
|
|
||||||
activity: SessionActivity | null;
|
|
||||||
onAbort?: () => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ACTION_KEYS = [
|
|
||||||
'claudeStatus.actions.thinking',
|
|
||||||
'claudeStatus.actions.processing',
|
|
||||||
'claudeStatus.actions.analyzing',
|
|
||||||
'claudeStatus.actions.working',
|
|
||||||
'claudeStatus.actions.computing',
|
|
||||||
'claudeStatus.actions.reasoning',
|
|
||||||
];
|
|
||||||
const DEFAULT_ACTION_WORDS = ['Thinking', 'Processing', 'Analyzing', 'Working', 'Computing', 'Reasoning'];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Minimal response-in-progress indicator, in the spirit of the inline status
|
|
||||||
* lines in Claude Code / Codex / OpenCode: a shimmering activity label, the
|
|
||||||
* elapsed time, and an interrupt affordance. Rendered only while the viewed
|
|
||||||
* session has an entry in the processing map; it disappears the instant that
|
|
||||||
* entry is removed.
|
|
||||||
*/
|
|
||||||
export default function ActivityIndicator({ activity, onAbort }: ActivityIndicatorProps) {
|
|
||||||
const { t } = useTranslation('chat');
|
|
||||||
const startedAt = activity?.startedAt ?? null;
|
|
||||||
const [elapsedSeconds, setElapsedSeconds] = useState(0);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (startedAt === null) return;
|
|
||||||
const update = () => setElapsedSeconds(Math.max(0, Math.floor((Date.now() - startedAt) / 1000)));
|
|
||||||
update();
|
|
||||||
const timer = setInterval(update, 1000);
|
|
||||||
return () => clearInterval(timer);
|
|
||||||
}, [startedAt]);
|
|
||||||
|
|
||||||
if (!activity) return null;
|
|
||||||
|
|
||||||
const actionWords = ACTION_KEYS.map((key, i) => t(key, { defaultValue: DEFAULT_ACTION_WORDS[i] }));
|
|
||||||
const label = (activity.statusText || actionWords[Math.floor(elapsedSeconds / 4) % actionWords.length])
|
|
||||||
.replace(/\.+$/, '');
|
|
||||||
|
|
||||||
const minutes = Math.floor(elapsedSeconds / 60);
|
|
||||||
const seconds = elapsedSeconds % 60;
|
|
||||||
const elapsedLabel = minutes < 1
|
|
||||||
? t('claudeStatus.elapsed.seconds', { count: seconds, defaultValue: '{{count}}s' })
|
|
||||||
: t('claudeStatus.elapsed.minutesSeconds', { minutes, seconds, defaultValue: '{{minutes}}m {{seconds}}s' });
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="animate-in fade-in mb-2 w-full duration-300">
|
|
||||||
<div className="mx-auto flex max-w-4xl items-center gap-2 px-1">
|
|
||||||
<span className="h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-primary" aria-hidden />
|
|
||||||
<Shimmer className="text-xs font-medium">{`${label}…`}</Shimmer>
|
|
||||||
<span className="text-xs tabular-nums text-muted-foreground/60">{elapsedLabel}</span>
|
|
||||||
|
|
||||||
{activity.canInterrupt && onAbort && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onAbort}
|
|
||||||
className="ml-auto flex items-center gap-1.5 rounded-md px-2 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
|
|
||||||
aria-label={t('claudeStatus.stop', { defaultValue: 'Stop' })}
|
|
||||||
>
|
|
||||||
<svg className="h-2.5 w-2.5 fill-current" viewBox="0 0 24 24" aria-hidden>
|
|
||||||
<rect x="5" y="5" width="14" height="14" rx="2" />
|
|
||||||
</svg>
|
|
||||||
<span>{t('claudeStatus.stop', { defaultValue: 'Stop' })}</span>
|
|
||||||
<kbd className="hidden rounded border border-border/60 px-1 text-[10px] text-muted-foreground/70 sm:inline-block">
|
|
||||||
esc
|
|
||||||
</kbd>
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -11,8 +11,7 @@ import type {
|
|||||||
} from 'react';
|
} from 'react';
|
||||||
import { ImageIcon, MessageSquareIcon, XIcon, ArrowDownIcon } from 'lucide-react';
|
import { ImageIcon, MessageSquareIcon, XIcon, ArrowDownIcon } from 'lucide-react';
|
||||||
|
|
||||||
import type { SessionActivity } from '../../../../hooks/useSessionProtection';
|
import type { PendingPermissionRequest, PermissionMode, Provider } from '../../types/types';
|
||||||
import type { PendingPermissionRequest, PermissionMode } from '../../types/types';
|
|
||||||
import {
|
import {
|
||||||
PromptInput,
|
PromptInput,
|
||||||
PromptInputHeader,
|
PromptInputHeader,
|
||||||
@@ -25,7 +24,7 @@ import {
|
|||||||
} from '../../../../shared/view/ui';
|
} from '../../../../shared/view/ui';
|
||||||
|
|
||||||
import CommandMenu from './CommandMenu';
|
import CommandMenu from './CommandMenu';
|
||||||
import ActivityIndicator from './ActivityIndicator';
|
import ClaudeStatus from './ClaudeStatus';
|
||||||
import ImageAttachment from './ImageAttachment';
|
import ImageAttachment from './ImageAttachment';
|
||||||
import PermissionRequestsBanner from './PermissionRequestsBanner';
|
import PermissionRequestsBanner from './PermissionRequestsBanner';
|
||||||
import TokenUsageSummary from './TokenUsageSummary';
|
import TokenUsageSummary from './TokenUsageSummary';
|
||||||
@@ -52,9 +51,10 @@ interface ChatComposerProps {
|
|||||||
decision: { allow?: boolean; message?: string; rememberEntry?: string | null; updatedInput?: unknown },
|
decision: { allow?: boolean; message?: string; rememberEntry?: string | null; updatedInput?: unknown },
|
||||||
) => void;
|
) => void;
|
||||||
handleGrantToolPermission: (suggestion: { entry: string; toolName: string }) => { success: boolean };
|
handleGrantToolPermission: (suggestion: { entry: string; toolName: string }) => { success: boolean };
|
||||||
activity: SessionActivity | null;
|
claudeStatus: { text: string; tokens: number; can_interrupt: boolean } | null;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
onAbortSession: () => void;
|
onAbortSession: () => void;
|
||||||
|
provider: Provider | string;
|
||||||
permissionMode: PermissionMode | string;
|
permissionMode: PermissionMode | string;
|
||||||
onModeSwitch: () => void;
|
onModeSwitch: () => void;
|
||||||
tokenBudget: Record<string, unknown> | null;
|
tokenBudget: Record<string, unknown> | null;
|
||||||
@@ -105,9 +105,10 @@ export default function ChatComposer({
|
|||||||
pendingPermissionRequests,
|
pendingPermissionRequests,
|
||||||
handlePermissionDecision,
|
handlePermissionDecision,
|
||||||
handleGrantToolPermission,
|
handleGrantToolPermission,
|
||||||
activity,
|
claudeStatus,
|
||||||
isLoading,
|
isLoading,
|
||||||
onAbortSession,
|
onAbortSession,
|
||||||
|
provider,
|
||||||
permissionMode,
|
permissionMode,
|
||||||
onModeSwitch,
|
onModeSwitch,
|
||||||
tokenBudget,
|
tokenBudget,
|
||||||
@@ -172,7 +173,12 @@ export default function ChatComposer({
|
|||||||
return (
|
return (
|
||||||
<div className="flex-shrink-0 p-2 pb-2 sm:p-4 sm:pb-4 md:p-4 md:pb-6">
|
<div className="flex-shrink-0 p-2 pb-2 sm:p-4 sm:pb-4 md:p-4 md:pb-6">
|
||||||
{!hasPendingPermissions && (
|
{!hasPendingPermissions && (
|
||||||
<ActivityIndicator activity={activity} onAbort={onAbortSession} />
|
<ClaudeStatus
|
||||||
|
status={claudeStatus}
|
||||||
|
isLoading={isLoading}
|
||||||
|
onAbort={onAbortSession}
|
||||||
|
provider={provider}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{pendingPermissionRequests.length > 0 && (
|
{pendingPermissionRequests.length > 0 && (
|
||||||
|
|||||||
@@ -19,8 +19,6 @@ interface ChatMessagesPaneProps {
|
|||||||
onWheel: () => void;
|
onWheel: () => void;
|
||||||
onTouchMove: () => void;
|
onTouchMove: () => void;
|
||||||
isLoadingSessionMessages: boolean;
|
isLoadingSessionMessages: boolean;
|
||||||
/** True while the viewed session has an active provider run in flight. */
|
|
||||||
isProcessing?: boolean;
|
|
||||||
chatMessages: ChatMessage[];
|
chatMessages: ChatMessage[];
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
currentSessionId: string | null;
|
currentSessionId: string | null;
|
||||||
@@ -70,7 +68,6 @@ export default function ChatMessagesPane({
|
|||||||
onWheel,
|
onWheel,
|
||||||
onTouchMove,
|
onTouchMove,
|
||||||
isLoadingSessionMessages,
|
isLoadingSessionMessages,
|
||||||
isProcessing = false,
|
|
||||||
chatMessages,
|
chatMessages,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
currentSessionId,
|
currentSessionId,
|
||||||
@@ -150,7 +147,7 @@ export default function ChatMessagesPane({
|
|||||||
onTouchMove={onTouchMove}
|
onTouchMove={onTouchMove}
|
||||||
className="relative flex-1 space-y-3 overflow-y-auto overflow-x-hidden px-0 py-3 sm:space-y-4 sm:p-4"
|
className="relative flex-1 space-y-3 overflow-y-auto overflow-x-hidden px-0 py-3 sm:space-y-4 sm:p-4"
|
||||||
>
|
>
|
||||||
{(isLoadingSessionMessages || isProcessing) && chatMessages.length === 0 ? (
|
{isLoadingSessionMessages && chatMessages.length === 0 ? (
|
||||||
<div className="mt-8 text-center text-gray-500 dark:text-gray-400">
|
<div className="mt-8 text-center text-gray-500 dark:text-gray-400">
|
||||||
<div className="flex items-center justify-center space-x-2">
|
<div className="flex items-center justify-center space-x-2">
|
||||||
<div className="h-4 w-4 animate-spin rounded-full border-b-2 border-gray-400" />
|
<div className="h-4 w-4 animate-spin rounded-full border-b-2 border-gray-400" />
|
||||||
|
|||||||
130
src/components/chat/view/subcomponents/ClaudeStatus.tsx
Normal file
130
src/components/chat/view/subcomponents/ClaudeStatus.tsx
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { cn } from '../../../../lib/utils';
|
||||||
|
import SessionProviderLogo from '../../../llm-logo-provider/SessionProviderLogo';
|
||||||
|
|
||||||
|
type ClaudeStatusProps = {
|
||||||
|
status: {
|
||||||
|
text?: string;
|
||||||
|
tokens?: number;
|
||||||
|
can_interrupt?: boolean;
|
||||||
|
} | null;
|
||||||
|
onAbort?: () => void;
|
||||||
|
isLoading: boolean;
|
||||||
|
provider?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const ACTION_KEYS = [
|
||||||
|
'claudeStatus.actions.thinking',
|
||||||
|
'claudeStatus.actions.processing',
|
||||||
|
'claudeStatus.actions.analyzing',
|
||||||
|
'claudeStatus.actions.working',
|
||||||
|
'claudeStatus.actions.computing',
|
||||||
|
'claudeStatus.actions.reasoning',
|
||||||
|
];
|
||||||
|
const DEFAULT_ACTION_WORDS = ['Thinking', 'Processing', 'Analyzing', 'Working', 'Computing', 'Reasoning'];
|
||||||
|
|
||||||
|
const PROVIDER_LABEL_KEYS: Record<string, string> = {
|
||||||
|
claude: 'messageTypes.claude',
|
||||||
|
codex: 'messageTypes.codex',
|
||||||
|
cursor: 'messageTypes.cursor',
|
||||||
|
gemini: 'messageTypes.gemini',
|
||||||
|
opencode: 'messageTypes.opencode',
|
||||||
|
};
|
||||||
|
|
||||||
|
function formatElapsedTime(totalSeconds: number) {
|
||||||
|
const mins = Math.floor(totalSeconds / 60);
|
||||||
|
const secs = totalSeconds % 60;
|
||||||
|
return mins < 1 ? `${secs}s` : `${mins}m ${secs}s`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ClaudeStatus({
|
||||||
|
status,
|
||||||
|
onAbort,
|
||||||
|
isLoading,
|
||||||
|
provider = 'claude',
|
||||||
|
}: ClaudeStatusProps) {
|
||||||
|
const { t } = useTranslation('chat');
|
||||||
|
const [elapsedTime, setElapsedTime] = useState(0);
|
||||||
|
const [dots, setDots] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isLoading) {
|
||||||
|
setElapsedTime(0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const startTime = Date.now();
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
setElapsedTime(Math.floor((Date.now() - startTime) / 1000));
|
||||||
|
}, 1000);
|
||||||
|
const dotTimer = setInterval(() => {
|
||||||
|
setDots((prev) => (prev.length >= 3 ? '' : prev + '.'));
|
||||||
|
}, 500);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearInterval(timer);
|
||||||
|
clearInterval(dotTimer);
|
||||||
|
};
|
||||||
|
}, [isLoading]);
|
||||||
|
|
||||||
|
if (!isLoading && !status) return null;
|
||||||
|
|
||||||
|
const actionWords = ACTION_KEYS.map((key, i) => t(key, { defaultValue: DEFAULT_ACTION_WORDS[i] }));
|
||||||
|
const statusText = (status?.text || actionWords[Math.floor(elapsedTime / 3) % actionWords.length]).replace(/[.]+$/, '');
|
||||||
|
|
||||||
|
const providerLabel = t(PROVIDER_LABEL_KEYS[provider] || 'claudeStatus.providers.assistant', { defaultValue: 'Assistant' });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="animate-in fade-in slide-in-from-bottom-2 mb-3 w-full duration-500">
|
||||||
|
<div className="mx-auto flex max-w-4xl items-center justify-between gap-3 overflow-hidden rounded-full border border-border/50 bg-slate-100 px-3 py-1.5 shadow-sm backdrop-blur-md dark:bg-slate-900">
|
||||||
|
|
||||||
|
{/* Left Side: Identity & Status */}
|
||||||
|
<div className="flex min-w-0 items-center gap-2.5">
|
||||||
|
<div className="relative flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/20 ring-1 ring-primary/10">
|
||||||
|
<SessionProviderLogo provider={provider} className="h-3.5 w-3.5" />
|
||||||
|
{isLoading && (
|
||||||
|
<span className="absolute inset-0 animate-pulse rounded-full ring-2 ring-emerald-500/20" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex min-w-0 flex-col sm:flex-row sm:items-center sm:gap-2">
|
||||||
|
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground/70">
|
||||||
|
{providerLabel}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className={cn("h-1.5 w-1.5 rounded-full", isLoading ? "bg-emerald-500 animate-pulse" : "bg-amber-500")} />
|
||||||
|
<p className="truncate text-xs font-medium text-foreground">
|
||||||
|
{statusText}<span className="inline-block w-4 text-primary">{isLoading ? dots : ''}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right Side: Metrics & Actions */}
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{isLoading && status?.can_interrupt !== false && onAbort && (
|
||||||
|
<>
|
||||||
|
<div className="hidden items-center rounded-md bg-muted/50 px-2 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground sm:flex">
|
||||||
|
{formatElapsedTime(elapsedTime)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onAbort}
|
||||||
|
className="group flex items-center gap-1.5 rounded-full bg-destructive/10 px-2.5 py-1 text-[10px] font-bold text-destructive transition-all hover:bg-destructive hover:text-destructive-foreground"
|
||||||
|
>
|
||||||
|
<svg className="h-3 w-3 fill-current" viewBox="0 0 24 24">
|
||||||
|
<path d="M6 6h12v12H6z" />
|
||||||
|
</svg>
|
||||||
|
<span className="hidden sm:inline">STOP</span>
|
||||||
|
<kbd className="hidden rounded bg-black/10 px-1 text-[9px] group-hover:bg-white/20 sm:block">
|
||||||
|
ESC
|
||||||
|
</kbd>
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,6 +11,10 @@ export type SessionResult = {
|
|||||||
|
|
||||||
interface SessionsResponse {
|
interface SessionsResponse {
|
||||||
sessions?: ProjectSession[];
|
sessions?: ProjectSession[];
|
||||||
|
cursorSessions?: ProjectSession[];
|
||||||
|
codexSessions?: ProjectSession[];
|
||||||
|
geminiSessions?: ProjectSession[];
|
||||||
|
opencodeSessions?: ProjectSession[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useSessionsSource(projectId: string | undefined, enabled: boolean) {
|
export function useSessionsSource(projectId: string | undefined, enabled: boolean) {
|
||||||
@@ -25,10 +29,17 @@ export function useSessionsSource(projectId: string | undefined, enabled: boolea
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
parse: (data) => {
|
parse: (data) => {
|
||||||
return (data.sessions ?? []).map<SessionResult>((s) => ({
|
const all: ProjectSession[] = [
|
||||||
|
...(data.sessions ?? []),
|
||||||
|
...(data.cursorSessions ?? []),
|
||||||
|
...(data.codexSessions ?? []),
|
||||||
|
...(data.geminiSessions ?? []),
|
||||||
|
...(data.opencodeSessions ?? []),
|
||||||
|
];
|
||||||
|
return all.map<SessionResult>((s) => ({
|
||||||
id: s.id,
|
id: s.id,
|
||||||
label: (s.title || s.summary || s.name || s.id) as string,
|
label: (s.title || s.summary || s.name || s.id) as string,
|
||||||
provider: (s.__provider || s.provider) as LLMProvider | undefined,
|
provider: s.__provider,
|
||||||
}));
|
}));
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,27 +1,14 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
type ClaudeLogoProps = {
|
type ClaudeLogoProps = {
|
||||||
className?: string;
|
className?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const ClaudeLogo = ({ className = 'w-5 h-5' }: ClaudeLogoProps) => (
|
const ClaudeLogo = ({ className = 'w-5 h-5' }: ClaudeLogoProps) => {
|
||||||
<svg
|
return (
|
||||||
viewBox="0 0 512 509.64"
|
<img src="/icons/claude-ai-icon.svg" alt="Claude" className={className} />
|
||||||
role="img"
|
);
|
||||||
aria-label="Claude"
|
};
|
||||||
className={className}
|
|
||||||
fill="none"
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
fill="#D77655"
|
|
||||||
d="M115.612 0h280.775C459.974 0 512 52.026 512 115.612v278.415c0 63.587-52.026 115.612-115.613 115.612H115.612C52.026 509.639 0 457.614 0 394.027V115.612C0 52.026 52.026 0 115.612 0z"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
fill="#FCF2EE"
|
|
||||||
fillRule="nonzero"
|
|
||||||
d="M142.27 316.619l73.655-41.326 1.238-3.589-1.238-1.996-3.589-.001-12.31-.759-42.084-1.138-36.498-1.516-35.361-1.896-8.897-1.895-8.34-10.995.859-5.484 7.482-5.03 10.717.935 23.683 1.617 35.537 2.452 25.782 1.517 38.193 3.968h6.064l.86-2.451-2.073-1.517-1.618-1.517-36.776-24.922-39.81-26.338-20.852-15.166-11.273-7.683-5.687-7.204-2.451-15.721 10.237-11.273 13.75.935 3.513.936 13.928 10.716 29.749 23.027 38.848 28.612 5.687 4.727 2.275-1.617.278-1.138-2.553-4.271-21.13-38.193-22.546-38.848-10.035-16.101-2.654-9.655c-.935-3.968-1.617-7.304-1.617-11.374l11.652-15.823 6.445-2.073 15.545 2.073 6.547 5.687 9.655 22.092 15.646 34.78 24.265 47.291 7.103 14.028 3.791 12.992 1.416 3.968 2.449-.001v-2.275l1.997-26.641 3.69-32.707 3.589-42.084 1.239-11.854 5.863-14.206 11.652-7.683 9.099 4.348 7.482 10.716-1.036 6.926-4.449 28.915-8.72 45.294-5.687 30.331h3.313l3.792-3.791 15.342-20.372 25.782-32.227 11.374-12.789 13.27-14.129 8.517-6.724 16.1-.001 11.854 17.617-5.307 18.199-16.581 21.029-13.75 17.819-19.716 26.54-12.309 21.231 1.138 1.694 2.932-.278 44.536-9.479 24.062-4.347 28.714-4.928 12.992 6.066 1.416 6.167-5.106 12.613-30.71 7.583-36.018 7.204-53.636 12.689-.657.48.758.935 24.164 2.275 10.337.556h25.301l47.114 3.514 12.309 8.139 7.381 9.959-1.238 7.583-18.957 9.655-25.579-6.066-59.702-14.205-20.474-5.106-2.83-.001v1.694l17.061 16.682 31.266 28.233 39.152 36.397 1.997 8.999-5.03 7.102-5.307-.758-34.401-25.883-13.27-11.651-30.053-25.302-1.996-.001v2.654l6.926 10.136 36.574 54.975 1.895 16.859-2.653 5.485-9.479 3.311-10.414-1.895-21.408-30.054-22.092-33.844-17.819-30.331-2.173 1.238-10.515 113.261-4.929 5.788-11.374 4.348-9.478-7.204-5.03-11.652 5.03-23.027 6.066-30.052 4.928-23.886 4.449-29.674 2.654-9.858-.177-.657-2.173.278-22.37 30.71-34.021 45.977-26.919 28.815-6.445 2.553-11.173-5.789 1.037-10.337 6.243-9.2 37.257-47.392 22.47-29.371 14.508-16.961-.101-2.451h-.859l-98.954 64.251-17.618 2.275-7.583-7.103.936-11.652 3.589-3.791 29.749-20.474-.101.102.024.101z"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
export default ClaudeLogo;
|
export default ClaudeLogo;
|
||||||
|
|
||||||
|
|||||||
@@ -1,21 +1,20 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useTheme } from '../../contexts/ThemeContext';
|
||||||
|
|
||||||
type CodexLogoProps = {
|
type CodexLogoProps = {
|
||||||
className?: string;
|
className?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const CodexLogo = ({ className = 'w-5 h-5' }: CodexLogoProps) => (
|
const CodexLogo = ({ className = 'w-5 h-5' }: CodexLogoProps) => {
|
||||||
<svg
|
const { isDarkMode } = useTheme();
|
||||||
viewBox="100 100 520 520"
|
|
||||||
role="img"
|
return (
|
||||||
aria-label="Codex"
|
<img
|
||||||
className={className}
|
src={isDarkMode ? "/icons/codex-white.svg" : "/icons/codex.svg"}
|
||||||
fill="none"
|
alt="Codex"
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
className={className}
|
||||||
>
|
|
||||||
<path
|
|
||||||
d="M304.246 294.611V249.028C304.246 245.189 305.687 242.309 309.044 240.392L400.692 187.612C413.167 180.415 428.042 177.058 443.394 177.058C500.971 177.058 537.44 221.682 537.44 269.182C537.44 272.54 537.44 276.379 536.959 280.218L441.954 224.558C436.197 221.201 430.437 221.201 424.68 224.558L304.246 294.611ZM518.245 472.145V363.224C518.245 356.505 515.364 351.707 509.608 348.349L389.174 278.296L428.519 255.743C431.877 253.826 434.757 253.826 438.115 255.743L529.762 308.523C556.154 323.879 573.905 356.505 573.905 388.171C573.905 424.636 552.315 458.225 518.245 472.141V472.145ZM275.937 376.182L236.592 353.152C233.235 351.235 231.794 348.354 231.794 344.515V238.956C231.794 187.617 271.139 148.749 324.4 148.749C344.555 148.749 363.264 155.468 379.102 167.463L284.578 222.164C278.822 225.521 275.942 230.319 275.942 237.039V376.186L275.937 376.182ZM360.626 425.122L304.246 393.455V326.283L360.626 294.616L417.002 326.283V393.455L360.626 425.122ZM396.852 570.989C376.698 570.989 357.989 564.27 342.151 552.276L436.674 497.574C442.431 494.217 445.311 489.419 445.311 482.699V343.552L485.138 366.582C488.495 368.499 489.936 371.379 489.936 375.219V480.778C489.936 532.117 450.109 570.985 396.852 570.985V570.989ZM283.134 463.99L191.486 411.211C165.094 395.854 147.343 363.229 147.343 331.562C147.343 294.616 169.415 261.509 203.48 247.593V356.991C203.48 363.71 206.361 368.508 212.117 371.866L332.074 441.437L292.729 463.99C289.372 465.907 286.491 465.907 283.134 463.99ZM277.859 542.68C223.639 542.68 183.813 501.895 183.813 451.514C183.813 447.675 184.294 443.836 184.771 439.997L279.295 494.698C285.051 498.056 290.812 498.056 296.568 494.698L417.002 425.127V470.71C417.002 474.549 415.562 477.429 412.204 479.346L320.557 532.126C308.081 539.323 293.206 542.68 277.854 542.68H277.859ZM396.852 599.776C454.911 599.776 503.37 558.513 514.41 503.812C568.149 489.896 602.696 439.515 602.696 388.176C602.696 354.587 588.303 321.962 562.392 298.45C564.791 288.373 566.231 278.296 566.231 268.224C566.231 199.611 510.571 148.267 446.274 148.267C433.322 148.267 420.846 150.184 408.37 154.505C386.775 133.392 357.026 119.958 324.4 119.958C266.342 119.958 217.883 161.22 206.843 215.921C153.104 229.837 118.557 280.218 118.557 331.557C118.557 365.146 132.95 397.771 158.861 421.283C156.462 431.36 155.022 441.437 155.022 451.51C155.022 520.123 210.682 571.466 274.978 571.466C287.931 571.466 300.407 569.549 312.883 565.228C334.473 586.341 364.222 599.776 396.852 599.776Z"
|
|
||||||
fill="currentColor"
|
|
||||||
/>
|
/>
|
||||||
</svg>
|
);
|
||||||
);
|
};
|
||||||
|
|
||||||
export default CodexLogo;
|
export default CodexLogo;
|
||||||
|
|||||||
@@ -1,26 +1,20 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useTheme } from '../../contexts/ThemeContext';
|
||||||
|
|
||||||
type CursorLogoProps = {
|
type CursorLogoProps = {
|
||||||
className?: string;
|
className?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const CursorLogo = ({ className = 'w-5 h-5' }: CursorLogoProps) => (
|
const CursorLogo = ({ className = 'w-5 h-5' }: CursorLogoProps) => {
|
||||||
<svg
|
const { isDarkMode } = useTheme();
|
||||||
viewBox="0 0 24 24"
|
|
||||||
role="img"
|
return (
|
||||||
aria-label="Cursor"
|
<img
|
||||||
className={className}
|
src={isDarkMode ? "/icons/cursor-white.svg" : "/icons/cursor.svg"}
|
||||||
fill="none"
|
alt="Cursor"
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
className={className}
|
||||||
>
|
|
||||||
<path
|
|
||||||
d="M11.925 24l10.425-6-10.425-6L1.5 18l10.425 6z"
|
|
||||||
fill="currentColor"
|
|
||||||
opacity=".39"
|
|
||||||
/>
|
/>
|
||||||
<path d="M22.35 18V6L11.925 0v12l10.425 6z" fill="currentColor" opacity=".8" />
|
);
|
||||||
<path d="M11.925 0L1.5 6v12l10.425-6V0z" fill="currentColor" opacity=".6" />
|
};
|
||||||
<path d="M22.35 6L11.925 24V12L22.35 6z" fill="currentColor" opacity=".72" />
|
|
||||||
<path d="M22.35 6l-10.425 6L1.5 6h20.85z" fill="currentColor" opacity=".95" />
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
export default CursorLogo;
|
export default CursorLogo;
|
||||||
|
|||||||
@@ -1,263 +1,7 @@
|
|||||||
import { useId } from 'react';
|
const GeminiLogo = ({className = 'w-5 h-5'}) => {
|
||||||
|
|
||||||
type GeminiLogoProps = {
|
|
||||||
className?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const GeminiLogo = ({ className = 'w-5 h-5' }: GeminiLogoProps) => {
|
|
||||||
const id = useId().replace(/:/g, '');
|
|
||||||
const maskId = `${id}-gemini-mask`;
|
|
||||||
const gradientId = `${id}-gemini-gradient`;
|
|
||||||
const filterIds = Array.from({ length: 11 }, (_, index) => `${id}-gemini-filter-${index}`);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<svg
|
<img src="/icons/gemini-ai-icon.svg" alt="Gemini" className={className} />
|
||||||
viewBox="0 0 65 65"
|
|
||||||
role="img"
|
|
||||||
aria-label="Gemini"
|
|
||||||
className={className}
|
|
||||||
fill="none"
|
|
||||||
xmlns="http://www.w3.org/2000/svg"
|
|
||||||
>
|
|
||||||
<mask
|
|
||||||
id={maskId}
|
|
||||||
style={{ maskType: 'alpha' }}
|
|
||||||
maskUnits="userSpaceOnUse"
|
|
||||||
x="0"
|
|
||||||
y="0"
|
|
||||||
width="65"
|
|
||||||
height="65"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
d="M32.447 0c.68 0 1.273.465 1.439 1.125a38.904 38.904 0 001.999 5.905c2.152 5 5.105 9.376 8.854 13.125 3.751 3.75 8.126 6.703 13.125 8.855a38.98 38.98 0 005.906 1.999c.66.166 1.124.758 1.124 1.438 0 .68-.464 1.273-1.125 1.439a38.902 38.902 0 00-5.905 1.999c-5 2.152-9.375 5.105-13.125 8.854-3.749 3.751-6.702 8.126-8.854 13.125a38.973 38.973 0 00-2 5.906 1.485 1.485 0 01-1.438 1.124c-.68 0-1.272-.464-1.438-1.125a38.913 38.913 0 00-2-5.905c-2.151-5-5.103-9.375-8.854-13.125-3.75-3.749-8.125-6.702-13.125-8.854a38.973 38.973 0 00-5.905-2A1.485 1.485 0 010 32.448c0-.68.465-1.272 1.125-1.438a38.903 38.903 0 005.905-2c5-2.151 9.376-5.104 13.125-8.854 3.75-3.749 6.703-8.125 8.855-13.125a38.972 38.972 0 001.999-5.905A1.485 1.485 0 0132.447 0z"
|
|
||||||
fill="#000"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M32.447 0c.68 0 1.273.465 1.439 1.125a38.904 38.904 0 001.999 5.905c2.152 5 5.105 9.376 8.854 13.125 3.751 3.75 8.126 6.703 13.125 8.855a38.98 38.98 0 005.906 1.999c.66.166 1.124.758 1.124 1.438 0 .68-.464 1.273-1.125 1.439a38.902 38.902 0 00-5.905 1.999c-5 2.152-9.375 5.105-13.125 8.854-3.749 3.751-6.702 8.126-8.854 13.125a38.973 38.973 0 00-2 5.906 1.485 1.485 0 01-1.438 1.124c-.68 0-1.272-.464-1.438-1.125a38.913 38.913 0 00-2-5.905c-2.151-5-5.103-9.375-8.854-13.125-3.75-3.749-8.125-6.702-13.125-8.854a38.973 38.973 0 00-5.905-2A1.485 1.485 0 010 32.448c0-.68.465-1.272 1.125-1.438a38.903 38.903 0 005.905-2c5-2.151 9.376-5.104 13.125-8.854 3.75-3.749 6.703-8.125 8.855-13.125a38.972 38.972 0 001.999-5.905A1.485 1.485 0 0132.447 0z"
|
|
||||||
fill={`url(#${gradientId})`}
|
|
||||||
/>
|
|
||||||
</mask>
|
|
||||||
<g mask={`url(#${maskId})`}>
|
|
||||||
<g filter={`url(#${filterIds[0]})`}>
|
|
||||||
<path
|
|
||||||
d="M-5.859 50.734c7.498 2.663 16.116-2.33 19.249-11.152 3.133-8.821-.406-18.131-7.904-20.794-7.498-2.663-16.116 2.33-19.25 11.151-3.132 8.822.407 18.132 7.905 20.795z"
|
|
||||||
fill="#FFE432"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[1]})`}>
|
|
||||||
<path
|
|
||||||
d="M27.433 21.649c10.3 0 18.651-8.535 18.651-19.062 0-10.528-8.35-19.062-18.651-19.062S8.78-7.94 8.78 2.587c0 10.527 8.35 19.062 18.652 19.062z"
|
|
||||||
fill="#FC413D"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[2]})`}>
|
|
||||||
<path
|
|
||||||
d="M20.184 82.608c10.753-.525 18.918-12.244 18.237-26.174-.68-13.93-9.95-24.797-20.703-24.271C6.965 32.689-1.2 44.407-.519 58.337c.681 13.93 9.95 24.797 20.703 24.271z"
|
|
||||||
fill="#00B95C"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[3]})`}>
|
|
||||||
<path
|
|
||||||
d="M20.184 82.608c10.753-.525 18.918-12.244 18.237-26.174-.68-13.93-9.95-24.797-20.703-24.271C6.965 32.689-1.2 44.407-.519 58.337c.681 13.93 9.95 24.797 20.703 24.271z"
|
|
||||||
fill="#00B95C"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[4]})`}>
|
|
||||||
<path
|
|
||||||
d="M30.954 74.181c9.014-5.485 11.427-17.976 5.389-27.9-6.038-9.925-18.241-13.524-27.256-8.04-9.015 5.486-11.428 17.977-5.39 27.902 6.04 9.924 18.242 13.523 27.257 8.038z"
|
|
||||||
fill="#00B95C"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[5]})`}>
|
|
||||||
<path
|
|
||||||
d="M67.391 42.993c10.132 0 18.346-7.91 18.346-17.666 0-9.757-8.214-17.667-18.346-17.667s-18.346 7.91-18.346 17.667c0 9.757 8.214 17.666 18.346 17.666z"
|
|
||||||
fill="#3186FF"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[6]})`}>
|
|
||||||
<path
|
|
||||||
d="M-13.065 40.944c9.33 7.094 22.959 4.869 30.442-4.972 7.483-9.84 5.987-23.569-3.343-30.663C4.704-1.786-8.924.439-16.408 10.28c-7.483 9.84-5.986 23.57 3.343 30.664z"
|
|
||||||
fill="#FBBC04"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[7]})`}>
|
|
||||||
<path
|
|
||||||
d="M34.74 51.43c11.135 7.656 25.896 5.524 32.968-4.764 7.073-10.287 3.779-24.832-7.357-32.488C49.215 6.52 34.455 8.654 27.382 18.94c-7.072 10.288-3.779 24.833 7.357 32.49z"
|
|
||||||
fill="#3186FF"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[8]})`}>
|
|
||||||
<path
|
|
||||||
d="M54.984-2.336c2.833 3.852-.808 11.34-8.131 16.727-7.324 5.387-15.557 6.631-18.39 2.78-2.833-3.853.807-11.342 8.13-16.728 7.324-5.387 15.558-6.631 18.39-2.78z"
|
|
||||||
fill="#749BFF"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[9]})`}>
|
|
||||||
<path
|
|
||||||
d="M31.727 16.104C43.053 5.598 46.94-8.626 40.41-15.666c-6.53-7.04-21.006-4.232-32.332 6.274s-15.214 24.73-8.683 31.77c6.53 7.04 21.006 4.232 32.332-6.274z"
|
|
||||||
fill="#FC413D"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<g filter={`url(#${filterIds[10]})`}>
|
|
||||||
<path
|
|
||||||
d="M8.51 53.838c6.732 4.818 14.46 5.55 17.262 1.636 2.802-3.915-.384-10.994-7.116-15.812-6.731-4.818-14.46-5.55-17.261-1.636-2.802 3.915.383 10.994 7.115 15.812z"
|
|
||||||
fill="#FFEE48"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
</g>
|
|
||||||
<defs>
|
|
||||||
<filter
|
|
||||||
id={filterIds[0]}
|
|
||||||
x="-19.824"
|
|
||||||
y="13.152"
|
|
||||||
width="39.274"
|
|
||||||
height="43.217"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="2.46" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[1]}
|
|
||||||
x="-15.001"
|
|
||||||
y="-40.257"
|
|
||||||
width="84.868"
|
|
||||||
height="85.688"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="11.891" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[2]}
|
|
||||||
x="-20.776"
|
|
||||||
y="11.927"
|
|
||||||
width="79.454"
|
|
||||||
height="90.916"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="10.109" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[3]}
|
|
||||||
x="-20.776"
|
|
||||||
y="11.927"
|
|
||||||
width="79.454"
|
|
||||||
height="90.916"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="10.109" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[4]}
|
|
||||||
x="-19.845"
|
|
||||||
y="15.459"
|
|
||||||
width="79.731"
|
|
||||||
height="81.505"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="10.109" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[5]}
|
|
||||||
x="29.832"
|
|
||||||
y="-11.552"
|
|
||||||
width="75.117"
|
|
||||||
height="73.758"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="9.606" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[6]}
|
|
||||||
x="-38.583"
|
|
||||||
y="-16.253"
|
|
||||||
width="78.135"
|
|
||||||
height="78.758"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="8.706" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[7]}
|
|
||||||
x="8.107"
|
|
||||||
y="-5.966"
|
|
||||||
width="78.877"
|
|
||||||
height="77.539"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="7.775" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[8]}
|
|
||||||
x="13.587"
|
|
||||||
y="-18.488"
|
|
||||||
width="56.272"
|
|
||||||
height="51.81"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="6.957" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[9]}
|
|
||||||
x="-15.526"
|
|
||||||
y="-31.297"
|
|
||||||
width="70.856"
|
|
||||||
height="69.306"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="5.876" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<filter
|
|
||||||
id={filterIds[10]}
|
|
||||||
x="-14.168"
|
|
||||||
y="20.964"
|
|
||||||
width="55.501"
|
|
||||||
height="51.571"
|
|
||||||
filterUnits="userSpaceOnUse"
|
|
||||||
colorInterpolationFilters="sRGB"
|
|
||||||
>
|
|
||||||
<feFlood floodOpacity="0" result="BackgroundImageFix" />
|
|
||||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
|
|
||||||
<feGaussianBlur stdDeviation="7.273" result="effect1_foregroundBlur_2001_67" />
|
|
||||||
</filter>
|
|
||||||
<linearGradient id={gradientId} x1="18.447" x2="52.153" y1="43.42" y2="15.004" gradientUnits="userSpaceOnUse">
|
|
||||||
<stop stopColor="#4893FC" />
|
|
||||||
<stop offset=".27" stopColor="#4893FC" />
|
|
||||||
<stop offset=".777" stopColor="#969DFF" />
|
|
||||||
<stop offset="1" stopColor="#BD99FE" />
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
</svg>
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default GeminiLogo;
|
export default GeminiLogo;
|
||||||
@@ -1,12 +1,9 @@
|
|||||||
import type { Dispatch, SetStateAction } from 'react';
|
import type { Dispatch, SetStateAction } from 'react';
|
||||||
|
|
||||||
import type { AppTab, Project, ProjectSession } from '../../../types/app';
|
import type { AppTab, Project, ProjectSession } from '../../../types/app';
|
||||||
import type {
|
import type { SessionNavigationOptions } from '../../chat/types/types';
|
||||||
MarkSessionIdle,
|
|
||||||
MarkSessionProcessing,
|
export type SessionLifecycleHandler = (sessionId?: string | null) => void;
|
||||||
SessionActivityMap,
|
|
||||||
} from '../../../hooks/useSessionProtection';
|
|
||||||
import type { SessionEstablishedContext, SessionNavigationOptions } from '../../chat/types/types';
|
|
||||||
|
|
||||||
export type TaskMasterTask = {
|
export type TaskMasterTask = {
|
||||||
id: string | number;
|
id: string | number;
|
||||||
@@ -44,15 +41,17 @@ export type MainContentProps = {
|
|||||||
setActiveTab: Dispatch<SetStateAction<AppTab>>;
|
setActiveTab: Dispatch<SetStateAction<AppTab>>;
|
||||||
ws: WebSocket | null;
|
ws: WebSocket | null;
|
||||||
sendMessage: (message: unknown) => void;
|
sendMessage: (message: unknown) => void;
|
||||||
|
latestMessage: unknown;
|
||||||
isMobile: boolean;
|
isMobile: boolean;
|
||||||
onMenuClick: () => void;
|
onMenuClick: () => void;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
onInputFocusChange: (focused: boolean) => void;
|
onInputFocusChange: (focused: boolean) => void;
|
||||||
onSessionProcessing: MarkSessionProcessing;
|
onSessionActive: SessionLifecycleHandler;
|
||||||
onSessionIdle: MarkSessionIdle;
|
onSessionInactive: SessionLifecycleHandler;
|
||||||
processingSessions: SessionActivityMap;
|
onSessionProcessing: SessionLifecycleHandler;
|
||||||
|
onSessionNotProcessing: SessionLifecycleHandler;
|
||||||
|
processingSessions: Set<string>;
|
||||||
onNavigateToSession: (targetSessionId: string, options?: SessionNavigationOptions) => void;
|
onNavigateToSession: (targetSessionId: string, options?: SessionNavigationOptions) => void;
|
||||||
onSessionEstablished: (sessionId: string, context: SessionEstablishedContext) => void;
|
|
||||||
onShowSettings: () => void;
|
onShowSettings: () => void;
|
||||||
externalMessageUpdate: number;
|
externalMessageUpdate: number;
|
||||||
newSessionTrigger: number;
|
newSessionTrigger: number;
|
||||||
|
|||||||
@@ -37,15 +37,17 @@ function MainContent({
|
|||||||
setActiveTab,
|
setActiveTab,
|
||||||
ws,
|
ws,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
|
latestMessage,
|
||||||
isMobile,
|
isMobile,
|
||||||
onMenuClick,
|
onMenuClick,
|
||||||
isLoading,
|
isLoading,
|
||||||
onInputFocusChange,
|
onInputFocusChange,
|
||||||
|
onSessionActive,
|
||||||
|
onSessionInactive,
|
||||||
onSessionProcessing,
|
onSessionProcessing,
|
||||||
onSessionIdle,
|
onSessionNotProcessing,
|
||||||
processingSessions,
|
processingSessions,
|
||||||
onNavigateToSession,
|
onNavigateToSession,
|
||||||
onSessionEstablished,
|
|
||||||
onShowSettings,
|
onShowSettings,
|
||||||
externalMessageUpdate,
|
externalMessageUpdate,
|
||||||
newSessionTrigger,
|
newSessionTrigger,
|
||||||
@@ -126,13 +128,15 @@ function MainContent({
|
|||||||
selectedSession={selectedSession}
|
selectedSession={selectedSession}
|
||||||
ws={ws}
|
ws={ws}
|
||||||
sendMessage={sendMessage}
|
sendMessage={sendMessage}
|
||||||
|
latestMessage={latestMessage}
|
||||||
onFileOpen={handleFileOpen}
|
onFileOpen={handleFileOpen}
|
||||||
onInputFocusChange={onInputFocusChange}
|
onInputFocusChange={onInputFocusChange}
|
||||||
|
onSessionActive={onSessionActive}
|
||||||
|
onSessionInactive={onSessionInactive}
|
||||||
onSessionProcessing={onSessionProcessing}
|
onSessionProcessing={onSessionProcessing}
|
||||||
onSessionIdle={onSessionIdle}
|
onSessionNotProcessing={onSessionNotProcessing}
|
||||||
processingSessions={processingSessions}
|
processingSessions={processingSessions}
|
||||||
onNavigateToSession={onNavigateToSession}
|
onNavigateToSession={onNavigateToSession}
|
||||||
onSessionEstablished={onSessionEstablished}
|
|
||||||
onShowSettings={onShowSettings}
|
onShowSettings={onShowSettings}
|
||||||
autoExpandTools={autoExpandTools}
|
autoExpandTools={autoExpandTools}
|
||||||
showRawParameters={showRawParameters}
|
showRawParameters={showRawParameters}
|
||||||
|
|||||||
@@ -4,11 +4,14 @@ import {
|
|||||||
Activity,
|
Activity,
|
||||||
BarChart3,
|
BarChart3,
|
||||||
BookOpen,
|
BookOpen,
|
||||||
|
Calculator,
|
||||||
Clock,
|
Clock,
|
||||||
Download,
|
Download,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
|
Github,
|
||||||
GitBranch,
|
GitBranch,
|
||||||
Loader2,
|
Loader2,
|
||||||
|
ListTodo,
|
||||||
RefreshCw,
|
RefreshCw,
|
||||||
ServerCrash,
|
ServerCrash,
|
||||||
ShieldAlert,
|
ShieldAlert,
|
||||||
@@ -27,6 +30,10 @@ const TERMINAL_PLUGIN_URL = 'https://github.com/cloudcli-ai/cloudcli-plugin-term
|
|||||||
const SCHEDULED_PROMPT_PLUGIN_URL = 'https://github.com/grostim/cloudcli-cron';
|
const SCHEDULED_PROMPT_PLUGIN_URL = 'https://github.com/grostim/cloudcli-cron';
|
||||||
const CLAUDE_WATCH_PLUGIN_URL = 'https://github.com/satsuki19980613/cloudcli-claude-watch';
|
const CLAUDE_WATCH_PLUGIN_URL = 'https://github.com/satsuki19980613/cloudcli-claude-watch';
|
||||||
const PRISM_CLOUDCLI_PLUGIN_URL = 'https://github.com/jakeefr/cloudcli-plugin-prism';
|
const PRISM_CLOUDCLI_PLUGIN_URL = 'https://github.com/jakeefr/cloudcli-plugin-prism';
|
||||||
|
const SESSION_MANAGER_PLUGIN_URL = 'https://github.com/strykereye2/cloudcli-plugin-session-manager';
|
||||||
|
const TOKEN_COST_CALCULATOR_PLUGIN_URL = 'https://github.com/NightmareAway/cloudcli-plugin-token-cost-calculator';
|
||||||
|
const TASK_QUEUE_PLUGIN_URL = 'https://github.com/TadMSTR/cloudcli-plugin-task-queue';
|
||||||
|
const GITHUB_ISSUES_BOARD_PLUGIN_URL = 'https://github.com/szmidtpiotr/claude-github-issue';
|
||||||
|
|
||||||
type PluginRecommendation = {
|
type PluginRecommendation = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -79,8 +86,40 @@ const UNOFFICIAL_PLUGIN_RECOMMENDATIONS: PluginRecommendation[] = [
|
|||||||
repoUrl: PRISM_CLOUDCLI_PLUGIN_URL,
|
repoUrl: PRISM_CLOUDCLI_PLUGIN_URL,
|
||||||
installedNames: ['prism'],
|
installedNames: ['prism'],
|
||||||
icon: Activity,
|
icon: Activity,
|
||||||
source: 'unofficial'
|
source: 'unofficial',
|
||||||
}
|
},
|
||||||
|
{
|
||||||
|
id: 'session-manager',
|
||||||
|
translationKey: 'sessionManagerPlugin',
|
||||||
|
repoUrl: SESSION_MANAGER_PLUGIN_URL,
|
||||||
|
installedNames: ['session-manager'],
|
||||||
|
icon: Activity,
|
||||||
|
source: 'unofficial',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'token-cost-calculator',
|
||||||
|
translationKey: 'tokenCostCalculatorPlugin',
|
||||||
|
repoUrl: TOKEN_COST_CALCULATOR_PLUGIN_URL,
|
||||||
|
installedNames: ['token-cost-calculator'],
|
||||||
|
icon: Calculator,
|
||||||
|
source: 'unofficial',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'task-queue',
|
||||||
|
translationKey: 'taskQueuePlugin',
|
||||||
|
repoUrl: TASK_QUEUE_PLUGIN_URL,
|
||||||
|
installedNames: ['task-queue'],
|
||||||
|
icon: ListTodo,
|
||||||
|
source: 'unofficial',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'claude-github-issue',
|
||||||
|
translationKey: 'githubIssuesBoardPlugin',
|
||||||
|
repoUrl: GITHUB_ISSUES_BOARD_PLUGIN_URL,
|
||||||
|
installedNames: ['claude-github-issue'],
|
||||||
|
icon: Github,
|
||||||
|
source: 'unofficial',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
function repoSlug(repoUrl: string) {
|
function repoSlug(repoUrl: string) {
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import type { TFunction } from 'i18next';
|
|||||||
import { api } from '../../../utils/api';
|
import { api } from '../../../utils/api';
|
||||||
import { usePaletteOps } from '../../../contexts/PaletteOpsContext';
|
import { usePaletteOps } from '../../../contexts/PaletteOpsContext';
|
||||||
import type { Project, ProjectSession, LLMProvider } from '../../../types/app';
|
import type { Project, ProjectSession, LLMProvider } from '../../../types/app';
|
||||||
import type { SessionActivityMap } from '../../../hooks/useSessionProtection';
|
|
||||||
import type {
|
import type {
|
||||||
ArchivedProjectListItem,
|
ArchivedProjectListItem,
|
||||||
ArchivedSessionListItem,
|
ArchivedSessionListItem,
|
||||||
@@ -82,7 +81,6 @@ type UseSidebarControllerArgs = {
|
|||||||
projects: Project[];
|
projects: Project[];
|
||||||
selectedProject: Project | null;
|
selectedProject: Project | null;
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
activeSessions: SessionActivityMap;
|
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
isMobile: boolean;
|
isMobile: boolean;
|
||||||
t: TFunction;
|
t: TFunction;
|
||||||
@@ -102,7 +100,6 @@ export function useSidebarController({
|
|||||||
projects,
|
projects,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
selectedSession: _selectedSession,
|
selectedSession: _selectedSession,
|
||||||
activeSessions,
|
|
||||||
isLoading,
|
isLoading,
|
||||||
isMobile,
|
isMobile,
|
||||||
t,
|
t,
|
||||||
@@ -149,8 +146,6 @@ export function useSidebarController({
|
|||||||
const onRefreshRef = useRef(onRefresh);
|
const onRefreshRef = useRef(onRefresh);
|
||||||
|
|
||||||
const isSidebarCollapsed = !isMobile && !sidebarVisible;
|
const isSidebarCollapsed = !isMobile && !sidebarVisible;
|
||||||
const activeSessionIds = useMemo(() => new Set(activeSessions.keys()), [activeSessions]);
|
|
||||||
const runningSessionsCount = activeSessionIds.size;
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setInterval(() => {
|
const timer = setInterval(() => {
|
||||||
@@ -587,35 +582,9 @@ export function useSidebarController({
|
|||||||
[projectSortOrder, projectsWithResolvedStarState],
|
[projectSortOrder, projectsWithResolvedStarState],
|
||||||
);
|
);
|
||||||
|
|
||||||
const runningProjects = useMemo(() => {
|
|
||||||
if (activeSessionIds.size === 0) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return sortedProjects.reduce<Project[]>((acc, project) => {
|
|
||||||
const sessions = (project.sessions ?? []).filter((session) => activeSessionIds.has(String(session.id)));
|
|
||||||
const runningCount = sessions.length;
|
|
||||||
|
|
||||||
if (runningCount === 0) {
|
|
||||||
return acc;
|
|
||||||
}
|
|
||||||
|
|
||||||
acc.push({
|
|
||||||
...project,
|
|
||||||
sessions,
|
|
||||||
sessionMeta: {
|
|
||||||
...project.sessionMeta,
|
|
||||||
total: runningCount,
|
|
||||||
hasMore: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return acc;
|
|
||||||
}, []);
|
|
||||||
}, [activeSessionIds, sortedProjects]);
|
|
||||||
|
|
||||||
const filteredProjects = useMemo(
|
const filteredProjects = useMemo(
|
||||||
() => filterProjects(searchMode === 'running' ? runningProjects : sortedProjects, debouncedSearchQuery),
|
() => filterProjects(sortedProjects, debouncedSearchQuery),
|
||||||
[debouncedSearchQuery, runningProjects, searchMode, sortedProjects],
|
[debouncedSearchQuery, sortedProjects],
|
||||||
);
|
);
|
||||||
|
|
||||||
const filteredArchivedSessions = useMemo(() => {
|
const filteredArchivedSessions = useMemo(() => {
|
||||||
@@ -945,7 +914,6 @@ export function useSidebarController({
|
|||||||
sessionDeleteConfirmation,
|
sessionDeleteConfirmation,
|
||||||
showVersionModal,
|
showVersionModal,
|
||||||
filteredProjects,
|
filteredProjects,
|
||||||
runningSessionsCount,
|
|
||||||
archivedProjects: filteredArchivedProjects,
|
archivedProjects: filteredArchivedProjects,
|
||||||
archivedSessions: filteredArchivedSessions,
|
archivedSessions: filteredArchivedSessions,
|
||||||
archivedSessionsCount: archivedProjects.length + archivedSessions.length,
|
archivedSessionsCount: archivedProjects.length + archivedSessions.length,
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
import type { LoadingProgress, Project, ProjectSession, LLMProvider } from '../../../types/app';
|
import type { LoadingProgress, Project, ProjectSession, LLMProvider } from '../../../types/app';
|
||||||
import type { SessionActivityMap } from '../../../hooks/useSessionProtection';
|
|
||||||
|
|
||||||
export type ProjectSortOrder = 'name' | 'date';
|
export type ProjectSortOrder = 'name' | 'date';
|
||||||
export type SidebarSearchMode = 'projects' | 'conversations' | 'running' | 'archived';
|
export type SidebarSearchMode = 'projects' | 'conversations' | 'archived';
|
||||||
export type ArchivedProjectListItem = Project & { isArchived: true };
|
export type ArchivedProjectListItem = Project & { isArchived: true };
|
||||||
|
|
||||||
export type SessionWithProvider = ProjectSession & {
|
export type SessionWithProvider = ProjectSession & {
|
||||||
@@ -41,7 +40,6 @@ export type SidebarProps = {
|
|||||||
projects: Project[];
|
projects: Project[];
|
||||||
selectedProject: Project | null;
|
selectedProject: Project | null;
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
activeSessions: SessionActivityMap;
|
|
||||||
onProjectSelect: (project: Project) => void;
|
onProjectSelect: (project: Project) => void;
|
||||||
onSessionSelect: (session: ProjectSession) => void;
|
onSessionSelect: (session: ProjectSession) => void;
|
||||||
onNewSession: (project: Project) => void;
|
onNewSession: (project: Project) => void;
|
||||||
@@ -61,6 +59,10 @@ export type SidebarProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export type SessionViewModel = {
|
export type SessionViewModel = {
|
||||||
|
isCursorSession: boolean;
|
||||||
|
isCodexSession: boolean;
|
||||||
|
isGeminiSession: boolean;
|
||||||
|
isOpenCodeSession: boolean;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
sessionName: string;
|
sessionName: string;
|
||||||
sessionTime: string;
|
sessionTime: string;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { TFunction } from 'i18next';
|
import type { TFunction } from 'i18next';
|
||||||
|
|
||||||
import type { LLMProvider, Project, ProjectSession } from '../../../types/app';
|
import type { Project } from '../../../types/app';
|
||||||
import type { ProjectSortOrder, SettingsProject, SessionViewModel, SessionWithProvider } from '../types/types';
|
import type { ProjectSortOrder, SettingsProject, SessionViewModel, SessionWithProvider } from '../types/types';
|
||||||
|
|
||||||
export const readProjectSortOrder = (): ProjectSortOrder => {
|
export const readProjectSortOrder = (): ProjectSortOrder => {
|
||||||
@@ -61,13 +61,6 @@ const getUpdatedTimestamp = (session: SessionWithProvider): string => {
|
|||||||
return String(session.lastActivity || '');
|
return String(session.lastActivity || '');
|
||||||
};
|
};
|
||||||
|
|
||||||
const getSessionProvider = (session: ProjectSession): LLMProvider => {
|
|
||||||
const provider = session.__provider ?? session.provider;
|
|
||||||
return typeof provider === 'string' && provider.trim()
|
|
||||||
? provider as LLMProvider
|
|
||||||
: 'claude';
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getSessionDate = (session: SessionWithProvider): Date => {
|
export const getSessionDate = (session: SessionWithProvider): Date => {
|
||||||
return new Date(getUpdatedTimestamp(session) || getCreatedTimestamp(session) || 0);
|
return new Date(getUpdatedTimestamp(session) || getCreatedTimestamp(session) || 0);
|
||||||
};
|
};
|
||||||
@@ -89,6 +82,10 @@ export const createSessionViewModel = (
|
|||||||
const diffInMinutes = Math.floor((currentTime.getTime() - sessionDate.getTime()) / (1000 * 60));
|
const diffInMinutes = Math.floor((currentTime.getTime() - sessionDate.getTime()) / (1000 * 60));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
isCursorSession: session.__provider === 'cursor',
|
||||||
|
isCodexSession: session.__provider === 'codex',
|
||||||
|
isGeminiSession: session.__provider === 'gemini',
|
||||||
|
isOpenCodeSession: session.__provider === 'opencode',
|
||||||
isActive: diffInMinutes < 10,
|
isActive: diffInMinutes < 10,
|
||||||
sessionName: getSessionName(session, t),
|
sessionName: getSessionName(session, t),
|
||||||
sessionTime: getSessionTime(session),
|
sessionTime: getSessionTime(session),
|
||||||
@@ -97,10 +94,32 @@ export const createSessionViewModel = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const getAllSessions = (project: Project): SessionWithProvider[] => {
|
export const getAllSessions = (project: Project): SessionWithProvider[] => {
|
||||||
return (project.sessions || []).map((session) => ({
|
const claudeSessions = [...(project.sessions || [])].map((session) => ({
|
||||||
...session,
|
...session,
|
||||||
__provider: getSessionProvider(session),
|
__provider: 'claude' as const,
|
||||||
})).sort(
|
}));
|
||||||
|
|
||||||
|
const cursorSessions = (project.cursorSessions || []).map((session) => ({
|
||||||
|
...session,
|
||||||
|
__provider: 'cursor' as const,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const codexSessions = (project.codexSessions || []).map((session) => ({
|
||||||
|
...session,
|
||||||
|
__provider: 'codex' as const,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const geminiSessions = (project.geminiSessions || []).map((session) => ({
|
||||||
|
...session,
|
||||||
|
__provider: 'gemini' as const,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const opencodeSessions = (project.opencodeSessions || []).map((session) => ({
|
||||||
|
...session,
|
||||||
|
__provider: 'opencode' as const,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return [...claudeSessions, ...cursorSessions, ...codexSessions, ...geminiSessions, ...opencodeSessions].sort(
|
||||||
(a, b) => getSessionDate(b).getTime() - getSessionDate(a).getTime(),
|
(a, b) => getSessionDate(b).getTime() - getSessionDate(a).getTime(),
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ function Sidebar({
|
|||||||
projects,
|
projects,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
activeSessions,
|
|
||||||
onProjectSelect,
|
onProjectSelect,
|
||||||
onSessionSelect,
|
onSessionSelect,
|
||||||
onNewSession,
|
onNewSession,
|
||||||
@@ -71,7 +70,6 @@ function Sidebar({
|
|||||||
isSearching,
|
isSearching,
|
||||||
searchProgress,
|
searchProgress,
|
||||||
clearConversationResults,
|
clearConversationResults,
|
||||||
runningSessionsCount,
|
|
||||||
deletingProjects,
|
deletingProjects,
|
||||||
deleteConfirmation,
|
deleteConfirmation,
|
||||||
sessionDeleteConfirmation,
|
sessionDeleteConfirmation,
|
||||||
@@ -115,7 +113,6 @@ function Sidebar({
|
|||||||
projects,
|
projects,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
activeSessions,
|
|
||||||
isLoading,
|
isLoading,
|
||||||
isMobile,
|
isMobile,
|
||||||
t,
|
t,
|
||||||
@@ -162,8 +159,6 @@ function Sidebar({
|
|||||||
mcpServerStatus,
|
mcpServerStatus,
|
||||||
getProjectSessions,
|
getProjectSessions,
|
||||||
loadingMoreProjects,
|
loadingMoreProjects,
|
||||||
activeSessions,
|
|
||||||
forceExpanded: searchMode === 'running',
|
|
||||||
isProjectStarred,
|
isProjectStarred,
|
||||||
onEditingNameChange: setEditingName,
|
onEditingNameChange: setEditingName,
|
||||||
onToggleProject: toggleProject,
|
onToggleProject: toggleProject,
|
||||||
@@ -234,7 +229,6 @@ function Sidebar({
|
|||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
projects={projects}
|
projects={projects}
|
||||||
runningSessionsCount={runningSessionsCount}
|
|
||||||
archivedProjects={archivedProjects}
|
archivedProjects={archivedProjects}
|
||||||
archivedSessions={archivedSessions}
|
archivedSessions={archivedSessions}
|
||||||
archivedSessionsCount={archivedSessionsCount}
|
archivedSessionsCount={archivedSessionsCount}
|
||||||
|
|||||||
@@ -1,18 +1,16 @@
|
|||||||
import { type ReactNode } from 'react';
|
import { type ReactNode } from 'react';
|
||||||
import { Activity, Archive, Folder, MessageSquare, RotateCcw, Search, Trash2 } from 'lucide-react';
|
import { Archive, Folder, MessageSquare, RotateCcw, Search, Trash2 } from 'lucide-react';
|
||||||
import type { TFunction } from 'i18next';
|
import type { TFunction } from 'i18next';
|
||||||
|
|
||||||
import { ScrollArea } from '../../../../shared/view/ui';
|
import { ScrollArea } from '../../../../shared/view/ui';
|
||||||
import type { Project } from '../../../../types/app';
|
import type { Project } from '../../../../types/app';
|
||||||
import type { ReleaseInfo } from '../../../../types/sharedTypes';
|
import type { ReleaseInfo } from '../../../../types/sharedTypes';
|
||||||
import type { ConversationSearchResults, SearchProgress } from '../../hooks/useSidebarController';
|
import type { ConversationSearchResults, SearchProgress } from '../../hooks/useSidebarController';
|
||||||
import type { ArchivedProjectListItem, ArchivedSessionListItem, SidebarSearchMode } from '../../types/types';
|
import type { ArchivedProjectListItem, ArchivedSessionListItem, SidebarSearchMode } from '../../types/types';
|
||||||
import SessionProviderLogo from '../../../llm-logo-provider/SessionProviderLogo';
|
import SessionProviderLogo from '../../../llm-logo-provider/SessionProviderLogo';
|
||||||
import { getAllSessions } from '../../utils/utils';
|
|
||||||
|
|
||||||
import SidebarFooter from './SidebarFooter';
|
import SidebarFooter from './SidebarFooter';
|
||||||
import SidebarHeader from './SidebarHeader';
|
import SidebarHeader from './SidebarHeader';
|
||||||
import SidebarProjectList, { type SidebarProjectListProps } from './SidebarProjectList';
|
import SidebarProjectList, { type SidebarProjectListProps } from './SidebarProjectList';
|
||||||
|
import { getAllSessions } from '../../utils/utils';
|
||||||
|
|
||||||
function HighlightedSnippet({ snippet, highlights }: { snippet: string; highlights: { start: number; end: number }[] }) {
|
function HighlightedSnippet({ snippet, highlights }: { snippet: string; highlights: { start: number; end: number }[] }) {
|
||||||
const parts: ReactNode[] = [];
|
const parts: ReactNode[] = [];
|
||||||
@@ -116,7 +114,6 @@ type SidebarContentProps = {
|
|||||||
isMobile: boolean;
|
isMobile: boolean;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
projects: Project[];
|
projects: Project[];
|
||||||
runningSessionsCount: number;
|
|
||||||
archivedProjects: ArchivedProjectListItem[];
|
archivedProjects: ArchivedProjectListItem[];
|
||||||
archivedSessions: ArchivedSessionListItem[];
|
archivedSessions: ArchivedSessionListItem[];
|
||||||
archivedSessionsCount: number;
|
archivedSessionsCount: number;
|
||||||
@@ -155,7 +152,6 @@ export default function SidebarContent({
|
|||||||
isMobile,
|
isMobile,
|
||||||
isLoading,
|
isLoading,
|
||||||
projects,
|
projects,
|
||||||
runningSessionsCount,
|
|
||||||
archivedProjects,
|
archivedProjects,
|
||||||
archivedSessions,
|
archivedSessions,
|
||||||
archivedSessionsCount,
|
archivedSessionsCount,
|
||||||
@@ -200,7 +196,6 @@ export default function SidebarContent({
|
|||||||
isMobile={isMobile}
|
isMobile={isMobile}
|
||||||
isLoading={isLoading}
|
isLoading={isLoading}
|
||||||
projectsCount={projects.length}
|
projectsCount={projects.length}
|
||||||
runningSessionsCount={runningSessionsCount}
|
|
||||||
archivedSessionsCount={archivedSessionsCount}
|
archivedSessionsCount={archivedSessionsCount}
|
||||||
isArchivedSessionsLoading={isArchivedSessionsLoading}
|
isArchivedSessionsLoading={isArchivedSessionsLoading}
|
||||||
searchFilter={searchFilter}
|
searchFilter={searchFilter}
|
||||||
@@ -312,39 +307,6 @@ export default function SidebarContent({
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
) : null
|
) : null
|
||||||
) : searchMode === 'running' ? (
|
|
||||||
projectListProps.filteredProjects.length === 0 ? (
|
|
||||||
<div className="px-4 py-12 text-center md:py-8">
|
|
||||||
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-lg border border-border/70 bg-muted/50 md:mb-3">
|
|
||||||
<Activity className="h-6 w-6 text-muted-foreground" />
|
|
||||||
</div>
|
|
||||||
<h3 className="mb-2 text-base font-medium text-foreground md:mb-1">
|
|
||||||
{t('running.emptyTitle', 'No sessions running')}
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
{runningSessionsCount > 0
|
|
||||||
? t('running.noMatchingSessions', 'No running sessions match this search.')
|
|
||||||
: t('running.emptyDescription', 'Active work will appear here while a provider is processing.')}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<div className="mx-2 flex items-center justify-between rounded-lg border border-border/60 bg-card/50 px-3 py-2 shadow-sm">
|
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
|
||||||
<span className="flex h-6 w-6 items-center justify-center rounded-md bg-emerald-500/10 text-emerald-600 dark:text-emerald-400">
|
|
||||||
<Activity className="h-3.5 w-3.5" />
|
|
||||||
</span>
|
|
||||||
<span className="truncate text-xs font-medium text-foreground">
|
|
||||||
{t('running.title', 'Running now')}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">
|
|
||||||
{runningSessionsCount}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<SidebarProjectList {...projectListProps} />
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
) : searchMode === 'archived' ? (
|
) : searchMode === 'archived' ? (
|
||||||
isArchivedSessionsLoading ? (
|
isArchivedSessionsLoading ? (
|
||||||
<div className="px-4 py-12 text-center md:py-8">
|
<div className="px-4 py-12 text-center md:py-8">
|
||||||
@@ -396,7 +358,7 @@ export default function SidebarContent({
|
|||||||
<span className="truncate text-sm font-medium text-foreground">
|
<span className="truncate text-sm font-medium text-foreground">
|
||||||
{project.displayName}
|
{project.displayName}
|
||||||
</span>
|
</span>
|
||||||
<span className="inline-flex items-center justify-center rounded-full bg-muted px-1 py-px text-center text-[7px] font-medium uppercase leading-none tracking-[0.02em] text-muted-foreground">
|
<span className="inline-flex items-center justify-center rounded-full bg-muted px-1 py-px text-[7px] font-medium uppercase leading-none tracking-[0.02em] text-center text-muted-foreground">
|
||||||
{t('archived.projectArchived', 'Project archived')}
|
{t('archived.projectArchived', 'Project archived')}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -486,7 +448,7 @@ export default function SidebarContent({
|
|||||||
{group.projectDisplayName}
|
{group.projectDisplayName}
|
||||||
</span>
|
</span>
|
||||||
{group.isProjectArchived && (
|
{group.isProjectArchived && (
|
||||||
<span className="inline-flex items-center justify-center rounded-full bg-muted px-1 py-px text-center text-[7px] font-medium uppercase leading-none tracking-[0.02em] text-muted-foreground">
|
<span className="inline-flex items-center justify-center rounded-full bg-muted px-1 py-px text-[7px] font-medium uppercase leading-none tracking-[0.02em] text-center text-muted-foreground">
|
||||||
{t('archived.projectArchived', 'Project archived')}
|
{t('archived.projectArchived', 'Project archived')}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
import { Activity, Archive, Folder, FolderPlus, MessageSquare, Plus, RefreshCw, Search, X, PanelLeftClose } from 'lucide-react';
|
import { Archive, Folder, FolderPlus, MessageSquare, Plus, RefreshCw, Search, X, PanelLeftClose } from 'lucide-react';
|
||||||
import type { TFunction } from 'i18next';
|
import type { TFunction } from 'i18next';
|
||||||
|
|
||||||
import { Button, Input, Tooltip } from '../../../../shared/view/ui';
|
import { Button, Input, Tooltip } from '../../../../shared/view/ui';
|
||||||
import { IS_PLATFORM } from '../../../../constants/config';
|
import { IS_PLATFORM } from '../../../../constants/config';
|
||||||
import { cn } from '../../../../lib/utils';
|
import { cn } from '../../../../lib/utils';
|
||||||
import type { SidebarSearchMode } from '../../types/types';
|
import type { SidebarSearchMode } from '../../types/types';
|
||||||
|
|
||||||
import GitHubStarBadge from './GitHubStarBadge';
|
import GitHubStarBadge from './GitHubStarBadge';
|
||||||
|
|
||||||
const MOD_KEY =
|
const MOD_KEY =
|
||||||
@@ -16,7 +14,6 @@ type SidebarHeaderProps = {
|
|||||||
isMobile: boolean;
|
isMobile: boolean;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
projectsCount: number;
|
projectsCount: number;
|
||||||
runningSessionsCount: number;
|
|
||||||
archivedSessionsCount: number;
|
archivedSessionsCount: number;
|
||||||
isArchivedSessionsLoading: boolean;
|
isArchivedSessionsLoading: boolean;
|
||||||
searchFilter: string;
|
searchFilter: string;
|
||||||
@@ -36,7 +33,6 @@ export default function SidebarHeader({
|
|||||||
isMobile,
|
isMobile,
|
||||||
isLoading,
|
isLoading,
|
||||||
projectsCount,
|
projectsCount,
|
||||||
runningSessionsCount,
|
|
||||||
archivedSessionsCount,
|
archivedSessionsCount,
|
||||||
isArchivedSessionsLoading,
|
isArchivedSessionsLoading,
|
||||||
searchFilter,
|
searchFilter,
|
||||||
@@ -50,15 +46,12 @@ export default function SidebarHeader({
|
|||||||
onCollapseSidebar,
|
onCollapseSidebar,
|
||||||
t,
|
t,
|
||||||
}: SidebarHeaderProps) {
|
}: SidebarHeaderProps) {
|
||||||
const showSearchTools = (projectsCount > 0 || runningSessionsCount > 0 || archivedSessionsCount > 0 || isArchivedSessionsLoading) && !isLoading;
|
const showSearchTools = (projectsCount > 0 || archivedSessionsCount > 0 || isArchivedSessionsLoading) && !isLoading;
|
||||||
const searchPlaceholder = searchMode === 'conversations'
|
const searchPlaceholder = searchMode === 'conversations'
|
||||||
? t('search.conversationsPlaceholder')
|
? t('search.conversationsPlaceholder')
|
||||||
: searchMode === 'archived'
|
: searchMode === 'archived'
|
||||||
? t('search.archivedPlaceholder', 'Search archived sessions...')
|
? t('search.archivedPlaceholder', 'Search archived sessions...')
|
||||||
: searchMode === 'running'
|
: t('projects.searchPlaceholder');
|
||||||
? t('search.runningPlaceholder', 'Search running sessions...')
|
|
||||||
: t('projects.searchPlaceholder');
|
|
||||||
const runningBadgeText = runningSessionsCount > 99 ? '99+' : String(runningSessionsCount);
|
|
||||||
|
|
||||||
const LogoBlock = () => (
|
const LogoBlock = () => (
|
||||||
<div className="flex min-w-0 items-center gap-2.5">
|
<div className="flex min-w-0 items-center gap-2.5">
|
||||||
@@ -160,29 +153,6 @@ export default function SidebarHeader({
|
|||||||
<MessageSquare className="h-3 w-3" />
|
<MessageSquare className="h-3 w-3" />
|
||||||
{t('search.modeConversations')}
|
{t('search.modeConversations')}
|
||||||
</button>
|
</button>
|
||||||
<Tooltip content={t('search.runningTooltip', 'Running sessions')} position="top">
|
|
||||||
<button
|
|
||||||
onClick={() => onSearchModeChange('running')}
|
|
||||||
aria-pressed={searchMode === 'running'}
|
|
||||||
aria-label={t('search.runningTooltip', 'Running sessions')}
|
|
||||||
title={t('search.runningTooltip', 'Running sessions')}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium transition-all",
|
|
||||||
searchMode === 'running'
|
|
||||||
? "bg-background shadow-sm text-foreground ring-1 ring-emerald-500/15"
|
|
||||||
: "text-muted-foreground hover:text-foreground"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span className="relative flex h-3 w-3 items-center justify-center">
|
|
||||||
<Activity className={cn("h-3 w-3", runningSessionsCount > 0 && "text-emerald-500")} />
|
|
||||||
{runningSessionsCount > 0 && (
|
|
||||||
<span className="absolute -right-2.5 -top-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-emerald-500 px-0.5 text-[8px] font-semibold leading-none text-white shadow-sm ring-1 ring-background">
|
|
||||||
{runningBadgeText}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip content={t('search.archiveOnlyTooltip', 'Archive only')} position="top">
|
<Tooltip content={t('search.archiveOnlyTooltip', 'Archive only')} position="top">
|
||||||
<button
|
<button
|
||||||
onClick={() => onSearchModeChange('archived')}
|
onClick={() => onSearchModeChange('archived')}
|
||||||
@@ -300,30 +270,6 @@ export default function SidebarHeader({
|
|||||||
<MessageSquare className="h-3 w-3" />
|
<MessageSquare className="h-3 w-3" />
|
||||||
{t('search.modeConversations')}
|
{t('search.modeConversations')}
|
||||||
</button>
|
</button>
|
||||||
<Tooltip content={t('search.runningTooltip', 'Running sessions')} position="top">
|
|
||||||
<button
|
|
||||||
onClick={() => onSearchModeChange('running')}
|
|
||||||
aria-pressed={searchMode === 'running'}
|
|
||||||
aria-label={t('search.runningTooltip', 'Running sessions')}
|
|
||||||
title={t('search.runningTooltip', 'Running sessions')}
|
|
||||||
className={cn(
|
|
||||||
"flex items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-xs font-medium transition-all",
|
|
||||||
searchMode === 'running'
|
|
||||||
? "bg-background shadow-sm text-foreground ring-1 ring-emerald-500/15"
|
|
||||||
: "text-muted-foreground hover:text-foreground"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<span className="relative flex h-3 w-3 items-center justify-center">
|
|
||||||
<Activity className={cn("h-3 w-3", runningSessionsCount > 0 && "text-emerald-500")} />
|
|
||||||
{runningSessionsCount > 0 && (
|
|
||||||
<span className="absolute -right-2.5 -top-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-emerald-500 px-0.5 text-[8px] font-semibold leading-none text-white shadow-sm ring-1 ring-background">
|
|
||||||
{runningBadgeText}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
<span className="sr-only">{t('search.modeRunning', 'Running')}</span>
|
|
||||||
</button>
|
|
||||||
</Tooltip>
|
|
||||||
<Tooltip content={t('search.archiveOnlyTooltip', 'Archive only')} position="top">
|
<Tooltip content={t('search.archiveOnlyTooltip', 'Archive only')} position="top">
|
||||||
<button
|
<button
|
||||||
onClick={() => onSearchModeChange('archived')}
|
onClick={() => onSearchModeChange('archived')}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import type { TFunction } from 'i18next';
|
|||||||
import { Button } from '../../../../shared/view/ui';
|
import { Button } from '../../../../shared/view/ui';
|
||||||
import { cn } from '../../../../lib/utils';
|
import { cn } from '../../../../lib/utils';
|
||||||
import type { Project, ProjectSession, LLMProvider } from '../../../../types/app';
|
import type { Project, ProjectSession, LLMProvider } from '../../../../types/app';
|
||||||
import type { SessionActivityMap } from '../../../../hooks/useSessionProtection';
|
|
||||||
import type { MCPServerStatus, SessionWithProvider } from '../../types/types';
|
import type { MCPServerStatus, SessionWithProvider } from '../../types/types';
|
||||||
import { getTaskIndicatorStatus } from '../../utils/utils';
|
import { getTaskIndicatorStatus } from '../../utils/utils';
|
||||||
|
|
||||||
@@ -44,7 +43,6 @@ type SidebarProjectItemProps = {
|
|||||||
provider: LLMProvider,
|
provider: LLMProvider,
|
||||||
) => void;
|
) => void;
|
||||||
onLoadMoreSessions: (projectId: string) => void;
|
onLoadMoreSessions: (projectId: string) => void;
|
||||||
activeSessions: SessionActivityMap;
|
|
||||||
onNewSession: (project: Project) => void;
|
onNewSession: (project: Project) => void;
|
||||||
onEditingSessionNameChange: (value: string) => void;
|
onEditingSessionNameChange: (value: string) => void;
|
||||||
onStartEditingSession: (sessionId: string, initialName: string) => void;
|
onStartEditingSession: (sessionId: string, initialName: string) => void;
|
||||||
@@ -86,7 +84,6 @@ export default function SidebarProjectItem({
|
|||||||
onSessionSelect,
|
onSessionSelect,
|
||||||
onDeleteSession,
|
onDeleteSession,
|
||||||
onLoadMoreSessions,
|
onLoadMoreSessions,
|
||||||
activeSessions,
|
|
||||||
onNewSession,
|
onNewSession,
|
||||||
onEditingSessionNameChange,
|
onEditingSessionNameChange,
|
||||||
onStartEditingSession,
|
onStartEditingSession,
|
||||||
@@ -398,7 +395,6 @@ export default function SidebarProjectItem({
|
|||||||
initialSessionsLoaded={initialSessionsLoaded}
|
initialSessionsLoaded={initialSessionsLoaded}
|
||||||
hasMoreSessions={Boolean(project.sessionMeta?.hasMore)}
|
hasMoreSessions={Boolean(project.sessionMeta?.hasMore)}
|
||||||
isLoadingMoreSessions={isLoadingMoreSessions}
|
isLoadingMoreSessions={isLoadingMoreSessions}
|
||||||
activeSessions={activeSessions}
|
|
||||||
currentTime={currentTime}
|
currentTime={currentTime}
|
||||||
editingSession={editingSession}
|
editingSession={editingSession}
|
||||||
editingSessionName={editingSessionName}
|
editingSessionName={editingSessionName}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { useEffect } from 'react';
|
|||||||
import type { TFunction } from 'i18next';
|
import type { TFunction } from 'i18next';
|
||||||
|
|
||||||
import type { LoadingProgress, Project, ProjectSession, LLMProvider } from '../../../../types/app';
|
import type { LoadingProgress, Project, ProjectSession, LLMProvider } from '../../../../types/app';
|
||||||
import type { SessionActivityMap } from '../../../../hooks/useSessionProtection';
|
|
||||||
import type { MCPServerStatus, SessionWithProvider } from '../../types/types';
|
import type { MCPServerStatus, SessionWithProvider } from '../../types/types';
|
||||||
|
|
||||||
import SidebarProjectItem from './SidebarProjectItem';
|
import SidebarProjectItem from './SidebarProjectItem';
|
||||||
@@ -28,8 +27,6 @@ export type SidebarProjectListProps = {
|
|||||||
getProjectSessions: (project: Project) => SessionWithProvider[];
|
getProjectSessions: (project: Project) => SessionWithProvider[];
|
||||||
onLoadMoreSessions: (projectId: string) => void;
|
onLoadMoreSessions: (projectId: string) => void;
|
||||||
loadingMoreProjects: Set<string>;
|
loadingMoreProjects: Set<string>;
|
||||||
activeSessions: SessionActivityMap;
|
|
||||||
forceExpanded?: boolean;
|
|
||||||
isProjectStarred: (projectName: string) => boolean;
|
isProjectStarred: (projectName: string) => boolean;
|
||||||
onEditingNameChange: (value: string) => void;
|
onEditingNameChange: (value: string) => void;
|
||||||
onToggleProject: (projectName: string) => void;
|
onToggleProject: (projectName: string) => void;
|
||||||
@@ -74,8 +71,6 @@ export default function SidebarProjectList({
|
|||||||
getProjectSessions,
|
getProjectSessions,
|
||||||
onLoadMoreSessions,
|
onLoadMoreSessions,
|
||||||
loadingMoreProjects,
|
loadingMoreProjects,
|
||||||
activeSessions,
|
|
||||||
forceExpanded = false,
|
|
||||||
isProjectStarred,
|
isProjectStarred,
|
||||||
onEditingNameChange,
|
onEditingNameChange,
|
||||||
onToggleProject,
|
onToggleProject,
|
||||||
@@ -127,7 +122,7 @@ export default function SidebarProjectList({
|
|||||||
project={project}
|
project={project}
|
||||||
selectedProject={selectedProject}
|
selectedProject={selectedProject}
|
||||||
selectedSession={selectedSession}
|
selectedSession={selectedSession}
|
||||||
isExpanded={forceExpanded || expandedProjects.has(project.projectId)}
|
isExpanded={expandedProjects.has(project.projectId)}
|
||||||
isDeleting={deletingProjects.has(project.projectId)}
|
isDeleting={deletingProjects.has(project.projectId)}
|
||||||
isStarred={isProjectStarred(project.projectId)}
|
isStarred={isProjectStarred(project.projectId)}
|
||||||
editingProject={editingProject}
|
editingProject={editingProject}
|
||||||
@@ -151,7 +146,6 @@ export default function SidebarProjectList({
|
|||||||
onSessionSelect={onSessionSelect}
|
onSessionSelect={onSessionSelect}
|
||||||
onDeleteSession={onDeleteSession}
|
onDeleteSession={onDeleteSession}
|
||||||
onLoadMoreSessions={onLoadMoreSessions}
|
onLoadMoreSessions={onLoadMoreSessions}
|
||||||
activeSessions={activeSessions}
|
|
||||||
onNewSession={onNewSession}
|
onNewSession={onNewSession}
|
||||||
onEditingSessionNameChange={onEditingSessionNameChange}
|
onEditingSessionNameChange={onEditingSessionNameChange}
|
||||||
onStartEditingSession={onStartEditingSession}
|
onStartEditingSession={onStartEditingSession}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { Plus } from 'lucide-react';
|
|||||||
import type { TFunction } from 'i18next';
|
import type { TFunction } from 'i18next';
|
||||||
|
|
||||||
import { Button } from '../../../../shared/view/ui';
|
import { Button } from '../../../../shared/view/ui';
|
||||||
import type { SessionActivityMap } from '../../../../hooks/useSessionProtection';
|
|
||||||
import type { Project, ProjectSession, LLMProvider } from '../../../../types/app';
|
import type { Project, ProjectSession, LLMProvider } from '../../../../types/app';
|
||||||
import type { SessionWithProvider } from '../../types/types';
|
import type { SessionWithProvider } from '../../types/types';
|
||||||
|
|
||||||
@@ -16,7 +15,6 @@ type SidebarProjectSessionsProps = {
|
|||||||
initialSessionsLoaded: boolean;
|
initialSessionsLoaded: boolean;
|
||||||
hasMoreSessions: boolean;
|
hasMoreSessions: boolean;
|
||||||
isLoadingMoreSessions: boolean;
|
isLoadingMoreSessions: boolean;
|
||||||
activeSessions: SessionActivityMap;
|
|
||||||
currentTime: Date;
|
currentTime: Date;
|
||||||
editingSession: string | null;
|
editingSession: string | null;
|
||||||
editingSessionName: string;
|
editingSessionName: string;
|
||||||
@@ -63,7 +61,6 @@ export default function SidebarProjectSessions({
|
|||||||
initialSessionsLoaded,
|
initialSessionsLoaded,
|
||||||
hasMoreSessions,
|
hasMoreSessions,
|
||||||
isLoadingMoreSessions,
|
isLoadingMoreSessions,
|
||||||
activeSessions,
|
|
||||||
currentTime,
|
currentTime,
|
||||||
editingSession,
|
editingSession,
|
||||||
editingSessionName,
|
editingSessionName,
|
||||||
@@ -123,7 +120,6 @@ export default function SidebarProjectSessions({
|
|||||||
project={project}
|
project={project}
|
||||||
session={session}
|
session={session}
|
||||||
selectedSession={selectedSession}
|
selectedSession={selectedSession}
|
||||||
isProcessing={activeSessions.has(session.id)}
|
|
||||||
currentTime={currentTime}
|
currentTime={currentTime}
|
||||||
editingSession={editingSession}
|
editingSession={editingSession}
|
||||||
editingSessionName={editingSessionName}
|
editingSessionName={editingSessionName}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { Check, Edit2, Loader2, Trash2, X } from 'lucide-react';
|
import { Check, Edit2, Trash2, X } from 'lucide-react';
|
||||||
import type { TFunction } from 'i18next';
|
import type { TFunction } from 'i18next';
|
||||||
|
|
||||||
import { Badge, Button, Tooltip } from '../../../../shared/view/ui';
|
import { Badge, Button, Tooltip } from '../../../../shared/view/ui';
|
||||||
@@ -13,7 +13,6 @@ type SidebarSessionItemProps = {
|
|||||||
project: Project;
|
project: Project;
|
||||||
session: SessionWithProvider;
|
session: SessionWithProvider;
|
||||||
selectedSession: ProjectSession | null;
|
selectedSession: ProjectSession | null;
|
||||||
isProcessing: boolean;
|
|
||||||
currentTime: Date;
|
currentTime: Date;
|
||||||
editingSession: string | null;
|
editingSession: string | null;
|
||||||
editingSessionName: string;
|
editingSessionName: string;
|
||||||
@@ -64,7 +63,6 @@ export default function SidebarSessionItem({
|
|||||||
project,
|
project,
|
||||||
session,
|
session,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
isProcessing,
|
|
||||||
currentTime,
|
currentTime,
|
||||||
editingSession,
|
editingSession,
|
||||||
editingSessionName,
|
editingSessionName,
|
||||||
@@ -82,7 +80,6 @@ export default function SidebarSessionItem({
|
|||||||
const isEditing = editingSession === session.id;
|
const isEditing = editingSession === session.id;
|
||||||
const compactSessionAge = formatCompactSessionAge(sessionView.sessionTime, currentTime);
|
const compactSessionAge = formatCompactSessionAge(sessionView.sessionTime, currentTime);
|
||||||
const editingContainerRef = useRef<HTMLDivElement>(null);
|
const editingContainerRef = useRef<HTMLDivElement>(null);
|
||||||
const showRecentIndicator = !isProcessing && sessionView.isActive;
|
|
||||||
|
|
||||||
// The rename panel sits inside a group-hover opacity wrapper, so leaving the row
|
// The rename panel sits inside a group-hover opacity wrapper, so leaving the row
|
||||||
// would visually hide it. While editing, dismiss only when the user clicks outside
|
// would visually hide it. While editing, dismiss only when the user clicks outside
|
||||||
@@ -120,7 +117,7 @@ export default function SidebarSessionItem({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="group relative">
|
<div className="group relative">
|
||||||
{showRecentIndicator && (
|
{sessionView.isActive && (
|
||||||
<div className="absolute left-0 top-1/2 -translate-x-1 -translate-y-1/2 transform">
|
<div className="absolute left-0 top-1/2 -translate-x-1 -translate-y-1/2 transform">
|
||||||
<Tooltip content={t('tooltips.activeSessionIndicator')} position="right">
|
<Tooltip content={t('tooltips.activeSessionIndicator')} position="right">
|
||||||
<div
|
<div
|
||||||
@@ -137,9 +134,7 @@ export default function SidebarSessionItem({
|
|||||||
className={cn(
|
className={cn(
|
||||||
'p-2 mx-3 my-0.5 rounded-md bg-card border active:scale-[0.98] transition-all duration-150 relative',
|
'p-2 mx-3 my-0.5 rounded-md bg-card border active:scale-[0.98] transition-all duration-150 relative',
|
||||||
isSelected ? 'bg-primary/5 border-primary/20' : '',
|
isSelected ? 'bg-primary/5 border-primary/20' : '',
|
||||||
!isSelected && isProcessing
|
!isSelected && sessionView.isActive
|
||||||
? 'border-border/60 bg-muted/20'
|
|
||||||
: !isSelected && sessionView.isActive
|
|
||||||
? 'border-green-500/30 bg-green-50/5 dark:bg-green-900/5'
|
? 'border-green-500/30 bg-green-50/5 dark:bg-green-900/5'
|
||||||
: 'border-border/30',
|
: 'border-border/30',
|
||||||
)}
|
)}
|
||||||
@@ -157,16 +152,8 @@ export default function SidebarSessionItem({
|
|||||||
|
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">{sessionView.sessionName}</div>
|
<div className="truncate text-xs font-medium text-foreground">{sessionView.sessionName}</div>
|
||||||
{isProcessing ? (
|
{compactSessionAge && (
|
||||||
<span className="ml-auto flex-shrink-0">
|
|
||||||
<Tooltip content={t('tooltips.processingSessionIndicator', 'Processing session')} position="top">
|
|
||||||
<span className="flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground">
|
|
||||||
<Loader2 className="h-3 w-3 animate-spin" />
|
|
||||||
</span>
|
|
||||||
</Tooltip>
|
|
||||||
</span>
|
|
||||||
) : compactSessionAge && (
|
|
||||||
<span className="ml-auto flex-shrink-0 text-[11px] text-muted-foreground">{compactSessionAge}</span>
|
<span className="ml-auto flex-shrink-0 text-[11px] text-muted-foreground">{compactSessionAge}</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -179,7 +166,7 @@ export default function SidebarSessionItem({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!isProcessing && (
|
{!sessionView.isCursorSession && (
|
||||||
<button
|
<button
|
||||||
className="ml-1 flex h-5 w-5 items-center justify-center rounded-md bg-red-50 opacity-70 transition-transform active:scale-95 dark:bg-red-900/20"
|
className="ml-1 flex h-5 w-5 items-center justify-center rounded-md bg-red-50 opacity-70 transition-transform active:scale-95 dark:bg-red-900/20"
|
||||||
onClick={(event) => {
|
onClick={(event) => {
|
||||||
@@ -198,42 +185,17 @@ export default function SidebarSessionItem({
|
|||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
className={cn(
|
className={cn(
|
||||||
'h-auto w-full justify-start rounded-md border bg-card p-2 text-left font-normal transition-all duration-150',
|
'w-full justify-start p-2 h-auto font-normal text-left hover:bg-accent/50 transition-colors duration-200',
|
||||||
isSelected ? 'border-primary/20 bg-primary/5' : 'border-border/30',
|
isSelected && 'bg-accent text-accent-foreground',
|
||||||
!isSelected && isProcessing
|
|
||||||
? 'border-border/60 bg-muted/20 hover:bg-muted/25'
|
|
||||||
: !isSelected && sessionView.isActive
|
|
||||||
? 'border-green-500/30 bg-green-50/5 hover:bg-green-50/10 dark:bg-green-900/5 dark:hover:bg-green-900/10'
|
|
||||||
: 'hover:bg-accent/50',
|
|
||||||
)}
|
)}
|
||||||
onClick={() => onSessionSelect(session, project.projectId)}
|
onClick={() => onSessionSelect(session, project.projectId)}
|
||||||
>
|
>
|
||||||
<div className="flex w-full min-w-0 items-center gap-2">
|
<div className="flex w-full min-w-0 items-start gap-2">
|
||||||
<div
|
<SessionProviderLogo provider={session.__provider} className="mt-0.5 h-3 w-3 flex-shrink-0" />
|
||||||
className={cn(
|
|
||||||
'flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-md',
|
|
||||||
isSelected ? 'bg-primary/10' : 'bg-muted/50',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<SessionProviderLogo provider={session.__provider} className="h-3 w-3" />
|
|
||||||
</div>
|
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">{sessionView.sessionName}</div>
|
<div className="truncate text-xs font-medium text-foreground">{sessionView.sessionName}</div>
|
||||||
{isProcessing ? (
|
{compactSessionAge && (
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'ml-auto flex-shrink-0 transition-opacity duration-200',
|
|
||||||
isEditing ? 'opacity-0' : 'group-hover:opacity-0',
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Tooltip content={t('tooltips.processingSessionIndicator', 'Processing session')} position="top">
|
|
||||||
<span className="flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground">
|
|
||||||
<Loader2 className="h-3 w-3 animate-spin" />
|
|
||||||
</span>
|
|
||||||
</Tooltip>
|
|
||||||
</span>
|
|
||||||
) : compactSessionAge && (
|
|
||||||
<span
|
<span
|
||||||
className={cn(
|
className={cn(
|
||||||
'ml-auto flex-shrink-0 text-[11px] text-muted-foreground transition-opacity duration-200',
|
'ml-auto flex-shrink-0 text-[11px] text-muted-foreground transition-opacity duration-200',
|
||||||
@@ -309,7 +271,7 @@ export default function SidebarSessionItem({
|
|||||||
>
|
>
|
||||||
<Edit2 className="h-3 w-3 text-gray-600 dark:text-gray-400" />
|
<Edit2 className="h-3 w-3 text-gray-600 dark:text-gray-400" />
|
||||||
</button>
|
</button>
|
||||||
{!isProcessing && (
|
{!sessionView.isCursorSession && (
|
||||||
<button
|
<button
|
||||||
className="flex h-6 w-6 items-center justify-center rounded bg-red-50 hover:bg-red-100 dark:bg-red-900/20 dark:hover:bg-red-900/40"
|
className="flex h-6 w-6 items-center justify-center rounded bg-red-50 hover:bg-red-100 dark:bg-red-900/20 dark:hover:bg-red-900/40"
|
||||||
onClick={(event) => {
|
onClick={(event) => {
|
||||||
|
|||||||
@@ -2,42 +2,10 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, use
|
|||||||
import { useAuth } from '../components/auth/context/AuthContext';
|
import { useAuth } from '../components/auth/context/AuthContext';
|
||||||
import { IS_PLATFORM } from '../constants/config';
|
import { IS_PLATFORM } from '../constants/config';
|
||||||
|
|
||||||
/**
|
|
||||||
* One frame received from the chat websocket. The server guarantees every
|
|
||||||
* frame carries a `kind` (provider message kinds plus gateway kinds such as
|
|
||||||
* `chat_subscribed`, `session_upserted`, `loading_progress`,
|
|
||||||
* `protocol_error`). The synthetic `websocket_reconnected` kind is injected
|
|
||||||
* client-side when the socket re-opens after a drop.
|
|
||||||
*/
|
|
||||||
export type ServerEvent = {
|
|
||||||
kind?: string;
|
|
||||||
type?: string;
|
|
||||||
sessionId?: string;
|
|
||||||
seq?: number;
|
|
||||||
[key: string]: unknown;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ServerEventListener = (event: ServerEvent) => void;
|
|
||||||
|
|
||||||
type WebSocketContextType = {
|
type WebSocketContextType = {
|
||||||
ws: WebSocket | null;
|
ws: WebSocket | null;
|
||||||
sendMessage: (message: unknown) => void;
|
sendMessage: (message: any) => void;
|
||||||
/**
|
latestMessage: any | null;
|
||||||
* Subscribes to every websocket frame. Returns an unsubscribe function.
|
|
||||||
*
|
|
||||||
* This is the primary consumption API: events are dispatched synchronously
|
|
||||||
* to every listener, so rapid back-to-back frames can never be coalesced or
|
|
||||||
* dropped the way a single "latest message" state slot could.
|
|
||||||
*/
|
|
||||||
subscribe: (listener: ServerEventListener) => () => void;
|
|
||||||
/**
|
|
||||||
* Legacy state-based access to the most recent frame.
|
|
||||||
*
|
|
||||||
* Kept only for low-frequency consumers (TaskMaster broadcasts). High-rate
|
|
||||||
* chat streams must use `subscribe` — React may batch state updates, which
|
|
||||||
* makes `latestMessage` lossy under load.
|
|
||||||
*/
|
|
||||||
latestMessage: ServerEvent | null;
|
|
||||||
isConnected: boolean;
|
isConnected: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -62,28 +30,11 @@ const useWebSocketProviderState = (): WebSocketContextType => {
|
|||||||
const wsRef = useRef<WebSocket | null>(null);
|
const wsRef = useRef<WebSocket | null>(null);
|
||||||
const unmountedRef = useRef(false); // Track if component is unmounted
|
const unmountedRef = useRef(false); // Track if component is unmounted
|
||||||
const hasConnectedRef = useRef(false); // Track if we've ever connected (to detect reconnects)
|
const hasConnectedRef = useRef(false); // Track if we've ever connected (to detect reconnects)
|
||||||
/**
|
const [latestMessage, setLatestMessage] = useState<any>(null);
|
||||||
* Listener registry for the subscribe API. A ref (not state) because the
|
|
||||||
* set must be readable synchronously inside `onmessage` and never trigger
|
|
||||||
* re-renders of the provider tree.
|
|
||||||
*/
|
|
||||||
const listenersRef = useRef(new Set<ServerEventListener>());
|
|
||||||
const [latestMessage, setLatestMessage] = useState<ServerEvent | null>(null);
|
|
||||||
const [isConnected, setIsConnected] = useState(false);
|
const [isConnected, setIsConnected] = useState(false);
|
||||||
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
const { token } = useAuth();
|
const { token } = useAuth();
|
||||||
|
|
||||||
const dispatch = useCallback((event: ServerEvent) => {
|
|
||||||
for (const listener of listenersRef.current) {
|
|
||||||
try {
|
|
||||||
listener(event);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('WebSocket listener error:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setLatestMessage(event);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// The cleanup below sets unmountedRef = true. Without this reset, every
|
// The cleanup below sets unmountedRef = true. Without this reset, every
|
||||||
// re-run of the effect (e.g. on token refresh) would short-circuit connect()
|
// re-run of the effect (e.g. on token refresh) would short-circuit connect()
|
||||||
@@ -109,7 +60,7 @@ const useWebSocketProviderState = (): WebSocketContextType => {
|
|||||||
const wsUrl = buildWebSocketUrl(token);
|
const wsUrl = buildWebSocketUrl(token);
|
||||||
|
|
||||||
if (!wsUrl) return console.warn('No authentication token found for WebSocket connection');
|
if (!wsUrl) return console.warn('No authentication token found for WebSocket connection');
|
||||||
|
|
||||||
const websocket = new WebSocket(wsUrl);
|
const websocket = new WebSocket(wsUrl);
|
||||||
|
|
||||||
websocket.onopen = () => {
|
websocket.onopen = () => {
|
||||||
@@ -117,15 +68,15 @@ const useWebSocketProviderState = (): WebSocketContextType => {
|
|||||||
wsRef.current = websocket;
|
wsRef.current = websocket;
|
||||||
if (hasConnectedRef.current) {
|
if (hasConnectedRef.current) {
|
||||||
// This is a reconnect — signal so components can catch up on missed messages
|
// This is a reconnect — signal so components can catch up on missed messages
|
||||||
dispatch({ kind: 'websocket_reconnected', timestamp: Date.now() });
|
setLatestMessage({ type: 'websocket-reconnected', timestamp: Date.now() });
|
||||||
}
|
}
|
||||||
hasConnectedRef.current = true;
|
hasConnectedRef.current = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
websocket.onmessage = (event) => {
|
websocket.onmessage = (event) => {
|
||||||
try {
|
try {
|
||||||
const data = JSON.parse(event.data) as ServerEvent;
|
const data = JSON.parse(event.data);
|
||||||
dispatch(data);
|
setLatestMessage(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error parsing WebSocket message:', error);
|
console.error('Error parsing WebSocket message:', error);
|
||||||
}
|
}
|
||||||
@@ -134,7 +85,7 @@ const useWebSocketProviderState = (): WebSocketContextType => {
|
|||||||
websocket.onclose = () => {
|
websocket.onclose = () => {
|
||||||
setIsConnected(false);
|
setIsConnected(false);
|
||||||
wsRef.current = null;
|
wsRef.current = null;
|
||||||
|
|
||||||
// Attempt to reconnect after 3 seconds
|
// Attempt to reconnect after 3 seconds
|
||||||
reconnectTimeoutRef.current = setTimeout(() => {
|
reconnectTimeoutRef.current = setTimeout(() => {
|
||||||
if (unmountedRef.current) return; // Prevent reconnection if unmounted
|
if (unmountedRef.current) return; // Prevent reconnection if unmounted
|
||||||
@@ -149,9 +100,9 @@ const useWebSocketProviderState = (): WebSocketContextType => {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error creating WebSocket connection:', error);
|
console.error('Error creating WebSocket connection:', error);
|
||||||
}
|
}
|
||||||
}, [token, dispatch]); // everytime token changes, we reconnect
|
}, [token]); // everytime token changes, we reconnect
|
||||||
|
|
||||||
const sendMessage = useCallback((message: unknown) => {
|
const sendMessage = useCallback((message: any) => {
|
||||||
const socket = wsRef.current;
|
const socket = wsRef.current;
|
||||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||||
socket.send(JSON.stringify(message));
|
socket.send(JSON.stringify(message));
|
||||||
@@ -160,28 +111,20 @@ const useWebSocketProviderState = (): WebSocketContextType => {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const subscribe = useCallback((listener: ServerEventListener) => {
|
|
||||||
listenersRef.current.add(listener);
|
|
||||||
return () => {
|
|
||||||
listenersRef.current.delete(listener);
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const value: WebSocketContextType = useMemo(() =>
|
const value: WebSocketContextType = useMemo(() =>
|
||||||
({
|
({
|
||||||
ws: wsRef.current,
|
ws: wsRef.current,
|
||||||
sendMessage,
|
sendMessage,
|
||||||
subscribe,
|
|
||||||
latestMessage,
|
latestMessage,
|
||||||
isConnected
|
isConnected
|
||||||
}), [sendMessage, subscribe, latestMessage, isConnected]);
|
}), [sendMessage, latestMessage, isConnected]);
|
||||||
|
|
||||||
return value;
|
return value;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const WebSocketProvider = ({ children }: { children: React.ReactNode }) => {
|
export const WebSocketProvider = ({ children }: { children: React.ReactNode }) => {
|
||||||
const webSocketData = useWebSocketProviderState();
|
const webSocketData = useWebSocketProviderState();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<WebSocketContext.Provider value={webSocketData}>
|
<WebSocketContext.Provider value={webSocketData}>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -2,86 +2,34 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|||||||
import type { NavigateFunction } from 'react-router-dom';
|
import type { NavigateFunction } from 'react-router-dom';
|
||||||
|
|
||||||
import { api } from '../utils/api';
|
import { api } from '../utils/api';
|
||||||
import type { ServerEvent } from '../contexts/WebSocketContext';
|
|
||||||
import type {
|
import type {
|
||||||
|
AppSocketMessage,
|
||||||
AppTab,
|
AppTab,
|
||||||
LLMProvider,
|
LLMProvider,
|
||||||
LoadingProgress,
|
LoadingProgress,
|
||||||
Project,
|
Project,
|
||||||
ProjectSession,
|
ProjectSession,
|
||||||
|
ProjectsUpdatedMessage,
|
||||||
} from '../types/app';
|
} from '../types/app';
|
||||||
|
|
||||||
import type { SessionActivityMap } from './useSessionProtection';
|
|
||||||
|
|
||||||
type UseProjectsStateArgs = {
|
type UseProjectsStateArgs = {
|
||||||
sessionId?: string;
|
sessionId?: string;
|
||||||
navigate: NavigateFunction;
|
navigate: NavigateFunction;
|
||||||
/** Subscription to the unified websocket event stream. */
|
latestMessage: AppSocketMessage | null;
|
||||||
subscribe: (listener: (event: ServerEvent) => void) => () => void;
|
|
||||||
isMobile: boolean;
|
isMobile: boolean;
|
||||||
activeSessions: SessionActivityMap;
|
activeSessions: Set<string>;
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Shape of the per-session sidebar delta broadcast by the backend file
|
|
||||||
* watcher (`kind: session_upserted`). It carries everything needed to upsert
|
|
||||||
* one session row in place — no full project-list snapshot is ever pushed.
|
|
||||||
*/
|
|
||||||
type SessionUpsertedEvent = ServerEvent & {
|
|
||||||
sessionId: string;
|
|
||||||
providerSessionId?: string | null;
|
|
||||||
provider: LLMProvider;
|
|
||||||
session: ProjectSession;
|
|
||||||
project: {
|
|
||||||
projectId: string;
|
|
||||||
path: string;
|
|
||||||
fullPath: string;
|
|
||||||
displayName: string;
|
|
||||||
isStarred: boolean;
|
|
||||||
} | null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type FetchProjectsOptions = {
|
type FetchProjectsOptions = {
|
||||||
showLoadingState?: boolean;
|
showLoadingState?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type RegisterOptimisticSessionArgs = {
|
|
||||||
sessionId: string;
|
|
||||||
provider: LLMProvider;
|
|
||||||
project: Project;
|
|
||||||
summary?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ProjectSessionPage = Pick<Project, 'sessions' | 'sessionMeta'>;
|
|
||||||
|
|
||||||
const DEFAULT_PROVIDER: LLMProvider = 'claude';
|
|
||||||
|
|
||||||
const serialize = (value: unknown) => JSON.stringify(value ?? null);
|
const serialize = (value: unknown) => JSON.stringify(value ?? null);
|
||||||
|
|
||||||
const readSelectedProvider = (): LLMProvider => {
|
|
||||||
try {
|
|
||||||
const storedProvider = localStorage.getItem('selected-provider');
|
|
||||||
return storedProvider ? storedProvider as LLMProvider : DEFAULT_PROVIDER;
|
|
||||||
} catch {
|
|
||||||
return DEFAULT_PROVIDER;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getSessionProvider = (session: ProjectSession): LLMProvider => {
|
|
||||||
const provider = session.__provider ?? session.provider;
|
|
||||||
return typeof provider === 'string' && provider.trim()
|
|
||||||
? provider as LLMProvider
|
|
||||||
: DEFAULT_PROVIDER;
|
|
||||||
};
|
|
||||||
|
|
||||||
const normalizeSessionProvider = (session: ProjectSession): ProjectSession => ({
|
|
||||||
...session,
|
|
||||||
__provider: getSessionProvider(session),
|
|
||||||
});
|
|
||||||
|
|
||||||
const projectsHaveChanges = (
|
const projectsHaveChanges = (
|
||||||
prevProjects: Project[],
|
prevProjects: Project[],
|
||||||
nextProjects: Project[],
|
nextProjects: Project[],
|
||||||
|
includeExternalSessions: boolean,
|
||||||
): boolean => {
|
): boolean => {
|
||||||
if (prevProjects.length !== nextProjects.length) {
|
if (prevProjects.length !== nextProjects.length) {
|
||||||
return true;
|
return true;
|
||||||
@@ -93,14 +41,28 @@ const projectsHaveChanges = (
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
const baseChanged =
|
||||||
nextProject.projectId !== prevProject.projectId ||
|
nextProject.projectId !== prevProject.projectId ||
|
||||||
nextProject.displayName !== prevProject.displayName ||
|
nextProject.displayName !== prevProject.displayName ||
|
||||||
nextProject.fullPath !== prevProject.fullPath ||
|
nextProject.fullPath !== prevProject.fullPath ||
|
||||||
Boolean(nextProject.isStarred) !== Boolean(prevProject.isStarred) ||
|
Boolean(nextProject.isStarred) !== Boolean(prevProject.isStarred) ||
|
||||||
serialize(nextProject.sessionMeta) !== serialize(prevProject.sessionMeta) ||
|
serialize(nextProject.sessionMeta) !== serialize(prevProject.sessionMeta) ||
|
||||||
serialize(nextProject.sessions) !== serialize(prevProject.sessions) ||
|
serialize(nextProject.sessions) !== serialize(prevProject.sessions) ||
|
||||||
serialize(nextProject.taskmaster) !== serialize(prevProject.taskmaster)
|
serialize(nextProject.taskmaster) !== serialize(prevProject.taskmaster);
|
||||||
|
|
||||||
|
if (baseChanged) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!includeExternalSessions) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
serialize(nextProject.cursorSessions) !== serialize(prevProject.cursorSessions) ||
|
||||||
|
serialize(nextProject.codexSessions) !== serialize(prevProject.codexSessions) ||
|
||||||
|
serialize(nextProject.geminiSessions) !== serialize(prevProject.geminiSessions) ||
|
||||||
|
serialize(nextProject.opencodeSessions) !== serialize(prevProject.opencodeSessions)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -132,7 +94,13 @@ const mergeTaskMasterCache = (nextProjects: Project[], previousProjects: Project
|
|||||||
};
|
};
|
||||||
|
|
||||||
const getProjectSessions = (project: Project): ProjectSession[] => {
|
const getProjectSessions = (project: Project): ProjectSession[] => {
|
||||||
return project.sessions ?? [];
|
return [
|
||||||
|
...(project.sessions ?? []),
|
||||||
|
...(project.codexSessions ?? []),
|
||||||
|
...(project.cursorSessions ?? []),
|
||||||
|
...(project.geminiSessions ?? []),
|
||||||
|
...(project.opencodeSessions ?? []),
|
||||||
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
const countLoadedProjectSessions = (project: Project): number => getProjectSessions(project).length;
|
const countLoadedProjectSessions = (project: Project): number => getProjectSessions(project).length;
|
||||||
@@ -176,6 +144,10 @@ const mergeExpandedSessionPages = (previousProjects: Project[], incomingProjects
|
|||||||
const mergedProject: Project = {
|
const mergedProject: Project = {
|
||||||
...incomingProject,
|
...incomingProject,
|
||||||
sessions: mergeSessionProviderLists(incomingProject.sessions ?? [], previousProject.sessions ?? []),
|
sessions: mergeSessionProviderLists(incomingProject.sessions ?? [], previousProject.sessions ?? []),
|
||||||
|
cursorSessions: mergeSessionProviderLists(incomingProject.cursorSessions ?? [], previousProject.cursorSessions ?? []),
|
||||||
|
codexSessions: mergeSessionProviderLists(incomingProject.codexSessions ?? [], previousProject.codexSessions ?? []),
|
||||||
|
geminiSessions: mergeSessionProviderLists(incomingProject.geminiSessions ?? [], previousProject.geminiSessions ?? []),
|
||||||
|
opencodeSessions: mergeSessionProviderLists(incomingProject.opencodeSessions ?? [], previousProject.opencodeSessions ?? []),
|
||||||
};
|
};
|
||||||
|
|
||||||
const totalSessions = Number(incomingProject.sessionMeta?.total ?? previousLoadedCount);
|
const totalSessions = Number(incomingProject.sessionMeta?.total ?? previousLoadedCount);
|
||||||
@@ -191,11 +163,15 @@ const mergeExpandedSessionPages = (previousProjects: Project[], incomingProjects
|
|||||||
|
|
||||||
const mergeProjectSessionPage = (
|
const mergeProjectSessionPage = (
|
||||||
existingProject: Project,
|
existingProject: Project,
|
||||||
sessionsPage: ProjectSessionPage,
|
sessionsPage: Pick<Project, 'sessions' | 'cursorSessions' | 'codexSessions' | 'geminiSessions' | 'opencodeSessions' | 'sessionMeta'>,
|
||||||
): Project => {
|
): Project => {
|
||||||
const mergedProject: Project = {
|
const mergedProject: Project = {
|
||||||
...existingProject,
|
...existingProject,
|
||||||
sessions: mergeSessionProviderLists(existingProject.sessions ?? [], sessionsPage.sessions ?? []),
|
sessions: mergeSessionProviderLists(existingProject.sessions ?? [], sessionsPage.sessions ?? []),
|
||||||
|
cursorSessions: mergeSessionProviderLists(existingProject.cursorSessions ?? [], sessionsPage.cursorSessions ?? []),
|
||||||
|
codexSessions: mergeSessionProviderLists(existingProject.codexSessions ?? [], sessionsPage.codexSessions ?? []),
|
||||||
|
geminiSessions: mergeSessionProviderLists(existingProject.geminiSessions ?? [], sessionsPage.geminiSessions ?? []),
|
||||||
|
opencodeSessions: mergeSessionProviderLists(existingProject.opencodeSessions ?? [], sessionsPage.opencodeSessions ?? []),
|
||||||
};
|
};
|
||||||
|
|
||||||
const totalSessions = Number(sessionsPage.sessionMeta?.total ?? existingProject.sessionMeta?.total ?? 0);
|
const totalSessions = Number(sessionsPage.sessionMeta?.total ?? existingProject.sessionMeta?.total ?? 0);
|
||||||
@@ -209,119 +185,40 @@ const mergeProjectSessionPage = (
|
|||||||
return mergedProject;
|
return mergedProject;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getSessionAliasIds = (event: SessionUpsertedEvent): Set<string> => {
|
const isUpdateAdditive = (
|
||||||
const ids = new Set<string>();
|
currentProjects: Project[],
|
||||||
const add = (value: unknown) => {
|
updatedProjects: Project[],
|
||||||
if (typeof value !== 'string') {
|
selectedProject: Project | null,
|
||||||
return;
|
selectedSession: ProjectSession | null,
|
||||||
}
|
): boolean => {
|
||||||
|
if (!selectedProject || !selectedSession) {
|
||||||
const trimmed = value.trim();
|
return true;
|
||||||
if (trimmed) {
|
|
||||||
ids.add(trimmed);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
add(event.sessionId);
|
|
||||||
add(event.providerSessionId);
|
|
||||||
add(event.session?.id);
|
|
||||||
|
|
||||||
return ids;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Upserts one session into a project's normalized session list.
|
|
||||||
*
|
|
||||||
* Existing rows are updated in place (summary/lastActivity changes from the
|
|
||||||
* watcher); new rows are prepended since the watcher only fires for sessions
|
|
||||||
* with fresh activity. `sessionMeta.total` grows only on insert.
|
|
||||||
*/
|
|
||||||
const upsertSessionIntoProject = (project: Project, event: SessionUpsertedEvent): Project => {
|
|
||||||
const sessions = project.sessions ?? [];
|
|
||||||
const aliasIds = getSessionAliasIds(event);
|
|
||||||
const normalizedSession: ProjectSession = {
|
|
||||||
...event.session,
|
|
||||||
id: event.sessionId,
|
|
||||||
__provider: event.provider,
|
|
||||||
};
|
|
||||||
const existingIndex = sessions.findIndex((session) => aliasIds.has(String(session.id)));
|
|
||||||
|
|
||||||
let nextSessions: ProjectSession[];
|
|
||||||
let inserted = false;
|
|
||||||
if (existingIndex >= 0) {
|
|
||||||
let changed = false;
|
|
||||||
nextSessions = [];
|
|
||||||
|
|
||||||
for (const [index, session] of sessions.entries()) {
|
|
||||||
if (index === existingIndex) {
|
|
||||||
const updated = { ...session, ...normalizedSession };
|
|
||||||
if (serialize(session) !== serialize(updated)) {
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
nextSessions.push(updated);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (aliasIds.has(String(session.id))) {
|
|
||||||
changed = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
nextSessions.push(session);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!changed) {
|
|
||||||
return project;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
nextSessions = [normalizedSession, ...sessions];
|
|
||||||
inserted = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const next: Project = { ...project, sessions: nextSessions };
|
const currentSelectedProject = currentProjects.find((project) => project.projectId === selectedProject.projectId);
|
||||||
if (inserted) {
|
const updatedSelectedProject = updatedProjects.find((project) => project.projectId === selectedProject.projectId);
|
||||||
const total = Number(project.sessionMeta?.total ?? 0) + 1;
|
|
||||||
next.sessionMeta = {
|
if (!currentSelectedProject || !updatedSelectedProject) {
|
||||||
...project.sessionMeta,
|
return false;
|
||||||
total,
|
|
||||||
hasMore: countLoadedProjectSessions(next) < total,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return next;
|
const currentSelectedSession = getProjectSessions(currentSelectedProject).find(
|
||||||
};
|
(session) => session.id === selectedSession.id,
|
||||||
|
);
|
||||||
|
const updatedSelectedSession = getProjectSessions(updatedSelectedProject).find(
|
||||||
|
(session) => session.id === selectedSession.id,
|
||||||
|
);
|
||||||
|
|
||||||
const projectFromRegistration = (project: Project): Project => ({
|
if (!currentSelectedSession || !updatedSelectedSession) {
|
||||||
projectId: project.projectId,
|
return false;
|
||||||
path: project.path || project.fullPath,
|
|
||||||
fullPath: project.fullPath || project.path || '',
|
|
||||||
displayName: project.displayName,
|
|
||||||
isStarred: project.isStarred,
|
|
||||||
sessions: project.sessions ?? [],
|
|
||||||
sessionMeta: project.sessionMeta ?? { hasMore: false, total: countLoadedProjectSessions(project) },
|
|
||||||
taskmaster: project.taskmaster,
|
|
||||||
});
|
|
||||||
|
|
||||||
const removeSessionFromProject = (project: Project, sessionIdToDelete: string): Project => {
|
|
||||||
const sessions = project.sessions ?? [];
|
|
||||||
const nextSessions = sessions.filter((session) => session.id !== sessionIdToDelete);
|
|
||||||
if (nextSessions.length === sessions.length) {
|
|
||||||
return project;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const updatedProject: Project = {
|
return (
|
||||||
...project,
|
currentSelectedSession.id === updatedSelectedSession.id &&
|
||||||
sessions: nextSessions,
|
currentSelectedSession.title === updatedSelectedSession.title &&
|
||||||
};
|
currentSelectedSession.created_at === updatedSelectedSession.created_at &&
|
||||||
|
currentSelectedSession.updated_at === updatedSelectedSession.updated_at
|
||||||
const totalSessions = Math.max(0, Number(project.sessionMeta?.total ?? 0) - 1);
|
);
|
||||||
updatedProject.sessionMeta = {
|
|
||||||
...project.sessionMeta,
|
|
||||||
total: totalSessions,
|
|
||||||
hasMore: countLoadedProjectSessions(updatedProject) < totalSessions,
|
|
||||||
};
|
|
||||||
|
|
||||||
return updatedProject;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const VALID_TABS: Set<string> = new Set(['chat', 'files', 'shell', 'git', 'tasks', 'preview']);
|
const VALID_TABS: Set<string> = new Set(['chat', 'files', 'shell', 'git', 'tasks', 'preview']);
|
||||||
@@ -345,7 +242,7 @@ const readPersistedTab = (): AppTab => {
|
|||||||
export function useProjectsState({
|
export function useProjectsState({
|
||||||
sessionId,
|
sessionId,
|
||||||
navigate,
|
navigate,
|
||||||
subscribe,
|
latestMessage,
|
||||||
isMobile,
|
isMobile,
|
||||||
activeSessions,
|
activeSessions,
|
||||||
}: UseProjectsStateArgs) {
|
}: UseProjectsStateArgs) {
|
||||||
@@ -392,18 +289,7 @@ export function useProjectsState({
|
|||||||
const [newSessionTrigger, setNewSessionTrigger] = useState(0);
|
const [newSessionTrigger, setNewSessionTrigger] = useState(0);
|
||||||
|
|
||||||
const loadingProgressTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
const loadingProgressTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
/**
|
const lastHandledMessageRef = useRef<AppSocketMessage | null>(null);
|
||||||
* Ref mirrors for state the websocket subscription handler needs.
|
|
||||||
*
|
|
||||||
* The subscription is registered once (per `subscribe` identity) and events
|
|
||||||
* are dispatched synchronously outside React's render cycle, so the handler
|
|
||||||
* must read the latest values through refs instead of stale closures —
|
|
||||||
* re-subscribing on every state change would risk missing events.
|
|
||||||
*/
|
|
||||||
const selectedSessionRef = useRef(selectedSession);
|
|
||||||
selectedSessionRef.current = selectedSession;
|
|
||||||
const activeSessionsRef = useRef(activeSessions);
|
|
||||||
activeSessionsRef.current = activeSessions;
|
|
||||||
|
|
||||||
const fetchProjects = useCallback(async ({ showLoadingState = true }: FetchProjectsOptions = {}) => {
|
const fetchProjects = useCallback(async ({ showLoadingState = true }: FetchProjectsOptions = {}) => {
|
||||||
try {
|
try {
|
||||||
@@ -421,7 +307,7 @@ export function useProjectsState({
|
|||||||
return mergedProjects;
|
return mergedProjects;
|
||||||
}
|
}
|
||||||
|
|
||||||
return projectsHaveChanges(prevProjects, mergedProjects)
|
return projectsHaveChanges(prevProjects, mergedProjects, true)
|
||||||
? mergedProjects
|
? mergedProjects
|
||||||
: prevProjects;
|
: prevProjects;
|
||||||
});
|
});
|
||||||
@@ -439,75 +325,6 @@ export function useProjectsState({
|
|||||||
await fetchProjects({ showLoadingState: false });
|
await fetchProjects({ showLoadingState: false });
|
||||||
}, [fetchProjects]);
|
}, [fetchProjects]);
|
||||||
|
|
||||||
const registerOptimisticSession = useCallback(({
|
|
||||||
sessionId: newSessionId,
|
|
||||||
provider,
|
|
||||||
project,
|
|
||||||
summary,
|
|
||||||
}: RegisterOptimisticSessionArgs) => {
|
|
||||||
if (!newSessionId || !project?.projectId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
const optimisticSession: ProjectSession = {
|
|
||||||
id: newSessionId,
|
|
||||||
summary: summary ?? '',
|
|
||||||
messageCount: 0,
|
|
||||||
createdAt: now,
|
|
||||||
created_at: now,
|
|
||||||
updated_at: now,
|
|
||||||
lastActivity: now,
|
|
||||||
__provider: provider,
|
|
||||||
__projectId: project.projectId,
|
|
||||||
};
|
|
||||||
const upsert: SessionUpsertedEvent = {
|
|
||||||
kind: 'session_upserted',
|
|
||||||
sessionId: newSessionId,
|
|
||||||
provider,
|
|
||||||
session: optimisticSession,
|
|
||||||
project: {
|
|
||||||
projectId: project.projectId,
|
|
||||||
path: project.path || project.fullPath,
|
|
||||||
fullPath: project.fullPath || project.path || '',
|
|
||||||
displayName: project.displayName,
|
|
||||||
isStarred: Boolean(project.isStarred),
|
|
||||||
},
|
|
||||||
timestamp: now,
|
|
||||||
};
|
|
||||||
|
|
||||||
setProjects((previousProjects) => {
|
|
||||||
const existingProject = previousProjects.find((candidate) => candidate.projectId === project.projectId);
|
|
||||||
if (!existingProject) {
|
|
||||||
return [upsertSessionIntoProject(projectFromRegistration(project), upsert), ...previousProjects];
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedProject = upsertSessionIntoProject(existingProject, upsert);
|
|
||||||
if (updatedProject === existingProject) {
|
|
||||||
return previousProjects;
|
|
||||||
}
|
|
||||||
|
|
||||||
return previousProjects.map((candidate) =>
|
|
||||||
candidate.projectId === existingProject.projectId ? updatedProject : candidate,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
setSelectedProject((previousProject) => {
|
|
||||||
if (!previousProject || previousProject.projectId !== project.projectId) {
|
|
||||||
return previousProject;
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedProject = upsertSessionIntoProject(previousProject, upsert);
|
|
||||||
return updatedProject === previousProject ? previousProject : updatedProject;
|
|
||||||
});
|
|
||||||
|
|
||||||
setSelectedSession((previousSession) => (
|
|
||||||
previousSession?.id === newSessionId
|
|
||||||
? { ...previousSession, ...optimisticSession }
|
|
||||||
: optimisticSession
|
|
||||||
));
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Hydrates TaskMaster details for the given `projectId`. The project
|
// Hydrates TaskMaster details for the given `projectId`. The project
|
||||||
// identifier comes directly from the DB-driven /api/projects response.
|
// identifier comes directly from the DB-driven /api/projects response.
|
||||||
const hydrateProjectTaskMaster = useCallback(async (projectId: string) => {
|
const hydrateProjectTaskMaster = useCallback(async (projectId: string) => {
|
||||||
@@ -574,135 +391,98 @@ export function useProjectsState({
|
|||||||
}
|
}
|
||||||
}, [isLoadingProjects, projects, selectedProject, sessionId]);
|
}, [isLoadingProjects, projects, selectedProject, sessionId]);
|
||||||
|
|
||||||
// Realtime sidebar updates. The backend pushes per-session deltas
|
|
||||||
// (`session_upserted`) instead of full project snapshots, so each event is
|
|
||||||
// a keyed upsert that can never clobber unrelated client state — no
|
|
||||||
// "suppress updates while a run is active" protection is needed anymore.
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const handleEvent = (event: ServerEvent) => {
|
if (!latestMessage) {
|
||||||
if (event.kind === 'loading_progress') {
|
return;
|
||||||
if (loadingProgressTimeoutRef.current) {
|
}
|
||||||
clearTimeout(loadingProgressTimeoutRef.current);
|
|
||||||
|
// `latestMessage` is event-like data. This effect also depends on local state
|
||||||
|
// (`projects`, `selectedProject`, `selectedSession`) to compute derived updates.
|
||||||
|
// Without this guard, handling one websocket message can update that local
|
||||||
|
// state, retrigger the effect, and re-handle the same websocket message.
|
||||||
|
if (lastHandledMessageRef.current === latestMessage) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
lastHandledMessageRef.current = latestMessage;
|
||||||
|
|
||||||
|
if (latestMessage.type === 'loading_progress') {
|
||||||
|
if (loadingProgressTimeoutRef.current) {
|
||||||
|
clearTimeout(loadingProgressTimeoutRef.current);
|
||||||
|
loadingProgressTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoadingProgress(latestMessage as LoadingProgress);
|
||||||
|
|
||||||
|
if (latestMessage.phase === 'complete') {
|
||||||
|
loadingProgressTimeoutRef.current = setTimeout(() => {
|
||||||
|
setLoadingProgress(null);
|
||||||
loadingProgressTimeoutRef.current = null;
|
loadingProgressTimeoutRef.current = null;
|
||||||
}
|
}, 500);
|
||||||
|
|
||||||
setLoadingProgress(event as unknown as LoadingProgress);
|
|
||||||
|
|
||||||
if (event.phase === 'complete') {
|
|
||||||
loadingProgressTimeoutRef.current = setTimeout(() => {
|
|
||||||
setLoadingProgress(null);
|
|
||||||
loadingProgressTimeoutRef.current = null;
|
|
||||||
}, 500);
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.kind !== 'session_upserted') {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const upsert = event as SessionUpsertedEvent;
|
if (latestMessage.type !== 'projects_updated') {
|
||||||
if (!upsert.sessionId || !upsert.session) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// The transcript of the currently viewed session changed on disk while
|
const projectsMessage = latestMessage as ProjectsUpdatedMessage;
|
||||||
// no run is active here (e.g. edited from another client or the CLI):
|
|
||||||
// signal the chat view to reload its messages.
|
|
||||||
const currentSelectedSession = selectedSessionRef.current;
|
|
||||||
if (
|
|
||||||
currentSelectedSession
|
|
||||||
&& upsert.sessionId === currentSelectedSession.id
|
|
||||||
&& !activeSessionsRef.current.has(upsert.sessionId)
|
|
||||||
) {
|
|
||||||
setExternalMessageUpdate((prev) => prev + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
setProjects((previousProjects) => {
|
if (projectsMessage.updatedSessionId && selectedSession && selectedProject) {
|
||||||
const targetProjectId = upsert.project?.projectId;
|
if (projectsMessage.updatedSessionId === selectedSession.id) {
|
||||||
const existingProject = previousProjects.find((project) =>
|
const isSessionActive = activeSessions.has(selectedSession.id);
|
||||||
targetProjectId ? project.projectId === targetProjectId : getProjectSessions(project).some((session) => session.id === upsert.sessionId),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!existingProject) {
|
if (!isSessionActive) {
|
||||||
// First session of a project this client has never seen: create the
|
setExternalMessageUpdate((prev) => prev + 1);
|
||||||
// project entry from the event payload.
|
|
||||||
if (!upsert.project) {
|
|
||||||
return previousProjects;
|
|
||||||
}
|
|
||||||
|
|
||||||
const newProject: Project = {
|
|
||||||
projectId: upsert.project.projectId,
|
|
||||||
path: upsert.project.path,
|
|
||||||
fullPath: upsert.project.fullPath,
|
|
||||||
displayName: upsert.project.displayName,
|
|
||||||
isStarred: upsert.project.isStarred,
|
|
||||||
sessions: [],
|
|
||||||
sessionMeta: { hasMore: false, total: 0 },
|
|
||||||
} as Project;
|
|
||||||
|
|
||||||
return [...previousProjects, upsertSessionIntoProject(newProject, upsert)];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const updatedProject = upsertSessionIntoProject(existingProject, upsert);
|
|
||||||
if (updatedProject === existingProject) {
|
|
||||||
return previousProjects;
|
|
||||||
}
|
|
||||||
|
|
||||||
return previousProjects.map((project) =>
|
|
||||||
project.projectId === existingProject.projectId ? updatedProject : project,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Keep the selected project reference in sync with the upsert.
|
|
||||||
setSelectedProject((previousProject) => {
|
|
||||||
if (!previousProject) {
|
|
||||||
return previousProject;
|
|
||||||
}
|
|
||||||
const matches = upsert.project
|
|
||||||
? previousProject.projectId === upsert.project.projectId
|
|
||||||
: getProjectSessions(previousProject).some((session) => session.id === upsert.sessionId);
|
|
||||||
if (!matches) {
|
|
||||||
return previousProject;
|
|
||||||
}
|
|
||||||
const updated = upsertSessionIntoProject(previousProject, upsert);
|
|
||||||
return updated === previousProject ? previousProject : updated;
|
|
||||||
});
|
|
||||||
|
|
||||||
const aliasedSelectedSessionId =
|
|
||||||
typeof upsert.providerSessionId === 'string' && upsert.providerSessionId !== upsert.sessionId
|
|
||||||
? upsert.providerSessionId
|
|
||||||
: null;
|
|
||||||
if (!aliasedSelectedSessionId) {
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const normalizedSelectedSession: ProjectSession = {
|
const hasActiveSession = Boolean(selectedSession && activeSessions.has(selectedSession.id));
|
||||||
...upsert.session,
|
|
||||||
id: upsert.sessionId,
|
|
||||||
__provider: upsert.provider,
|
|
||||||
__projectId: upsert.project?.projectId ?? currentSelectedSession?.__projectId,
|
|
||||||
};
|
|
||||||
|
|
||||||
setSelectedSession((previousSession) => {
|
const updatedProjectsWithTaskMaster = mergeTaskMasterCache(projectsMessage.projects, projects);
|
||||||
if (previousSession?.id !== aliasedSelectedSessionId) {
|
const updatedProjects = mergeExpandedSessionPages(projects, updatedProjectsWithTaskMaster);
|
||||||
return previousSession;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
if (
|
||||||
...previousSession,
|
hasActiveSession &&
|
||||||
...normalizedSelectedSession,
|
!isUpdateAdditive(projects, updatedProjects, selectedProject, selectedSession)
|
||||||
};
|
) {
|
||||||
});
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (sessionId === aliasedSelectedSessionId) {
|
setProjects((previousProjects) =>
|
||||||
navigate(`/session/${upsert.sessionId}`);
|
projectsHaveChanges(previousProjects, updatedProjects, true) ? updatedProjects : previousProjects,
|
||||||
}
|
);
|
||||||
};
|
|
||||||
|
|
||||||
return subscribe(handleEvent);
|
if (!selectedProject) {
|
||||||
}, [navigate, sessionId, subscribe]);
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedSelectedProject = updatedProjects.find(
|
||||||
|
(project) => project.projectId === selectedProject.projectId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!updatedSelectedProject) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (serialize(updatedSelectedProject) !== serialize(selectedProject)) {
|
||||||
|
setSelectedProject(updatedSelectedProject);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!selectedSession) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedSelectedSession = getProjectSessions(updatedSelectedProject).find(
|
||||||
|
(session) => session.id === selectedSession.id,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!updatedSelectedSession) {
|
||||||
|
setSelectedSession(null);
|
||||||
|
}
|
||||||
|
}, [latestMessage, selectedProject, selectedSession, activeSessions, projects]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
@@ -720,29 +500,86 @@ export function useProjectsState({
|
|||||||
|
|
||||||
// Project membership is resolved through `projectId` after the migration.
|
// Project membership is resolved through `projectId` after the migration.
|
||||||
for (const project of projects) {
|
for (const project of projects) {
|
||||||
const match = project.sessions?.find((session) => session.id === sessionId);
|
const claudeSession = project.sessions?.find((session) => session.id === sessionId);
|
||||||
if (match) {
|
if (claudeSession) {
|
||||||
const normalizedSession = normalizeSessionProvider(match);
|
|
||||||
const shouldUpdateProject = selectedProject?.projectId !== project.projectId;
|
const shouldUpdateProject = selectedProject?.projectId !== project.projectId;
|
||||||
const shouldUpdateSession =
|
const shouldUpdateSession =
|
||||||
selectedSession?.id !== sessionId || selectedSession.__provider !== normalizedSession.__provider;
|
selectedSession?.id !== sessionId || selectedSession.__provider !== 'claude';
|
||||||
|
|
||||||
if (shouldUpdateProject) {
|
if (shouldUpdateProject) {
|
||||||
setSelectedProject(project);
|
setSelectedProject(project);
|
||||||
}
|
}
|
||||||
if (shouldUpdateSession) {
|
if (shouldUpdateSession) {
|
||||||
setSelectedSession(normalizedSession);
|
setSelectedSession({ ...claudeSession, __provider: 'claude' });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cursorSession = project.cursorSessions?.find((session) => session.id === sessionId);
|
||||||
|
if (cursorSession) {
|
||||||
|
const shouldUpdateProject = selectedProject?.projectId !== project.projectId;
|
||||||
|
const shouldUpdateSession =
|
||||||
|
selectedSession?.id !== sessionId || selectedSession.__provider !== 'cursor';
|
||||||
|
|
||||||
|
if (shouldUpdateProject) {
|
||||||
|
setSelectedProject(project);
|
||||||
|
}
|
||||||
|
if (shouldUpdateSession) {
|
||||||
|
setSelectedSession({ ...cursorSession, __provider: 'cursor' });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const codexSession = project.codexSessions?.find((session) => session.id === sessionId);
|
||||||
|
if (codexSession) {
|
||||||
|
const shouldUpdateProject = selectedProject?.projectId !== project.projectId;
|
||||||
|
const shouldUpdateSession =
|
||||||
|
selectedSession?.id !== sessionId || selectedSession.__provider !== 'codex';
|
||||||
|
|
||||||
|
if (shouldUpdateProject) {
|
||||||
|
setSelectedProject(project);
|
||||||
|
}
|
||||||
|
if (shouldUpdateSession) {
|
||||||
|
setSelectedSession({ ...codexSession, __provider: 'codex' });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const geminiSession = project.geminiSessions?.find((session) => session.id === sessionId);
|
||||||
|
if (geminiSession) {
|
||||||
|
const shouldUpdateProject = selectedProject?.projectId !== project.projectId;
|
||||||
|
const shouldUpdateSession =
|
||||||
|
selectedSession?.id !== sessionId || selectedSession.__provider !== 'gemini';
|
||||||
|
|
||||||
|
if (shouldUpdateProject) {
|
||||||
|
setSelectedProject(project);
|
||||||
|
}
|
||||||
|
if (shouldUpdateSession) {
|
||||||
|
setSelectedSession({ ...geminiSession, __provider: 'gemini' });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const opencodeSession = project.opencodeSessions?.find((session) => session.id === sessionId);
|
||||||
|
if (opencodeSession) {
|
||||||
|
const shouldUpdateProject = selectedProject?.projectId !== project.projectId;
|
||||||
|
const shouldUpdateSession =
|
||||||
|
selectedSession?.id !== sessionId || selectedSession.__provider !== 'opencode';
|
||||||
|
|
||||||
|
if (shouldUpdateProject) {
|
||||||
|
setSelectedProject(project);
|
||||||
|
}
|
||||||
|
if (shouldUpdateSession) {
|
||||||
|
setSelectedSession({ ...opencodeSession, __provider: 'opencode' });
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Session id is in the URL but not yet present on any project payload
|
// Session id is in the URL but not yet present on any project payload (common
|
||||||
// (normal for a brand-new conversation: the composer allocates the id and
|
// right after `session_created` + navigate, before the next projects refresh).
|
||||||
// navigates before the sidebar learns about the session via
|
// Without a `selectedSession`, chat state clears `currentSessionId` and the
|
||||||
// `session_upserted`). Without a `selectedSession`, chat state clears
|
// UI stops reading the session store even though messages stream under this id.
|
||||||
// `currentSessionId` and the UI stops reading the session store even
|
|
||||||
// though messages stream under this id — so synthesize a placeholder.
|
|
||||||
if (selectedSession?.id === sessionId) {
|
if (selectedSession?.id === sessionId) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -751,9 +588,27 @@ export function useProjectsState({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let providerFromStorage: string | null = null;
|
||||||
|
try {
|
||||||
|
providerFromStorage = localStorage.getItem('selected-provider');
|
||||||
|
} catch {
|
||||||
|
providerFromStorage = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedProvider: LLMProvider =
|
||||||
|
providerFromStorage === 'cursor'
|
||||||
|
? 'cursor'
|
||||||
|
: providerFromStorage === 'codex'
|
||||||
|
? 'codex'
|
||||||
|
: providerFromStorage === 'gemini'
|
||||||
|
? 'gemini'
|
||||||
|
: providerFromStorage === 'opencode'
|
||||||
|
? 'opencode'
|
||||||
|
: 'claude';
|
||||||
|
|
||||||
setSelectedSession({
|
setSelectedSession({
|
||||||
id: sessionId,
|
id: sessionId,
|
||||||
__provider: readSelectedProvider(),
|
__provider: normalizedProvider,
|
||||||
__projectId: selectedProject.projectId,
|
__projectId: selectedProject.projectId,
|
||||||
summary: '',
|
summary: '',
|
||||||
});
|
});
|
||||||
@@ -780,6 +635,11 @@ export function useProjectsState({
|
|||||||
setActiveTab('chat');
|
setActiveTab('chat');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const provider = localStorage.getItem('selected-provider') || 'claude';
|
||||||
|
if (provider === 'cursor') {
|
||||||
|
sessionStorage.setItem('cursorSessionId', session.id);
|
||||||
|
}
|
||||||
|
|
||||||
if (isMobile) {
|
if (isMobile) {
|
||||||
// Sessions are tagged with the owning project's DB `projectId` when
|
// Sessions are tagged with the owning project's DB `projectId` when
|
||||||
// picked from the sidebar (see useSidebarController); compare against
|
// picked from the sidebar (see useSidebarController); compare against
|
||||||
@@ -821,7 +681,43 @@ export function useProjectsState({
|
|||||||
}
|
}
|
||||||
|
|
||||||
setProjects((prevProjects) =>
|
setProjects((prevProjects) =>
|
||||||
prevProjects.map((project) => removeSessionFromProject(project, sessionIdToDelete)),
|
prevProjects.map((project) => {
|
||||||
|
const sessions = project.sessions?.filter((session) => session.id !== sessionIdToDelete) ?? [];
|
||||||
|
const cursorSessions = project.cursorSessions?.filter((session) => session.id !== sessionIdToDelete) ?? [];
|
||||||
|
const codexSessions = project.codexSessions?.filter((session) => session.id !== sessionIdToDelete) ?? [];
|
||||||
|
const geminiSessions = project.geminiSessions?.filter((session) => session.id !== sessionIdToDelete) ?? [];
|
||||||
|
const opencodeSessions = project.opencodeSessions?.filter((session) => session.id !== sessionIdToDelete) ?? [];
|
||||||
|
|
||||||
|
const removedFromProject = (
|
||||||
|
sessions.length !== (project.sessions?.length ?? 0)
|
||||||
|
|| cursorSessions.length !== (project.cursorSessions?.length ?? 0)
|
||||||
|
|| codexSessions.length !== (project.codexSessions?.length ?? 0)
|
||||||
|
|| geminiSessions.length !== (project.geminiSessions?.length ?? 0)
|
||||||
|
|| opencodeSessions.length !== (project.opencodeSessions?.length ?? 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!removedFromProject) {
|
||||||
|
return project;
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedProject: Project = {
|
||||||
|
...project,
|
||||||
|
sessions,
|
||||||
|
cursorSessions,
|
||||||
|
codexSessions,
|
||||||
|
geminiSessions,
|
||||||
|
opencodeSessions,
|
||||||
|
};
|
||||||
|
|
||||||
|
const totalSessions = Math.max(0, Number(project.sessionMeta?.total ?? 0) - 1);
|
||||||
|
updatedProject.sessionMeta = {
|
||||||
|
...project.sessionMeta,
|
||||||
|
total: totalSessions,
|
||||||
|
hasMore: countLoadedProjectSessions(updatedProject) < totalSessions,
|
||||||
|
};
|
||||||
|
|
||||||
|
return updatedProject;
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
[navigate, selectedSession?.id],
|
[navigate, selectedSession?.id],
|
||||||
@@ -835,7 +731,7 @@ export function useProjectsState({
|
|||||||
const mergedProjects = mergeExpandedSessionPages(projects, projectsWithTaskMaster);
|
const mergedProjects = mergeExpandedSessionPages(projects, projectsWithTaskMaster);
|
||||||
|
|
||||||
setProjects((prevProjects) =>
|
setProjects((prevProjects) =>
|
||||||
projectsHaveChanges(prevProjects, mergedProjects) ? mergedProjects : prevProjects,
|
projectsHaveChanges(prevProjects, mergedProjects, true) ? mergedProjects : prevProjects,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!selectedProject) {
|
if (!selectedProject) {
|
||||||
@@ -904,7 +800,7 @@ export function useProjectsState({
|
|||||||
throw new Error(message);
|
throw new Error(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
const sessionsPage = (await response.json()) as ProjectSessionPage;
|
const sessionsPage = (await response.json()) as Pick<Project, 'sessions' | 'cursorSessions' | 'codexSessions' | 'geminiSessions' | 'opencodeSessions' | 'sessionMeta'>;
|
||||||
|
|
||||||
let mergedProjectForSelection: Project | null = null;
|
let mergedProjectForSelection: Project | null = null;
|
||||||
setProjects((previousProjects) =>
|
setProjects((previousProjects) =>
|
||||||
@@ -944,7 +840,6 @@ export function useProjectsState({
|
|||||||
projects,
|
projects,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
selectedSession,
|
selectedSession,
|
||||||
activeSessions,
|
|
||||||
onProjectSelect: handleProjectSelect,
|
onProjectSelect: handleProjectSelect,
|
||||||
onSessionSelect: handleSessionSelect,
|
onSessionSelect: handleSessionSelect,
|
||||||
onNewSession: handleNewSession,
|
onNewSession: handleNewSession,
|
||||||
@@ -971,7 +866,6 @@ export function useProjectsState({
|
|||||||
isLoadingProjects,
|
isLoadingProjects,
|
||||||
isMobile,
|
isMobile,
|
||||||
loadingProgress,
|
loadingProgress,
|
||||||
activeSessions,
|
|
||||||
projects,
|
projects,
|
||||||
settingsInitialTab,
|
settingsInitialTab,
|
||||||
selectedProject,
|
selectedProject,
|
||||||
@@ -1000,7 +894,6 @@ export function useProjectsState({
|
|||||||
openSettings,
|
openSettings,
|
||||||
fetchProjects,
|
fetchProjects,
|
||||||
refreshProjectsSilently,
|
refreshProjectsSilently,
|
||||||
registerOptimisticSession,
|
|
||||||
sidebarSharedProps,
|
sidebarSharedProps,
|
||||||
handleProjectSelect,
|
handleProjectSelect,
|
||||||
handleSessionSelect,
|
handleSessionSelect,
|
||||||
|
|||||||
@@ -1,172 +1,55 @@
|
|||||||
import { useCallback, useState } from 'react';
|
import { useCallback, useState } from 'react';
|
||||||
|
|
||||||
export interface SessionActivity {
|
|
||||||
/** Provider-supplied status line; null renders the default activity label. */
|
|
||||||
statusText: string | null;
|
|
||||||
canInterrupt: boolean;
|
|
||||||
/**
|
|
||||||
* When this request was first marked as processing (client clock). Drives
|
|
||||||
* the elapsed-time display and the stale `session-status` reply guard.
|
|
||||||
*/
|
|
||||||
startedAt: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type SessionActivityMap = ReadonlyMap<string, SessionActivity>;
|
|
||||||
|
|
||||||
export type SessionActivitySnapshot = {
|
|
||||||
sessionId: string;
|
|
||||||
statusText?: string | null;
|
|
||||||
canInterrupt?: boolean;
|
|
||||||
startedAt?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type MarkSessionProcessing = (
|
|
||||||
sessionId?: string | null,
|
|
||||||
activity?: { statusText?: string | null; canInterrupt?: boolean },
|
|
||||||
) => void;
|
|
||||||
|
|
||||||
export type MarkSessionIdle = (
|
|
||||||
sessionId?: string | null,
|
|
||||||
opts?: { ifStartedBefore?: number },
|
|
||||||
) => void;
|
|
||||||
|
|
||||||
export type SyncProcessingSessions = (
|
|
||||||
sessions: readonly SessionActivitySnapshot[],
|
|
||||||
) => void;
|
|
||||||
|
|
||||||
const LOCAL_ACTIVITY_GRACE_MS = 10_000;
|
|
||||||
|
|
||||||
const sessionActivityMapsMatch = (
|
|
||||||
left: ReadonlyMap<string, SessionActivity>,
|
|
||||||
right: ReadonlyMap<string, SessionActivity>,
|
|
||||||
): boolean => {
|
|
||||||
if (left.size !== right.size) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const [sessionId, leftActivity] of left) {
|
|
||||||
const rightActivity = right.get(sessionId);
|
|
||||||
if (
|
|
||||||
!rightActivity
|
|
||||||
|| leftActivity.statusText !== rightActivity.statusText
|
|
||||||
|| leftActivity.canInterrupt !== rightActivity.canInterrupt
|
|
||||||
|| leftActivity.startedAt !== rightActivity.startedAt
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Single source of truth for which sessions are actively processing a
|
|
||||||
* request. Everything the chat UI shows (activity indicator, abort
|
|
||||||
* availability, status text) is derived from this map; terminal events
|
|
||||||
* (`complete`, abort, an authoritative idle subscribe ack) delete the entry
|
|
||||||
* atomically. Session ids are always concrete (allocated before the first
|
|
||||||
* send), so entries are keyed by real session ids only.
|
|
||||||
*/
|
|
||||||
export function useSessionProtection() {
|
export function useSessionProtection() {
|
||||||
const [processingSessions, setProcessingSessions] = useState<Map<string, SessionActivity>>(
|
const [activeSessions, setActiveSessions] = useState<Set<string>>(new Set());
|
||||||
new Map(),
|
const [processingSessions, setProcessingSessions] = useState<Set<string>>(new Set());
|
||||||
);
|
|
||||||
|
|
||||||
const markSessionProcessing = useCallback<MarkSessionProcessing>((sessionId, activity) => {
|
const markSessionAsActive = useCallback((sessionId?: string | null) => {
|
||||||
|
if (!sessionId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setActiveSessions((prev) => new Set([...prev, sessionId]));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const markSessionAsInactive = useCallback((sessionId?: string | null) => {
|
||||||
|
if (!sessionId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setActiveSessions((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
next.delete(sessionId);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const markSessionAsProcessing = useCallback((sessionId?: string | null) => {
|
||||||
|
if (!sessionId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setProcessingSessions((prev) => new Set([...prev, sessionId]));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const markSessionAsNotProcessing = useCallback((sessionId?: string | null) => {
|
||||||
if (!sessionId) {
|
if (!sessionId) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setProcessingSessions((prev) => {
|
setProcessingSessions((prev) => {
|
||||||
const existing = prev.get(sessionId);
|
const next = new Set(prev);
|
||||||
const next: SessionActivity = {
|
next.delete(sessionId);
|
||||||
statusText:
|
return next;
|
||||||
activity?.statusText !== undefined ? activity.statusText : existing?.statusText ?? null,
|
|
||||||
canInterrupt: activity?.canInterrupt ?? existing?.canInterrupt ?? true,
|
|
||||||
startedAt: existing?.startedAt ?? Date.now(),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (
|
|
||||||
existing
|
|
||||||
&& existing.statusText === next.statusText
|
|
||||||
&& existing.canInterrupt === next.canInterrupt
|
|
||||||
) {
|
|
||||||
return prev;
|
|
||||||
}
|
|
||||||
|
|
||||||
const updated = new Map(prev);
|
|
||||||
updated.set(sessionId, next);
|
|
||||||
return updated;
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const markSessionIdle = useCallback<MarkSessionIdle>((sessionId, opts) => {
|
|
||||||
if (!sessionId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setProcessingSessions((prev) => {
|
|
||||||
const existing = prev.get(sessionId);
|
|
||||||
if (!existing) {
|
|
||||||
return prev;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Guard against stale `chat_subscribed` idle acks: if a new request
|
|
||||||
// started after the subscribe was sent, the idle ack describes the
|
|
||||||
// older request and must not clear the newer one.
|
|
||||||
if (opts?.ifStartedBefore !== undefined && existing.startedAt >= opts.ifStartedBefore) {
|
|
||||||
return prev;
|
|
||||||
}
|
|
||||||
|
|
||||||
const updated = new Map(prev);
|
|
||||||
updated.delete(sessionId);
|
|
||||||
return updated;
|
|
||||||
});
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const syncProcessingSessions = useCallback<SyncProcessingSessions>((sessions) => {
|
|
||||||
const now = Date.now();
|
|
||||||
|
|
||||||
setProcessingSessions((prev) => {
|
|
||||||
const incoming = new Map<string, SessionActivitySnapshot>();
|
|
||||||
for (const session of sessions) {
|
|
||||||
if (!session.sessionId) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
incoming.set(session.sessionId, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
const updated = new Map<string, SessionActivity>();
|
|
||||||
|
|
||||||
for (const [sessionId, snapshot] of incoming) {
|
|
||||||
const existing = prev.get(sessionId);
|
|
||||||
const snapshotStartedAt =
|
|
||||||
typeof snapshot.startedAt === 'number' && Number.isFinite(snapshot.startedAt) && snapshot.startedAt > 0
|
|
||||||
? snapshot.startedAt
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
updated.set(sessionId, {
|
|
||||||
statusText:
|
|
||||||
snapshot.statusText !== undefined ? snapshot.statusText : existing?.statusText ?? null,
|
|
||||||
canInterrupt: snapshot.canInterrupt ?? existing?.canInterrupt ?? true,
|
|
||||||
startedAt: snapshotStartedAt ?? existing?.startedAt ?? now,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const [sessionId, activity] of prev) {
|
|
||||||
if (!incoming.has(sessionId) && now - activity.startedAt < LOCAL_ACTIVITY_GRACE_MS) {
|
|
||||||
updated.set(sessionId, activity);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return sessionActivityMapsMatch(prev, updated) ? prev : updated;
|
|
||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
activeSessions,
|
||||||
processingSessions,
|
processingSessions,
|
||||||
markSessionProcessing,
|
markSessionAsActive,
|
||||||
markSessionIdle,
|
markSessionAsInactive,
|
||||||
syncProcessingSessions,
|
markSessionAsProcessing,
|
||||||
|
markSessionAsNotProcessing,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -224,7 +224,6 @@
|
|||||||
"label": "{{time}} elapsed",
|
"label": "{{time}} elapsed",
|
||||||
"startingNow": "Starting now"
|
"startingNow": "Starting now"
|
||||||
},
|
},
|
||||||
"stop": "Stop",
|
|
||||||
"controls": {
|
"controls": {
|
||||||
"stopGeneration": "Stop Generation",
|
"stopGeneration": "Stop Generation",
|
||||||
"pressEscToStop": "Press Esc anytime to stop"
|
"pressEscToStop": "Press Esc anytime to stop"
|
||||||
|
|||||||
@@ -514,6 +514,30 @@
|
|||||||
"description": "Session intelligence for Claude Code, inside CloudCLI. See why your sessions are burning tokens without leaving the browser.",
|
"description": "Session intelligence for Claude Code, inside CloudCLI. See why your sessions are burning tokens without leaving the browser.",
|
||||||
"install": "Install"
|
"install": "Install"
|
||||||
},
|
},
|
||||||
|
"sessionManagerPlugin": {
|
||||||
|
"name": "Sessions",
|
||||||
|
"badge": "unofficial",
|
||||||
|
"description": "View, manage, and kill active Claude Code sessions.",
|
||||||
|
"install": "Install"
|
||||||
|
},
|
||||||
|
"tokenCostCalculatorPlugin": {
|
||||||
|
"name": "Token Cost Calculator",
|
||||||
|
"badge": "unofficial",
|
||||||
|
"description": "Calculate API costs from model prices and token usage, with preset model pricing support.",
|
||||||
|
"install": "Install"
|
||||||
|
},
|
||||||
|
"taskQueuePlugin": {
|
||||||
|
"name": "Task Queue",
|
||||||
|
"badge": "unofficial",
|
||||||
|
"description": "Task queue dashboard to view, filter, and launch agent tasks.",
|
||||||
|
"install": "Install"
|
||||||
|
},
|
||||||
|
"githubIssuesBoardPlugin": {
|
||||||
|
"name": "GitHub Issues Board",
|
||||||
|
"badge": "unofficial",
|
||||||
|
"description": "Kanban board for GitHub Issues with bidirectional TaskMaster sync and /github-task CLI skill auto-install",
|
||||||
|
"install": "Install"
|
||||||
|
},
|
||||||
"morePlugins": "More",
|
"morePlugins": "More",
|
||||||
"enable": "Enable",
|
"enable": "Enable",
|
||||||
"disable": "Disable",
|
"disable": "Disable",
|
||||||
|
|||||||
@@ -36,12 +36,6 @@ export interface NormalizedMessage {
|
|||||||
timestamp: string;
|
timestamp: string;
|
||||||
provider: LLMProvider;
|
provider: LLMProvider;
|
||||||
kind: MessageKind;
|
kind: MessageKind;
|
||||||
/**
|
|
||||||
* Per-run monotonic sequence number assigned by the backend to live
|
|
||||||
* websocket events. Used to compute `lastSeq` for `chat.subscribe` replay;
|
|
||||||
* REST history messages do not carry it.
|
|
||||||
*/
|
|
||||||
seq?: number;
|
|
||||||
|
|
||||||
// kind-specific fields (flat for simplicity)
|
// kind-specific fields (flat for simplicity)
|
||||||
role?: 'user' | 'assistant';
|
role?: 'user' | 'assistant';
|
||||||
@@ -128,146 +122,12 @@ function createEmptySlot(): SessionSlot {
|
|||||||
* assistant echo (same trimmed text), so finalized stream rows do not stack
|
* assistant echo (same trimmed text), so finalized stream rows do not stack
|
||||||
* on top of the persisted copy before realtime is cleared.
|
* on top of the persisted copy before realtime is cleared.
|
||||||
*/
|
*/
|
||||||
const LOCAL_USER_DEDUPE_WINDOW_MS = 5 * 60 * 1000;
|
|
||||||
const LOCAL_USER_DEDUPE_CLOCK_SKEW_MS = 10_000;
|
|
||||||
|
|
||||||
function userTextFingerprint(m: NormalizedMessage): string | null {
|
function userTextFingerprint(m: NormalizedMessage): string | null {
|
||||||
if (m.kind !== 'text' || m.role !== 'user') return null;
|
if (m.kind !== 'text' || m.role !== 'user') return null;
|
||||||
const t = (m.content || '').trim();
|
const t = (m.content || '').trim();
|
||||||
return t.length > 0 ? t : null;
|
return t.length > 0 ? t : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function readMessageTime(m: NormalizedMessage): number | null {
|
|
||||||
const time = Date.parse(m.timestamp);
|
|
||||||
return Number.isFinite(time) ? time : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasServerEchoForLocalUser(
|
|
||||||
localMessage: NormalizedMessage,
|
|
||||||
serverMessages: NormalizedMessage[],
|
|
||||||
): boolean {
|
|
||||||
const localText = userTextFingerprint(localMessage);
|
|
||||||
const localTime = readMessageTime(localMessage);
|
|
||||||
if (!localText || localTime === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return serverMessages.some((serverMessage) => {
|
|
||||||
if (userTextFingerprint(serverMessage) !== localText) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const serverTime = readMessageTime(serverMessage);
|
|
||||||
return (
|
|
||||||
serverTime !== null
|
|
||||||
&& serverTime >= localTime - LOCAL_USER_DEDUPE_CLOCK_SKEW_MS
|
|
||||||
&& serverTime - localTime <= LOCAL_USER_DEDUPE_WINDOW_MS
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function compareMessagesChronologically(a: NormalizedMessage, b: NormalizedMessage): number {
|
|
||||||
const timeA = readMessageTime(a) ?? 0;
|
|
||||||
const timeB = readMessageTime(b) ?? 0;
|
|
||||||
if (timeA !== timeB) {
|
|
||||||
return timeA - timeB;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Count how many user turns precede `message` in a chronologically merged view
|
|
||||||
* of server + realtime rows. Used to match a realtime row to the correct turn
|
|
||||||
* on disk when several turns share identical assistant text.
|
|
||||||
*/
|
|
||||||
function getUserTurnOrdinalBefore(
|
|
||||||
message: NormalizedMessage,
|
|
||||||
serverMessages: NormalizedMessage[],
|
|
||||||
realtimeMessages: NormalizedMessage[],
|
|
||||||
): number {
|
|
||||||
const messageTime = readMessageTime(message);
|
|
||||||
let userCount = 0;
|
|
||||||
|
|
||||||
for (const candidate of [...serverMessages, ...realtimeMessages].sort(compareMessagesChronologically)) {
|
|
||||||
if (candidate.id === message.id) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
const candidateTime = readMessageTime(candidate);
|
|
||||||
if (
|
|
||||||
messageTime !== null
|
|
||||||
&& candidateTime !== null
|
|
||||||
&& candidateTime > messageTime
|
|
||||||
) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (candidate.kind === 'text' && candidate.role === 'user') {
|
|
||||||
userCount++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Math.max(0, userCount - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function findServerTurnRangeByOrdinal(
|
|
||||||
serverMessages: NormalizedMessage[],
|
|
||||||
turnOrdinal: number,
|
|
||||||
): { start: number; end: number } | null {
|
|
||||||
let userCount = -1;
|
|
||||||
let start = -1;
|
|
||||||
|
|
||||||
for (let index = 0; index < serverMessages.length; index++) {
|
|
||||||
const message = serverMessages[index];
|
|
||||||
if (message.kind === 'text' && message.role === 'user') {
|
|
||||||
userCount++;
|
|
||||||
if (userCount === turnOrdinal) {
|
|
||||||
start = index;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (start < 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
let end = serverMessages.length;
|
|
||||||
for (let index = start + 1; index < serverMessages.length; index++) {
|
|
||||||
if (serverMessages[index].kind === 'text' && serverMessages[index].role === 'user') {
|
|
||||||
end = index;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { start, end };
|
|
||||||
}
|
|
||||||
|
|
||||||
function isAssistantTextEchoedInSameTurnOnServer(
|
|
||||||
message: NormalizedMessage,
|
|
||||||
serverMessages: NormalizedMessage[],
|
|
||||||
realtimeMessages: NormalizedMessage[],
|
|
||||||
): boolean {
|
|
||||||
const assistantText = (message.content || '').trim();
|
|
||||||
if (!assistantText) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const turnOrdinal = getUserTurnOrdinalBefore(message, serverMessages, realtimeMessages);
|
|
||||||
const turnRange = findServerTurnRangeByOrdinal(serverMessages, turnOrdinal);
|
|
||||||
if (!turnRange) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return serverMessages
|
|
||||||
.slice(turnRange.start + 1, turnRange.end)
|
|
||||||
.some((serverMessage) =>
|
|
||||||
serverMessage.kind === 'text'
|
|
||||||
&& serverMessage.role === 'assistant'
|
|
||||||
&& (serverMessage.content || '').trim() === assistantText,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* After `finalizeStreaming`, the client holds a synthetic assistant `text` row
|
* After `finalizeStreaming`, the client holds a synthetic assistant `text` row
|
||||||
* while the sessions API soon returns the same reply with a different id.
|
* while the sessions API soon returns the same reply with a different id.
|
||||||
@@ -305,92 +165,79 @@ function dedupeAdjacentAssistantEchoes(merged: NormalizedMessage[]): NormalizedM
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function computeMerged(server: NormalizedMessage[], realtime: NormalizedMessage[]): NormalizedMessage[] {
|
||||||
* After a server refresh, drop only the realtime rows the persisted transcript
|
if (realtime.length === 0) return server;
|
||||||
* already owns. Anything not yet on disk (common right after `complete`, while
|
if (server.length === 0) return dedupeAdjacentAssistantEchoes(realtime);
|
||||||
* JSONL indexing lags) stays in `realtimeMessages` so the chat pane never
|
const serverIds = new Set(server.map(m => m.id));
|
||||||
* flashes the empty "Continue your conversation" state.
|
const serverUserTexts = new Set(
|
||||||
*/
|
server.map(userTextFingerprint).filter((t): t is string => t !== null),
|
||||||
function pruneRealtimeSupersededByServer(
|
);
|
||||||
serverMessages: NormalizedMessage[],
|
const extra = realtime.filter((m) => {
|
||||||
realtimeMessages: NormalizedMessage[],
|
if (serverIds.has(m.id)) return false;
|
||||||
): NormalizedMessage[] {
|
// Optimistic user rows use `local_*` ids; once the same text exists on the
|
||||||
if (realtimeMessages.length === 0) {
|
// server-backed copy, drop the realtime echo to avoid duplicate bubbles.
|
||||||
return realtimeMessages;
|
if (m.id.startsWith('local_')) {
|
||||||
}
|
const fp = userTextFingerprint(m);
|
||||||
|
if (fp && serverUserTexts.has(fp)) return false;
|
||||||
const serverIds = new Set(serverMessages.map((message) => message.id));
|
|
||||||
|
|
||||||
return realtimeMessages.filter((message) => {
|
|
||||||
if (serverIds.has(message.id)) {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (message.id.startsWith('local_') && hasServerEchoForLocalUser(message, serverMessages)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (message.kind === 'stream_delta' || message.id === `__streaming_${message.sessionId}`) {
|
|
||||||
if (isAssistantTextEchoedInSameTurnOnServer(message, serverMessages, realtimeMessages)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (message.kind === 'text' && message.role === 'assistant') {
|
|
||||||
if (isAssistantTextEchoedInSameTurnOnServer(message, serverMessages, realtimeMessages)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (message.kind === 'text' && message.role === 'user') {
|
|
||||||
return !hasServerEchoForLocalUser(message, serverMessages);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (message.kind === 'tool_use' && message.toolId) {
|
|
||||||
if (serverMessages.some((serverMessage) => serverMessage.kind === 'tool_use' && serverMessage.toolId === message.toolId)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
if (extra.length === 0) return server;
|
||||||
|
return dedupeAdjacentAssistantEchoes([...server, ...extra]);
|
||||||
}
|
}
|
||||||
|
|
||||||
function computeMerged(server: NormalizedMessage[], realtime: NormalizedMessage[]): NormalizedMessage[] {
|
function compareMessagesByTimestamp(left: NormalizedMessage, right: NormalizedMessage): number {
|
||||||
if (realtime.length === 0) {
|
const leftTime = Date.parse(left.timestamp);
|
||||||
return dedupeAdjacentAssistantEchoes(server);
|
const rightTime = Date.parse(right.timestamp);
|
||||||
}
|
|
||||||
if (server.length === 0) {
|
if (Number.isNaN(leftTime) || Number.isNaN(rightTime) || leftTime === rightTime) {
|
||||||
return dedupeAdjacentAssistantEchoes(realtime);
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
const serverIds = new Set(server.map((message) => message.id));
|
return leftTime - rightTime;
|
||||||
const extra = realtime.filter((message) => {
|
}
|
||||||
if (serverIds.has(message.id)) {
|
|
||||||
return false;
|
function rewriteMessageSessionId(
|
||||||
|
msg: NormalizedMessage,
|
||||||
|
fromSessionId: string,
|
||||||
|
toSessionId: string,
|
||||||
|
): NormalizedMessage {
|
||||||
|
const streamingSourceId = `__streaming_${fromSessionId}`;
|
||||||
|
const nextId = msg.id === streamingSourceId ? `__streaming_${toSessionId}` : msg.id;
|
||||||
|
|
||||||
|
if (msg.sessionId === toSessionId && nextId === msg.id) {
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...msg,
|
||||||
|
id: nextId,
|
||||||
|
sessionId: toSessionId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeMessagesById(
|
||||||
|
existing: NormalizedMessage[],
|
||||||
|
incoming: NormalizedMessage[],
|
||||||
|
): NormalizedMessage[] {
|
||||||
|
if (existing.length === 0) return incoming;
|
||||||
|
if (incoming.length === 0) return existing;
|
||||||
|
|
||||||
|
const merged = [...existing, ...incoming];
|
||||||
|
const deduped: NormalizedMessage[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
for (const msg of merged) {
|
||||||
|
if (seen.has(msg.id)) {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
// Optimistic user rows use `local_*` ids; once the same text exists on the
|
|
||||||
// server-backed copy from the same send window, drop the realtime echo to
|
|
||||||
// avoid duplicate bubbles without hiding repeated prompts from history.
|
|
||||||
if (message.id.startsWith('local_')) {
|
|
||||||
if (hasServerEchoForLocalUser(message, server)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (extra.length === 0) {
|
seen.add(msg.id);
|
||||||
return dedupeAdjacentAssistantEchoes(server);
|
deduped.push(msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Interleave by timestamp so live rows stay with their turn instead of
|
deduped.sort(compareMessagesByTimestamp);
|
||||||
// piling up at the bottom after every refresh.
|
return deduped;
|
||||||
return dedupeAdjacentAssistantEchoes(
|
|
||||||
[...server, ...extra].sort(compareMessagesChronologically),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -417,50 +264,79 @@ const MAX_REALTIME_MESSAGES = 500;
|
|||||||
|
|
||||||
export function useSessionStore() {
|
export function useSessionStore() {
|
||||||
const storeRef = useRef(new Map<string, SessionSlot>());
|
const storeRef = useRef(new Map<string, SessionSlot>());
|
||||||
|
const sessionAliasesRef = useRef(new Map<string, string>());
|
||||||
const activeSessionIdRef = useRef<string | null>(null);
|
const activeSessionIdRef = useRef<string | null>(null);
|
||||||
// Bump to force re-render — only when the active session's data changes.
|
// Bump to force re-render — only when the active session's data changes
|
||||||
// Session ids are stable for the whole conversation lifetime (the backend
|
|
||||||
// allocates them before the first send), so slots are keyed directly with
|
|
||||||
// no alias/redirect indirection.
|
|
||||||
const [, setTick] = useState(0);
|
const [, setTick] = useState(0);
|
||||||
const notify = useCallback((sessionId: string) => {
|
const notify = useCallback((sessionId: string) => {
|
||||||
if (sessionId === activeSessionIdRef.current) {
|
const aliases = sessionAliasesRef.current;
|
||||||
|
let resolvedSessionId = sessionId;
|
||||||
|
const visited = new Set<string>();
|
||||||
|
|
||||||
|
while (aliases.has(resolvedSessionId) && !visited.has(resolvedSessionId)) {
|
||||||
|
visited.add(resolvedSessionId);
|
||||||
|
resolvedSessionId = aliases.get(resolvedSessionId)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resolvedSessionId === activeSessionIdRef.current) {
|
||||||
setTick(n => n + 1);
|
setTick(n => n + 1);
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const setActiveSession = useCallback((sessionId: string | null) => {
|
const resolveSessionId = useCallback((sessionId: string | null | undefined): string | null => {
|
||||||
activeSessionIdRef.current = sessionId;
|
if (!sessionId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const aliases = sessionAliasesRef.current;
|
||||||
|
let resolvedSessionId = sessionId;
|
||||||
|
const visited = new Set<string>();
|
||||||
|
|
||||||
|
while (aliases.has(resolvedSessionId) && !visited.has(resolvedSessionId)) {
|
||||||
|
visited.add(resolvedSessionId);
|
||||||
|
resolvedSessionId = aliases.get(resolvedSessionId)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolvedSessionId;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const setActiveSession = useCallback((sessionId: string | null) => {
|
||||||
|
activeSessionIdRef.current = resolveSessionId(sessionId);
|
||||||
|
}, [resolveSessionId]);
|
||||||
|
|
||||||
const getSlot = useCallback((sessionId: string): SessionSlot => {
|
const getSlot = useCallback((sessionId: string): SessionSlot => {
|
||||||
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
const store = storeRef.current;
|
const store = storeRef.current;
|
||||||
if (!store.has(sessionId)) {
|
if (!store.has(resolvedSessionId)) {
|
||||||
store.set(sessionId, createEmptySlot());
|
store.set(resolvedSessionId, createEmptySlot());
|
||||||
}
|
}
|
||||||
return store.get(sessionId)!;
|
return store.get(resolvedSessionId)!;
|
||||||
}, []);
|
}, [resolveSessionId]);
|
||||||
|
|
||||||
const has = useCallback((sessionId: string) => {
|
const has = useCallback((sessionId: string) => {
|
||||||
return storeRef.current.has(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
}, []);
|
return storeRef.current.has(resolvedSessionId);
|
||||||
|
}, [resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch messages from the provider sessions endpoint and populate serverMessages.
|
* Fetch messages from the provider sessions endpoint and populate serverMessages.
|
||||||
*
|
*
|
||||||
* Provider and project metadata are resolved server-side from `sessionId`.
|
* Provider and project metadata are resolved server-side from `sessionId`.
|
||||||
* The endpoint returns the standard `{ success, data }` envelope.
|
|
||||||
*/
|
*/
|
||||||
const fetchFromServer = useCallback(async (
|
const fetchFromServer = useCallback(async (
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
opts: {
|
opts: {
|
||||||
|
provider?: LLMProvider;
|
||||||
|
projectId?: string;
|
||||||
|
projectPath?: string;
|
||||||
limit?: number | null;
|
limit?: number | null;
|
||||||
offset?: number;
|
offset?: number;
|
||||||
} = {},
|
} = {},
|
||||||
) => {
|
) => {
|
||||||
const slot = getSlot(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = getSlot(resolvedSessionId);
|
||||||
slot.status = 'loading';
|
slot.status = 'loading';
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@@ -470,15 +346,14 @@ export function useSessionStore() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const qs = params.toString();
|
const qs = params.toString();
|
||||||
const url = `/api/providers/sessions/${encodeURIComponent(sessionId)}/messages${qs ? `?${qs}` : ''}`;
|
const url = `/api/providers/sessions/${encodeURIComponent(resolvedSessionId)}/messages${qs ? `?${qs}` : ''}`;
|
||||||
const response = await authenticatedFetch(url);
|
const response = await authenticatedFetch(url);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`HTTP ${response.status}`);
|
throw new Error(`HTTP ${response.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = await response.json();
|
const data = await response.json();
|
||||||
const data = body?.data ?? body;
|
|
||||||
const messages: NormalizedMessage[] = data.messages || [];
|
const messages: NormalizedMessage[] = data.messages || [];
|
||||||
|
|
||||||
slot.serverMessages = messages;
|
slot.serverMessages = messages;
|
||||||
@@ -492,15 +367,15 @@ export function useSessionStore() {
|
|||||||
slot.tokenUsage = data.tokenUsage;
|
slot.tokenUsage = data.tokenUsage;
|
||||||
}
|
}
|
||||||
|
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
return slot;
|
return slot;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[SessionStore] fetch failed for ${sessionId}:`, error);
|
console.error(`[SessionStore] fetch failed for ${resolvedSessionId}:`, error);
|
||||||
slot.status = 'error';
|
slot.status = 'error';
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
return slot;
|
return slot;
|
||||||
}
|
}
|
||||||
}, [getSlot, notify]);
|
}, [getSlot, notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load older (paginated) messages and prepend to serverMessages.
|
* Load older (paginated) messages and prepend to serverMessages.
|
||||||
@@ -508,10 +383,14 @@ export function useSessionStore() {
|
|||||||
const fetchMore = useCallback(async (
|
const fetchMore = useCallback(async (
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
opts: {
|
opts: {
|
||||||
|
provider?: LLMProvider;
|
||||||
|
projectId?: string;
|
||||||
|
projectPath?: string;
|
||||||
limit?: number;
|
limit?: number;
|
||||||
} = {},
|
} = {},
|
||||||
) => {
|
) => {
|
||||||
const slot = getSlot(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = getSlot(resolvedSessionId);
|
||||||
if (!slot.hasMore) return slot;
|
if (!slot.hasMore) return slot;
|
||||||
|
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
@@ -520,13 +399,12 @@ export function useSessionStore() {
|
|||||||
params.append('offset', String(slot.offset));
|
params.append('offset', String(slot.offset));
|
||||||
|
|
||||||
const qs = params.toString();
|
const qs = params.toString();
|
||||||
const url = `/api/providers/sessions/${encodeURIComponent(sessionId)}/messages${qs ? `?${qs}` : ''}`;
|
const url = `/api/providers/sessions/${encodeURIComponent(resolvedSessionId)}/messages${qs ? `?${qs}` : ''}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await authenticatedFetch(url);
|
const response = await authenticatedFetch(url);
|
||||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||||
const body = await response.json();
|
const data = await response.json();
|
||||||
const data = body?.data ?? body;
|
|
||||||
const olderMessages: NormalizedMessage[] = data.messages || [];
|
const olderMessages: NormalizedMessage[] = data.messages || [];
|
||||||
|
|
||||||
// Prepend older messages (they're earlier in the conversation)
|
// Prepend older messages (they're earlier in the conversation)
|
||||||
@@ -534,43 +412,45 @@ export function useSessionStore() {
|
|||||||
slot.hasMore = Boolean(data.hasMore);
|
slot.hasMore = Boolean(data.hasMore);
|
||||||
slot.offset = slot.offset + olderMessages.length;
|
slot.offset = slot.offset + olderMessages.length;
|
||||||
recomputeMergedIfNeeded(slot);
|
recomputeMergedIfNeeded(slot);
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
return slot;
|
return slot;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[SessionStore] fetchMore failed for ${sessionId}:`, error);
|
console.error(`[SessionStore] fetchMore failed for ${resolvedSessionId}:`, error);
|
||||||
return slot;
|
return slot;
|
||||||
}
|
}
|
||||||
}, [getSlot, notify]);
|
}, [getSlot, notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Append a realtime (WebSocket) message to the correct session slot.
|
* Append a realtime (WebSocket) message to the correct session slot.
|
||||||
* This works regardless of which session is actively viewed.
|
* This works regardless of which session is actively viewed.
|
||||||
*/
|
*/
|
||||||
const appendRealtime = useCallback((sessionId: string, msg: NormalizedMessage) => {
|
const appendRealtime = useCallback((sessionId: string, msg: NormalizedMessage) => {
|
||||||
const slot = getSlot(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = getSlot(resolvedSessionId);
|
||||||
const normalizedMessage =
|
const normalizedMessage =
|
||||||
msg.sessionId === sessionId
|
msg.sessionId === resolvedSessionId
|
||||||
? msg
|
? msg
|
||||||
: { ...msg, sessionId };
|
: { ...msg, sessionId: resolvedSessionId };
|
||||||
let updated = [...slot.realtimeMessages, normalizedMessage];
|
let updated = [...slot.realtimeMessages, normalizedMessage];
|
||||||
if (updated.length > MAX_REALTIME_MESSAGES) {
|
if (updated.length > MAX_REALTIME_MESSAGES) {
|
||||||
updated = updated.slice(-MAX_REALTIME_MESSAGES);
|
updated = updated.slice(-MAX_REALTIME_MESSAGES);
|
||||||
}
|
}
|
||||||
slot.realtimeMessages = updated;
|
slot.realtimeMessages = updated;
|
||||||
recomputeMergedIfNeeded(slot);
|
recomputeMergedIfNeeded(slot);
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
}, [getSlot, notify]);
|
}, [getSlot, notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Append multiple realtime messages at once (batch).
|
* Append multiple realtime messages at once (batch).
|
||||||
*/
|
*/
|
||||||
const appendRealtimeBatch = useCallback((sessionId: string, msgs: NormalizedMessage[]) => {
|
const appendRealtimeBatch = useCallback((sessionId: string, msgs: NormalizedMessage[]) => {
|
||||||
if (msgs.length === 0) return;
|
if (msgs.length === 0) return;
|
||||||
const slot = getSlot(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = getSlot(resolvedSessionId);
|
||||||
const normalizedMessages = msgs.map((msg) =>
|
const normalizedMessages = msgs.map((msg) =>
|
||||||
msg.sessionId === sessionId
|
msg.sessionId === resolvedSessionId
|
||||||
? msg
|
? msg
|
||||||
: { ...msg, sessionId },
|
: { ...msg, sessionId: resolvedSessionId },
|
||||||
);
|
);
|
||||||
let updated = [...slot.realtimeMessages, ...normalizedMessages];
|
let updated = [...slot.realtimeMessages, ...normalizedMessages];
|
||||||
if (updated.length > MAX_REALTIME_MESSAGES) {
|
if (updated.length > MAX_REALTIME_MESSAGES) {
|
||||||
@@ -578,70 +458,76 @@ export function useSessionStore() {
|
|||||||
}
|
}
|
||||||
slot.realtimeMessages = updated;
|
slot.realtimeMessages = updated;
|
||||||
recomputeMergedIfNeeded(slot);
|
recomputeMergedIfNeeded(slot);
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
}, [getSlot, notify]);
|
}, [getSlot, notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Re-fetch serverMessages from the provider sessions endpoint.
|
* Re-fetch serverMessages from the provider sessions endpoint.
|
||||||
*/
|
*/
|
||||||
const refreshFromServer = useCallback(async (
|
const refreshFromServer = useCallback(async (
|
||||||
sessionId: string,
|
sessionId: string,
|
||||||
|
_opts: {
|
||||||
|
provider?: LLMProvider;
|
||||||
|
projectId?: string;
|
||||||
|
projectPath?: string;
|
||||||
|
} = {},
|
||||||
) => {
|
) => {
|
||||||
const slot = getSlot(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = getSlot(resolvedSessionId);
|
||||||
try {
|
try {
|
||||||
const url = `/api/providers/sessions/${encodeURIComponent(sessionId)}/messages`;
|
const params = new URLSearchParams();
|
||||||
|
|
||||||
|
const qs = params.toString();
|
||||||
|
const url = `/api/providers/sessions/${encodeURIComponent(resolvedSessionId)}/messages${qs ? `?${qs}` : ''}`;
|
||||||
const response = await authenticatedFetch(url);
|
const response = await authenticatedFetch(url);
|
||||||
|
|
||||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||||
const body = await response.json();
|
const data = await response.json();
|
||||||
const data = body?.data ?? body;
|
|
||||||
|
|
||||||
slot.serverMessages = data.messages || [];
|
slot.serverMessages = data.messages || [];
|
||||||
slot.total = data.total ?? slot.serverMessages.length;
|
slot.total = data.total ?? slot.serverMessages.length;
|
||||||
slot.hasMore = Boolean(data.hasMore);
|
slot.hasMore = Boolean(data.hasMore);
|
||||||
slot.fetchedAt = Date.now();
|
slot.fetchedAt = Date.now();
|
||||||
// Only drop realtime rows the server transcript now owns. A blind clear
|
// drop realtime messages that the server has caught up with to prevent unbounded growth.
|
||||||
// here caused the chat pane to flash "Continue your conversation" after
|
slot.realtimeMessages = [];
|
||||||
// `complete` while JSONL / provider_session_id indexing was still behind.
|
|
||||||
slot.realtimeMessages = pruneRealtimeSupersededByServer(
|
|
||||||
slot.serverMessages,
|
|
||||||
slot.realtimeMessages,
|
|
||||||
);
|
|
||||||
recomputeMergedIfNeeded(slot);
|
recomputeMergedIfNeeded(slot);
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[SessionStore] refresh failed for ${sessionId}:`, error);
|
console.error(`[SessionStore] refresh failed for ${resolvedSessionId}:`, error);
|
||||||
}
|
}
|
||||||
}, [getSlot, notify]);
|
}, [getSlot, notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update session status.
|
* Update session status.
|
||||||
*/
|
*/
|
||||||
const setStatus = useCallback((sessionId: string, status: SessionStatus) => {
|
const setStatus = useCallback((sessionId: string, status: SessionStatus) => {
|
||||||
const slot = getSlot(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = getSlot(resolvedSessionId);
|
||||||
slot.status = status;
|
slot.status = status;
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
}, [getSlot, notify]);
|
}, [getSlot, notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if a session's data is stale (>30s old).
|
* Check if a session's data is stale (>30s old).
|
||||||
*/
|
*/
|
||||||
const isStale = useCallback((sessionId: string) => {
|
const isStale = useCallback((sessionId: string) => {
|
||||||
const slot = storeRef.current.get(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = storeRef.current.get(resolvedSessionId);
|
||||||
if (!slot) return true;
|
if (!slot) return true;
|
||||||
return Date.now() - slot.fetchedAt > STALE_THRESHOLD_MS;
|
return Date.now() - slot.fetchedAt > STALE_THRESHOLD_MS;
|
||||||
}, []);
|
}, [resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update or create a streaming message (accumulated text so far).
|
* Update or create a streaming message (accumulated text so far).
|
||||||
* Uses a well-known ID so subsequent calls replace the same message.
|
* Uses a well-known ID so subsequent calls replace the same message.
|
||||||
*/
|
*/
|
||||||
const updateStreaming = useCallback((sessionId: string, accumulatedText: string, msgProvider: LLMProvider) => {
|
const updateStreaming = useCallback((sessionId: string, accumulatedText: string, msgProvider: LLMProvider) => {
|
||||||
const slot = getSlot(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
const streamId = `__streaming_${sessionId}`;
|
const slot = getSlot(resolvedSessionId);
|
||||||
|
const streamId = `__streaming_${resolvedSessionId}`;
|
||||||
const msg: NormalizedMessage = {
|
const msg: NormalizedMessage = {
|
||||||
id: streamId,
|
id: streamId,
|
||||||
sessionId,
|
sessionId: resolvedSessionId,
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
provider: msgProvider,
|
provider: msgProvider,
|
||||||
kind: 'stream_delta',
|
kind: 'stream_delta',
|
||||||
@@ -655,17 +541,18 @@ export function useSessionStore() {
|
|||||||
slot.realtimeMessages = [...slot.realtimeMessages, msg];
|
slot.realtimeMessages = [...slot.realtimeMessages, msg];
|
||||||
}
|
}
|
||||||
recomputeMergedIfNeeded(slot);
|
recomputeMergedIfNeeded(slot);
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
}, [getSlot, notify]);
|
}, [getSlot, notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Finalize streaming: convert the streaming message to a regular text message.
|
* Finalize streaming: convert the streaming message to a regular text message.
|
||||||
* The well-known streaming ID is replaced with a unique text message ID.
|
* The well-known streaming ID is replaced with a unique text message ID.
|
||||||
*/
|
*/
|
||||||
const finalizeStreaming = useCallback((sessionId: string) => {
|
const finalizeStreaming = useCallback((sessionId: string) => {
|
||||||
const slot = storeRef.current.get(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = storeRef.current.get(resolvedSessionId);
|
||||||
if (!slot) return;
|
if (!slot) return;
|
||||||
const streamId = `__streaming_${sessionId}`;
|
const streamId = `__streaming_${resolvedSessionId}`;
|
||||||
const idx = slot.realtimeMessages.findIndex(m => m.id === streamId);
|
const idx = slot.realtimeMessages.findIndex(m => m.id === streamId);
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
const stream = slot.realtimeMessages[idx];
|
const stream = slot.realtimeMessages[idx];
|
||||||
@@ -677,35 +564,104 @@ export function useSessionStore() {
|
|||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
};
|
};
|
||||||
recomputeMergedIfNeeded(slot);
|
recomputeMergedIfNeeded(slot);
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
}
|
}
|
||||||
}, [notify]);
|
}, [notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clear realtime messages for a session (e.g., after stream completes and server fetch catches up).
|
* Clear realtime messages for a session (e.g., after stream completes and server fetch catches up).
|
||||||
*/
|
*/
|
||||||
const clearRealtime = useCallback((sessionId: string) => {
|
const clearRealtime = useCallback((sessionId: string) => {
|
||||||
const slot = storeRef.current.get(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
|
const slot = storeRef.current.get(resolvedSessionId);
|
||||||
if (slot) {
|
if (slot) {
|
||||||
slot.realtimeMessages = [];
|
slot.realtimeMessages = [];
|
||||||
recomputeMergedIfNeeded(slot);
|
recomputeMergedIfNeeded(slot);
|
||||||
notify(sessionId);
|
notify(resolvedSessionId);
|
||||||
}
|
}
|
||||||
}, [notify]);
|
}, [notify, resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get merged messages for a session (for rendering).
|
* Get merged messages for a session (for rendering).
|
||||||
*/
|
*/
|
||||||
const getMessages = useCallback((sessionId: string): NormalizedMessage[] => {
|
const getMessages = useCallback((sessionId: string): NormalizedMessage[] => {
|
||||||
return storeRef.current.get(sessionId)?.merged ?? [];
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
}, []);
|
return storeRef.current.get(resolvedSessionId)?.merged ?? [];
|
||||||
|
}, [resolveSessionId]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get session slot (for status, pagination info, etc.).
|
* Get session slot (for status, pagination info, etc.).
|
||||||
*/
|
*/
|
||||||
const getSessionSlot = useCallback((sessionId: string): SessionSlot | undefined => {
|
const getSessionSlot = useCallback((sessionId: string): SessionSlot | undefined => {
|
||||||
return storeRef.current.get(sessionId);
|
const resolvedSessionId = resolveSessionId(sessionId) ?? sessionId;
|
||||||
}, []);
|
return storeRef.current.get(resolvedSessionId);
|
||||||
|
}, [resolveSessionId]);
|
||||||
|
|
||||||
|
const replaceSessionId = useCallback((fromSessionId: string, toSessionId: string) => {
|
||||||
|
const resolvedFromSessionId = resolveSessionId(fromSessionId) ?? fromSessionId;
|
||||||
|
const resolvedToSessionId = resolveSessionId(toSessionId) ?? toSessionId;
|
||||||
|
|
||||||
|
if (resolvedFromSessionId === resolvedToSessionId) {
|
||||||
|
sessionAliasesRef.current.set(fromSessionId, resolvedToSessionId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const store = storeRef.current;
|
||||||
|
const sourceSlot = store.get(resolvedFromSessionId);
|
||||||
|
const targetSlot = store.get(resolvedToSessionId) ?? createEmptySlot();
|
||||||
|
|
||||||
|
if (sourceSlot) {
|
||||||
|
const migratedServerMessages = sourceSlot.serverMessages.map((msg) =>
|
||||||
|
rewriteMessageSessionId(msg, resolvedFromSessionId, resolvedToSessionId),
|
||||||
|
);
|
||||||
|
const migratedRealtimeMessages = sourceSlot.realtimeMessages.map((msg) =>
|
||||||
|
rewriteMessageSessionId(msg, resolvedFromSessionId, resolvedToSessionId),
|
||||||
|
);
|
||||||
|
|
||||||
|
targetSlot.serverMessages = mergeMessagesById(targetSlot.serverMessages, migratedServerMessages);
|
||||||
|
targetSlot.realtimeMessages = mergeMessagesById(targetSlot.realtimeMessages, migratedRealtimeMessages);
|
||||||
|
if (targetSlot.realtimeMessages.length > MAX_REALTIME_MESSAGES) {
|
||||||
|
targetSlot.realtimeMessages = targetSlot.realtimeMessages.slice(-MAX_REALTIME_MESSAGES);
|
||||||
|
}
|
||||||
|
targetSlot.status =
|
||||||
|
sourceSlot.status === 'error'
|
||||||
|
? 'error'
|
||||||
|
: sourceSlot.status === 'streaming' || targetSlot.status === 'streaming'
|
||||||
|
? 'streaming'
|
||||||
|
: sourceSlot.status === 'loading' || targetSlot.status === 'loading'
|
||||||
|
? 'loading'
|
||||||
|
: targetSlot.status;
|
||||||
|
targetSlot.fetchedAt = Math.max(targetSlot.fetchedAt, sourceSlot.fetchedAt, Date.now());
|
||||||
|
targetSlot.total = Math.max(
|
||||||
|
targetSlot.total,
|
||||||
|
sourceSlot.total,
|
||||||
|
targetSlot.serverMessages.length,
|
||||||
|
targetSlot.realtimeMessages.length,
|
||||||
|
);
|
||||||
|
targetSlot.hasMore = targetSlot.hasMore || sourceSlot.hasMore;
|
||||||
|
targetSlot.offset = Math.max(targetSlot.offset, sourceSlot.offset);
|
||||||
|
targetSlot.tokenUsage = targetSlot.tokenUsage ?? sourceSlot.tokenUsage;
|
||||||
|
recomputeMergedIfNeeded(targetSlot);
|
||||||
|
|
||||||
|
store.set(resolvedToSessionId, targetSlot);
|
||||||
|
store.delete(resolvedFromSessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
sessionAliasesRef.current.set(resolvedFromSessionId, resolvedToSessionId);
|
||||||
|
sessionAliasesRef.current.set(fromSessionId, resolvedToSessionId);
|
||||||
|
|
||||||
|
for (const [aliasSessionId, targetSessionId] of sessionAliasesRef.current.entries()) {
|
||||||
|
if (targetSessionId === resolvedFromSessionId) {
|
||||||
|
sessionAliasesRef.current.set(aliasSessionId, resolvedToSessionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (activeSessionIdRef.current === resolvedFromSessionId) {
|
||||||
|
activeSessionIdRef.current = resolvedToSessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
notify(resolvedToSessionId);
|
||||||
|
}, [notify, resolveSessionId]);
|
||||||
|
|
||||||
return useMemo(() => ({
|
return useMemo(() => ({
|
||||||
getSlot,
|
getSlot,
|
||||||
@@ -723,11 +679,12 @@ export function useSessionStore() {
|
|||||||
clearRealtime,
|
clearRealtime,
|
||||||
getMessages,
|
getMessages,
|
||||||
getSessionSlot,
|
getSessionSlot,
|
||||||
|
replaceSessionId,
|
||||||
}), [
|
}), [
|
||||||
getSlot, has, fetchFromServer, fetchMore,
|
getSlot, has, fetchFromServer, fetchMore,
|
||||||
appendRealtime, appendRealtimeBatch, refreshFromServer,
|
appendRealtime, appendRealtimeBatch, refreshFromServer,
|
||||||
setActiveSession, setStatus, isStale, updateStreaming, finalizeStreaming,
|
setActiveSession, setStatus, isStale, updateStreaming, finalizeStreaming,
|
||||||
clearRealtime, getMessages, getSessionSlot,
|
clearRealtime, getMessages, getSessionSlot, replaceSessionId,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ export interface ProjectSession {
|
|||||||
updated_at?: string;
|
updated_at?: string;
|
||||||
lastActivity?: string;
|
lastActivity?: string;
|
||||||
messageCount?: number;
|
messageCount?: number;
|
||||||
provider?: LLMProvider;
|
|
||||||
__provider?: LLMProvider;
|
__provider?: LLMProvider;
|
||||||
// Tags the session with the owning project's DB `projectId` so UI handlers
|
// Tags the session with the owning project's DB `projectId` so UI handlers
|
||||||
// (session switching, sidebar focus, etc.) can match against selectedProject.
|
// (session switching, sidebar focus, etc.) can match against selectedProject.
|
||||||
@@ -61,16 +60,42 @@ export interface Project {
|
|||||||
path?: string;
|
path?: string;
|
||||||
isStarred?: boolean;
|
isStarred?: boolean;
|
||||||
sessions?: ProjectSession[];
|
sessions?: ProjectSession[];
|
||||||
|
cursorSessions?: ProjectSession[];
|
||||||
|
codexSessions?: ProjectSession[];
|
||||||
|
geminiSessions?: ProjectSession[];
|
||||||
|
opencodeSessions?: ProjectSession[];
|
||||||
sessionMeta?: ProjectSessionMeta;
|
sessionMeta?: ProjectSessionMeta;
|
||||||
taskmaster?: ProjectTaskmasterInfo;
|
taskmaster?: ProjectTaskmasterInfo;
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LoadingProgress {
|
export interface LoadingProgress {
|
||||||
kind?: 'loading_progress';
|
type?: 'loading_progress';
|
||||||
phase?: string;
|
phase?: string;
|
||||||
current: number;
|
current: number;
|
||||||
total: number;
|
total: number;
|
||||||
currentProject?: string;
|
currentProject?: string;
|
||||||
[key: string]: unknown;
|
[key: string]: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ProjectsUpdatedMessage {
|
||||||
|
type: 'projects_updated';
|
||||||
|
projects: Project[];
|
||||||
|
updatedSessionId?: string;
|
||||||
|
updatedSessionIds?: string[];
|
||||||
|
watchProvider?: LLMProvider;
|
||||||
|
watchProviders?: LLMProvider[];
|
||||||
|
changeType?: 'add' | 'change';
|
||||||
|
changeTypes?: Array<'add' | 'change'>;
|
||||||
|
batched?: boolean;
|
||||||
|
[key: string]: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoadingProgressMessage extends LoadingProgress {
|
||||||
|
type: 'loading_progress';
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AppSocketMessage =
|
||||||
|
| LoadingProgressMessage
|
||||||
|
| ProjectsUpdatedMessage
|
||||||
|
| { type?: string;[key: string]: unknown };
|
||||||
|
|||||||
@@ -98,8 +98,6 @@ export const api = {
|
|||||||
},
|
},
|
||||||
getArchivedSessions: () =>
|
getArchivedSessions: () =>
|
||||||
authenticatedFetch('/api/providers/sessions/archived'),
|
authenticatedFetch('/api/providers/sessions/archived'),
|
||||||
runningSessions: () =>
|
|
||||||
authenticatedFetch('/api/providers/sessions/running'),
|
|
||||||
restoreSession: (sessionId) =>
|
restoreSession: (sessionId) =>
|
||||||
authenticatedFetch(`/api/providers/sessions/${sessionId}/restore`, {
|
authenticatedFetch(`/api/providers/sessions/${sessionId}/restore`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
Reference in New Issue
Block a user