mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 14:10:45 -05:00
14 files changed
+841
-187
No files matched your search
+21
-9
@@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.7.4] - 2026-06-30
|
||||
|
||||
### Added
|
||||
|
||||
- 🖥️ **Live command sessions in chat.** Running commands now appear in the chat status menu, where you can open live output, keep an eye on long jobs, and terminate a stuck command without leaving the conversation.
|
||||
- 📊 **More useful chat status.** Chats now have a compact status bar with the conversation title, context usage, queued messages, Chat ID, and active command count in one place.
|
||||
|
||||
### Fixed
|
||||
|
||||
- ⌨️ **More reliable command control.** Long-running commands now keep accepting input and can be stopped from either the chat tools or the live session view.
|
||||
- 🧹 **Cleaner activity details.** Chat activity stays aligned and easier to scan while command output remains available where it is useful.
|
||||
|
||||
## [0.7.3] - 2026-06-30
|
||||
|
||||
### Fixed
|
||||
@@ -188,12 +200,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Changed
|
||||
|
||||
- 📁 **File browser drag-and-drop completely reworked.** You can now freely drag and drop files and folders anywhere — into folders, onto breadcrumbs, or between nested directories. Multi-select drag, auto-expand on hover, and full expanded-area highlighting are all supported.
|
||||
- 📁 **File browser drag-and-drop completely reworked.** You can now freely drag and drop files and folders anywhere: into folders, onto breadcrumbs, or between nested directories. Multi-select drag, auto-expand on hover, and full expanded-area highlighting are all supported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 📋 **Dropdown menus no longer get cut off by the keyboard on mobile.** Menus that open upward (like the model picker) now anchor from the bottom of the screen instead of the top, so they stay fully visible even when the on-screen keyboard is open.
|
||||
- 🔄 **Renamed files no longer break git operations.** Renaming or moving a file could cause errors when staging, discarding, or viewing changes — the file list would show garbled entries like "R100 old-name.txt" instead of the actual file. This is now handled correctly.
|
||||
- 🔄 **Renamed files no longer break git operations.** Renaming or moving a file could cause errors when staging, discarding, or viewing changes, and the file list would show garbled entries like "R100 old-name.txt" instead of the actual file. This is now handled correctly.
|
||||
|
||||
## [0.4.9] - 2026-06-15
|
||||
|
||||
@@ -238,7 +250,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
- 🧠 **Reasoning models no longer lose chain of thought across parallel tool calls.** Multiple tool calls in the same turn are now grouped into a single assistant message with shared reasoning items, instead of being split into separate messages that broke reasoning model round-tripping (e.g. o3, o4-mini).
|
||||
- 🛡️ **Orphaned tool calls no longer break chat history.** If a crash or data corruption left a function call without a matching result, the Responses API conversion now skips the orphaned call instead of sending invalid input that caused permanent 400 errors.
|
||||
- 🔄 **Tool output ordering prevents corrupted history on crash.** Tool call outputs are now appended to the output list *before* marking the call as "completed", so a crash between the two steps can no longer produce a "completed" call with no output — which would corrupt the message history on reload.
|
||||
- 🔄 **Tool output ordering prevents corrupted history on crash.** Tool call outputs are now appended to the output list *before* marking the call as "completed", so a crash between the two steps can no longer produce a "completed" call with no output and corrupt the message history on reload.
|
||||
- 🧹 **In-progress tool calls scrubbed on error or cancellation.** When a chat task is cancelled or hits an error, any tool calls still marked "in_progress" are now set to "failed" before persisting, preventing stale in-progress items from lingering in the database.
|
||||
|
||||
## [0.4.4] - 2026-06-15
|
||||
@@ -246,9 +258,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
### Added
|
||||
|
||||
- 🧙 **Setup wizard.** A friendly first-run guide walks you through picking a folder and connecting your AI. Pops up automatically after sign-up.
|
||||
- 🔌 **Local tool servers (stdio).** You can now connect MCP tool servers that run as local commands — not just over HTTP. Add the command and arguments from the Tool Servers tab.
|
||||
- 🔌 **Local tool servers (stdio).** You can now connect MCP tool servers that run as local commands, not just over HTTP. Add the command and arguments from the Tool Servers tab.
|
||||
- 📄 **Read documents.** The AI can now open and read PDFs, Word docs, Excel spreadsheets, PowerPoint files, and more.
|
||||
- 💬 **Send input to running commands.** The AI can now type into running processes — answering prompts, interacting with REPLs, or sending Ctrl-C.
|
||||
- 💬 **Send input to running commands.** The AI can now type into running processes, answer prompts, interact with REPLs, or send Ctrl-C.
|
||||
- ↩️ **Undo last commit.** Changed your mind? Undo the last commit from the Git history and get your changes back in staging.
|
||||
- 🚀 **Publish branches.** Push a new branch for the first time with one click. The button says "Publish" when there's no upstream yet.
|
||||
- 🔗 **View on GitHub / GitLab.** A new link in the Git panel takes you straight to your repo on the web.
|
||||
@@ -414,7 +426,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- 🔍 **Global search modal.** New unified search (⌘K / ⌘⇧F) that finds chats by title *and* message content, plus files by name — across all workspaces or scoped to the active one. Shows recent chats when the query is empty. Replaces the old QuickOpen modal.
|
||||
- 🔍 **Global search modal.** New unified search (⌘K / ⌘⇧F) that finds chats by title *and* message content, plus files by name across all workspaces or scoped to the active one. Shows recent chats when the query is empty. Replaces the old QuickOpen modal.
|
||||
- 🌐 **Perplexity web search provider.** Added Perplexity as a first-class search provider (auto-detected between Exa and Tavily when `PERPLEXITY_API_KEY` is set).
|
||||
- 🌐 **Chat Completions search provider.** Any OpenAI-compatible `/chat/completions` endpoint (e.g. Perplexity Sonar, LiteLLM proxy) can now be used for web search. Configure via Settings or environment variables.
|
||||
- ➕ **New Chat button per workspace.** Each workspace row in the sidebar now shows a pencil icon on hover to quickly create a new chat.
|
||||
@@ -487,7 +499,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
### Fixed
|
||||
|
||||
- 🗄️ **Alembic migration no longer fails on startup.** Renamed migration revision IDs from 3-character (`001`) to 4-character (`0001`) identifiers, fixing Alembic's `ResolutionError` for partial revision matches.
|
||||
- 📦 **PyPI wheel no longer bundles frontend source code.** Fixed `.gitignore` paths (old `computr/` → `cptr/`) and added an explicit `exclude` in `pyproject.toml` so only `cptr/frontend/build` ships in the wheel — eliminating ~14,000 unnecessary files including `node_modules`.
|
||||
- 📦 **PyPI wheel no longer bundles frontend source code.** Fixed `.gitignore` paths (old `computr/` → `cptr/`) and added an explicit `exclude` in `pyproject.toml` so only `cptr/frontend/build` ships in the wheel, eliminating ~14,000 unnecessary files including `node_modules`.
|
||||
|
||||
## [0.1.4] - 2026-06-06
|
||||
|
||||
@@ -533,7 +545,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🛑 **File browser no longer refreshes constantly.** Replaced the macOS `PollingObserver` (which generated a feedback loop of phantom filesystem events) with the native `FSEventsObserver`. Background refreshes are now silent — no more loading spinner flash on every update.
|
||||
- 🛑 **File browser no longer refreshes constantly.** Replaced the macOS `PollingObserver` (which generated a feedback loop of phantom filesystem events) with the native `FSEventsObserver`. Background refreshes are now silent, so there is no more loading spinner flash on every update.
|
||||
- 🔇 **Eliminated noisy filesystem watcher events.** The watcher now ignores changes in `.git`, `__pycache__`, `.DS_Store`, and `node_modules` directories, which were triggering unnecessary file browser refreshes.
|
||||
- ⚡ **Centralized git status store.** All components (GitBar, GitView, FileEditor, layout) now share a single `gitStatusStore` instead of each independently polling `git/status`. On page load, this reduces git status API calls from ~6+ down to 1.
|
||||
- 🔁 **Reduced git polling frequency.** Removed the 5-second git status polling intervals that were running in multiple components simultaneously.
|
||||
@@ -547,7 +559,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- 💬 **AI chat.** Built-in chat panel with multi-provider LLM support (OpenAI, Anthropic, Ollama, and OpenAI-compatible endpoints), model selector, tool calling, and streaming responses.
|
||||
- 🔧 **Tool system.** Extensible tool framework enabling AI agents to interact with the local filesystem, run commands, search the web (Brave, DuckDuckGo, Exa, Tavily), and read URLs. Streaming JSON parser for improved tool-calling reliability.
|
||||
- 📎 **File mentions.** Type `@` in the chat input to mention files with an inline suggestion popup, giving the AI context about your codebase.
|
||||
- 🔄 **Queued messages.** Queue follow-up messages while the AI is responding — they'll be sent automatically when the current response completes.
|
||||
- 🔄 **Queued messages.** Queue follow-up messages while the AI is responding. They will be sent automatically when the current response completes.
|
||||
- ✏️ **Output editing.** Review and edit AI-generated file changes before applying them.
|
||||
- 📁 **File browser.** Web-based file explorer with directory navigation, file viewing, file icons by extension, and management capabilities.
|
||||
- ⌨️ **Keyboard shortcuts.** Customizable keybinding system with a dedicated settings panel, including support for new-tab, quick-open, and other common actions.
|
||||
|
||||
@@ -7,6 +7,22 @@ export interface TerminalSession {
|
||||
session_id: string;
|
||||
}
|
||||
|
||||
export interface CommandSession {
|
||||
command_session_id: string;
|
||||
task_id: string;
|
||||
workspace: string;
|
||||
chat_id: string | null;
|
||||
message_id: string | null;
|
||||
call_id: string | null;
|
||||
command: string;
|
||||
created_at: number;
|
||||
status: 'running' | 'completed';
|
||||
done: boolean;
|
||||
exit_code: number | null;
|
||||
total_bytes: number;
|
||||
output: string;
|
||||
}
|
||||
|
||||
export const listSessions = () => fetchJSON<TerminalSession[]>('/api/terminal');
|
||||
|
||||
export const createSession = (cwd: string) =>
|
||||
@@ -14,3 +30,8 @@ export const createSession = (cwd: string) =>
|
||||
|
||||
export const deleteSession = (sessionId: string) =>
|
||||
fetchHandler(`/api/terminal/${sessionId}`, { method: 'DELETE' }).catch(() => {});
|
||||
|
||||
export const listCommandSessions = (workspace: string, chatId?: string | null) =>
|
||||
fetchJSON<CommandSession[]>(
|
||||
`/api/terminal/sessions?workspace=${encodeURIComponent(workspace)}${chatId ? `&chat_id=${encodeURIComponent(chatId)}` : ''}`
|
||||
);
|
||||
@@ -45,6 +45,8 @@
|
||||
footerDivider?: boolean;
|
||||
/** Optional snippet rendered when items array is empty. */
|
||||
empty?: Snippet;
|
||||
/** Optional custom dropdown content. */
|
||||
children?: Snippet;
|
||||
/** Additional CSS classes for the menu container. */
|
||||
className?: string;
|
||||
/** Horizontal alignment relative to anchor: 'start' (left) or 'end' (right). */
|
||||
@@ -65,6 +67,7 @@
|
||||
headerDivider = true,
|
||||
footerDivider = true,
|
||||
empty,
|
||||
children,
|
||||
className = '',
|
||||
align = 'start'
|
||||
}: Props = $props();
|
||||
@@ -355,7 +358,9 @@
|
||||
{/if}
|
||||
|
||||
<div class="flex-1 min-h-0 overflow-y-auto" style={maxHeight ? `max-height: ${maxHeight};` : ''}>
|
||||
{#if items.length === 0 && empty}
|
||||
{#if children}
|
||||
{@render children()}
|
||||
{:else if items.length === 0 && empty}
|
||||
{@render empty()}
|
||||
{:else}
|
||||
{#each items as item}
|
||||
|
||||
@@ -4,10 +4,16 @@
|
||||
interface Props {
|
||||
onclose: () => void;
|
||||
class?: string;
|
||||
overlayClass?: string;
|
||||
children: Snippet;
|
||||
}
|
||||
|
||||
let { onclose, class: className = '', children }: Props = $props();
|
||||
let {
|
||||
onclose,
|
||||
class: className = '',
|
||||
overlayClass = 'bg-black/50 items-center justify-center',
|
||||
children
|
||||
}: Props = $props();
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') onclose();
|
||||
@@ -18,7 +24,7 @@
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="fixed inset-0 bg-black/50 z-[100] flex items-center justify-center"
|
||||
class="fixed inset-0 z-[100] flex {overlayClass}"
|
||||
onmousedown={onclose}
|
||||
onkeydown={() => {}}
|
||||
>
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
|
||||
// ── Compact binary WebSocket protocol ─────────────────────
|
||||
// Client → Server: byte 0 = type, rest = payload
|
||||
// 0x00 + raw input bytes (microtask-batched for throughput)
|
||||
// 0x02 + uint16 cols + uint16 rows, big-endian (5 bytes total)
|
||||
// Server → Client: raw PTY output bytes (no prefix)
|
||||
const MSG_INPUT = 0;
|
||||
const MSG_RESIZE = 2;
|
||||
// 0x00 + raw input bytes (microtask-batched for throughput)
|
||||
// 0x02 + uint16 cols + uint16 rows, big-endian (5 bytes total)
|
||||
// 0x03 stop, 0x04 force stop
|
||||
// Server → Client: raw PTY output bytes (no prefix)
|
||||
const MSG_INPUT = 0;
|
||||
const MSG_RESIZE = 2;
|
||||
const MSG_STOP = 3;
|
||||
const MSG_FORCE_STOP = 4;
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
@@ -35,10 +38,24 @@
|
||||
}
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
}
|
||||
sessionId?: string;
|
||||
wsPath?: string;
|
||||
initialOutput?: string;
|
||||
initialOffset?: number;
|
||||
stopSignal?: number;
|
||||
forceStopSignal?: number;
|
||||
readOnly?: boolean;
|
||||
}
|
||||
|
||||
let { sessionId }: Props = $props();
|
||||
let {
|
||||
sessionId = '',
|
||||
wsPath = '',
|
||||
initialOutput = '',
|
||||
initialOffset = 0,
|
||||
stopSignal = 0,
|
||||
forceStopSignal = 0,
|
||||
readOnly = false
|
||||
}: Props = $props();
|
||||
|
||||
let containerEl: HTMLDivElement | undefined = $state();
|
||||
let term: Terminal | null = null;
|
||||
@@ -61,7 +78,9 @@
|
||||
try {
|
||||
if ('wakeLock' in navigator) {
|
||||
wakeLock = await navigator.wakeLock.request('screen');
|
||||
wakeLock.addEventListener('release', () => { wakeLock = null; });
|
||||
wakeLock.addEventListener('release', () => {
|
||||
wakeLock = null;
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Wake lock request can fail if document is hidden or permission denied
|
||||
@@ -111,7 +130,11 @@
|
||||
|
||||
function getWsUrl(sid: string): string {
|
||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return `${proto}//${window.location.host}/api/terminal/${sid}/ws`;
|
||||
const path = wsPath || `/api/terminal/${sid}/ws`;
|
||||
const url = new URL(path, `${window.location.protocol}//${window.location.host}`);
|
||||
if (initialOffset > 0) url.searchParams.set('offset', String(initialOffset));
|
||||
url.protocol = proto;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function doFit() {
|
||||
@@ -156,6 +179,7 @@
|
||||
// Writes directly into the pre-allocated buffer. Zero allocation
|
||||
// for the common single-ASCII-keystroke path.
|
||||
function sendInput(data: string) {
|
||||
if (readOnly) return;
|
||||
if (ws?.readyState !== WebSocket.OPEN) return;
|
||||
|
||||
if (data.length === 1 && data.charCodeAt(0) < 128) {
|
||||
@@ -187,6 +211,28 @@
|
||||
ws!.send(resizeBuf);
|
||||
}
|
||||
|
||||
let lastStopSignal = 0;
|
||||
$effect(() => {
|
||||
if (!stopSignal || stopSignal === lastStopSignal) return;
|
||||
lastStopSignal = stopSignal;
|
||||
if (ws?.readyState === WebSocket.OPEN) {
|
||||
ws.send(new Uint8Array([MSG_STOP]));
|
||||
}
|
||||
});
|
||||
|
||||
let lastForceStopSignal = 0;
|
||||
$effect(() => {
|
||||
if (!forceStopSignal || forceStopSignal === lastForceStopSignal) return;
|
||||
lastForceStopSignal = forceStopSignal;
|
||||
if (ws?.readyState === WebSocket.OPEN) {
|
||||
ws.send(new Uint8Array([MSG_FORCE_STOP]));
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (term) term.options.disableStdin = readOnly;
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
if (!containerEl) return;
|
||||
|
||||
@@ -209,6 +255,7 @@
|
||||
lineHeight: 1.3,
|
||||
scrollback: 10000,
|
||||
macOptionClickForceSelection: true,
|
||||
disableStdin: readOnly,
|
||||
theme: isDarkMode() ? darkTheme : lightTheme
|
||||
});
|
||||
|
||||
@@ -258,6 +305,7 @@
|
||||
fitAddon = new FitAddon();
|
||||
term.loadAddon(fitAddon);
|
||||
term.open(containerEl);
|
||||
if (initialOutput) term.write(initialOutput);
|
||||
// // iOS: Move xterm's textarea from inside .xterm-helpers (position:absolute,
|
||||
// // offscreen) to a flex sibling BELOW the terminal.
|
||||
// if ('ontouchstart' in window && term.textarea) {
|
||||
@@ -404,12 +452,13 @@
|
||||
if (!term || destroyed) return;
|
||||
|
||||
const url = getWsUrl(sessionId);
|
||||
const label = sessionId || wsPath;
|
||||
console.log(`[terminal] connecting to ${url}`);
|
||||
ws = new WebSocket(url);
|
||||
ws.binaryType = 'arraybuffer';
|
||||
|
||||
ws.onopen = () => {
|
||||
console.log(`[terminal] WebSocket open for ${sessionId}`);
|
||||
console.log(`[terminal] WebSocket open for ${label}`);
|
||||
if (term) {
|
||||
// Send ONE resize message with current dimensions.
|
||||
// Do NOT call doFit() here; that would trigger term.onResize
|
||||
@@ -430,9 +479,7 @@
|
||||
};
|
||||
|
||||
ws.onclose = (e) => {
|
||||
console.log(
|
||||
`[terminal] WebSocket closed for ${sessionId}, code=${e.code}, reason=${e.reason}`
|
||||
);
|
||||
console.log(`[terminal] WebSocket closed for ${label}, code=${e.code}, reason=${e.reason}`);
|
||||
if (destroyed) return;
|
||||
reconnectTimer = setTimeout(() => {
|
||||
if (!destroyed) connectWebSocket();
|
||||
@@ -440,7 +487,7 @@
|
||||
};
|
||||
|
||||
ws.onerror = (e) => {
|
||||
console.error(`[terminal] WebSocket error for ${sessionId}`, e);
|
||||
console.error(`[terminal] WebSocket error for ${label}`, e);
|
||||
};
|
||||
|
||||
// NOTE: term.onData and term.onResize are registered in onMount,
|
||||
|
||||
@@ -10,7 +10,11 @@
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
import { createFileMention, extractMentionedFiles, type FileMentionAttrs } from './FileMention';
|
||||
import { createSkillMention, extractMentionedSkills, type SkillMentionAttrs } from './SkillMention';
|
||||
import {
|
||||
createSkillMention,
|
||||
extractMentionedSkills,
|
||||
type SkillMentionAttrs
|
||||
} from './SkillMention';
|
||||
import FileSuggestionPopup from './FileSuggestionPopup.svelte';
|
||||
import SkillSuggestionPopup from './SkillSuggestionPopup.svelte';
|
||||
import { searchFiles } from '$lib/apis/files';
|
||||
@@ -43,7 +47,9 @@
|
||||
try {
|
||||
if ('wakeLock' in navigator) {
|
||||
voiceWakeLock = await navigator.wakeLock.request('screen');
|
||||
voiceWakeLock.addEventListener('release', () => { voiceWakeLock = null; });
|
||||
voiceWakeLock.addEventListener('release', () => {
|
||||
voiceWakeLock = null;
|
||||
});
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
@@ -124,7 +130,9 @@
|
||||
};
|
||||
|
||||
// ── File Uploads ────────────────────────────────
|
||||
let attachedUploads = $state<{ id: string; name: string; url: string; type: string; loading?: boolean }[]>([]);
|
||||
let attachedUploads = $state<
|
||||
{ id: string; name: string; url: string; type: string; loading?: boolean }[]
|
||||
>([]);
|
||||
let isDragging = $state(false);
|
||||
|
||||
async function processFiles(files: File[]) {
|
||||
@@ -133,21 +141,21 @@
|
||||
const isImage = file.type.startsWith('image/');
|
||||
const type = isImage ? 'image' : 'file';
|
||||
attachedUploads = [...attachedUploads, { id, name: file.name, url: '', type, loading: true }];
|
||||
|
||||
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const res = await uploadFile(form);
|
||||
if (res && res.id) {
|
||||
attachedUploads = attachedUploads.map(u =>
|
||||
attachedUploads = attachedUploads.map((u) =>
|
||||
u.id === id ? { ...u, id: res.id, url: res.url, loading: false } : u
|
||||
);
|
||||
} else {
|
||||
attachedUploads = attachedUploads.filter(u => u.id !== id);
|
||||
attachedUploads = attachedUploads.filter((u) => u.id !== id);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Upload failed", err);
|
||||
attachedUploads = attachedUploads.filter(u => u.id !== id);
|
||||
console.error('Upload failed', err);
|
||||
attachedUploads = attachedUploads.filter((u) => u.id !== id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,7 +185,7 @@
|
||||
}
|
||||
|
||||
function removeUpload(id: string) {
|
||||
attachedUploads = attachedUploads.filter(u => u.id !== id);
|
||||
attachedUploads = attachedUploads.filter((u) => u.id !== id);
|
||||
}
|
||||
|
||||
// ── @file mention suggestion ────────────────────
|
||||
@@ -344,7 +352,7 @@
|
||||
id: s.name,
|
||||
label: s.name,
|
||||
description: s.description,
|
||||
source: s.source,
|
||||
source: s.source
|
||||
}));
|
||||
}
|
||||
if (!query) return cachedSkills;
|
||||
@@ -363,7 +371,9 @@
|
||||
onselect: (i: number) => void
|
||||
) {
|
||||
if (skillPopupComponent) {
|
||||
try { unmount(skillPopupComponent); } catch {}
|
||||
try {
|
||||
unmount(skillPopupComponent);
|
||||
} catch {}
|
||||
skillPopupComponent = null;
|
||||
}
|
||||
if (!skillPopupEl) {
|
||||
@@ -433,7 +443,8 @@
|
||||
return true;
|
||||
}
|
||||
if (event.key === 'ArrowUp') {
|
||||
selectedIndex = (selectedIndex - 1 + currentItems.length) % Math.max(currentItems.length, 1);
|
||||
selectedIndex =
|
||||
(selectedIndex - 1 + currentItems.length) % Math.max(currentItems.length, 1);
|
||||
remount();
|
||||
return true;
|
||||
}
|
||||
@@ -468,7 +479,9 @@
|
||||
stopSkillRepositionLoop();
|
||||
skillActiveClientRectFn = null;
|
||||
if (skillPopupComponent) {
|
||||
try { unmount(skillPopupComponent); } catch {}
|
||||
try {
|
||||
unmount(skillPopupComponent);
|
||||
} catch {}
|
||||
skillPopupComponent = null;
|
||||
}
|
||||
if (skillPopupEl) {
|
||||
@@ -594,7 +607,7 @@
|
||||
}
|
||||
|
||||
export function getFiles(): any[] {
|
||||
return attachedUploads.filter(u => !u.loading);
|
||||
return attachedUploads.filter((u) => !u.loading);
|
||||
}
|
||||
|
||||
export function clearUploads() {
|
||||
@@ -625,7 +638,8 @@
|
||||
streaming ||
|
||||
sending ||
|
||||
inputText.trim()
|
||||
) return;
|
||||
)
|
||||
return;
|
||||
voiceRearming = true;
|
||||
voiceRestartTimer = window.setTimeout(() => {
|
||||
voiceRestartTimer = 0;
|
||||
@@ -679,7 +693,11 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function stopVoiceCapture(): Promise<{ blob: Blob; filename: string; contentType: string } | null> {
|
||||
async function stopVoiceCapture(): Promise<{
|
||||
blob: Blob;
|
||||
filename: string;
|
||||
contentType: string;
|
||||
} | null> {
|
||||
const recorder = voiceCaptureRecorder;
|
||||
const stream = voiceCaptureStream;
|
||||
const chunks = voiceCaptureChunks;
|
||||
@@ -732,9 +750,11 @@
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function transcribeVoiceModeCapture(
|
||||
capture: { blob: Blob; filename: string; contentType: string }
|
||||
): Promise<string> {
|
||||
async function transcribeVoiceModeCapture(capture: {
|
||||
blob: Blob;
|
||||
filename: string;
|
||||
contentType: string;
|
||||
}): Promise<string> {
|
||||
const form = new FormData();
|
||||
form.append('file', capture.blob, capture.filename);
|
||||
form.append('workspace', workspace);
|
||||
@@ -937,12 +957,17 @@
|
||||
const canSend = $derived(!!(inputText.trim() && selectedModel && !sending));
|
||||
</script>
|
||||
|
||||
<div
|
||||
<div
|
||||
class="relative {isDragging ? 'ring-2 ring-blue-500 rounded-3xl' : ''}"
|
||||
ondrop={handleDrop}
|
||||
onpaste={handlePaste}
|
||||
ondragover={(e) => { e.preventDefault(); isDragging = true; }}
|
||||
ondragleave={() => { isDragging = false; }}
|
||||
ondragover={(e) => {
|
||||
e.preventDefault();
|
||||
isDragging = true;
|
||||
}}
|
||||
ondragleave={() => {
|
||||
isDragging = false;
|
||||
}}
|
||||
role="presentation"
|
||||
>
|
||||
<!-- Queued messages (above input, matching open-webui layout) -->
|
||||
@@ -966,7 +991,9 @@
|
||||
<div
|
||||
class="absolute left-2 bottom-full mb-1 z-50 w-60 max-h-40 overflow-y-auto rounded-xl bg-white dark:bg-[#1a1a1a] border border-gray-150 dark:border-white/6 shadow-xl p-0.5"
|
||||
>
|
||||
<div class="mb-0.5 px-2 pt-1 pb-0.5 text-[10px] leading-none text-gray-400 dark:text-gray-600">
|
||||
<div
|
||||
class="mb-0.5 px-2 pt-1 pb-0.5 text-[10px] leading-none text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
Commands
|
||||
</div>
|
||||
{#if slashCommandIds.includes('compact')}
|
||||
@@ -983,7 +1010,9 @@
|
||||
}}
|
||||
onmouseenter={() => (selectedSlashCommandIndex = slashCommandIds.indexOf('compact'))}
|
||||
>
|
||||
<span class="flex items-center justify-center w-4 shrink-0 text-gray-400 dark:text-gray-500">
|
||||
<span
|
||||
class="flex items-center justify-center w-4 shrink-0 text-gray-400 dark:text-gray-500"
|
||||
>
|
||||
<svg class="size-3.5 -rotate-90" viewBox="0 0 20 20" aria-hidden="true">
|
||||
<circle
|
||||
cx="10"
|
||||
@@ -1028,7 +1057,9 @@
|
||||
}}
|
||||
onmouseenter={() => (selectedSlashCommandIndex = slashCommandIds.indexOf('plan'))}
|
||||
>
|
||||
<span class="flex items-center justify-center w-4 shrink-0 text-gray-400 dark:text-gray-500">
|
||||
<span
|
||||
class="flex items-center justify-center w-4 shrink-0 text-gray-400 dark:text-gray-500"
|
||||
>
|
||||
<svg
|
||||
class="size-3.5"
|
||||
viewBox="0 0 24 24"
|
||||
@@ -1066,7 +1097,9 @@
|
||||
}}
|
||||
onmouseenter={() => (selectedSlashCommandIndex = slashCommandIds.indexOf('status'))}
|
||||
>
|
||||
<span class="flex items-center justify-center w-4 shrink-0 text-gray-400 dark:text-gray-500">
|
||||
<span
|
||||
class="flex items-center justify-center w-4 shrink-0 text-gray-400 dark:text-gray-500"
|
||||
>
|
||||
<svg
|
||||
class="size-3.5"
|
||||
viewBox="0 0 24 24"
|
||||
@@ -1101,34 +1134,54 @@
|
||||
{#each attachedUploads as upload}
|
||||
<div class="relative group flex-shrink-0">
|
||||
{#if upload.loading}
|
||||
<div class="flex items-center justify-center size-8 bg-gray-50 dark:bg-white/5 rounded-xl border border-gray-200 dark:border-white/10 shadow-sm">
|
||||
<div
|
||||
class="flex items-center justify-center size-8 bg-gray-50 dark:bg-white/5 rounded-xl border border-gray-200 dark:border-white/10 shadow-sm"
|
||||
>
|
||||
<Spinner size={16} />
|
||||
</div>
|
||||
{:else if upload.type === 'image'}
|
||||
<img src={upload.url} alt={upload.name} class="size-8 object-cover rounded-xl border border-gray-200 dark:border-white/10 shadow-sm" />
|
||||
<img
|
||||
src={upload.url}
|
||||
alt={upload.name}
|
||||
class="size-8 object-cover rounded-xl border border-gray-200 dark:border-white/10 shadow-sm"
|
||||
/>
|
||||
{:else}
|
||||
<div class="relative group px-2 w-48 h-8 flex items-center gap-1.5 bg-white dark:bg-[#1a1a1a] border border-gray-100 dark:border-white/5 rounded-xl text-left flex-shrink-0 shadow-sm">
|
||||
<div
|
||||
class="relative group px-2 w-48 h-8 flex items-center gap-1.5 bg-white dark:bg-[#1a1a1a] border border-gray-100 dark:border-white/5 rounded-xl text-left flex-shrink-0 shadow-sm"
|
||||
>
|
||||
<div class="shrink-0">
|
||||
<Icon name="page-text" size={14} class="text-gray-500 dark:text-gray-400" />
|
||||
</div>
|
||||
<div class="flex flex-col justify-center w-full overflow-hidden">
|
||||
<div class="dark:text-gray-100 text-xs flex justify-between items-center w-full gap-2">
|
||||
<div
|
||||
class="dark:text-gray-100 text-xs flex justify-between items-center w-full gap-2"
|
||||
>
|
||||
<div class="font-medium truncate flex-1">{upload.name}</div>
|
||||
<div class="text-[10px] text-gray-500 capitalize shrink-0">{upload.type === 'file' ? 'File' : upload.type}</div>
|
||||
<div class="text-[10px] text-gray-500 capitalize shrink-0">
|
||||
{upload.type === 'file' ? 'File' : upload.type}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
<div class="absolute -top-1.5 -right-1.5 z-10">
|
||||
<button
|
||||
<button
|
||||
class="bg-white text-black border border-white rounded-full group-hover:visible invisible transition outline-none shadow-sm flex items-center justify-center"
|
||||
type="button"
|
||||
onclick={() => removeUpload(upload.id)}
|
||||
aria-label={$t('chat.removeUpload')}
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="size-3.5" aria-hidden="true">
|
||||
<path d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"/>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
class="size-3.5"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
@@ -1139,9 +1192,15 @@
|
||||
<!-- Editor area -->
|
||||
<div class="px-2.5">
|
||||
{#if $voiceModeEnabled}
|
||||
<div class="pt-2 flex items-center gap-2 text-[11px] font-medium text-gray-600 dark:text-gray-300">
|
||||
<div
|
||||
class="pt-2 flex items-center gap-2 text-[11px] font-medium text-gray-600 dark:text-gray-300"
|
||||
>
|
||||
<span class="relative flex size-2">
|
||||
<span class="absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-70 {voiceListening ? 'animate-ping' : ''}"></span>
|
||||
<span
|
||||
class="absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-70 {voiceListening
|
||||
? 'animate-ping'
|
||||
: ''}"
|
||||
></span>
|
||||
<span class="relative inline-flex size-2 rounded-full bg-emerald-500"></span>
|
||||
</span>
|
||||
<span>{voiceStatusLabel}</span>
|
||||
|
||||
@@ -53,7 +53,9 @@
|
||||
import AssistantMessage from './AssistantMessage.svelte';
|
||||
import ChatHistory from './ChatHistory.svelte';
|
||||
import StatusModal from './StatusModal.svelte';
|
||||
import { listCommandSessions, type CommandSession } from '$lib/apis/terminal';
|
||||
import Spinner from '../common/Spinner.svelte';
|
||||
import Icon from '../Icon.svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
@@ -77,14 +79,17 @@
|
||||
let currentMessageId = $state<string | null>(null);
|
||||
let contextUsage = $state<ContextUsage | null>(null);
|
||||
let showStatusModal = $state(false);
|
||||
let commandSessions = $state<CommandSession[]>([]);
|
||||
let initialCommandSessionId = $state<string | null>(null);
|
||||
let previousChats = $state<ChatInfo[]>([]);
|
||||
let messagesEl: HTMLDivElement;
|
||||
let chatInputEl: ChatInput;
|
||||
let statusButtonEl: HTMLButtonElement | undefined = $state();
|
||||
let sending = $state(false);
|
||||
let autoScroll = $state(true);
|
||||
let cancelledMessageId: string | null = null;
|
||||
let loading = $state(!!initialChatId);
|
||||
let chatTitle = '';
|
||||
let chatTitle = $state('');
|
||||
let ttsQueue: string[] = [];
|
||||
let ttsBuffer = '';
|
||||
let ttsInsideCodeFence = false;
|
||||
@@ -97,6 +102,7 @@
|
||||
let ttsErrorShown = false;
|
||||
let speakingMessageId = $state<string | null>(null);
|
||||
let ttsStopRequested = false;
|
||||
let commandSessionsChatId: string | null = null;
|
||||
// This browser memory cache only helps while the current page is open, such as when
|
||||
// someone taps the same speak button twice. The backend cache is the durable source
|
||||
// for cross-session reuse and the workspace data flywheel.
|
||||
@@ -106,6 +112,7 @@
|
||||
const TTS_AUDIO_CACHE_LIMIT_BYTES = 20 * 1024 * 1024;
|
||||
const TTS_MAX_PREFETCH = 2;
|
||||
let unbindSocketListeners: (() => void) | null = null;
|
||||
let commandSessionsTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
onMount(() => {
|
||||
if (initialChatId || typeof sessionStorage === 'undefined') return;
|
||||
@@ -283,6 +290,12 @@
|
||||
const streaming = $derived(allMessages.some((m) => m.role === 'assistant' && !m.done));
|
||||
const isLanding = $derived(allMessages.length === 0 && !chatId);
|
||||
const workspaceDisplayName = $derived(getPathDisplayName(workspace, 'workspace'));
|
||||
const displayChatTitle = $derived(chatTitle || firstUserMessageTitle() || workspaceDisplayName);
|
||||
const runningCommandSessions = $derived(commandSessions.filter((session) => !session.done));
|
||||
const summaryCount = $derived(runningCommandSessions.length);
|
||||
const statusButtonClass =
|
||||
'text-gray-400 hover:bg-gray-50 hover:text-gray-700 dark:text-gray-600 dark:hover:bg-white/5 dark:hover:text-gray-300';
|
||||
const statusTitle = $derived(summaryCount > 0 ? `${summaryCount} active command session` : 'Status');
|
||||
|
||||
// Queued messages: user-authored messages waiting behind an active response.
|
||||
const queuedMessages = $derived(
|
||||
@@ -296,6 +309,13 @@
|
||||
.map((m) => ({ id: m.id, content: m.content }))
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
if (chatId === commandSessionsChatId) return;
|
||||
commandSessionsChatId = chatId;
|
||||
commandSessions = [];
|
||||
if (chatId) refreshCommandSessions();
|
||||
});
|
||||
|
||||
// ── Load chat from DB ───────────────────────────────────────
|
||||
|
||||
let loadGeneration = 0;
|
||||
@@ -531,6 +551,9 @@
|
||||
} else {
|
||||
loadPreviousChats();
|
||||
}
|
||||
refreshCommandSessions();
|
||||
commandSessionsTimer = setInterval(refreshCommandSessions, 5000);
|
||||
window.addEventListener('cptr:inspect-command-session', handleInspectCommandSession);
|
||||
|
||||
const offChat = socketStore.on('events:chat', handleSocketEvent);
|
||||
const offConnect = socketStore.on('connect', handleReconnect);
|
||||
@@ -544,6 +567,9 @@
|
||||
stopTtsPlayback();
|
||||
unbindSocketListeners?.();
|
||||
unbindSocketListeners = null;
|
||||
if (commandSessionsTimer) clearInterval(commandSessionsTimer);
|
||||
commandSessionsTimer = null;
|
||||
window.removeEventListener('cptr:inspect-command-session', handleInspectCommandSession);
|
||||
if (landingRefreshTimer) clearTimeout(landingRefreshTimer);
|
||||
// Don't clear streamingChatTabs here -- the global listener in
|
||||
// chat.ts handles cleanup when the "done" event arrives, so the
|
||||
@@ -825,8 +851,40 @@
|
||||
planMode.set(!get(planMode));
|
||||
}
|
||||
|
||||
function firstUserMessageTitle(): string {
|
||||
const message = allMessages.find((m) => m.role === 'user' && !isPendingHiddenMessage(m));
|
||||
return message ? message.content.replace(/\s+/g, ' ').trim().slice(0, 80) : '';
|
||||
}
|
||||
|
||||
function handleStatusCommand() {
|
||||
if (isLanding) return;
|
||||
initialCommandSessionId = null;
|
||||
showStatusModal = true;
|
||||
refreshCommandSessions();
|
||||
}
|
||||
|
||||
async function refreshCommandSessions() {
|
||||
const currentChatId = chatId;
|
||||
if (!currentChatId) {
|
||||
commandSessions = [];
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const sessions = await listCommandSessions(workspace, currentChatId);
|
||||
if (chatId !== currentChatId) return;
|
||||
commandSessions = sessions;
|
||||
} catch (err) {
|
||||
console.error('[chat] command sessions refresh error', err);
|
||||
if (chatId === currentChatId) commandSessions = [];
|
||||
}
|
||||
}
|
||||
|
||||
function handleInspectCommandSession(e: Event) {
|
||||
const id = (e as CustomEvent<{ commandSessionId?: string }>).detail?.commandSessionId;
|
||||
if (!id) return;
|
||||
initialCommandSessionId = id;
|
||||
showStatusModal = true;
|
||||
refreshCommandSessions();
|
||||
}
|
||||
|
||||
// ── Queue actions ──────────────────────────────────────────
|
||||
@@ -1354,7 +1412,27 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full bg-white dark:bg-black">
|
||||
<div class="relative flex h-full flex-col bg-white dark:bg-black">
|
||||
{#if !isLanding}
|
||||
<div
|
||||
class="flex h-7 shrink-0 items-center gap-2 border-b border-gray-100 px-3 dark:border-white/6"
|
||||
>
|
||||
<div class="min-w-0 flex-1 truncate text-[11px] font-medium text-gray-600 dark:text-gray-400">
|
||||
{displayChatTitle}
|
||||
</div>
|
||||
<button
|
||||
bind:this={statusButtonEl}
|
||||
type="button"
|
||||
class="relative flex size-6 shrink-0 items-center justify-center rounded-lg transition-colors duration-75 {statusButtonClass}"
|
||||
aria-label={statusTitle}
|
||||
title={statusTitle}
|
||||
onclick={handleStatusCommand}
|
||||
>
|
||||
<Icon name="list" size={13} />
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if isLanding}
|
||||
<!-- Landing: input + recent chats -->
|
||||
<div class="flex-1 overflow-y-auto flex flex-col">
|
||||
@@ -1378,6 +1456,7 @@
|
||||
{workspace}
|
||||
placeholder={$t('chat.placeholder', { name: workspaceDisplayName })}
|
||||
onsend={send}
|
||||
onstatus={handleStatusCommand}
|
||||
{queuedMessages}
|
||||
onqueuesendnow={handleQueueSendNow}
|
||||
onqueueedit={handleQueueEdit}
|
||||
@@ -1496,5 +1575,16 @@
|
||||
</div>
|
||||
|
||||
{#if showStatusModal}
|
||||
<StatusModal {chatId} {contextUsage} onclose={() => (showStatusModal = false)} />
|
||||
<StatusModal
|
||||
{chatId}
|
||||
{contextUsage}
|
||||
{commandSessions}
|
||||
{queuedMessages}
|
||||
{initialCommandSessionId}
|
||||
anchor={statusButtonEl ?? { x: 0, y: 0 }}
|
||||
onclose={() => {
|
||||
showStatusModal = false;
|
||||
initialCommandSessionId = null;
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
@@ -1,20 +1,53 @@
|
||||
<script lang="ts">
|
||||
import Modal from '../Modal.svelte';
|
||||
import Terminal from '../Terminal.svelte';
|
||||
import DropdownMenu from '../DropdownMenu.svelte';
|
||||
import Icon from '../Icon.svelte';
|
||||
import type { ContextUsage } from '$lib/apis/chat';
|
||||
import type { CommandSession } from '$lib/apis/terminal';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
chatId: string | null;
|
||||
contextUsage: ContextUsage | null;
|
||||
commandSessions?: CommandSession[];
|
||||
queuedMessages?: { id: string; content: string }[];
|
||||
initialCommandSessionId?: string | null;
|
||||
anchor: HTMLElement | { x: number; y: number };
|
||||
onclose: () => void;
|
||||
}
|
||||
|
||||
let { chatId, contextUsage, onclose }: Props = $props();
|
||||
let {
|
||||
chatId,
|
||||
contextUsage,
|
||||
commandSessions = [],
|
||||
queuedMessages = [],
|
||||
initialCommandSessionId = null,
|
||||
anchor,
|
||||
onclose
|
||||
}: Props = $props();
|
||||
|
||||
let copied = $state(false);
|
||||
let selectedSessionId = $state<string | null>(null);
|
||||
let appliedInitialSessionId = $state<string | null>(null);
|
||||
let missingSessionId = $state<string | null>(null);
|
||||
let forceStopSignal = $state(0);
|
||||
let terminatingSessionId = $state<string | null>(null);
|
||||
|
||||
const runningSessions = $derived(commandSessions.filter((session) => !session.done));
|
||||
const selectedSession = $derived(
|
||||
runningSessions.find((session) => session.command_session_id === selectedSessionId) ?? null
|
||||
);
|
||||
const terminatingSelectedSession = $derived(
|
||||
!!selectedSession && terminatingSessionId === selectedSession.command_session_id
|
||||
);
|
||||
const contextPercent = $derived(Math.max(0, Math.round(contextUsage?.percent ?? 0)));
|
||||
const progressWidth = $derived(`${Math.min(contextPercent, 100)}%`);
|
||||
const tokenCount = $derived(contextUsage?.tokens ?? contextUsage?.estimated_tokens ?? 0);
|
||||
const contextValue = $derived(
|
||||
contextUsage
|
||||
? `${contextPercent}% ${formatTokenCount(contextUsage.estimated_tokens || contextUsage.tokens)}/${formatTokenCount(contextUsage.threshold)}`
|
||||
: $t('chat.statusUnknown')
|
||||
);
|
||||
const contextBarPercent = $derived(Math.min(contextPercent, 100));
|
||||
|
||||
function copyChatId() {
|
||||
if (!chatId) return;
|
||||
@@ -22,57 +55,190 @@
|
||||
copied = true;
|
||||
setTimeout(() => (copied = false), 1600);
|
||||
}
|
||||
|
||||
function elapsedLabel(ts: number): string {
|
||||
const seconds = Math.max(0, Math.floor(Date.now() / 1000 - ts));
|
||||
if (seconds < 60) return `${seconds}s`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return `${minutes}m`;
|
||||
return `${Math.floor(minutes / 60)}h`;
|
||||
}
|
||||
|
||||
function shortCommand(command: string): string {
|
||||
return command.length > 92 ? `${command.slice(0, 92)}...` : command;
|
||||
}
|
||||
|
||||
function formatTokenCount(value: number): string {
|
||||
if (value >= 1_000_000) return `${trimNumber(value / 1_000_000)}m`;
|
||||
if (value >= 1_000) return `${trimNumber(value / 1_000)}k`;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function trimNumber(value: number): string {
|
||||
return value >= 10 ? String(Math.round(value)) : value.toFixed(1).replace(/\.0$/, '');
|
||||
}
|
||||
|
||||
function sessionLabel(session: CommandSession): string {
|
||||
return session.command_session_id;
|
||||
}
|
||||
|
||||
function statusLabel(session: CommandSession): string {
|
||||
if (!session.done) return elapsedLabel(session.created_at);
|
||||
if (session.exit_code && session.exit_code !== 0) return `Failed ${session.exit_code}`;
|
||||
return 'Finished';
|
||||
}
|
||||
|
||||
function terminateSelectedSession() {
|
||||
if (!selectedSession || terminatingSelectedSession) return;
|
||||
terminatingSessionId = selectedSession.command_session_id;
|
||||
forceStopSignal += 1;
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!initialCommandSessionId) return;
|
||||
const exists = runningSessions.some(
|
||||
(session) => session.command_session_id === initialCommandSessionId
|
||||
);
|
||||
if (exists) {
|
||||
selectedSessionId = initialCommandSessionId;
|
||||
appliedInitialSessionId = initialCommandSessionId;
|
||||
missingSessionId = null;
|
||||
} else if (initialCommandSessionId !== appliedInitialSessionId) {
|
||||
selectedSessionId = null;
|
||||
appliedInitialSessionId = initialCommandSessionId;
|
||||
missingSessionId = initialCommandSessionId;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<Modal {onclose} class="w-full max-w-[300px] mx-4">
|
||||
<div class="px-4 py-3.5">
|
||||
<div class="flex items-baseline justify-between gap-3 mb-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{$t('chat.commandStatus')}
|
||||
</h2>
|
||||
<span class="text-[11px] font-mono text-gray-400 dark:text-gray-600">
|
||||
{contextUsage ? `${contextPercent}%` : $t('chat.statusUnknown')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<div class="h-1 overflow-hidden rounded-full bg-gray-100 dark:bg-white/6">
|
||||
<div
|
||||
class="h-full rounded-full bg-gray-900 dark:bg-white transition-[width] duration-200"
|
||||
style={`width: ${progressWidth};`}
|
||||
></div>
|
||||
</div>
|
||||
<div class="mt-1.5 flex items-baseline justify-between gap-3">
|
||||
<span class="text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{$t('chat.statusEstimated')}
|
||||
</span>
|
||||
<span class="font-mono text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{#if contextUsage}
|
||||
{tokenCount.toLocaleString()} / {contextUsage.threshold.toLocaleString()}
|
||||
{:else}
|
||||
{$t('chat.statusUnknown')}
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div class="text-[10px] text-gray-400 dark:text-gray-600 mb-1">
|
||||
{$t('chat.statusChatId')}
|
||||
</div>
|
||||
{#if chatId}
|
||||
{#if selectedSession}
|
||||
<Modal
|
||||
{onclose}
|
||||
class="mx-4 flex h-[min(760px,82dvh)] w-full max-w-[min(960px,calc(100vw-2rem))] flex-col overflow-hidden max-sm:mx-0 max-sm:h-[100dvh] max-sm:max-w-none max-sm:rounded-none"
|
||||
>
|
||||
<div class="flex h-full min-h-0 flex-col overflow-hidden">
|
||||
<div class="flex h-9 shrink-0 items-center gap-3 border-b border-gray-100 px-3 dark:border-white/8">
|
||||
<button
|
||||
type="button"
|
||||
class="block w-full text-left font-mono text-[11px] leading-relaxed text-gray-700 dark:text-gray-300 break-all hover:text-gray-900 dark:hover:text-white transition-colors"
|
||||
onclick={copyChatId}
|
||||
class="flex h-7 shrink-0 items-center gap-1.5 rounded-lg pr-2 text-xs text-gray-400 transition-colors duration-75 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300"
|
||||
onclick={onclose}
|
||||
>
|
||||
{copied ? $t('about.copied') : chatId}
|
||||
<Icon name="chevron-left" size={12} />
|
||||
<span>Back</span>
|
||||
</button>
|
||||
{:else}
|
||||
<div class="font-mono text-[11px] leading-relaxed text-gray-700 dark:text-gray-300">
|
||||
{$t('chat.statusNoChat')}
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate font-mono text-xs font-medium text-gray-900 dark:text-white">
|
||||
{sessionLabel(selectedSession)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="h-7 shrink-0 px-1.5 text-xs text-gray-400 underline-offset-2 transition-colors duration-75 hover:text-gray-700 hover:underline disabled:cursor-default disabled:text-gray-300 disabled:no-underline dark:text-gray-600 dark:hover:text-gray-200 dark:disabled:text-gray-700"
|
||||
title={terminatingSelectedSession ? 'Terminating' : 'Force terminate'}
|
||||
disabled={terminatingSelectedSession}
|
||||
onclick={terminateSelectedSession}
|
||||
>
|
||||
{terminatingSelectedSession ? 'Terminating' : 'Terminate'}
|
||||
</button>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 bg-white dark:bg-black">
|
||||
<Terminal
|
||||
wsPath={`/api/terminal/sessions/${selectedSession.command_session_id}/ws`}
|
||||
initialOutput={selectedSession.output ?? ''}
|
||||
initialOffset={selectedSession.total_bytes ?? 0}
|
||||
{forceStopSignal}
|
||||
readOnly={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
{:else}
|
||||
<DropdownMenu
|
||||
items={[]}
|
||||
{anchor}
|
||||
{onclose}
|
||||
align="end"
|
||||
className="w-80 max-w-[calc(100vw-1.5rem)] p-0"
|
||||
>
|
||||
<div class="max-h-[70dvh] overflow-y-auto px-1 py-0.5 text-xs sm:max-h-[min(72dvh,520px)]">
|
||||
{#if missingSessionId}
|
||||
<div
|
||||
class="rounded-xl px-1.5 py-1.5 text-[11px] leading-relaxed text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
Live session unavailable. Saved output remains in the chat.
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if runningSessions.length}
|
||||
<section>
|
||||
<div
|
||||
class="px-1.5 pb-0.5 pt-1.5 text-[10px] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-600"
|
||||
>
|
||||
Sessions
|
||||
</div>
|
||||
{#each runningSessions as session}
|
||||
<div class="flex h-7 min-w-0 items-center gap-3 rounded-xl px-1.5 text-gray-600 dark:text-gray-400">
|
||||
<button
|
||||
type="button"
|
||||
class="min-w-0 flex-1 truncate text-left font-mono text-[11px] text-gray-400 underline-offset-2 transition-colors duration-75 hover:text-gray-700 hover:underline dark:text-gray-600 dark:hover:text-gray-200"
|
||||
title={shortCommand(session.command)}
|
||||
onclick={() => (selectedSessionId = session.command_session_id)}
|
||||
>
|
||||
{sessionLabel(session)}
|
||||
</button>
|
||||
<span class="shrink-0 text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{statusLabel(session)}
|
||||
</span>
|
||||
</div>
|
||||
{/each}
|
||||
</section>
|
||||
{/if}
|
||||
|
||||
<section>
|
||||
<div class="rounded-xl px-1.5 py-1.5 text-gray-600 dark:text-gray-400">
|
||||
<div class="flex h-5 items-center gap-3">
|
||||
<span class="min-w-0 flex-1 truncate">Context</span>
|
||||
<span class="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{contextValue}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 h-px overflow-hidden rounded-full bg-gray-100 dark:bg-white/8">
|
||||
<div
|
||||
class="h-full rounded-full bg-gray-300 dark:bg-white/20"
|
||||
style={`width: ${contextBarPercent}%`}
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if queuedMessages.length}
|
||||
<div class="flex h-7 items-center gap-3 rounded-xl px-1.5 text-gray-600 dark:text-gray-400">
|
||||
<span class="min-w-0 flex-1 truncate">Queued messages</span>
|
||||
<span class="font-mono text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{queuedMessages.length}
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if chatId}
|
||||
<div class="flex h-7 items-center gap-3 rounded-xl px-1.5 text-gray-600 dark:text-gray-400">
|
||||
<span class="min-w-0 flex-1 truncate">Chat ID</span>
|
||||
<button
|
||||
type="button"
|
||||
class="min-w-0 max-w-[11rem] truncate font-mono text-[10px] text-gray-400 underline-offset-2 transition-colors duration-75 hover:text-gray-700 hover:underline dark:text-gray-600 dark:hover:text-gray-200"
|
||||
onclick={copyChatId}
|
||||
>
|
||||
{copied ? $t('about.copied') : chatId}
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex h-7 items-center gap-3 rounded-xl px-1.5 text-gray-600 dark:text-gray-400">
|
||||
<span class="min-w-0 flex-1 truncate">Chat ID</span>
|
||||
<span class="font-mono text-[10px] text-gray-400 dark:text-gray-600">
|
||||
{$t('chat.statusNoChat')}
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</DropdownMenu>
|
||||
{/if}
|
||||
@@ -46,7 +46,6 @@
|
||||
return pairedOutput.output;
|
||||
}
|
||||
});
|
||||
|
||||
function toggleExpanded() {
|
||||
expanded = !expanded;
|
||||
}
|
||||
@@ -57,6 +56,7 @@
|
||||
toggleExpanded();
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<div class="w-full min-w-0 flex flex-col">
|
||||
@@ -178,7 +178,7 @@
|
||||
>
|
||||
</span>
|
||||
{:else}
|
||||
<div class="flex shrink-0 self-center translate-y-[1px]">
|
||||
<div class="flex shrink-0 items-center gap-1 self-center">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
|
||||
@@ -12,6 +12,15 @@ from pydantic import BaseModel
|
||||
|
||||
from cptr.utils.config import check_access, get_auth_mode, get_user_uid_gid, AuthMode
|
||||
from cptr.utils.terminal import manager, IS_WINDOWS
|
||||
from cptr.utils.tools import (
|
||||
command_session_bytes_since,
|
||||
drain_command_session_input,
|
||||
get_command_session,
|
||||
list_command_sessions,
|
||||
resize_command_session,
|
||||
send_command_session_input,
|
||||
stop_command_session,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("cptr.terminal")
|
||||
|
||||
@@ -29,6 +38,22 @@ class SessionInfo(BaseModel):
|
||||
cwd: str
|
||||
|
||||
|
||||
class CommandSessionInfo(BaseModel):
|
||||
command_session_id: str
|
||||
task_id: str
|
||||
workspace: str
|
||||
chat_id: str | None = None
|
||||
message_id: str | None = None
|
||||
call_id: str | None = None
|
||||
command: str
|
||||
created_at: float
|
||||
status: str
|
||||
done: bool
|
||||
exit_code: int | None = None
|
||||
total_bytes: int
|
||||
output: str = ""
|
||||
|
||||
|
||||
@router.post("", response_model=SessionInfo)
|
||||
async def create_session(req: CreateSessionRequest):
|
||||
"""Create a new terminal session."""
|
||||
@@ -48,6 +73,12 @@ async def list_sessions():
|
||||
return [SessionInfo(**s) for s in sessions]
|
||||
|
||||
|
||||
@router.get("/sessions", response_model=List[CommandSessionInfo])
|
||||
async def list_command_session_endpoint(workspace: str | None = None, chat_id: str | None = None):
|
||||
"""List live command sessions created by run_command."""
|
||||
return [CommandSessionInfo(**s) for s in list_command_sessions(workspace, chat_id)]
|
||||
|
||||
|
||||
@router.delete("/{session_id}")
|
||||
async def delete_session(session_id: str):
|
||||
"""Kill a terminal session."""
|
||||
@@ -57,6 +88,114 @@ async def delete_session(session_id: str):
|
||||
return {"status": "closed"}
|
||||
|
||||
|
||||
@router.websocket("/sessions/{command_session_id}/ws")
|
||||
async def command_session_ws(websocket: WebSocket, command_session_id: str):
|
||||
"""WebSocket endpoint for command-session I/O.
|
||||
|
||||
Uses the same compact binary client protocol as normal terminals:
|
||||
0x00 + raw input bytes
|
||||
0x02 + uint16 cols + uint16 rows
|
||||
0x03 stop
|
||||
Server → Client: raw command output bytes.
|
||||
"""
|
||||
client_host = websocket.client.host if websocket.client else "127.0.0.1"
|
||||
token = websocket.cookies.get("cptr_session") or websocket.query_params.get("token")
|
||||
auth = check_access(client_host=client_host, jwt_token=token)
|
||||
if auth is None:
|
||||
await websocket.close(code=4001, reason="unauthorized")
|
||||
return
|
||||
|
||||
session = get_command_session(command_session_id)
|
||||
if not session:
|
||||
await websocket.close(code=4004, reason="Command session not found")
|
||||
return
|
||||
|
||||
await websocket.accept()
|
||||
|
||||
MSG_INPUT = 0
|
||||
MSG_RESIZE = 2
|
||||
MSG_STOP = 3
|
||||
MSG_FORCE_STOP = 4
|
||||
|
||||
try:
|
||||
initial_offset = max(0, int(websocket.query_params.get("offset", "0")))
|
||||
except ValueError:
|
||||
initial_offset = 0
|
||||
|
||||
async def stream_output():
|
||||
offset = initial_offset
|
||||
try:
|
||||
while True:
|
||||
session = get_command_session(command_session_id)
|
||||
if not session:
|
||||
break
|
||||
raw, offset = command_session_bytes_since(session, offset)
|
||||
if raw:
|
||||
await websocket.send_bytes(raw)
|
||||
if session.get("done"):
|
||||
break
|
||||
condition = session["condition"]
|
||||
async with condition:
|
||||
await condition.wait_for(
|
||||
lambda: (
|
||||
session.get("done") or int(session.get("total_bytes") or 0) != offset
|
||||
)
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error("command session stream error for %s: %s", command_session_id, e)
|
||||
|
||||
stream_task = asyncio.create_task(stream_output())
|
||||
|
||||
try:
|
||||
while True:
|
||||
raw = await websocket.receive_bytes()
|
||||
if len(raw) < 1:
|
||||
continue
|
||||
|
||||
msg_type = raw[0]
|
||||
payload = raw[1:]
|
||||
|
||||
if msg_type == MSG_INPUT:
|
||||
error = send_command_session_input(command_session_id, payload)
|
||||
if error:
|
||||
logger.debug(
|
||||
"command session input ignored for %s: %s", command_session_id, error
|
||||
)
|
||||
await drain_command_session_input(command_session_id)
|
||||
elif msg_type == MSG_RESIZE:
|
||||
try:
|
||||
if len(payload) == 4:
|
||||
cols = int.from_bytes(payload[0:2], "big")
|
||||
rows = int.from_bytes(payload[2:4], "big")
|
||||
else:
|
||||
import json as _json
|
||||
|
||||
resize_data = _json.loads(payload)
|
||||
cols = resize_data.get("cols", 80)
|
||||
rows = resize_data.get("rows", 24)
|
||||
resize_command_session(command_session_id, rows, cols)
|
||||
except (ValueError, KeyError) as e:
|
||||
logger.warning(
|
||||
"Invalid command-session resize payload for %s: %s", command_session_id, e
|
||||
)
|
||||
elif msg_type == MSG_STOP:
|
||||
stop_command_session(command_session_id)
|
||||
elif msg_type == MSG_FORCE_STOP:
|
||||
stop_command_session(command_session_id, force=True)
|
||||
except WebSocketDisconnect:
|
||||
logger.info("WebSocket disconnected for command session %s", command_session_id)
|
||||
except Exception as e:
|
||||
logger.error("WebSocket error for command session %s: %s", command_session_id, e)
|
||||
finally:
|
||||
stream_task.cancel()
|
||||
try:
|
||||
await stream_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
|
||||
@router.websocket("/{session_id}/ws")
|
||||
async def terminal_ws(websocket: WebSocket, session_id: str):
|
||||
"""WebSocket endpoint for terminal I/O.
|
||||
|
||||
+10
-2
@@ -1916,7 +1916,11 @@ async def run_chat_task(
|
||||
if tc["name"] == "create_artifact":
|
||||
result = await create_artifact(**tc["arguments"], workspace=workspace)
|
||||
else:
|
||||
result = await execute_tool(tc["name"], tc["arguments"], tool_ctx)
|
||||
result = await execute_tool(
|
||||
tc["name"],
|
||||
tc["arguments"],
|
||||
{**tool_ctx, "call_id": tc["call_id"]},
|
||||
)
|
||||
|
||||
# Append output BEFORE marking completed — if anything
|
||||
# between here and persist fails, the call stays
|
||||
@@ -1965,7 +1969,11 @@ async def run_chat_task(
|
||||
for idx in delegate_indices:
|
||||
tc, _ = call_items[idx]
|
||||
task = asyncio.create_task(
|
||||
execute_tool(tc["name"], tc["arguments"], tool_ctx)
|
||||
execute_tool(
|
||||
tc["name"],
|
||||
tc["arguments"],
|
||||
{**tool_ctx, "call_id": tc["call_id"]},
|
||||
)
|
||||
)
|
||||
inflight[task] = idx
|
||||
|
||||
|
||||
+167
-66
@@ -18,7 +18,7 @@ import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Literal, Optional, get_args, get_origin, get_type_hints
|
||||
from typing import Any, Literal, Optional, get_args, get_origin, get_type_hints
|
||||
from cptr.env import CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS, EXECUTE_TIMEOUT
|
||||
|
||||
try:
|
||||
@@ -37,10 +37,10 @@ except ImportError:
|
||||
_PTY_AVAILABLE = False # Windows
|
||||
|
||||
|
||||
# ── Background task state ───────────────────────────────────
|
||||
# ── Command session state ───────────────────────────────────
|
||||
|
||||
_bg_tasks: dict[str, dict] = {}
|
||||
# task_id → {
|
||||
command_sessions: dict[str, dict] = {}
|
||||
# command_session_id → {
|
||||
# "master_fd": int | None, PTY mode (Unix) — read/write through this fd
|
||||
# "proc": Popen | Process, The child process handle
|
||||
# "output": bytearray, In-memory ring buffer (256KB cap)
|
||||
@@ -49,7 +49,7 @@ _bg_tasks: dict[str, dict] = {}
|
||||
# "exit_code": int | None,
|
||||
# "log_path": str,
|
||||
# }
|
||||
_BG_TASK_LIMIT = 5
|
||||
MAX_COMMAND_SESSIONS = 5
|
||||
_MAX_LOG_SIZE = 50 * 1024 * 1024 # 50MB — rotate when exceeded
|
||||
|
||||
|
||||
@@ -112,17 +112,18 @@ def _rotate_log(log_path: str, log_file) -> tuple:
|
||||
return new_file, new_size
|
||||
|
||||
|
||||
async def _collect_bg_output(task_id: str):
|
||||
"""Read output from a background process (PTY or pipe) into memory + JSONL log."""
|
||||
task = _bg_tasks.get(task_id)
|
||||
if not task:
|
||||
async def stream_command_session_output(command_session_id: str):
|
||||
"""Read output from a command process into memory + JSONL log."""
|
||||
session = command_sessions.get(command_session_id)
|
||||
if not session:
|
||||
return
|
||||
|
||||
master_fd = task.get("master_fd")
|
||||
proc = task["proc"]
|
||||
log_path = task.get("log_path")
|
||||
master_fd = session.get("master_fd")
|
||||
proc = session["proc"]
|
||||
log_path = session.get("log_path")
|
||||
log_file = None
|
||||
log_bytes = 0
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
try:
|
||||
if log_path:
|
||||
@@ -132,7 +133,7 @@ async def _collect_bg_output(task_id: str):
|
||||
json.dumps(
|
||||
{
|
||||
"type": "start",
|
||||
"command": task["command"],
|
||||
"command": session["command"],
|
||||
"pid": proc.pid,
|
||||
"ts": time.time(),
|
||||
}
|
||||
@@ -143,8 +144,6 @@ async def _collect_bg_output(task_id: str):
|
||||
log_file.flush()
|
||||
log_bytes += len(entry.encode("utf-8", errors="replace"))
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
while True:
|
||||
# Read from PTY fd (Unix) or subprocess pipe (Windows fallback)
|
||||
if master_fd is not None:
|
||||
@@ -159,12 +158,14 @@ async def _collect_bg_output(task_id: str):
|
||||
if not chunk:
|
||||
break
|
||||
|
||||
task = _bg_tasks.get(task_id)
|
||||
if task:
|
||||
task["output"].extend(chunk)
|
||||
task["total_bytes"] += len(chunk)
|
||||
if len(task["output"]) > 256 * 1024:
|
||||
task["output"] = task["output"][-256 * 1024 :]
|
||||
session = command_sessions.get(command_session_id)
|
||||
if session:
|
||||
session["output"].extend(chunk)
|
||||
session["total_bytes"] += len(chunk)
|
||||
if len(session["output"]) > 256 * 1024:
|
||||
session["output"] = session["output"][-256 * 1024 :]
|
||||
async with session["condition"]:
|
||||
session["condition"].notify_all()
|
||||
|
||||
if log_file:
|
||||
entry = (
|
||||
@@ -187,7 +188,7 @@ async def _collect_bg_output(task_id: str):
|
||||
pass
|
||||
finally:
|
||||
# Wait for the process to finish and collect exit code
|
||||
task = _bg_tasks.get(task_id)
|
||||
session = command_sessions.get(command_session_id)
|
||||
if master_fd is not None:
|
||||
exit_code = await loop.run_in_executor(None, proc.wait)
|
||||
try:
|
||||
@@ -198,10 +199,12 @@ async def _collect_bg_output(task_id: str):
|
||||
await proc.wait()
|
||||
exit_code = proc.returncode
|
||||
|
||||
if task:
|
||||
task["done"] = True
|
||||
task["exit_code"] = exit_code
|
||||
task["master_fd"] = None # fd is closed
|
||||
if session:
|
||||
session["done"] = True
|
||||
session["exit_code"] = exit_code
|
||||
session["master_fd"] = None # fd is closed
|
||||
async with session["condition"]:
|
||||
session["condition"].notify_all()
|
||||
|
||||
if log_file:
|
||||
log_file.write(
|
||||
@@ -238,6 +241,114 @@ def _truncate_output(text: str, max_chars: int = 80_000) -> str:
|
||||
return text[:half] + "\n\n... (truncated) ...\n\n" + text[-half:]
|
||||
|
||||
|
||||
def _command_session_snapshot(command_session_id: str, session: dict) -> dict[str, Any]:
|
||||
return {
|
||||
"command_session_id": command_session_id,
|
||||
"task_id": command_session_id, # legacy UI/tool wording
|
||||
"workspace": session.get("workspace", ""),
|
||||
"chat_id": session.get("chat_id"),
|
||||
"message_id": session.get("message_id"),
|
||||
"call_id": session.get("call_id"),
|
||||
"command": session.get("command", ""),
|
||||
"created_at": session.get("created_at", 0),
|
||||
"status": "completed" if session.get("done") else "running",
|
||||
"done": bool(session.get("done")),
|
||||
"exit_code": session.get("exit_code"),
|
||||
"total_bytes": int(session.get("total_bytes") or 0),
|
||||
"output": bytes(session.get("output") or b"").decode(errors="replace"),
|
||||
}
|
||||
|
||||
|
||||
def list_command_sessions(
|
||||
workspace: str | None = None, chat_id: str | None = None
|
||||
) -> list[dict[str, Any]]:
|
||||
sessions: list[dict[str, Any]] = []
|
||||
for command_session_id, session in command_sessions.items():
|
||||
if session.get("done"):
|
||||
continue
|
||||
if workspace and session.get("workspace") != workspace:
|
||||
continue
|
||||
if chat_id and session.get("chat_id") != chat_id:
|
||||
continue
|
||||
sessions.append(_command_session_snapshot(command_session_id, session))
|
||||
sessions.sort(key=lambda item: (item["status"] != "running", -float(item["created_at"] or 0)))
|
||||
return sessions
|
||||
|
||||
|
||||
def get_command_session(command_session_id: str) -> dict | None:
|
||||
return command_sessions.get(command_session_id)
|
||||
|
||||
|
||||
def command_session_bytes_since(session: dict, offset: int) -> tuple[bytes, int]:
|
||||
buf = session["output"]
|
||||
total = int(session.get("total_bytes") or 0)
|
||||
buf_start = total - len(buf)
|
||||
if offset <= buf_start:
|
||||
raw = bytes(buf)
|
||||
else:
|
||||
raw = bytes(buf[offset - buf_start :])
|
||||
return raw, total
|
||||
|
||||
|
||||
def send_command_session_input(command_session_id: str, data: bytes) -> str | None:
|
||||
session = command_sessions.get(command_session_id)
|
||||
if not session:
|
||||
return "command session not found"
|
||||
if session.get("done"):
|
||||
return "command session already exited"
|
||||
|
||||
master_fd = session.get("master_fd")
|
||||
if master_fd is not None:
|
||||
try:
|
||||
os.write(master_fd, data)
|
||||
except OSError:
|
||||
return "PTY closed"
|
||||
else:
|
||||
proc = session["proc"]
|
||||
if proc.stdin is None:
|
||||
return "stdin unavailable"
|
||||
try:
|
||||
proc.stdin.write(data)
|
||||
if hasattr(proc.stdin, "drain"):
|
||||
# asyncio subprocess pipe
|
||||
return None
|
||||
except (BrokenPipeError, ConnectionResetError, OSError):
|
||||
return "stdin closed"
|
||||
return None
|
||||
|
||||
|
||||
async def drain_command_session_input(command_session_id: str) -> None:
|
||||
session = command_sessions.get(command_session_id)
|
||||
proc = session.get("proc") if session else None
|
||||
stdin = getattr(proc, "stdin", None)
|
||||
if stdin is not None and hasattr(stdin, "drain"):
|
||||
await stdin.drain()
|
||||
|
||||
|
||||
def resize_command_session(command_session_id: str, rows: int, cols: int) -> None:
|
||||
session = command_sessions.get(command_session_id)
|
||||
if not session or session.get("done"):
|
||||
return
|
||||
master_fd = session.get("master_fd")
|
||||
if master_fd is None or not _PTY_AVAILABLE:
|
||||
return
|
||||
try:
|
||||
winsize = struct.pack("HHHH", rows, cols, 0, 0)
|
||||
fcntl.ioctl(master_fd, termios.TIOCSWINSZ, winsize)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def stop_command_session(command_session_id: str, force: bool = False) -> str | None:
|
||||
session = command_sessions.get(command_session_id)
|
||||
if not session:
|
||||
return "command session not found"
|
||||
if session.get("done"):
|
||||
return None
|
||||
_kill_process_group(session["proc"].pid, force=force)
|
||||
return None
|
||||
|
||||
|
||||
# ── Image support ───────────────────────────────────────────
|
||||
|
||||
IMAGE_EXTENSIONS = {
|
||||
@@ -834,20 +945,21 @@ async def run_command(
|
||||
cwd: str = ".",
|
||||
wait: Optional[int] = None,
|
||||
*,
|
||||
workspace: str,
|
||||
__context__: dict,
|
||||
) -> str:
|
||||
"""Run a shell command. Returns a task_id for status checks and input.
|
||||
:param command: The shell command to execute.
|
||||
:param cwd: Working directory relative to workspace root.
|
||||
:param wait: Seconds to wait for the command to finish before returning (max 300). Returns early if done sooner. Null returns immediately. Use 30-60 for installs and builds, 5-10 for quick commands, null or 0 for long-lived servers.
|
||||
"""
|
||||
workspace = __context__["workspace"]
|
||||
work_dir = _resolve_path(cwd, workspace)
|
||||
if not work_dir.is_dir():
|
||||
return f"Error: not a directory: {cwd}"
|
||||
|
||||
active = sum(1 for t in _bg_tasks.values() if not t.get("done"))
|
||||
if active >= _BG_TASK_LIMIT:
|
||||
return f"Error: too many running tasks ({active}/{_BG_TASK_LIMIT}). Kill one first."
|
||||
active = sum(1 for t in command_sessions.values() if not t.get("done"))
|
||||
if active >= MAX_COMMAND_SESSIONS:
|
||||
return f"Error: too many running command sessions ({active}/{MAX_COMMAND_SESSIONS}). Stop one first."
|
||||
|
||||
env = {**os.environ, "PAGER": "cat", "GIT_PAGER": "cat"}
|
||||
master_fd = None
|
||||
@@ -867,24 +979,31 @@ async def run_command(
|
||||
except Exception as e:
|
||||
return f"Error: {e}"
|
||||
|
||||
task_id = uuid.uuid4().hex[:8]
|
||||
command_session_id = uuid.uuid4().hex[:8]
|
||||
log_dir = Path(workspace) / ".cptr" / "task_logs"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_path = log_dir / f"{task_id}.jsonl"
|
||||
log_path = log_dir / f"{command_session_id}.jsonl"
|
||||
|
||||
_bg_tasks[task_id] = {
|
||||
command_sessions[command_session_id] = {
|
||||
"command_session_id": command_session_id,
|
||||
"master_fd": master_fd,
|
||||
"proc": proc,
|
||||
"output": bytearray(),
|
||||
"total_bytes": 0,
|
||||
"command": command,
|
||||
"workspace": workspace,
|
||||
"chat_id": __context__.get("chat_id"),
|
||||
"message_id": __context__.get("message_id"),
|
||||
"call_id": __context__.get("call_id"),
|
||||
"created_at": time.time(),
|
||||
"done": False,
|
||||
"exit_code": None,
|
||||
"log_path": str(log_path),
|
||||
"log_task": None,
|
||||
"condition": asyncio.Condition(),
|
||||
}
|
||||
log_task = asyncio.create_task(_collect_bg_output(task_id))
|
||||
_bg_tasks[task_id]["log_task"] = log_task
|
||||
log_task = asyncio.create_task(stream_command_session_output(command_session_id))
|
||||
command_sessions[command_session_id]["log_task"] = log_task
|
||||
|
||||
# Wait for the command to finish inline (matches open-terminal behaviour)
|
||||
if wait is None and EXECUTE_TIMEOUT:
|
||||
@@ -895,7 +1014,7 @@ async def run_command(
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
task = _bg_tasks.get(task_id)
|
||||
task = command_sessions.get(command_session_id)
|
||||
output = task["output"].decode(errors="replace") if task else ""
|
||||
output = _truncate_output(output, max_chars=CHAT_TOOL_COMMAND_MAX_CHARS)
|
||||
done = task.get("done", False) if task else True
|
||||
@@ -907,9 +1026,7 @@ async def run_command(
|
||||
else:
|
||||
status = "running"
|
||||
|
||||
return (
|
||||
f"Task {task_id}: {status}\nCommand: {command}\nnext_offset: {next_offset}\n---\n{output}"
|
||||
)
|
||||
return f"Task {command_session_id}: {status}\nCommand: {command}\nnext_offset: {next_offset}\n---\n{output}"
|
||||
|
||||
|
||||
async def check_task(
|
||||
@@ -920,9 +1037,9 @@ async def check_task(
|
||||
:param offset: Byte offset from previous check. Pass next_offset from the last response to get only new output.
|
||||
:param wait: Seconds to wait for the task to finish before returning (max 300). Returns early if done sooner. Null returns immediately.
|
||||
"""
|
||||
task = _bg_tasks.get(task_id)
|
||||
task = command_sessions.get(task_id)
|
||||
if not task:
|
||||
available = list(_bg_tasks.keys())
|
||||
available = list(command_sessions.keys())
|
||||
return f"Error: no task with id '{task_id}'. Active tasks: {available or 'none'}"
|
||||
|
||||
# Optionally wait for the task to finish
|
||||
@@ -965,19 +1082,16 @@ async def kill_task(task_id: str, force: bool = False, *, workspace: str) -> str
|
||||
:param task_id: The task ID to kill.
|
||||
:param force: Send SIGKILL instead of SIGTERM for immediate termination.
|
||||
"""
|
||||
task = _bg_tasks.get(task_id)
|
||||
task = command_sessions.get(task_id)
|
||||
if not task:
|
||||
available = list(_bg_tasks.keys())
|
||||
available = list(command_sessions.keys())
|
||||
return f"Error: no task with id '{task_id}'. Active tasks: {available or 'none'}"
|
||||
|
||||
if task.get("done", False):
|
||||
exit_code = task.get("exit_code")
|
||||
_bg_tasks.pop(task_id, None)
|
||||
return f"Task {task_id} already finished (code {exit_code})"
|
||||
|
||||
proc = task["proc"]
|
||||
_kill_process_group(proc.pid, force=force)
|
||||
_bg_tasks.pop(task_id, None)
|
||||
stop_command_session(task_id, force=force)
|
||||
|
||||
action = "Killed" if force else "Terminated"
|
||||
return f"{action} task {task_id}"
|
||||
@@ -988,9 +1102,9 @@ async def send_input(task_id: str, input: str, *, workspace: str) -> str:
|
||||
:param task_id: The task ID returned by run_command.
|
||||
:param input: Text to send. Use \\n for Enter, \\x03 for Ctrl-C, \\x04 for Ctrl-D.
|
||||
"""
|
||||
task = _bg_tasks.get(task_id)
|
||||
task = command_sessions.get(task_id)
|
||||
if not task:
|
||||
available = list(_bg_tasks.keys())
|
||||
available = list(command_sessions.keys())
|
||||
return f"Error: no task '{task_id}'. Active: {available or 'none'}"
|
||||
|
||||
if task.get("done", False):
|
||||
@@ -1002,23 +1116,10 @@ async def send_input(task_id: str, input: str, *, workspace: str) -> str:
|
||||
except (UnicodeDecodeError, ValueError):
|
||||
text = input
|
||||
|
||||
master_fd = task.get("master_fd")
|
||||
if master_fd is not None:
|
||||
# PTY mode: write to master fd
|
||||
try:
|
||||
os.write(master_fd, text.encode())
|
||||
except OSError:
|
||||
return f"Error: PTY closed for task {task_id}"
|
||||
else:
|
||||
# Pipe mode fallback
|
||||
proc = task["proc"]
|
||||
if proc.stdin is None:
|
||||
return f"Error: task {task_id} has no stdin"
|
||||
try:
|
||||
proc.stdin.write(text.encode())
|
||||
await proc.stdin.drain()
|
||||
except (BrokenPipeError, ConnectionResetError, OSError):
|
||||
return f"Error: stdin closed for task {task_id}"
|
||||
error = send_command_session_input(task_id, text.encode())
|
||||
if error:
|
||||
return f"Error: {error} for task {task_id}"
|
||||
await drain_command_session_input(task_id)
|
||||
|
||||
return f"Sent {len(text)} bytes to task {task_id}"
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cptr"
|
||||
version = "0.7.3"
|
||||
version = "0.7.4"
|
||||
description = "Your computer, from anywhere. Code, manage, and control your machine from the web."
|
||||
license = {file = "LICENSE"}
|
||||
readme = "README.md"
|
||||
|
||||
Reference in new issue
Block a user