mirror of
https://github.com/open-webui/computer.git
synced 2026-11-30 17:05:17 -05:00
47 files changed
+2276
-395
No files matched your search
@@ -14,6 +14,9 @@ permissions:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
skip: ${{ steps.check.outputs.skip }}
|
||||
version: ${{ steps.pkg.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
@@ -69,6 +72,20 @@ jobs:
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: python -m build --wheel
|
||||
|
||||
- name: Build Linux wheelhouse
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: |
|
||||
VERSION="${{ steps.pkg.outputs.version }}"
|
||||
WHEEL="dist/cptr-${VERSION}-py3-none-any.whl"
|
||||
mkdir -p wheelhouse
|
||||
python -m pip download --dest wheelhouse "${WHEEL}[all]"
|
||||
tar -czf "cptr-${VERSION}-linux-wheelhouse.tar.gz" -C wheelhouse .
|
||||
|
||||
- name: Generate checksums
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: |
|
||||
sha256sum dist/*.whl cptr-*-linux-wheelhouse.tar.gz > SHA256SUMS
|
||||
|
||||
- name: Upload dist artifacts
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -76,12 +93,23 @@ jobs:
|
||||
name: dist
|
||||
path: dist/
|
||||
|
||||
- name: Upload release artifacts
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-assets
|
||||
path: |
|
||||
dist/*.whl
|
||||
cptr-*-linux-wheelhouse.tar.gz
|
||||
SHA256SUMS
|
||||
|
||||
publish:
|
||||
needs: build
|
||||
if: needs.build.outputs.skip != 'true'
|
||||
runs-on: ubuntu-latest
|
||||
environment: pypi
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Download dist artifacts
|
||||
@@ -90,7 +118,28 @@ jobs:
|
||||
name: dist
|
||||
path: dist/
|
||||
|
||||
- name: Download release artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-assets
|
||||
path: release-assets/
|
||||
|
||||
- name: Publish to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@release/v1
|
||||
# No API token needed - uses OIDC trusted publishing.
|
||||
# Configure at: https://pypi.org/manage/project/cptr/settings/publishing/
|
||||
|
||||
- name: Upload GitHub release artifacts
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
VERSION: ${{ needs.build.outputs.version }}
|
||||
run: |
|
||||
for attempt in {1..12}; do
|
||||
if gh release view "v${VERSION}" >/dev/null 2>&1; then
|
||||
gh release upload "v${VERSION}" release-assets/* --clobber
|
||||
exit 0
|
||||
fi
|
||||
sleep 10
|
||||
done
|
||||
echo "GitHub release v${VERSION} was not found" >&2
|
||||
exit 1
|
||||
@@ -5,6 +5,26 @@ 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.6] - 2026-07-06
|
||||
|
||||
### Added
|
||||
|
||||
- 🔔 **Notification targets.** Send chat alerts to a webhook or one of your messaging bots, choose when alerts are sent, and test each destination from Settings.
|
||||
- 🤖 **Cline agent support.** Add Cline as a coding agent and use it from chat alongside Codex, Claude Code, Cursor, Grok, and OpenCode.
|
||||
- 📦 **Offline install guide.** Added setup steps for installing Computer in places without internet access after download.
|
||||
|
||||
### Changed
|
||||
|
||||
- 🧭 **Easier workspace start.** Recent workspaces are easier to find, scan, and reopen from the home screen.
|
||||
- 🪟 **Better split tabs.** Drag tabs to the left, right, top, or bottom to make split panes, and move tabs between panes without losing them.
|
||||
- 🌍 **More complete labels.** Updated labels for new notification and agent settings across supported languages.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 📎 **Cleaner dragging.** Dragging tabs no longer wakes up file upload areas or chat attachments by mistake.
|
||||
- 💬 **Messaging bot setup.** Slack, WhatsApp, and Signal bots can now be created from the same admin flow as Telegram and Discord.
|
||||
- ✅ **More reliable chat endings.** Chats now settle more consistently at the end of a run, which keeps final status and alerts in sync.
|
||||
|
||||
## [0.7.5] - 2026-07-02
|
||||
|
||||
### Added
|
||||
|
||||
@@ -97,7 +97,7 @@ Bring your own API key (OpenAI, Anthropic, Ollama, or any OpenAI-compatible endp
|
||||
|
||||
Connect a coding agent as a native backend and use the subscription you already pay for. No separate API key needed.
|
||||
|
||||
**Codex** · **Claude Code** · **Cursor** · **Grok** · **OpenCode**
|
||||
**Codex** · **Claude Code** · **Cursor** · **Grok** · **OpenCode** · **Cline**
|
||||
|
||||
Add an agent profile from Settings, pick your models, and it shows up in the model selector like any other provider. Conversations run inside your workspace with full tool access and resume where you left off.
|
||||
|
||||
@@ -121,7 +121,7 @@ Open WebUI Computer exposes an OpenAI-compatible API (`/v1/chat/completions`). A
|
||||
|---|---|
|
||||
| 🎙️ **Voice memos** | Record audio, auto-transcribe to markdown. |
|
||||
| 💬 **Message queue** | Queue follow-up messages while the AI is responding. |
|
||||
| 🔔 **Notifications** | Browser notifications and webhooks (Slack, Discord, Teams) when tasks finish. |
|
||||
| 🔔 **Notifications** | Browser notifications plus named webhook or bot targets for chat events. |
|
||||
| 📊 **Usage** | Token counts and timing on every response. |
|
||||
| 📄 **System prompts** | Per-model, per-workspace, or global. Template variables included. |
|
||||
| 📋 **Audit logging** | Structured audit trail of all API mutations with automatic redaction of sensitive data. |
|
||||
@@ -170,6 +170,38 @@ If you bind-mount a host directory to `/data`, make sure that directory is writa
|
||||
|
||||
The `:dev` image is also available and tracks the `main` branch.
|
||||
|
||||
## Air-gapped installation
|
||||
|
||||
Open WebUI Computer does not need internet access after it is installed. The Python wheel includes the built frontend assets, and the Docker image is self-contained.
|
||||
|
||||
On a connected machine:
|
||||
|
||||
```bash
|
||||
pip download --dest wheelhouse 'cptr[all]'
|
||||
docker pull ghcr.io/open-webui/computer:latest
|
||||
docker save ghcr.io/open-webui/computer:latest -o cptr-image.tar
|
||||
```
|
||||
|
||||
Transfer the artifacts, then install or run offline:
|
||||
|
||||
```bash
|
||||
python -m venv .venv
|
||||
. .venv/bin/activate
|
||||
pip install --no-index --find-links ./wheelhouse 'cptr[all]'
|
||||
cptr run --host 0.0.0.0
|
||||
|
||||
docker load -i cptr-image.tar
|
||||
docker run --rm -it \
|
||||
--network=none \
|
||||
-p 8000:8000 \
|
||||
-v cptr-data:/data \
|
||||
-v "$PWD:/workspace" \
|
||||
-w /workspace \
|
||||
ghcr.io/open-webui/computer:latest
|
||||
```
|
||||
|
||||
Core local features run from local assets. External services such as hosted model APIs, web search providers, messaging adapters, Git remotes, and MCP/OpenAPI servers still require reachable endpoints.
|
||||
|
||||
## Security model
|
||||
|
||||
Open WebUI Computer is designed as **your computer, served to you**. Once authenticated, a user has full access to the host filesystem and shell, equivalent to an SSH session. There is no path sandboxing and no per-user isolation.
|
||||
|
||||
@@ -19,6 +19,7 @@ from cptr.routers import (
|
||||
git_router,
|
||||
images_router,
|
||||
memory_router,
|
||||
notifications_router,
|
||||
proxy_router,
|
||||
search_router,
|
||||
skills_router,
|
||||
@@ -267,6 +268,7 @@ app.include_router(gateway_router)
|
||||
app.include_router(git_router)
|
||||
app.include_router(images_router)
|
||||
app.include_router(memory_router)
|
||||
app.include_router(notifications_router)
|
||||
app.include_router(proxy_router)
|
||||
app.include_router(search_router)
|
||||
app.include_router(skills_router)
|
||||
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
"""Application event definitions and internal event bus."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from importlib.metadata import PackageNotFoundError, version as package_version
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_STRING_LENGTH = 1000
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EventDefinition:
|
||||
name: str
|
||||
description: str | None = None
|
||||
message: str | None = None
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return self.message or self.name.replace(".", " ").replace("_", " ").title()
|
||||
|
||||
|
||||
class EventDefinitions:
|
||||
CHAT_FINISHED = EventDefinition(
|
||||
"chat.finished",
|
||||
"A chat run finished successfully.",
|
||||
"Chat finished",
|
||||
)
|
||||
CHAT_FAILED = EventDefinition(
|
||||
"chat.failed",
|
||||
"A chat run failed.",
|
||||
"Chat failed",
|
||||
)
|
||||
NOTIFICATION_TEST = EventDefinition(
|
||||
"notification.test",
|
||||
"A notification target test was sent.",
|
||||
"Test notification",
|
||||
)
|
||||
NOTIFICATION_MANUAL = EventDefinition(
|
||||
"manual.notify",
|
||||
"A manual notification was sent.",
|
||||
"Notification",
|
||||
)
|
||||
|
||||
|
||||
EVENTS = EventDefinitions()
|
||||
EVENT_DEFINITIONS = tuple(
|
||||
value for value in vars(EventDefinitions).values() if isinstance(value, EventDefinition)
|
||||
)
|
||||
EVENT_DEFINITIONS_BY_NAME = {definition.name: definition for definition in EVENT_DEFINITIONS}
|
||||
EVENT_CATALOG = tuple(definition.name for definition in EVENT_DEFINITIONS)
|
||||
EVENT_CATALOG_SET = set(EVENT_CATALOG)
|
||||
|
||||
CHAT_NOTIFICATION_EVENTS = (
|
||||
EVENTS.CHAT_FINISHED,
|
||||
EVENTS.CHAT_FAILED,
|
||||
)
|
||||
|
||||
SENSITIVE_KEYS = {
|
||||
"password",
|
||||
"hashed_password",
|
||||
"token",
|
||||
"access_token",
|
||||
"refresh_token",
|
||||
"id_token",
|
||||
"api_key",
|
||||
"secret",
|
||||
"key",
|
||||
"authorization",
|
||||
"cookie",
|
||||
"webhook_token",
|
||||
}
|
||||
SAFE_ACTOR_FIELDS = ("id", "name", "email", "role", "created_at", "updated_at")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Event:
|
||||
schema: str
|
||||
id: str
|
||||
event: str
|
||||
resource: str
|
||||
operation: str
|
||||
created_at: int
|
||||
source: str
|
||||
actor: dict[str, Any] | None = None
|
||||
subject: dict[str, Any] | None = None
|
||||
data: dict[str, Any] = field(default_factory=dict)
|
||||
message: str | None = None
|
||||
|
||||
def model_dump(self) -> dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
|
||||
def _sanitize(value: Any) -> Any:
|
||||
if hasattr(value, "model_dump"):
|
||||
value = value.model_dump()
|
||||
|
||||
if isinstance(value, dict):
|
||||
sanitized = {}
|
||||
for key, item in value.items():
|
||||
normalized = str(key).lower().replace("-", "_")
|
||||
if (
|
||||
normalized in SENSITIVE_KEYS
|
||||
or normalized.endswith("_token")
|
||||
or normalized.endswith("_secret")
|
||||
or normalized.endswith("_api_key")
|
||||
or normalized.endswith("_key")
|
||||
):
|
||||
continue
|
||||
sanitized[key] = _sanitize(item)
|
||||
return sanitized
|
||||
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
return [_sanitize(item) for item in value]
|
||||
|
||||
if isinstance(value, str) and len(value) > MAX_STRING_LENGTH:
|
||||
return f"{value[:MAX_STRING_LENGTH]}..."
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def build_event(
|
||||
event: EventDefinition | str,
|
||||
*,
|
||||
actor: Any | None = None,
|
||||
subject_id: Any | None = None,
|
||||
subject_type: str | None = None,
|
||||
source: str = "api",
|
||||
data: dict | None = None,
|
||||
message: str | None = None,
|
||||
) -> Event:
|
||||
event_name_value = event.name if isinstance(event, EventDefinition) else str(event)
|
||||
if event_name_value not in EVENT_CATALOG_SET:
|
||||
raise ValueError(f"Unknown event: {event_name_value}")
|
||||
|
||||
parts = event_name_value.split(".")
|
||||
resource = ".".join(parts[:-1])
|
||||
subject = (
|
||||
{"type": subject_type or resource, "id": subject_id}
|
||||
if subject_id is not None or subject_type is not None
|
||||
else None
|
||||
)
|
||||
actor = _sanitize(actor)
|
||||
actor_payload = None
|
||||
if actor:
|
||||
get = actor.get if isinstance(actor, dict) else lambda key: getattr(actor, key, None)
|
||||
actor_payload = {field: get(field) for field in SAFE_ACTOR_FIELDS if get(field) is not None}
|
||||
if actor_payload:
|
||||
actor_payload["type"] = get("type") or "user"
|
||||
|
||||
try:
|
||||
schema = package_version("cptr")
|
||||
except PackageNotFoundError:
|
||||
schema = "dev"
|
||||
|
||||
return Event(
|
||||
schema=schema,
|
||||
id=str(uuid.uuid4()),
|
||||
event=event_name_value,
|
||||
resource=resource,
|
||||
operation=parts[-1],
|
||||
created_at=int(time.time()),
|
||||
source=source,
|
||||
actor=actor_payload,
|
||||
subject=_sanitize(subject) if subject else None,
|
||||
data=_sanitize(data or {}),
|
||||
message=message,
|
||||
)
|
||||
|
||||
|
||||
def get_event_catalog() -> list[dict[str, str]]:
|
||||
return [
|
||||
{
|
||||
"event": definition.name,
|
||||
"label": definition.label,
|
||||
"description": definition.description or "",
|
||||
}
|
||||
for definition in EVENT_DEFINITIONS
|
||||
]
|
||||
|
||||
|
||||
class NotificationEventSink:
|
||||
async def handle_event(self, event: Event) -> None:
|
||||
from cptr.utils.notifications import dispatch_notification_event
|
||||
|
||||
await dispatch_notification_event(event)
|
||||
|
||||
|
||||
EVENT_SINKS = [NotificationEventSink()]
|
||||
|
||||
|
||||
async def publish_event(
|
||||
event: EventDefinition | str,
|
||||
*,
|
||||
actor: Any | None = None,
|
||||
subject_id: Any | None = None,
|
||||
subject_type: str | None = None,
|
||||
source: str = "api",
|
||||
data: dict | None = None,
|
||||
message: str | None = None,
|
||||
) -> Event:
|
||||
event_payload = build_event(
|
||||
event,
|
||||
actor=actor,
|
||||
subject_id=subject_id,
|
||||
subject_type=subject_type,
|
||||
source=source,
|
||||
data=data,
|
||||
message=message,
|
||||
)
|
||||
|
||||
for sink in EVENT_SINKS:
|
||||
try:
|
||||
await sink.handle_event(event_payload)
|
||||
except Exception:
|
||||
logger.exception("Event sink failed for %s", event_payload.event)
|
||||
|
||||
return event_payload
|
||||
@@ -155,6 +155,11 @@
|
||||
color: var(--app-fg);
|
||||
}
|
||||
|
||||
.app-theme :where(option) {
|
||||
background: var(--app-bg);
|
||||
color: var(--app-fg);
|
||||
}
|
||||
|
||||
.app-theme:where([class*='border-gray-'], [class*='border-black/'], [class*='border-white/']),
|
||||
.app-theme :where([class*='border-gray-'], [class*='border-black/'], [class*='border-white/']) {
|
||||
border-color: var(--app-border);
|
||||
|
||||
@@ -60,7 +60,7 @@ export const updateConfig = (config: Record<string, unknown>) =>
|
||||
|
||||
// ── Agents ─────────────────────────────────────────────────
|
||||
|
||||
export type AgentType = 'codex' | 'claude_code' | 'cursor' | 'grok' | 'opencode';
|
||||
export type AgentType = 'codex' | 'claude_code' | 'cursor' | 'grok' | 'opencode' | 'cline';
|
||||
export type AgentMode = 'auto' | 'enabled' | 'disabled';
|
||||
export type AgentStatus = 'ready' | 'not_found' | 'missing_dependency' | 'auth_unknown' | 'error';
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { fetchJSON, jsonBody } from '$lib/apis';
|
||||
|
||||
export const CHAT_NOTIFICATION_EVENTS = {
|
||||
FINISHED: 'chat.finished',
|
||||
FAILED: 'chat.failed'
|
||||
} as const;
|
||||
|
||||
export type ChatNotificationEvent =
|
||||
(typeof CHAT_NOTIFICATION_EVENTS)[keyof typeof CHAT_NOTIFICATION_EVENTS];
|
||||
export type NotificationDelivery = 'away' | 'always';
|
||||
export type NotificationTargetType = 'webhook' | 'bot';
|
||||
|
||||
export interface NotificationEventOption {
|
||||
event: ChatNotificationEvent;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface NotificationTarget {
|
||||
id: string;
|
||||
type: NotificationTargetType;
|
||||
enabled: boolean;
|
||||
is_default?: boolean;
|
||||
events: ChatNotificationEvent[];
|
||||
delivery: NotificationDelivery;
|
||||
config: {
|
||||
url_masked?: string;
|
||||
bot_id?: string;
|
||||
destination_chat_id?: string;
|
||||
};
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
export interface BotOption {
|
||||
id: string;
|
||||
name: string;
|
||||
platform: string;
|
||||
is_active: boolean;
|
||||
is_running: boolean;
|
||||
}
|
||||
|
||||
export interface NotificationTargetPayload {
|
||||
id?: string;
|
||||
type?: NotificationTargetType;
|
||||
enabled?: boolean;
|
||||
events?: ChatNotificationEvent[];
|
||||
delivery?: NotificationDelivery;
|
||||
config?: Record<string, string>;
|
||||
}
|
||||
|
||||
export async function listNotificationTargets(): Promise<NotificationTarget[]> {
|
||||
const data = await fetchJSON<{ targets: NotificationTarget[] }>('/api/notifications/targets');
|
||||
return data.targets;
|
||||
}
|
||||
|
||||
export async function listNotificationEvents(): Promise<NotificationEventOption[]> {
|
||||
const data = await fetchJSON<{ events: NotificationEventOption[] }>('/api/notifications/events');
|
||||
return data.events;
|
||||
}
|
||||
|
||||
export function createNotificationTarget(payload: NotificationTargetPayload) {
|
||||
return fetchJSON<NotificationTarget>('/api/notifications/targets', jsonBody(payload));
|
||||
}
|
||||
|
||||
export function updateNotificationTarget(id: string, payload: NotificationTargetPayload) {
|
||||
return fetchJSON<NotificationTarget>(`/api/notifications/targets/${id}`, {
|
||||
...jsonBody(payload),
|
||||
method: 'PUT'
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteNotificationTarget(id: string) {
|
||||
return fetchJSON<{ ok: boolean }>(`/api/notifications/targets/${id}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export function testNotificationTarget(id: string) {
|
||||
return fetchJSON<{ ok: boolean }>(`/api/notifications/targets/${id}/test`, { method: 'POST' });
|
||||
}
|
||||
|
||||
export function setDefaultNotificationTarget(id: string) {
|
||||
return fetchJSON<NotificationTarget>(`/api/notifications/targets/${id}/default`, { method: 'PUT' });
|
||||
}
|
||||
|
||||
export async function listNotificationBotOptions(): Promise<BotOption[]> {
|
||||
const data = await fetchJSON<{ bots: BotOption[] }>('/api/notifications/bot-options');
|
||||
return data.bots;
|
||||
}
|
||||
@@ -47,7 +47,8 @@
|
||||
claude_code: 'claude',
|
||||
cursor: 'agent',
|
||||
grok: 'grok',
|
||||
opencode: 'opencode'
|
||||
opencode: 'opencode',
|
||||
cline: 'cline'
|
||||
}[agent];
|
||||
}
|
||||
|
||||
@@ -57,7 +58,8 @@
|
||||
claude_code: 'Claude Code',
|
||||
cursor: 'Cursor',
|
||||
grok: 'Grok',
|
||||
opencode: 'OpenCode'
|
||||
opencode: 'OpenCode',
|
||||
cline: 'Cline'
|
||||
}[agent];
|
||||
}
|
||||
</script>
|
||||
@@ -126,6 +128,7 @@
|
||||
<option value="cursor">Cursor</option>
|
||||
<option value="grok">Grok</option>
|
||||
<option value="opencode">OpenCode</option>
|
||||
<option value="cline">Cline</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -111,7 +111,8 @@
|
||||
claude_code: 'claude',
|
||||
cursor: 'agent',
|
||||
grok: 'grok',
|
||||
opencode: 'opencode'
|
||||
opencode: 'opencode',
|
||||
cline: 'cline'
|
||||
}[agent];
|
||||
}
|
||||
|
||||
@@ -121,7 +122,8 @@
|
||||
claude_code: 'Claude Code',
|
||||
cursor: 'Cursor',
|
||||
grok: 'Grok',
|
||||
opencode: 'OpenCode'
|
||||
opencode: 'OpenCode',
|
||||
cline: 'Cline'
|
||||
}[agent];
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
import Spinner from './common/Spinner.svelte';
|
||||
import DropdownMenu from './DropdownMenu.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import { TAB_DRAG_MIME } from '$lib/constants';
|
||||
|
||||
interface FileEntry {
|
||||
name: string;
|
||||
@@ -573,6 +574,12 @@
|
||||
|
||||
// ── Drag to move ────────────────────────────────────────────
|
||||
|
||||
function isTabDrag(e: DragEvent): boolean {
|
||||
return Boolean(
|
||||
e.dataTransfer?.types.includes(TAB_DRAG_MIME) || e.dataTransfer?.types.includes('text/tab-id')
|
||||
);
|
||||
}
|
||||
|
||||
/** Collect all paths being dragged: either selected items (if the dragged item is selected) or just the single item */
|
||||
function getDraggedPaths(entry: TreeEntry): string[] {
|
||||
if (selectedPaths.size > 0 && selectedPaths.has(entry.path)) {
|
||||
@@ -605,6 +612,8 @@
|
||||
}
|
||||
|
||||
function onDragOverDir(e: DragEvent, entry: TreeEntry) {
|
||||
if (isTabDrag(e)) return;
|
||||
|
||||
// Determine the target folder for this entry
|
||||
let targetDir: string | null;
|
||||
if (entry.type === 'directory') {
|
||||
@@ -665,6 +674,8 @@
|
||||
}
|
||||
|
||||
async function onDropOnDir(e: DragEvent, entry: TreeEntry) {
|
||||
if (isTabDrag(e)) return;
|
||||
|
||||
e.preventDefault();
|
||||
if (dragExpandTimer) {
|
||||
clearTimeout(dragExpandTimer);
|
||||
@@ -744,6 +755,11 @@
|
||||
|
||||
// ── Drop zone for uploads ───────────────────────────────────
|
||||
function onDropzoneOver(e: DragEvent) {
|
||||
if (isTabDrag(e)) {
|
||||
dropzoneActive = false;
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
if (draggedItem) {
|
||||
// Internal drag — allow drop to move to current directory
|
||||
@@ -762,6 +778,8 @@
|
||||
}
|
||||
|
||||
async function onDropzoneDrop(e: DragEvent) {
|
||||
if (isTabDrag(e)) return;
|
||||
|
||||
e.preventDefault();
|
||||
dropzoneActive = false;
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { t } from '$lib/i18n';
|
||||
import VoiceMemoModal from './VoiceMemoModal.svelte';
|
||||
import { TAB_DRAG_MIME } from '$lib/constants';
|
||||
|
||||
interface Props {
|
||||
group: EditorGroup;
|
||||
@@ -57,6 +58,8 @@
|
||||
// Drop target highlight for cross-group drag
|
||||
let dropHighlight = $state(false);
|
||||
|
||||
type TabDragPayload = { tabId: string; groupId: string };
|
||||
|
||||
const displayTabs = $derived((group?.tabs ?? []).filter((t) => t.type !== 'git'));
|
||||
|
||||
const isActiveGroup = $derived($activeWorkspace?.activeGroupId === group?.id);
|
||||
@@ -89,6 +92,11 @@
|
||||
closeTab(tabId, group.id);
|
||||
}
|
||||
|
||||
function handleCloseGroup(e: Event) {
|
||||
e.stopPropagation();
|
||||
closeGroup(group.id);
|
||||
}
|
||||
|
||||
function handleContextMenu(e: MouseEvent, tab: Tab) {
|
||||
if (!isWideScreen) return;
|
||||
e.preventDefault();
|
||||
@@ -108,11 +116,31 @@
|
||||
// Native drag handlers are NOT needed. Sortable's setData handles it.
|
||||
// We keep the native drop handlers on the bar for cross-group drops.
|
||||
|
||||
function hasTabDrag(dataTransfer: DataTransfer): boolean {
|
||||
return dataTransfer.types.includes(TAB_DRAG_MIME) || dataTransfer.types.includes('text/tab-id');
|
||||
}
|
||||
|
||||
function readTabDragPayload(dataTransfer: DataTransfer): TabDragPayload | null {
|
||||
const raw = dataTransfer.getData(TAB_DRAG_MIME);
|
||||
if (raw) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Partial<TabDragPayload>;
|
||||
if (typeof parsed.tabId === 'string' && typeof parsed.groupId === 'string') {
|
||||
return { tabId: parsed.tabId, groupId: parsed.groupId };
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the legacy payload below.
|
||||
}
|
||||
}
|
||||
|
||||
const tabId = dataTransfer.getData('text/tab-id');
|
||||
const groupId = dataTransfer.getData('text/group-id');
|
||||
return tabId && groupId ? { tabId, groupId } : null;
|
||||
}
|
||||
|
||||
function handleBarDragOver(e: DragEvent) {
|
||||
// Only accept tab drags (not file uploads)
|
||||
if (!e.dataTransfer?.types.includes('text/tab-id')) return;
|
||||
const sourceGroupId = e.dataTransfer.types.includes('text/group-id') ? 'unknown' : null;
|
||||
if (!sourceGroupId) return;
|
||||
if (!e.dataTransfer || !hasTabDrag(e.dataTransfer)) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
dropHighlight = true;
|
||||
@@ -125,12 +153,11 @@
|
||||
function handleBarDrop(e: DragEvent) {
|
||||
dropHighlight = false;
|
||||
if (!e.dataTransfer) return;
|
||||
const tabId = e.dataTransfer.getData('text/tab-id');
|
||||
const fromGroupId = e.dataTransfer.getData('text/group-id');
|
||||
if (!tabId || !fromGroupId) return;
|
||||
if (fromGroupId === group.id) return; // same group, ignore
|
||||
const payload = readTabDragPayload(e.dataTransfer);
|
||||
if (!payload) return;
|
||||
if (payload.groupId === group.id) return; // same group, ignore
|
||||
e.preventDefault();
|
||||
moveTabToGroup(tabId, fromGroupId, group.id);
|
||||
moveTabToGroup(payload.tabId, payload.groupId, group.id);
|
||||
}
|
||||
|
||||
const plusMenuItems = $derived([
|
||||
@@ -246,6 +273,7 @@
|
||||
touchStartThreshold: 5,
|
||||
setData: (dataTransfer: DataTransfer, dragEl: HTMLElement) => {
|
||||
const tabId = dragEl.dataset.tabId ?? '';
|
||||
dataTransfer.setData(TAB_DRAG_MIME, JSON.stringify({ tabId, groupId: group.id }));
|
||||
dataTransfer.setData('text/tab-id', tabId);
|
||||
dataTransfer.setData('text/group-id', group.id);
|
||||
},
|
||||
@@ -370,7 +398,7 @@
|
||||
{#if canClose}
|
||||
<button
|
||||
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
|
||||
onclick={() => closeGroup(group.id)}
|
||||
onclick={handleCloseGroup}
|
||||
aria-label={$t('a11y.closePane')}
|
||||
use:tooltip={$t('a11y.closePane')}
|
||||
>
|
||||
|
||||
@@ -1,60 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { streamingBehavior, showUpdateToastPref } from '$lib/stores';
|
||||
import type { StreamingBehavior } from '$lib/stores';
|
||||
import { t, locale, changeLocale, supportedLocales } from '$lib/i18n';
|
||||
import { notificationsEnabled, notificationSound } from '$lib/stores/chat';
|
||||
import { fetchJSON } from '$lib/apis';
|
||||
import { updateConfig } from '$lib/apis/admin';
|
||||
import { session } from '$lib/session';
|
||||
import ToggleSwitch from '../common/ToggleSwitch.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
// ── Webhook URL ─────────────────────────────────────────────
|
||||
let webhookUrl = $state('');
|
||||
let webhookUrlOriginal = $state('');
|
||||
let saving = $state(false);
|
||||
|
||||
let dirty = $derived(webhookUrl.trim() !== webhookUrlOriginal);
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
const data = await fetchJSON<{ config: Record<string, any> }>(
|
||||
'/api/admin/config/notifications'
|
||||
);
|
||||
const url = data.config?.['notifications.webhook_url'] || '';
|
||||
webhookUrl = url;
|
||||
webhookUrlOriginal = url;
|
||||
} catch {}
|
||||
});
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
await updateConfig({ 'notifications.webhook_url': webhookUrl.trim() || null });
|
||||
webhookUrlOriginal = webhookUrl.trim();
|
||||
toast.success($t('settings.saved'));
|
||||
} catch {
|
||||
toast.error($t('general.webhookUrlSaveFailed'));
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleNotifications() {
|
||||
if (!$notificationsEnabled) {
|
||||
if ('Notification' in window) {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission === 'granted') {
|
||||
notificationsEnabled.set(true);
|
||||
} else {
|
||||
toast.error($t('general.notificationPermissionDenied'));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
notificationsEnabled.set(false);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
@@ -72,49 +21,6 @@
|
||||
{/each}
|
||||
</select>
|
||||
|
||||
<!-- Notifications -->
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">
|
||||
{$t('general.notifications')}
|
||||
</h3>
|
||||
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<!-- Browser notifications toggle -->
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400"
|
||||
>{$t('general.browserNotifications')}</span
|
||||
>
|
||||
<ToggleSwitch value={$notificationsEnabled} onchange={() => toggleNotifications()} />
|
||||
</label>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
{$t('general.browserNotificationsDesc')}
|
||||
</p>
|
||||
|
||||
<!-- Sound toggle -->
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400"
|
||||
>{$t('general.notificationSound')}</span
|
||||
>
|
||||
<ToggleSwitch value={$notificationSound} onchange={(v) => notificationSound.set(v)} />
|
||||
</label>
|
||||
|
||||
<!-- Webhook URL -->
|
||||
<div class="mt-1">
|
||||
<label class="text-xs text-gray-600 dark:text-gray-400" for="webhook-url">
|
||||
{$t('general.webhookUrl')}
|
||||
</label>
|
||||
<input
|
||||
id="webhook-url"
|
||||
type="url"
|
||||
bind:value={webhookUrl}
|
||||
placeholder="https://hooks.slack.com/services/..."
|
||||
class="w-full mt-1 h-7 px-2 rounded-lg text-xs bg-gray-100 dark:bg-white/6 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-white/8 outline-none focus:border-blue-400 dark:focus:border-blue-500 transition-colors"
|
||||
/>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 mt-1">
|
||||
{$t('general.webhookUrlHint')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if $session?.role === 'admin'}
|
||||
<h3 class="text-xs text-gray-400 dark:text-gray-600 mb-2 mt-5">{$t('general.updates')}</h3>
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
@@ -146,15 +52,4 @@
|
||||
{$streamingBehavior === 'queue' ? $t('general.queueDesc') : $t('general.interruptDesc')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="shrink-0 pt-3 flex justify-end">
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors duration-100
|
||||
disabled:opacity-30 disabled:pointer-events-none"
|
||||
onclick={save}
|
||||
disabled={saving}
|
||||
>
|
||||
{#if saving}{$t('settings.saving')}{:else}{$t('settings.save')}{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,472 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { t } from '$lib/i18n';
|
||||
import { notificationsEnabled, notificationSound } from '$lib/stores/chat';
|
||||
import {
|
||||
createNotificationTarget,
|
||||
CHAT_NOTIFICATION_EVENTS,
|
||||
deleteNotificationTarget,
|
||||
listNotificationBotOptions,
|
||||
listNotificationEvents,
|
||||
listNotificationTargets,
|
||||
setDefaultNotificationTarget,
|
||||
testNotificationTarget,
|
||||
updateNotificationTarget,
|
||||
type BotOption,
|
||||
type ChatNotificationEvent,
|
||||
type NotificationEventOption,
|
||||
type NotificationDelivery,
|
||||
type NotificationTarget,
|
||||
type NotificationTargetType
|
||||
} from '$lib/apis/notifications';
|
||||
import Icon from '../Icon.svelte';
|
||||
import Modal from '../Modal.svelte';
|
||||
import ToggleSwitch from '../common/ToggleSwitch.svelte';
|
||||
|
||||
const fallbackEventOptions: NotificationEventOption[] = [
|
||||
{
|
||||
event: CHAT_NOTIFICATION_EVENTS.FINISHED,
|
||||
label: 'Chat finished',
|
||||
description: 'A chat run finished successfully.'
|
||||
},
|
||||
{
|
||||
event: CHAT_NOTIFICATION_EVENTS.FAILED,
|
||||
label: 'Chat failed',
|
||||
description: 'A chat run failed.'
|
||||
}
|
||||
];
|
||||
|
||||
let targets = $state<NotificationTarget[]>([]);
|
||||
let eventOptions = $state<NotificationEventOption[]>(fallbackEventOptions);
|
||||
let botOptions = $state<BotOption[]>([]);
|
||||
let loadingTargets = $state(false);
|
||||
let savingTarget = $state(false);
|
||||
let editingId = $state<string | null>(null);
|
||||
let formOpen = $state(false);
|
||||
let form = $state({
|
||||
id: '',
|
||||
type: 'webhook' as NotificationTargetType,
|
||||
url: '',
|
||||
bot_id: '',
|
||||
destination_chat_id: '',
|
||||
enabled: true,
|
||||
events: [] as ChatNotificationEvent[],
|
||||
delivery: 'away' as NotificationDelivery
|
||||
});
|
||||
let targetTypes = $derived<NotificationTargetType[]>(
|
||||
botOptions.length ? ['webhook', 'bot'] : ['webhook']
|
||||
);
|
||||
|
||||
onMount(() => {
|
||||
void loadNotificationTargets();
|
||||
});
|
||||
|
||||
async function loadNotificationTargets() {
|
||||
loadingTargets = true;
|
||||
const [targetResult, botResult, eventResult] = await Promise.allSettled([
|
||||
listNotificationTargets(),
|
||||
listNotificationBotOptions(),
|
||||
listNotificationEvents()
|
||||
]);
|
||||
if (targetResult.status === 'fulfilled') {
|
||||
targets = targetResult.value;
|
||||
} else {
|
||||
toast.error($t('general.notificationTargetsLoadFailed'));
|
||||
}
|
||||
botOptions = botResult.status === 'fulfilled' ? botResult.value : [];
|
||||
eventOptions =
|
||||
eventResult.status === 'fulfilled' && eventResult.value.length
|
||||
? eventResult.value
|
||||
: fallbackEventOptions;
|
||||
loadingTargets = false;
|
||||
}
|
||||
|
||||
async function toggleNotifications() {
|
||||
if (!$notificationsEnabled) {
|
||||
if ('Notification' in window) {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission === 'granted') {
|
||||
notificationsEnabled.set(true);
|
||||
} else {
|
||||
toast.error($t('general.notificationPermissionDenied'));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
notificationsEnabled.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
function openNewTarget(type: NotificationTargetType = 'webhook') {
|
||||
if (type === 'bot' && !botOptions.length) type = 'webhook';
|
||||
editingId = null;
|
||||
formOpen = true;
|
||||
form = {
|
||||
id: '',
|
||||
type,
|
||||
url: '',
|
||||
bot_id: botOptions[0]?.id || '',
|
||||
destination_chat_id: '',
|
||||
enabled: true,
|
||||
events: [],
|
||||
delivery: 'away'
|
||||
};
|
||||
}
|
||||
|
||||
function openEditTarget(target: NotificationTarget) {
|
||||
editingId = target.id;
|
||||
formOpen = true;
|
||||
form = {
|
||||
id: target.id,
|
||||
type: target.type,
|
||||
url: '',
|
||||
bot_id: target.config.bot_id || botOptions[0]?.id || '',
|
||||
destination_chat_id: target.config.destination_chat_id || '',
|
||||
enabled: target.enabled,
|
||||
events: [...target.events],
|
||||
delivery: target.delivery
|
||||
};
|
||||
}
|
||||
|
||||
function toggleFormEvent(event: ChatNotificationEvent) {
|
||||
form.events = form.events.includes(event)
|
||||
? form.events.filter((item) => item !== event)
|
||||
: [...form.events, event];
|
||||
}
|
||||
|
||||
async function saveTarget() {
|
||||
savingTarget = true;
|
||||
try {
|
||||
const originalId = editingId;
|
||||
const payload: any = {
|
||||
id: form.id.trim(),
|
||||
type: form.type,
|
||||
enabled: form.enabled,
|
||||
events: form.events,
|
||||
delivery: form.delivery
|
||||
};
|
||||
if (form.type === 'webhook') {
|
||||
if (!editingId || form.url.trim()) payload.config = { url: form.url.trim() };
|
||||
} else {
|
||||
payload.config = {
|
||||
bot_id: form.bot_id,
|
||||
destination_chat_id: form.destination_chat_id.trim()
|
||||
};
|
||||
}
|
||||
if (originalId) {
|
||||
await updateNotificationTarget(originalId, payload);
|
||||
} else {
|
||||
await createNotificationTarget(payload);
|
||||
}
|
||||
await loadNotificationTargets();
|
||||
formOpen = false;
|
||||
toast.success($t('settings.saved'));
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
} finally {
|
||||
savingTarget = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function patchTarget(target: NotificationTarget, patch: Partial<NotificationTarget>) {
|
||||
try {
|
||||
await updateNotificationTarget(target.id, patch as any);
|
||||
await loadNotificationTargets();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
async function removeTarget(target: NotificationTarget) {
|
||||
try {
|
||||
await deleteNotificationTarget(target.id);
|
||||
await loadNotificationTargets();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
async function makeDefault(target: NotificationTarget) {
|
||||
try {
|
||||
await setDefaultNotificationTarget(target.id);
|
||||
await loadNotificationTargets();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
async function sendTest(target: NotificationTarget) {
|
||||
try {
|
||||
await testNotificationTarget(target.id);
|
||||
toast.success($t('general.testSent'));
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : $t('general.notificationTargetSaveFailed'));
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
<div class="flex-1 min-h-0 overflow-y-auto scrollbar-hover pr-1.5 -mr-1.5">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-4">
|
||||
{$t('general.notifications')}
|
||||
</h2>
|
||||
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">
|
||||
{$t('general.browserNotifications')}
|
||||
</span>
|
||||
<ToggleSwitch value={$notificationsEnabled} onchange={() => toggleNotifications()} />
|
||||
</label>
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600 -mt-1">
|
||||
{$t('general.browserNotificationsDesc')}
|
||||
</p>
|
||||
|
||||
<label class="flex items-center justify-between cursor-pointer">
|
||||
<span class="text-xs text-gray-600 dark:text-gray-400">
|
||||
{$t('general.notificationSound')}
|
||||
</span>
|
||||
<ToggleSwitch value={$notificationSound} onchange={(v) => notificationSound.set(v)} />
|
||||
</label>
|
||||
|
||||
<div class="mt-3 flex items-center justify-between">
|
||||
<span class="text-xs font-medium text-gray-700 dark:text-gray-300">
|
||||
{$t('general.notificationTargets')}
|
||||
</span>
|
||||
<button
|
||||
class="flex items-center justify-center w-6 h-6 rounded-lg text-gray-400 hover:text-gray-700 dark:text-gray-600 dark:hover:text-gray-300 transition-colors duration-75"
|
||||
onclick={() => openNewTarget()}
|
||||
title={$t('general.addNotificationTarget')}
|
||||
aria-label={$t('general.addNotificationTarget')}
|
||||
>
|
||||
<Icon name="plus" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{#if loadingTargets}
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600">{$t('common.loading')}</p>
|
||||
{:else if !targets.length}
|
||||
<p class="text-[0.6875rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('general.noNotificationTargets')}
|
||||
</p>
|
||||
{:else}
|
||||
<div class="flex flex-col">
|
||||
{#each targets as target}
|
||||
{@const targetDestination =
|
||||
target.type === 'webhook' ? target.config.url_masked : target.config.destination_chat_id}
|
||||
{@const alertLabels = eventOptions
|
||||
.filter((event) => target.events.includes(event.event))
|
||||
.map((event) => event.label)
|
||||
.join(', ')}
|
||||
<div class="notification-target-row">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 min-w-0">
|
||||
<span class="truncate text-[0.71875rem] text-gray-700 dark:text-gray-300">
|
||||
{target.id}
|
||||
</span>
|
||||
<span class="shrink-0 text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{target.type === 'webhook' ? $t('general.webhook') : $t('general.bot')}
|
||||
</span>
|
||||
{#if target.is_default}
|
||||
<span class="shrink-0 text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('general.default')}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="truncate text-[0.625rem] text-gray-400 dark:text-gray-600 leading-tight">
|
||||
{targetDestination}
|
||||
</div>
|
||||
<div class="truncate text-[0.625rem] text-gray-400 dark:text-gray-600 leading-tight">
|
||||
{alertLabels || $t('general.noChatAlerts')}
|
||||
{#if target.events.length}
|
||||
· {target.delivery === 'away' ? $t('general.onlyWhenAway') : $t('general.always')}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => sendTest(target)}
|
||||
>
|
||||
{$t('general.sendTest')}
|
||||
</button>
|
||||
{#if !target.is_default}
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => makeDefault(target)}
|
||||
>
|
||||
{$t('general.makeDefault')}
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => openEditTarget(target)}
|
||||
>
|
||||
{$t('common.edit')}
|
||||
</button>
|
||||
<button
|
||||
class="text-[0.625rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => removeTarget(target)}
|
||||
>
|
||||
{$t('common.remove')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="w-9 shrink-0 flex justify-end">
|
||||
<ToggleSwitch
|
||||
value={target.enabled}
|
||||
onchange={(v) => patchTarget(target, { enabled: v })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if formOpen}
|
||||
<Modal onclose={() => (formOpen = false)} class="w-full max-w-md mx-4">
|
||||
<div class="p-4">
|
||||
<h2 class="text-sm font-medium text-gray-900 dark:text-white mb-3">
|
||||
{editingId ? $t('common.edit') : $t('general.addNotificationTarget')}
|
||||
</h2>
|
||||
|
||||
<div class="mb-2 flex gap-1">
|
||||
{#each targetTypes as type}
|
||||
<button
|
||||
class="h-7 rounded-md px-2 text-xs transition-colors
|
||||
{form.type === type
|
||||
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
|
||||
onclick={() => (form.type = type)}
|
||||
>
|
||||
{type === 'webhook' ? $t('general.webhook') : $t('general.bot')}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600">
|
||||
{$t('general.targetIdForNotify')}
|
||||
</label>
|
||||
<input
|
||||
bind:value={form.id}
|
||||
placeholder={$t('general.targetId')}
|
||||
autofocus
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
|
||||
{#if form.type === 'webhook'}
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('general.webhook')}
|
||||
</label>
|
||||
<input
|
||||
type="url"
|
||||
bind:value={form.url}
|
||||
placeholder={editingId ? $t('general.keepWebhookUrl') : 'https://hooks.slack.com/services/...'}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
{:else}
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('general.bot')}
|
||||
</label>
|
||||
<select
|
||||
bind:value={form.bot_id}
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 outline-none py-0.5 cursor-pointer"
|
||||
>
|
||||
{#each botOptions as bot}
|
||||
<option value={bot.id}>
|
||||
{bot.name} ({bot.platform}){bot.is_running ? '' : ' - stopped'}
|
||||
</option>
|
||||
{/each}
|
||||
</select>
|
||||
|
||||
<label class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-2">
|
||||
{$t('general.platformDestinationId')}
|
||||
</label>
|
||||
<input
|
||||
bind:value={form.destination_chat_id}
|
||||
placeholder={$t('general.platformDestinationId')}
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
class="block w-full bg-transparent text-[0.8125rem] text-gray-700 dark:text-gray-300 placeholder:text-gray-300 dark:placeholder:text-gray-700 outline-none py-0.5 font-mono"
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<label class="block text-[0.625rem] text-gray-400 dark:text-gray-600 mt-3 mb-1">
|
||||
{$t('general.automaticEvents')}
|
||||
</label>
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#each eventOptions as event}
|
||||
<button
|
||||
class="h-6 rounded-md px-2 text-[0.6875rem] transition-colors
|
||||
{form.events.includes(event.event)
|
||||
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
|
||||
onclick={() => toggleFormEvent(event.event)}
|
||||
>
|
||||
{event.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
{#if form.events.length}
|
||||
<label class="block text-[0.625rem] text-gray-400 dark:text-gray-600 mt-3 mb-1">
|
||||
{$t('general.automaticDelivery')}
|
||||
</label>
|
||||
<div class="flex gap-1">
|
||||
{#each ['away', 'always'] as mode}
|
||||
<button
|
||||
class="h-6 rounded-md px-2 text-[0.6875rem] transition-colors
|
||||
{form.delivery === mode
|
||||
? 'bg-gray-200/60 text-gray-900 dark:bg-white/10 dark:text-white'
|
||||
: 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-300'}"
|
||||
onclick={() => (form.delivery = mode as NotificationDelivery)}
|
||||
>
|
||||
{mode === 'away' ? $t('general.onlyWhenAway') : $t('general.always')}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<p class="text-[0.625rem] text-gray-400 dark:text-gray-600 mt-3">
|
||||
{$t('general.notifyToolAlwaysSends')}
|
||||
</p>
|
||||
|
||||
<div class="flex justify-end gap-3 mt-4">
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100"
|
||||
onclick={() => (formOpen = false)}
|
||||
>
|
||||
{$t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
class="text-[0.8125rem] text-gray-700 hover:text-gray-900 disabled:opacity-30 dark:text-gray-300 dark:hover:text-white transition-colors duration-100"
|
||||
onclick={saveTarget}
|
||||
disabled={savingTarget || (form.type === 'bot' && !botOptions.length)}
|
||||
>
|
||||
{savingTarget ? $t('settings.saving') : $t('settings.save')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
@reference "../../../app.css";
|
||||
|
||||
.notification-target-row {
|
||||
@apply flex items-center gap-3 px-1 py-1.5;
|
||||
border-bottom: 1px solid rgba(128, 128, 128, 0.04);
|
||||
}
|
||||
|
||||
.notification-target-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
</style>
|
||||
@@ -3,6 +3,7 @@
|
||||
import Icon from './Icon.svelte';
|
||||
import Modal from './Modal.svelte';
|
||||
import General from './Settings/General.svelte';
|
||||
import Notifications from './Settings/Notifications.svelte';
|
||||
import Appearance from './Settings/Appearance.svelte';
|
||||
import Memory from './Settings/Memory.svelte';
|
||||
import PWA from './Settings/PWA.svelte';
|
||||
@@ -25,6 +26,7 @@
|
||||
|
||||
type Tab =
|
||||
| 'general'
|
||||
| 'notifications'
|
||||
| 'appearance'
|
||||
| 'memory'
|
||||
| 'pwa'
|
||||
@@ -76,6 +78,7 @@
|
||||
const tabs: SettingsTab[] = [
|
||||
{ id: 'general', label: $t('settings.general'), icon: 'settings' },
|
||||
{ id: 'appearance', label: $t('settings.appearance'), icon: 'sun-light' },
|
||||
{ id: 'notifications', label: $t('general.notifications'), icon: 'chat-bubble' },
|
||||
{ id: 'keyboard', label: $t('settings.keyboard'), icon: 'terminal' },
|
||||
{ id: 'account', label: $t('settings.account'), icon: 'user' }
|
||||
];
|
||||
@@ -124,7 +127,7 @@
|
||||
|
||||
<Modal
|
||||
{onclose}
|
||||
class="w-full max-w-3xl mx-4 md:mx-0 flex flex-col md:flex-row max-h-[85vh] md:h-[35rem]"
|
||||
class="w-full max-w-3xl lg:max-w-4xl xl:max-w-5xl mx-4 md:mx-0 flex flex-col md:flex-row max-h-[85vh] lg:max-h-[90vh] md:h-[35rem] lg:h-[42rem] xl:h-[46rem]"
|
||||
>
|
||||
<nav
|
||||
class="shrink-0 min-w-0 md:min-h-0 overflow-x-auto md:overflow-x-hidden md:overflow-y-auto scrollbar-none border-b md:border-b-0 md:border-r border-gray-200 dark:border-white/6 md:w-[11.25rem]"
|
||||
@@ -178,6 +181,8 @@
|
||||
<div class="flex-1 overflow-y-auto scrollbar-none min-h-0 p-4 md:px-5">
|
||||
{#if activeTab === 'general'}
|
||||
<General />
|
||||
{:else if activeTab === 'notifications'}
|
||||
<Notifications />
|
||||
{:else if activeTab === 'appearance'}
|
||||
<Appearance />
|
||||
{:else if activeTab === 'memory'}
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
} from '$lib/stores/audio';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
import { TAB_DRAG_MIME } from '$lib/constants';
|
||||
|
||||
// Keep screen awake during voice mode conversations
|
||||
let voiceWakeLock: WakeLockSentinel | null = null;
|
||||
@@ -135,6 +136,12 @@
|
||||
>([]);
|
||||
let isDragging = $state(false);
|
||||
|
||||
function isTabDrag(e: DragEvent): boolean {
|
||||
return Boolean(
|
||||
e.dataTransfer?.types.includes(TAB_DRAG_MIME) || e.dataTransfer?.types.includes('text/tab-id')
|
||||
);
|
||||
}
|
||||
|
||||
async function processFiles(files: File[]) {
|
||||
for (const file of files) {
|
||||
const id = Math.random().toString(36).substring(7);
|
||||
@@ -161,6 +168,8 @@
|
||||
}
|
||||
|
||||
function handleDrop(e: DragEvent) {
|
||||
if (isTabDrag(e)) return;
|
||||
|
||||
e.preventDefault();
|
||||
isDragging = false;
|
||||
if (e.dataTransfer?.files) {
|
||||
@@ -962,6 +971,10 @@
|
||||
ondrop={handleDrop}
|
||||
onpaste={handlePaste}
|
||||
ondragover={(e) => {
|
||||
if (isTabDrag(e)) {
|
||||
isDragging = false;
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
isDragging = true;
|
||||
}}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const TAB_DRAG_MIME = 'application/x-cptr-tab';
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "Systembenachrichtigungen anzeigen, wenn eine Aufgabe abgeschlossen ist und der Tab nicht fokussiert ist.",
|
||||
"general.notificationSound": "Benachrichtigungston",
|
||||
"general.notificationPermissionDenied": "Browser-Benachrichtigungserlaubnis verweigert",
|
||||
"general.webhookUrl": "Webhook-URL",
|
||||
"general.webhookUrlSaved": "Webhook-URL gespeichert",
|
||||
"general.webhookUrlSaveFailed": "Webhook-URL konnte nicht gespeichert werden",
|
||||
"general.webhookUrlHint": "Unterstützt Slack, Discord, Teams und generische JSON-Webhooks.",
|
||||
"general.notificationTargets": "Benachrichtigungsziele",
|
||||
"general.addNotificationTarget": "Benachrichtigungsziel hinzufügen",
|
||||
"general.noNotificationTargets": "Noch keine Benachrichtigungsziele.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat beendet",
|
||||
"general.chatFailed": "Chat fehlgeschlagen",
|
||||
"general.automaticEvents": "Chat-Hinweise (optional)",
|
||||
"general.noChatAlerts": "Keine Chat-Hinweise",
|
||||
"general.automaticDelivery": "Chat-Hinweise senden",
|
||||
"general.onlyWhenAway": "Nur wenn ich abwesend bin",
|
||||
"general.always": "Immer",
|
||||
"general.sendTest": "Test senden",
|
||||
"general.makeDefault": "Als Standard festlegen",
|
||||
"general.platformDestinationId": "Plattform-Ziel-ID",
|
||||
"general.targetId": "Ziel-ID",
|
||||
"general.targetIdForNotify": "Ziel-ID",
|
||||
"general.notifyToolAlwaysSends": "Agenten können dieses Ziel auch aus einem Chat benachrichtigen.",
|
||||
"general.keepWebhookUrl": "Leer lassen, um die aktuelle URL zu behalten",
|
||||
"general.testSent": "Test gesendet",
|
||||
"general.notificationTargetsLoadFailed": "Benachrichtigungsziele konnten nicht geladen werden",
|
||||
"general.notificationTargetSaveFailed": "Benachrichtigungsziel konnte nicht gespeichert werden",
|
||||
"general.updates": "Aktualisierungen",
|
||||
"general.updateNotifications": "Update-Benachrichtigungen",
|
||||
"general.updateNotificationsDesc": "Eine Benachrichtigung anzeigen, wenn eine neue Version von Computer verfügbar ist.",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "Show OS-level notifications when a task completes and the tab is not focused.",
|
||||
"general.notificationSound": "Notification sound",
|
||||
"general.notificationPermissionDenied": "Browser notification permission denied",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URL saved",
|
||||
"general.webhookUrlSaveFailed": "Failed to save webhook URL",
|
||||
"general.webhookUrlHint": "Supports Slack, Discord, Teams, and generic JSON webhooks.",
|
||||
"general.notificationTargets": "Notification targets",
|
||||
"general.addNotificationTarget": "Add notification target",
|
||||
"general.noNotificationTargets": "No notification targets yet.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat finished",
|
||||
"general.chatFailed": "Chat failed",
|
||||
"general.automaticEvents": "Chat alerts (optional)",
|
||||
"general.noChatAlerts": "No chat alerts",
|
||||
"general.automaticDelivery": "Send chat alerts",
|
||||
"general.onlyWhenAway": "Only when I'm away",
|
||||
"general.always": "Always",
|
||||
"general.sendTest": "Send test",
|
||||
"general.makeDefault": "Make default",
|
||||
"general.platformDestinationId": "Platform destination ID",
|
||||
"general.targetId": "Target ID",
|
||||
"general.targetIdForNotify": "Target ID",
|
||||
"general.notifyToolAlwaysSends": "Agents can also notify this target from a chat.",
|
||||
"general.keepWebhookUrl": "Leave blank to keep current URL",
|
||||
"general.testSent": "Test sent",
|
||||
"general.notificationTargetsLoadFailed": "Failed to load notification targets",
|
||||
"general.notificationTargetSaveFailed": "Failed to save notification target",
|
||||
"general.updates": "Updates",
|
||||
"general.updateNotifications": "Update notifications",
|
||||
"general.updateNotificationsDesc": "Show a toast when a new version of Computer is available.",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "Mostrar notificaciones del sistema cuando una tarea se completa y la pestaña no está enfocada.",
|
||||
"general.notificationSound": "Sonido de notificación",
|
||||
"general.notificationPermissionDenied": "Permiso de notificación del navegador denegado",
|
||||
"general.webhookUrl": "URL del webhook",
|
||||
"general.webhookUrlSaved": "URL del webhook guardada",
|
||||
"general.webhookUrlSaveFailed": "Error al guardar URL del webhook",
|
||||
"general.webhookUrlHint": "Compatible con Slack, Discord, Teams y webhooks JSON genéricos.",
|
||||
"general.notificationTargets": "Destinos de notificación",
|
||||
"general.addNotificationTarget": "Agregar destino de notificación",
|
||||
"general.noNotificationTargets": "Aún no hay destinos de notificación.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat finalizado",
|
||||
"general.chatFailed": "Chat fallido",
|
||||
"general.automaticEvents": "Alertas de chat (opcional)",
|
||||
"general.noChatAlerts": "Sin alertas de chat",
|
||||
"general.automaticDelivery": "Enviar alertas de chat",
|
||||
"general.onlyWhenAway": "Solo cuando estoy ausente",
|
||||
"general.always": "Siempre",
|
||||
"general.sendTest": "Enviar prueba",
|
||||
"general.makeDefault": "Hacer predeterminado",
|
||||
"general.platformDestinationId": "ID de destino de la plataforma",
|
||||
"general.targetId": "ID del destino",
|
||||
"general.targetIdForNotify": "ID del destino",
|
||||
"general.notifyToolAlwaysSends": "Los agentes también pueden notificar a este destino desde un chat.",
|
||||
"general.keepWebhookUrl": "Deja en blanco para conservar la URL actual",
|
||||
"general.testSent": "Prueba enviada",
|
||||
"general.notificationTargetsLoadFailed": "Error al cargar destinos de notificación",
|
||||
"general.notificationTargetSaveFailed": "Error al guardar destino de notificación",
|
||||
"general.updates": "Actualizaciones",
|
||||
"general.updateNotifications": "Notificaciones de actualización",
|
||||
"general.updateNotificationsDesc": "Mostrar un aviso cuando hay una nueva versión de Computer disponible.",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "Afficher les notifications du système lorsqu'une tâche se termine et que l'onglet n'est pas actif.",
|
||||
"general.notificationSound": "Son de notification",
|
||||
"general.notificationPermissionDenied": "Permission de notification du navigateur refusée",
|
||||
"general.webhookUrl": "URL du webhook",
|
||||
"general.webhookUrlSaved": "URL du webhook enregistrée",
|
||||
"general.webhookUrlSaveFailed": "Échec de l'enregistrement de l'URL du webhook",
|
||||
"general.webhookUrlHint": "Prend en charge Slack, Discord, Teams et les webhooks JSON génériques.",
|
||||
"general.notificationTargets": "Cibles de notification",
|
||||
"general.addNotificationTarget": "Ajouter une cible de notification",
|
||||
"general.noNotificationTargets": "Aucune cible de notification pour l’instant.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat terminé",
|
||||
"general.chatFailed": "Échec du chat",
|
||||
"general.automaticEvents": "Alertes de chat (facultatif)",
|
||||
"general.noChatAlerts": "Aucune alerte de chat",
|
||||
"general.automaticDelivery": "Envoyer les alertes de chat",
|
||||
"general.onlyWhenAway": "Seulement quand je suis absent",
|
||||
"general.always": "Toujours",
|
||||
"general.sendTest": "Envoyer un test",
|
||||
"general.makeDefault": "Définir par défaut",
|
||||
"general.platformDestinationId": "ID de destination de la plateforme",
|
||||
"general.targetId": "ID de la cible",
|
||||
"general.targetIdForNotify": "ID de la cible",
|
||||
"general.notifyToolAlwaysSends": "Les agents peuvent aussi notifier cette cible depuis un chat.",
|
||||
"general.keepWebhookUrl": "Laisser vide pour conserver l’URL actuelle",
|
||||
"general.testSent": "Test envoyé",
|
||||
"general.notificationTargetsLoadFailed": "Échec du chargement des cibles de notification",
|
||||
"general.notificationTargetSaveFailed": "Échec de l’enregistrement de la cible de notification",
|
||||
"general.updates": "Mises à jour",
|
||||
"general.updateNotifications": "Notifications de mise à jour",
|
||||
"general.updateNotificationsDesc": "Afficher une notification lorsqu'une nouvelle version de Computer est disponible.",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "タスク完了時にタブがフォーカスされていない場合、OS通知を表示します。",
|
||||
"general.notificationSound": "通知音",
|
||||
"general.notificationPermissionDenied": "ブラウザ通知の許可が拒否されました",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URLを保存しました",
|
||||
"general.webhookUrlSaveFailed": "Webhook URLの保存に失敗しました",
|
||||
"general.webhookUrlHint": "Slack、Discord、Teams、汎用JSONウェブフックに対応。",
|
||||
"general.notificationTargets": "通知先",
|
||||
"general.addNotificationTarget": "通知先を追加",
|
||||
"general.noNotificationTargets": "通知先はまだありません。",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "チャット完了",
|
||||
"general.chatFailed": "チャット失敗",
|
||||
"general.automaticEvents": "チャット通知(任意)",
|
||||
"general.noChatAlerts": "チャット通知なし",
|
||||
"general.automaticDelivery": "チャット通知を送信",
|
||||
"general.onlyWhenAway": "離席中のみ",
|
||||
"general.always": "常に",
|
||||
"general.sendTest": "テスト送信",
|
||||
"general.makeDefault": "既定に設定",
|
||||
"general.platformDestinationId": "プラットフォーム送信先ID",
|
||||
"general.targetId": "通知先ID",
|
||||
"general.targetIdForNotify": "通知先ID",
|
||||
"general.notifyToolAlwaysSends": "エージェントはチャットからこの通知先へ通知することもできます。",
|
||||
"general.keepWebhookUrl": "現在のURLを保持する場合は空欄",
|
||||
"general.testSent": "テストを送信しました",
|
||||
"general.notificationTargetsLoadFailed": "通知先の読み込みに失敗しました",
|
||||
"general.notificationTargetSaveFailed": "通知先の保存に失敗しました",
|
||||
"general.updates": "アップデート",
|
||||
"general.updateNotifications": "アップデート通知",
|
||||
"general.updateNotificationsDesc": "Computerの新しいバージョンが利用可能な場合にトーストを表示します。",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "작업이 완료되고 탭이 포커스되지 않았을 때 OS 알림을 표시합니다.",
|
||||
"general.notificationSound": "알림 소리",
|
||||
"general.notificationPermissionDenied": "브라우저 알림 권한이 거부되었습니다",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URL이 저장되었습니다",
|
||||
"general.webhookUrlSaveFailed": "Webhook URL 저장에 실패했습니다",
|
||||
"general.webhookUrlHint": "Slack, Discord, Teams 및 일반 JSON 웹훅을 지원합니다.",
|
||||
"general.notificationTargets": "알림 대상",
|
||||
"general.addNotificationTarget": "알림 대상 추가",
|
||||
"general.noNotificationTargets": "아직 알림 대상이 없습니다.",
|
||||
"general.webhook": "웹훅",
|
||||
"general.bot": "봇",
|
||||
"general.chatFinished": "채팅 완료",
|
||||
"general.chatFailed": "채팅 실패",
|
||||
"general.automaticEvents": "채팅 알림 (선택 사항)",
|
||||
"general.noChatAlerts": "채팅 알림 없음",
|
||||
"general.automaticDelivery": "채팅 알림 보내기",
|
||||
"general.onlyWhenAway": "자리 비움일 때만",
|
||||
"general.always": "항상",
|
||||
"general.sendTest": "테스트 보내기",
|
||||
"general.makeDefault": "기본값으로 설정",
|
||||
"general.platformDestinationId": "플랫폼 대상 ID",
|
||||
"general.targetId": "대상 ID",
|
||||
"general.targetIdForNotify": "대상 ID",
|
||||
"general.notifyToolAlwaysSends": "에이전트가 채팅에서 이 대상으로 알림을 보낼 수도 있습니다.",
|
||||
"general.keepWebhookUrl": "현재 URL을 유지하려면 비워 두세요",
|
||||
"general.testSent": "테스트를 보냈습니다",
|
||||
"general.notificationTargetsLoadFailed": "알림 대상을 불러오지 못했습니다",
|
||||
"general.notificationTargetSaveFailed": "알림 대상을 저장하지 못했습니다",
|
||||
"general.updates": "업데이트",
|
||||
"general.updateNotifications": "업데이트 알림",
|
||||
"general.updateNotificationsDesc": "Computer의 새 버전이 사용 가능할 때 알림을 표시합니다.",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "Mostrar notificações do sistema quando uma tarefa é concluída e a aba não está em foco.",
|
||||
"general.notificationSound": "Som de notificação",
|
||||
"general.notificationPermissionDenied": "Permissão de notificação do navegador negada",
|
||||
"general.webhookUrl": "URL do webhook",
|
||||
"general.webhookUrlSaved": "URL do webhook salva",
|
||||
"general.webhookUrlSaveFailed": "Falha ao salvar URL do webhook",
|
||||
"general.webhookUrlHint": "Suporta Slack, Discord, Teams e webhooks JSON genéricos.",
|
||||
"general.notificationTargets": "Destinos de notificação",
|
||||
"general.addNotificationTarget": "Adicionar destino de notificação",
|
||||
"general.noNotificationTargets": "Ainda não há destinos de notificação.",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "Bot",
|
||||
"general.chatFinished": "Chat concluído",
|
||||
"general.chatFailed": "Chat falhou",
|
||||
"general.automaticEvents": "Alertas de chat (opcional)",
|
||||
"general.noChatAlerts": "Sem alertas de chat",
|
||||
"general.automaticDelivery": "Enviar alertas de chat",
|
||||
"general.onlyWhenAway": "Só quando eu estiver ausente",
|
||||
"general.always": "Sempre",
|
||||
"general.sendTest": "Enviar teste",
|
||||
"general.makeDefault": "Definir como padrão",
|
||||
"general.platformDestinationId": "ID do destino na plataforma",
|
||||
"general.targetId": "ID do destino",
|
||||
"general.targetIdForNotify": "ID do destino",
|
||||
"general.notifyToolAlwaysSends": "Agentes também podem notificar este destino a partir de um chat.",
|
||||
"general.keepWebhookUrl": "Deixe em branco para manter a URL atual",
|
||||
"general.testSent": "Teste enviado",
|
||||
"general.notificationTargetsLoadFailed": "Falha ao carregar destinos de notificação",
|
||||
"general.notificationTargetSaveFailed": "Falha ao salvar destino de notificação",
|
||||
"general.updates": "Atualizações",
|
||||
"general.updateNotifications": "Notificações de atualização",
|
||||
"general.updateNotificationsDesc": "Mostrar um aviso quando uma nova versão do Computer estiver disponível.",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "Показывать уведомления ОС при завершении задачи, когда вкладка не в фокусе.",
|
||||
"general.notificationSound": "Звук уведомления",
|
||||
"general.notificationPermissionDenied": "Разрешение на уведомления браузера отклонено",
|
||||
"general.webhookUrl": "URL вебхука",
|
||||
"general.webhookUrlSaved": "URL вебхука сохранён",
|
||||
"general.webhookUrlSaveFailed": "Не удалось сохранить URL вебхука",
|
||||
"general.webhookUrlHint": "Поддерживает Slack, Discord, Teams и универсальные JSON-вебхуки.",
|
||||
"general.notificationTargets": "Цели уведомлений",
|
||||
"general.addNotificationTarget": "Добавить цель уведомления",
|
||||
"general.noNotificationTargets": "Целей уведомлений пока нет.",
|
||||
"general.webhook": "Вебхук",
|
||||
"general.bot": "Бот",
|
||||
"general.chatFinished": "Чат завершён",
|
||||
"general.chatFailed": "Ошибка чата",
|
||||
"general.automaticEvents": "Оповещения чата (необязательно)",
|
||||
"general.noChatAlerts": "Нет оповещений чата",
|
||||
"general.automaticDelivery": "Отправлять оповещения чата",
|
||||
"general.onlyWhenAway": "Только когда меня нет",
|
||||
"general.always": "Всегда",
|
||||
"general.sendTest": "Отправить тест",
|
||||
"general.makeDefault": "Сделать по умолчанию",
|
||||
"general.platformDestinationId": "ID назначения платформы",
|
||||
"general.targetId": "ID цели",
|
||||
"general.targetIdForNotify": "ID цели",
|
||||
"general.notifyToolAlwaysSends": "Агенты также могут уведомлять эту цель из чата.",
|
||||
"general.keepWebhookUrl": "Оставьте пустым, чтобы сохранить текущий URL",
|
||||
"general.testSent": "Тест отправлен",
|
||||
"general.notificationTargetsLoadFailed": "Не удалось загрузить цели уведомлений",
|
||||
"general.notificationTargetSaveFailed": "Не удалось сохранить цель уведомлений",
|
||||
"general.updates": "Обновления",
|
||||
"general.updateNotifications": "Уведомления об обновлениях",
|
||||
"general.updateNotificationsDesc": "Показывать уведомление, когда доступна новая версия Computer.",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "当任务完成且标签页未聚焦时显示系统通知。",
|
||||
"general.notificationSound": "通知声音",
|
||||
"general.notificationPermissionDenied": "浏览器通知权限被拒绝",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URL 已保存",
|
||||
"general.webhookUrlSaveFailed": "保存 Webhook URL 失败",
|
||||
"general.webhookUrlHint": "支持 Slack、Discord、Teams 和通用 JSON Webhook。",
|
||||
"general.notificationTargets": "通知目标",
|
||||
"general.addNotificationTarget": "添加通知目标",
|
||||
"general.noNotificationTargets": "还没有通知目标。",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "机器人",
|
||||
"general.chatFinished": "聊天已完成",
|
||||
"general.chatFailed": "聊天失败",
|
||||
"general.automaticEvents": "聊天提醒(可选)",
|
||||
"general.noChatAlerts": "没有聊天提醒",
|
||||
"general.automaticDelivery": "发送聊天提醒",
|
||||
"general.onlyWhenAway": "仅在我离开时",
|
||||
"general.always": "始终",
|
||||
"general.sendTest": "发送测试",
|
||||
"general.makeDefault": "设为默认",
|
||||
"general.platformDestinationId": "平台目标 ID",
|
||||
"general.targetId": "目标 ID",
|
||||
"general.targetIdForNotify": "目标 ID",
|
||||
"general.notifyToolAlwaysSends": "代理也可以从聊天中通知此目标。",
|
||||
"general.keepWebhookUrl": "留空以保留当前 URL",
|
||||
"general.testSent": "测试已发送",
|
||||
"general.notificationTargetsLoadFailed": "无法加载通知目标",
|
||||
"general.notificationTargetSaveFailed": "无法保存通知目标",
|
||||
"general.updates": "更新",
|
||||
"general.updateNotifications": "更新通知",
|
||||
"general.updateNotificationsDesc": "当 Computer 有新版本可用时显示提示。",
|
||||
|
||||
@@ -399,10 +399,28 @@
|
||||
"general.browserNotificationsDesc": "當任務完成且分頁未聚焦時顯示系統通知。",
|
||||
"general.notificationSound": "通知聲音",
|
||||
"general.notificationPermissionDenied": "瀏覽器通知權限被拒絕",
|
||||
"general.webhookUrl": "Webhook URL",
|
||||
"general.webhookUrlSaved": "Webhook URL 已儲存",
|
||||
"general.webhookUrlSaveFailed": "儲存 Webhook URL 失敗",
|
||||
"general.webhookUrlHint": "支援 Slack、Discord、Teams 和通用 JSON Webhook。",
|
||||
"general.notificationTargets": "通知目標",
|
||||
"general.addNotificationTarget": "新增通知目標",
|
||||
"general.noNotificationTargets": "尚無通知目標。",
|
||||
"general.webhook": "Webhook",
|
||||
"general.bot": "機器人",
|
||||
"general.chatFinished": "聊天已完成",
|
||||
"general.chatFailed": "聊天失敗",
|
||||
"general.automaticEvents": "聊天提醒(選用)",
|
||||
"general.noChatAlerts": "沒有聊天提醒",
|
||||
"general.automaticDelivery": "傳送聊天提醒",
|
||||
"general.onlyWhenAway": "僅在我離開時",
|
||||
"general.always": "一律",
|
||||
"general.sendTest": "傳送測試",
|
||||
"general.makeDefault": "設為預設",
|
||||
"general.platformDestinationId": "平台目標 ID",
|
||||
"general.targetId": "目標 ID",
|
||||
"general.targetIdForNotify": "目標 ID",
|
||||
"general.notifyToolAlwaysSends": "代理也可以從聊天中通知此目標。",
|
||||
"general.keepWebhookUrl": "留空以保留目前 URL",
|
||||
"general.testSent": "測試已傳送",
|
||||
"general.notificationTargetsLoadFailed": "無法載入通知目標",
|
||||
"general.notificationTargetSaveFailed": "無法儲存通知目標",
|
||||
"general.updates": "更新",
|
||||
"general.updateNotifications": "更新通知",
|
||||
"general.updateNotificationsDesc": "當 Computer 有新版本可用時顯示提示。",
|
||||
|
||||
@@ -214,50 +214,6 @@ export const splitTab = derived(currentWorkspace, ($ws) => {
|
||||
return secondGroup?.tabs.find((t) => t.id === secondGroup.activeTabId) ?? null;
|
||||
});
|
||||
|
||||
/** @deprecated Use splitCurrentTab or openInGroup */
|
||||
export function openTabInSplit(tabId: string, direction?: SplitDirection): void {
|
||||
const ws = get(currentWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
// If already split, move tab to the other group
|
||||
if (ws.groups.length > 1) {
|
||||
const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId);
|
||||
if (otherGroup) {
|
||||
moveTabToGroup(tabId, ws.activeGroupId, otherGroup.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, create a new group with this tab
|
||||
const dir = direction ?? ws.splitDirection ?? 'horizontal';
|
||||
|
||||
// Find the tab in any group
|
||||
let sourceTab: Tab | undefined;
|
||||
for (const g of ws.groups) {
|
||||
sourceTab = g.tabs.find((t) => t.id === tabId);
|
||||
if (sourceTab) break;
|
||||
}
|
||||
if (!sourceTab) return;
|
||||
|
||||
const newTab: Tab = { ...sourceTab, id: nextId(), permanent: false };
|
||||
const newGroup: EditorGroup = {
|
||||
id: nextId(),
|
||||
tabs: [newTab],
|
||||
activeTabId: newTab.id
|
||||
};
|
||||
|
||||
currentWorkspace.update((ws) => {
|
||||
if (!ws) return ws;
|
||||
return {
|
||||
...ws,
|
||||
groups: [...ws.groups, newGroup],
|
||||
activeGroupId: newGroup.id,
|
||||
splitDirection: dir,
|
||||
splitRatio: ws.splitRatio ?? 0.5
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** @deprecated Use closeGroup */
|
||||
export function closeSplitPane(): void {
|
||||
const ws = get(currentWorkspace);
|
||||
@@ -1088,23 +1044,33 @@ export function closeGroup(groupId: string): void {
|
||||
currentWorkspace.update((ws) => {
|
||||
if (!ws) return ws;
|
||||
|
||||
// Clean up terminal sessions in this group
|
||||
const group = ws.groups.find((g) => g.id === groupId);
|
||||
if (group) {
|
||||
group.tabs.forEach((t) => {
|
||||
if (t.type === 'terminal' && t.sessionId) deleteSession(t.sessionId);
|
||||
});
|
||||
}
|
||||
const closingGroup = ws.groups.find((g) => g.id === groupId);
|
||||
const remainingGroups = ws.groups.filter((g) => g.id !== groupId);
|
||||
const targetGroup =
|
||||
remainingGroups.find((g) => g.id === ws.activeGroupId) ?? remainingGroups[0];
|
||||
if (!closingGroup || !targetGroup) return ws;
|
||||
|
||||
const existingTabIds = new Set(targetGroup.tabs.map((t) => t.id));
|
||||
const movedTabs = closingGroup.tabs.filter((t) => !existingTabIds.has(t.id));
|
||||
const tabs = [...targetGroup.tabs, ...movedTabs];
|
||||
const activeTabId =
|
||||
ws.activeGroupId === closingGroup.id && tabs.some((t) => t.id === closingGroup.activeTabId)
|
||||
? closingGroup.activeTabId
|
||||
: targetGroup.activeTabId;
|
||||
const newGroups = remainingGroups.map((g) =>
|
||||
g.id === targetGroup.id
|
||||
? {
|
||||
...g,
|
||||
tabs,
|
||||
activeTabId: tabs.some((t) => t.id === activeTabId) ? activeTabId : (tabs[0]?.id ?? '')
|
||||
}
|
||||
: g
|
||||
);
|
||||
|
||||
let newGroups = ws.groups.filter((g) => g.id !== groupId);
|
||||
if (newGroups.length === 0) {
|
||||
newGroups = [createDefaultGroup()];
|
||||
}
|
||||
const activeGroupStillExists = newGroups.some((g) => g.id === ws.activeGroupId);
|
||||
return {
|
||||
...ws,
|
||||
groups: newGroups,
|
||||
activeGroupId: activeGroupStillExists ? ws.activeGroupId : newGroups[0].id
|
||||
activeGroupId: targetGroup.id
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1134,11 +1100,46 @@ export function moveTabToGroup(tabId: string, fromGroupId: string, toGroupId: st
|
||||
newGroups = newGroups.filter((g) => g.tabs.length > 0);
|
||||
if (newGroups.length === 0) newGroups = [createDefaultGroup()];
|
||||
|
||||
const activeGroupStillExists = newGroups.some((g) => g.id === ws.activeGroupId);
|
||||
const targetGroupStillExists = newGroups.some((g) => g.id === toGroupId);
|
||||
return {
|
||||
...ws,
|
||||
groups: newGroups,
|
||||
activeGroupId: activeGroupStillExists ? ws.activeGroupId : newGroups[0].id
|
||||
activeGroupId: targetGroupStillExists ? toGroupId : newGroups[0].id
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function moveTabToNewSplit(
|
||||
tabId: string,
|
||||
fromGroupId: string,
|
||||
direction: SplitDirection,
|
||||
placement: 'before' | 'after' = 'after'
|
||||
): void {
|
||||
currentWorkspace.update((ws) => {
|
||||
if (!ws || ws.groups.length > 1) return ws;
|
||||
const fromGroup = ws.groups.find((g) => g.id === fromGroupId);
|
||||
if (!fromGroup) return ws;
|
||||
const tab = fromGroup.tabs.find((t) => t.id === tabId);
|
||||
if (!tab || tab.permanent) return ws;
|
||||
|
||||
const newGroup: EditorGroup = {
|
||||
id: nextId(),
|
||||
tabs: [tab],
|
||||
activeTabId: tab.id
|
||||
};
|
||||
let groups = ws.groups.map((g) => {
|
||||
if (g.id !== fromGroupId) return g;
|
||||
const tabs = g.tabs.filter((t) => t.id !== tabId);
|
||||
return { ...g, tabs, activeTabId: tabs[0]?.id ?? '' };
|
||||
});
|
||||
groups = groups.filter((g) => g.tabs.length > 0);
|
||||
|
||||
return {
|
||||
...ws,
|
||||
groups: placement === 'before' ? [newGroup, ...groups] : [...groups, newGroup],
|
||||
activeGroupId: newGroup.id,
|
||||
splitDirection: direction,
|
||||
splitRatio: ws.splitRatio ?? 0.5
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
gitReviewOpen,
|
||||
setActiveGroup,
|
||||
setSplitRatio,
|
||||
openTabInSplit,
|
||||
setSplitDirection,
|
||||
moveTabToNewSplit,
|
||||
openChatTab,
|
||||
openFileTab,
|
||||
openTerminalTab,
|
||||
@@ -20,7 +19,7 @@
|
||||
showSearch,
|
||||
pwaPreferences
|
||||
} from '$lib/stores';
|
||||
import type { Tab, EditorGroup, WorkspaceState } from '$lib/stores';
|
||||
import type { Tab, EditorGroup, SplitDirection, WorkspaceState } from '$lib/stores';
|
||||
import { t } from '$lib/i18n';
|
||||
import { get } from 'svelte/store';
|
||||
import { getWelcome, getWorkspaceState } from '$lib/apis/state';
|
||||
@@ -40,6 +39,7 @@
|
||||
import Icon from '$lib/components/Icon.svelte';
|
||||
import WorkspacePicker from '$lib/components/WorkspacePicker.svelte';
|
||||
import Spinner from '$lib/components/common/Spinner.svelte';
|
||||
import { TAB_DRAG_MIME } from '$lib/constants';
|
||||
import { isSupportedWorkspacePath } from '$lib/utils/paths';
|
||||
|
||||
let showPicker = $state(false);
|
||||
@@ -639,27 +639,78 @@
|
||||
|
||||
// ── Drag-to-split ─────────────────────────────────────────────
|
||||
|
||||
let dragOverZone = $state<'right' | 'bottom' | null>(null);
|
||||
const SPLIT_EDGE_FRACTION = 0.3;
|
||||
|
||||
type SplitDropZone = 'left' | 'right' | 'top' | 'bottom';
|
||||
type TabDragPayload = { tabId: string; groupId: string };
|
||||
|
||||
let dragOverZone = $state<SplitDropZone | null>(null);
|
||||
|
||||
function hasTabDrag(dataTransfer: DataTransfer): boolean {
|
||||
return dataTransfer.types.includes(TAB_DRAG_MIME) || dataTransfer.types.includes('text/tab-id');
|
||||
}
|
||||
|
||||
function readTabDragPayload(dataTransfer: DataTransfer): TabDragPayload | null {
|
||||
const raw = dataTransfer.getData(TAB_DRAG_MIME);
|
||||
if (raw) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Partial<TabDragPayload>;
|
||||
if (typeof parsed.tabId === 'string' && typeof parsed.groupId === 'string') {
|
||||
return { tabId: parsed.tabId, groupId: parsed.groupId };
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the legacy payload below.
|
||||
}
|
||||
}
|
||||
|
||||
const tabId = dataTransfer.getData('text/tab-id');
|
||||
const groupId = dataTransfer.getData('text/group-id');
|
||||
return tabId && groupId ? { tabId, groupId } : null;
|
||||
}
|
||||
|
||||
function getSplitDropZone(e: DragEvent): SplitDropZone | null {
|
||||
if (!containerEl || !isWideScreen || hasSplit || !e.dataTransfer) return null;
|
||||
if (e.dataTransfer.types.includes('Files') || !hasTabDrag(e.dataTransfer)) return null;
|
||||
|
||||
const rect = containerEl.getBoundingClientRect();
|
||||
if (
|
||||
e.clientX < rect.left ||
|
||||
e.clientX > rect.right ||
|
||||
e.clientY < rect.top ||
|
||||
e.clientY > rect.bottom
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const horizontalBand = rect.width * SPLIT_EDGE_FRACTION;
|
||||
const verticalBand = rect.height * SPLIT_EDGE_FRACTION;
|
||||
const leftDistance = e.clientX - rect.left;
|
||||
const rightDistance = rect.right - e.clientX;
|
||||
const topDistance = e.clientY - rect.top;
|
||||
const bottomDistance = rect.bottom - e.clientY;
|
||||
const candidates: { zone: SplitDropZone; distance: number }[] = [];
|
||||
|
||||
if (leftDistance <= horizontalBand) candidates.push({ zone: 'left', distance: leftDistance });
|
||||
if (rightDistance <= horizontalBand)
|
||||
candidates.push({ zone: 'right', distance: rightDistance });
|
||||
if (topDistance <= verticalBand) candidates.push({ zone: 'top', distance: topDistance });
|
||||
if (bottomDistance <= verticalBand)
|
||||
candidates.push({ zone: 'bottom', distance: bottomDistance });
|
||||
|
||||
candidates.sort((a, b) => a.distance - b.distance);
|
||||
return candidates[0]?.zone ?? null;
|
||||
}
|
||||
|
||||
function handleContainerDragOver(e: DragEvent) {
|
||||
if (!containerEl || !isWideScreen) return;
|
||||
// Only respond to tab drags, not file uploads
|
||||
if (!e.dataTransfer?.types.includes('text/tab-id')) return;
|
||||
// Only show drop zones when not already split
|
||||
if (hasSplit) return;
|
||||
const zone = getSplitDropZone(e);
|
||||
if (!zone) {
|
||||
dragOverZone = null;
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
const rect = containerEl.getBoundingClientRect();
|
||||
const xRatio = (e.clientX - rect.left) / rect.width;
|
||||
const yRatio = (e.clientY - rect.top) / rect.height;
|
||||
|
||||
if (xRatio > 0.75) {
|
||||
dragOverZone = 'right';
|
||||
} else if (yRatio > 0.75) {
|
||||
dragOverZone = 'bottom';
|
||||
} else {
|
||||
dragOverZone = null;
|
||||
}
|
||||
e.dataTransfer!.dropEffect = 'move';
|
||||
dragOverZone = zone;
|
||||
}
|
||||
|
||||
function handleContainerDragLeave(e: DragEvent) {
|
||||
@@ -670,36 +721,24 @@
|
||||
}
|
||||
|
||||
function handleContainerDrop(e: DragEvent) {
|
||||
if (!dragOverZone || !e.dataTransfer) {
|
||||
dragOverZone = null;
|
||||
return;
|
||||
}
|
||||
// Don't intercept file uploads
|
||||
if (e.dataTransfer.types.includes('Files')) {
|
||||
const zone = dragOverZone ?? getSplitDropZone(e);
|
||||
|
||||
if (!zone || !e.dataTransfer) {
|
||||
dragOverZone = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const tabId = e.dataTransfer.getData('text/tab-id');
|
||||
const fromGroupId = e.dataTransfer.getData('text/group-id');
|
||||
if (!tabId || !fromGroupId) {
|
||||
const payload = readTabDragPayload(e.dataTransfer);
|
||||
if (!payload) {
|
||||
dragOverZone = null;
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
const direction = dragOverZone === 'right' ? 'horizontal' : 'vertical';
|
||||
setSplitDirection(direction as any);
|
||||
|
||||
// Move the dragged tab into a new split pane
|
||||
const ws = $currentWorkspace;
|
||||
if (ws) {
|
||||
const sourceGroup = ws.groups.find((g) => g.id === fromGroupId);
|
||||
const tab = sourceGroup?.tabs.find((t) => t.id === tabId);
|
||||
if (tab) {
|
||||
openTabInSplit(tabId, direction as any);
|
||||
}
|
||||
}
|
||||
const direction: SplitDirection =
|
||||
zone === 'left' || zone === 'right' ? 'horizontal' : 'vertical';
|
||||
const placement = zone === 'left' || zone === 'top' ? 'before' : 'after';
|
||||
moveTabToNewSplit(payload.tabId, payload.groupId, direction, placement);
|
||||
dragOverZone = null;
|
||||
}
|
||||
</script>
|
||||
@@ -883,6 +922,7 @@
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="split-pane"
|
||||
class:split-pane-single={!hasSplit}
|
||||
style={hasSplit
|
||||
? splitDirection === 'horizontal'
|
||||
? `width: ${i === 0 ? splitRatio * 100 : (1 - splitRatio) * 100}%;`
|
||||
@@ -943,9 +983,15 @@
|
||||
{/each}
|
||||
|
||||
<!-- Drop zone indicators for drag-to-split -->
|
||||
{#if dragOverZone === 'left'}
|
||||
<div class="split-drop-zone split-drop-left"></div>
|
||||
{/if}
|
||||
{#if dragOverZone === 'right'}
|
||||
<div class="split-drop-zone split-drop-right"></div>
|
||||
{/if}
|
||||
{#if dragOverZone === 'top'}
|
||||
<div class="split-drop-zone split-drop-top"></div>
|
||||
{/if}
|
||||
{#if dragOverZone === 'bottom'}
|
||||
<div class="split-drop-zone split-drop-bottom"></div>
|
||||
{/if}
|
||||
@@ -1003,8 +1049,8 @@
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* Single pane takes all space */
|
||||
.split-pane:only-child {
|
||||
/* Single pane takes all space even while preview overlays are mounted. */
|
||||
.split-pane-single {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
@@ -1097,24 +1143,43 @@
|
||||
.split-drop-zone {
|
||||
position: absolute;
|
||||
z-index: 15;
|
||||
background: oklch(0.65 0.15 250 / 0.08);
|
||||
border: 0.125rem dashed oklch(0.65 0.15 250 / 0.3);
|
||||
border-radius: 0.5rem;
|
||||
display: block;
|
||||
flex: none;
|
||||
contain: layout paint;
|
||||
pointer-events: none;
|
||||
--split-tabbar-height: 2.25rem;
|
||||
background: color-mix(in oklab, var(--app-fg) 6%, transparent);
|
||||
box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--app-fg) 16%, transparent);
|
||||
}
|
||||
|
||||
.split-drop-left,
|
||||
.split-drop-right {
|
||||
top: var(--split-tabbar-height);
|
||||
bottom: 0;
|
||||
width: 50%;
|
||||
}
|
||||
|
||||
.split-drop-left {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.split-drop-right {
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
bottom: 0.5rem;
|
||||
width: 45%;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.split-drop-top,
|
||||
.split-drop-bottom {
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: calc((100% - var(--split-tabbar-height)) / 2);
|
||||
}
|
||||
|
||||
.split-drop-top {
|
||||
top: var(--split-tabbar-height);
|
||||
}
|
||||
|
||||
.split-drop-bottom {
|
||||
left: 0.5rem;
|
||||
right: 0.5rem;
|
||||
bottom: 0.5rem;
|
||||
height: 45%;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
/* ── Persisted file editor tabs ────────────────────── */
|
||||
|
||||
@@ -13,6 +13,7 @@ from cptr.routers.files import router as files_router
|
||||
from cptr.routers.git import router as git_router
|
||||
from cptr.routers.images import router as images_router
|
||||
from cptr.routers.memory import router as memory_router
|
||||
from cptr.routers.notifications import router as notifications_router
|
||||
from cptr.routers.proxy import router as proxy_router
|
||||
from cptr.routers.search import router as search_router
|
||||
from cptr.routers.skills import router as skills_router
|
||||
@@ -34,6 +35,7 @@ __all__ = [
|
||||
"git_router",
|
||||
"images_router",
|
||||
"memory_router",
|
||||
"notifications_router",
|
||||
"proxy_router",
|
||||
"search_router",
|
||||
"skills_router",
|
||||
|
||||
@@ -105,7 +105,7 @@ async def create_bot(request: Request, body: BotCreate):
|
||||
from cptr.utils.config import _get_jwt_secret
|
||||
from cptr.utils.crypto import encrypt_key
|
||||
|
||||
if body.platform not in ("telegram", "discord"):
|
||||
if body.platform not in ("telegram", "discord", "slack", "whatsapp", "signal"):
|
||||
raise HTTPException(400, f"Unsupported platform: {body.platform}")
|
||||
|
||||
now = int(time.time_ns())
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""User notification target API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from cptr.utils.notifications import (
|
||||
NotificationError,
|
||||
create_target,
|
||||
delete_target,
|
||||
get_notification_event_catalog,
|
||||
get_bot_options,
|
||||
list_targets,
|
||||
set_default_target,
|
||||
test_target,
|
||||
update_target,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/notifications", tags=["notifications"])
|
||||
|
||||
|
||||
class TargetPayload(BaseModel):
|
||||
id: str | None = None
|
||||
type: str | None = None
|
||||
enabled: bool | None = None
|
||||
events: list[str] | None = None
|
||||
delivery: str | None = None
|
||||
config: dict | None = None
|
||||
|
||||
|
||||
def _user_id(request: Request) -> str:
|
||||
auth = getattr(request.state, "auth", None)
|
||||
if not auth or not auth.user_id:
|
||||
raise HTTPException(401, "authentication required")
|
||||
return auth.user_id
|
||||
|
||||
|
||||
def _payload(body: TargetPayload) -> dict:
|
||||
if hasattr(body, "model_dump"):
|
||||
return body.model_dump(exclude_unset=True)
|
||||
return body.dict(exclude_unset=True)
|
||||
|
||||
|
||||
def _error(exc: NotificationError) -> HTTPException:
|
||||
message = str(exc)
|
||||
status = 404 if "not found" in message else 400
|
||||
return HTTPException(status, message)
|
||||
|
||||
|
||||
@router.get("/targets")
|
||||
async def api_list_targets(request: Request):
|
||||
return {"targets": await list_targets(_user_id(request))}
|
||||
|
||||
|
||||
@router.get("/events")
|
||||
async def api_list_events(request: Request):
|
||||
_user_id(request)
|
||||
return {"events": get_notification_event_catalog()}
|
||||
|
||||
|
||||
@router.post("/targets")
|
||||
async def api_create_target(request: Request, body: TargetPayload):
|
||||
try:
|
||||
return await create_target(_user_id(request), _payload(body))
|
||||
except NotificationError as exc:
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.put("/targets/{target_id}")
|
||||
async def api_update_target(request: Request, target_id: str, body: TargetPayload):
|
||||
try:
|
||||
return await update_target(_user_id(request), target_id, _payload(body))
|
||||
except NotificationError as exc:
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.delete("/targets/{target_id}")
|
||||
async def api_delete_target(request: Request, target_id: str):
|
||||
ok = await delete_target(_user_id(request), target_id)
|
||||
if not ok:
|
||||
raise HTTPException(404, "notification target not found")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/targets/{target_id}/test")
|
||||
async def api_test_target(request: Request, target_id: str):
|
||||
try:
|
||||
return await test_target(_user_id(request), target_id)
|
||||
except NotificationError as exc:
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.put("/targets/{target_id}/default")
|
||||
async def api_set_default_target(request: Request, target_id: str):
|
||||
try:
|
||||
return await set_default_target(_user_id(request), target_id)
|
||||
except NotificationError as exc:
|
||||
raise _error(exc) from exc
|
||||
|
||||
|
||||
@router.get("/bot-options")
|
||||
async def api_bot_options(request: Request):
|
||||
return {
|
||||
"bots": await get_bot_options(
|
||||
_user_id(request),
|
||||
bot_manager=getattr(request.app.state, "bot_manager", None),
|
||||
)
|
||||
}
|
||||
@@ -111,7 +111,8 @@ async def put_preferences(request: Request):
|
||||
if not user_id:
|
||||
return {"status": "skipped"}
|
||||
body = await request.json()
|
||||
await UserStates.save_data(user_id, body)
|
||||
current = await UserStates.get_data(user_id)
|
||||
await UserStates.save_data(user_id, {**current, **body})
|
||||
return {"status": "saved"}
|
||||
|
||||
|
||||
|
||||
@@ -55,6 +55,11 @@ async def emit_to_user(user_id: str, data: dict):
|
||||
await sio.emit("events:chat", data, to=sid)
|
||||
|
||||
|
||||
def is_user_active(user_id: str) -> bool:
|
||||
"""Return True when the user has at least one connected app session."""
|
||||
return bool(_user_sids.get(user_id))
|
||||
|
||||
|
||||
def get_asgi_app(other_app):
|
||||
"""Wrap a FastAPI/Starlette app with the Socket.IO ASGI layer."""
|
||||
return socketio.ASGIApp(sio, other_asgi_app=other_app)
|
||||
@@ -1 +1 @@
|
||||
"""Coding agent support for Codex and Claude Code."""
|
||||
"""Coding agent support."""
|
||||
@@ -17,7 +17,7 @@ class AcpClient:
|
||||
args: list[str],
|
||||
cwd: str,
|
||||
env: dict[str, str],
|
||||
auth_method_id: str,
|
||||
auth_method_id: str | None,
|
||||
client_capabilities: dict[str, Any] | None = None,
|
||||
resume_session_id: str | None = None,
|
||||
auto_approve_permissions: bool = False,
|
||||
@@ -37,6 +37,7 @@ class AcpClient:
|
||||
self.events: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
|
||||
self.next_id = 1
|
||||
self.session_id: str | None = None
|
||||
self.initialize_result: dict[str, Any] = {}
|
||||
self.setup_result: dict[str, Any] = {}
|
||||
self.model_config_id: str | None = None
|
||||
|
||||
@@ -52,7 +53,7 @@ class AcpClient:
|
||||
)
|
||||
self.reader_task = asyncio.create_task(self._reader_loop())
|
||||
self.stderr_task = asyncio.create_task(self._stderr_loop())
|
||||
await self.request(
|
||||
self.initialize_result = await self.request(
|
||||
"initialize",
|
||||
{
|
||||
"protocolVersion": 1,
|
||||
@@ -64,7 +65,9 @@ class AcpClient:
|
||||
"clientInfo": {"name": "cptr", "version": "0"},
|
||||
},
|
||||
)
|
||||
await self.request("authenticate", {"methodId": self.auth_method_id})
|
||||
auth_method_id = self.auth_method_id or _first_auth_method(self.initialize_result)
|
||||
if auth_method_id:
|
||||
await self.request("authenticate", {"methodId": auth_method_id})
|
||||
await self._open_session()
|
||||
|
||||
async def close(self) -> None:
|
||||
@@ -270,6 +273,18 @@ def _extract_model_config_id(setup: dict[str, Any]) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _first_auth_method(initialize_result: dict[str, Any]) -> str | None:
|
||||
methods = initialize_result.get("authMethods")
|
||||
if not isinstance(methods, list):
|
||||
return None
|
||||
for method in methods:
|
||||
if isinstance(method, dict):
|
||||
method_id = method.get("id")
|
||||
if isinstance(method_id, str) and method_id.strip():
|
||||
return method_id.strip()
|
||||
return None
|
||||
|
||||
|
||||
def _select_permission_option(params: dict[str, Any], kind: str) -> str | None:
|
||||
options = params.get("options")
|
||||
if not isinstance(options, list):
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Cline ACP adapter."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from contextlib import suppress
|
||||
from typing import Any, AsyncIterator
|
||||
|
||||
from cptr.utils.agents.acp import (
|
||||
AcpClient,
|
||||
acp_event_stream,
|
||||
acp_text_from_update,
|
||||
acp_tool_from_update,
|
||||
)
|
||||
from cptr.utils.agents.attachments import PreparedAgentAttachments
|
||||
from cptr.utils.agents.events import (
|
||||
AgentDone,
|
||||
AgentError,
|
||||
AgentEvent,
|
||||
AgentTextDelta,
|
||||
AgentToolUpdate,
|
||||
)
|
||||
|
||||
|
||||
def _prompt_from_messages(messages: list[dict[str, Any]]) -> str:
|
||||
parts: list[str] = []
|
||||
for message in messages:
|
||||
role = message.get("role", "user")
|
||||
content = message.get("content", "")
|
||||
if isinstance(content, list):
|
||||
text = "\n".join(
|
||||
str(block.get("text", "")) for block in content if isinstance(block, dict)
|
||||
)
|
||||
else:
|
||||
text = str(content or "")
|
||||
if text:
|
||||
parts.append(f"[{role}]\n{text}")
|
||||
return "\n\n".join(parts)
|
||||
|
||||
|
||||
def _auto_approve(chat_params: dict[str, Any]) -> bool:
|
||||
if chat_params.get("tool_approval_mode") == "full":
|
||||
return True
|
||||
return bool(chat_params.get("auto_approve_tools"))
|
||||
|
||||
|
||||
async def run_cline_agent(
|
||||
*,
|
||||
profile: dict[str, Any],
|
||||
model: str,
|
||||
workspace: str,
|
||||
messages: list[dict[str, Any]],
|
||||
system_prompt: str,
|
||||
chat_params: dict[str, Any],
|
||||
resume_state: dict[str, Any] | None,
|
||||
attachments: PreparedAgentAttachments,
|
||||
) -> AsyncIterator[AgentEvent]:
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
|
||||
session_id = None
|
||||
if resume_state and isinstance(resume_state.get("session_id"), str):
|
||||
session_id = resume_state["session_id"]
|
||||
|
||||
client = AcpClient(
|
||||
command=str(profile["command"]),
|
||||
args=["--acp"],
|
||||
cwd=workspace,
|
||||
env=env,
|
||||
auth_method_id=None,
|
||||
resume_session_id=session_id,
|
||||
auto_approve_permissions=_auto_approve(chat_params),
|
||||
)
|
||||
try:
|
||||
await client.start()
|
||||
if model != "default":
|
||||
await client.set_model(model)
|
||||
|
||||
prompt = _prompt_from_messages(messages)
|
||||
if system_prompt:
|
||||
prompt = f"{system_prompt}\n\n{prompt}" if prompt else system_prompt
|
||||
|
||||
images = [
|
||||
{"data": image.base64, "mimeType": image.mime_type} for image in attachments.images
|
||||
]
|
||||
prompt_task = asyncio.create_task(client.prompt(prompt, images=images))
|
||||
try:
|
||||
async for event in acp_event_stream(client):
|
||||
params = event.get("params") if isinstance(event.get("params"), dict) else {}
|
||||
text = acp_text_from_update(params)
|
||||
if text:
|
||||
yield AgentTextDelta(text)
|
||||
tool = acp_tool_from_update(params)
|
||||
if tool:
|
||||
yield AgentToolUpdate(**tool)
|
||||
if prompt_task.done():
|
||||
try:
|
||||
next_event = await asyncio.wait_for(client.events.get(), timeout=0.25)
|
||||
except asyncio.TimeoutError:
|
||||
break
|
||||
next_params = (
|
||||
next_event.get("params")
|
||||
if isinstance(next_event.get("params"), dict)
|
||||
else {}
|
||||
)
|
||||
next_text = acp_text_from_update(next_params)
|
||||
if next_text:
|
||||
yield AgentTextDelta(next_text)
|
||||
next_tool = acp_tool_from_update(next_params)
|
||||
if next_tool:
|
||||
yield AgentToolUpdate(**next_tool)
|
||||
await prompt_task
|
||||
finally:
|
||||
if not prompt_task.done():
|
||||
prompt_task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await prompt_task
|
||||
|
||||
yield AgentDone(
|
||||
resume_state={
|
||||
"profile_id": profile["id"],
|
||||
"session_id": client.session_id,
|
||||
"workspace": workspace,
|
||||
"model": model,
|
||||
}
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
await client.cancel()
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 - surfaced in chat.
|
||||
yield AgentError(str(exc))
|
||||
finally:
|
||||
await client.close()
|
||||
@@ -158,6 +158,18 @@ async def detect_profile(profile: dict[str, Any]) -> AgentDetection:
|
||||
)
|
||||
return AgentDetection("ready", command, version, None, models)
|
||||
|
||||
if profile.get("agent") == "cline":
|
||||
models = await _probe_cline_models(command, profile)
|
||||
if not models:
|
||||
return AgentDetection(
|
||||
"auth_unknown",
|
||||
command,
|
||||
version,
|
||||
"Could not discover Cline models. Check `cline auth` or add models manually.",
|
||||
[],
|
||||
)
|
||||
return AgentDetection("ready", command, version, None, models)
|
||||
|
||||
return AgentDetection("error", command, version, "Unknown agent")
|
||||
|
||||
|
||||
@@ -387,6 +399,28 @@ async def _probe_opencode_models(command: str, profile: dict[str, Any]) -> list[
|
||||
await proc.wait()
|
||||
|
||||
|
||||
async def _probe_cline_models(command: str, profile: dict[str, Any]) -> list[str] | None:
|
||||
from cptr.utils.agents.acp import AcpClient, acp_models_from_setup
|
||||
|
||||
env = os.environ.copy()
|
||||
if profile.get("home"):
|
||||
env["HOME"] = os.path.expanduser(str(profile["home"]))
|
||||
client = AcpClient(
|
||||
command=command,
|
||||
args=["--acp"],
|
||||
cwd=os.getcwd(),
|
||||
env=env,
|
||||
auth_method_id=None,
|
||||
)
|
||||
try:
|
||||
await asyncio.wait_for(client.start(), timeout=10)
|
||||
return acp_models_from_setup(client.setup_result) or None
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
|
||||
@@ -70,10 +70,20 @@ DEFAULT_AGENT_PROFILES: list[dict[str, Any]] = [
|
||||
"server_url": "",
|
||||
"server_password": "",
|
||||
},
|
||||
{
|
||||
"id": "cline",
|
||||
"agent": "cline",
|
||||
"name": "Cline",
|
||||
"mode": "auto",
|
||||
"command": "cline",
|
||||
"home": None,
|
||||
"models": [],
|
||||
"default_model": "",
|
||||
},
|
||||
]
|
||||
|
||||
_PROFILE_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
|
||||
_VALID_AGENTS = {"codex", "claude_code", "cursor", "grok", "opencode"}
|
||||
_VALID_AGENTS = {"codex", "claude_code", "cursor", "grok", "opencode", "cline"}
|
||||
_VALID_MODES = {"auto", "enabled", "disabled"}
|
||||
_VALID_CODEX_APPROVAL = {"ask", "auto", "full"}
|
||||
_VALID_CODEX_SANDBOX = {"read-only", "workspace-write", "danger-full-access"}
|
||||
@@ -92,6 +102,7 @@ _AGENT_DEFAULTS: dict[str, dict[str, str]] = {
|
||||
},
|
||||
"grok": {"name": "Grok", "command": "grok", "model": ""},
|
||||
"opencode": {"name": "OpenCode", "command": "opencode", "model": ""},
|
||||
"cline": {"name": "Cline", "command": "cline", "model": ""},
|
||||
}
|
||||
|
||||
|
||||
@@ -107,7 +118,9 @@ def normalize_agent_profile(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
agent = str(profile.get("agent") or "").strip()
|
||||
if agent not in _VALID_AGENTS:
|
||||
raise HTTPException(400, "agent must be codex, claude_code, cursor, grok, or opencode")
|
||||
raise HTTPException(
|
||||
400, "agent must be codex, claude_code, cursor, grok, opencode, or cline"
|
||||
)
|
||||
defaults = _AGENT_DEFAULTS[agent]
|
||||
|
||||
mode = str(profile.get("mode") or "auto").strip()
|
||||
|
||||
@@ -20,6 +20,7 @@ from dataclasses import dataclass, field
|
||||
from typing import Any, Awaitable, Callable, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_current_bot_manager: "BotManager | None" = None
|
||||
|
||||
# How often to edit the streaming message (seconds).
|
||||
STREAM_EDIT_INTERVAL = 2.0
|
||||
@@ -193,6 +194,10 @@ async def delete_bot_config(bot_id: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def get_current_bot_manager() -> "BotManager | None":
|
||||
return _current_bot_manager
|
||||
|
||||
|
||||
# ── Thread mapping via chat.meta ─────────────────────────────
|
||||
|
||||
|
||||
@@ -238,9 +243,11 @@ class BotManager:
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
global _current_bot_manager
|
||||
self._adapters: dict[str, BaseAdapter] = {} # bot_id → adapter
|
||||
self._tasks: dict[str, asyncio.Task] = {} # bot_id → polling task
|
||||
self._stream_tasks: dict[str, asyncio.Task] = {} # key → streaming task
|
||||
_current_bot_manager = self
|
||||
|
||||
# ── Lifecycle ──────────────────────────────────────────
|
||||
|
||||
@@ -317,6 +324,17 @@ class BotManager:
|
||||
def get_status(self) -> dict[str, bool]:
|
||||
return {bid: not t.done() for bid, t in self._tasks.items()}
|
||||
|
||||
async def send_notification(
|
||||
self,
|
||||
bot_id: str,
|
||||
destination_chat_id: str,
|
||||
text: str,
|
||||
) -> str | None:
|
||||
adapter = self._adapters.get(bot_id)
|
||||
if not adapter or not self.is_running(bot_id):
|
||||
raise RuntimeError("bot is not running")
|
||||
return await adapter.send(destination_chat_id, text)
|
||||
|
||||
# ── Adapter factory ────────────────────────────────────
|
||||
|
||||
def _create_adapter(self, bot: dict) -> BaseAdapter | None:
|
||||
|
||||
+69
-37
@@ -11,6 +11,7 @@ import logging
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from cptr.events import EVENTS, publish_event
|
||||
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS
|
||||
from cptr.utils.context import resolve_compact_token_threshold, should_compact
|
||||
from cptr.utils.skills import discover_skills, load_skill, format_skill_content
|
||||
@@ -1182,6 +1183,10 @@ async def run_chat_task(
|
||||
workspace_name=ws_name,
|
||||
)
|
||||
|
||||
event_workspace = (
|
||||
{"id": workspace, "name": workspace.rstrip("/").rsplit("/", 1)[-1]} if workspace else None
|
||||
)
|
||||
|
||||
# Load existing state so continuations don't overwrite previous output
|
||||
msg = await ChatMessage.get_by_id(message_id)
|
||||
summary_message_id = message_id
|
||||
@@ -1270,6 +1275,7 @@ async def run_chat_task(
|
||||
async def _run_agent_target(agent_target: AgentModelTarget):
|
||||
nonlocal content, text_buffer
|
||||
from cptr.utils.agents.claude_code import run_claude_code_agent
|
||||
from cptr.utils.agents.cline import run_cline_agent
|
||||
from cptr.utils.agents.codex import run_codex_agent
|
||||
from cptr.utils.agents.cursor import run_cursor_agent
|
||||
from cptr.utils.agents.grok import run_grok_agent
|
||||
@@ -1322,6 +1328,7 @@ async def run_chat_task(
|
||||
"cursor": run_cursor_agent,
|
||||
"grok": run_grok_agent,
|
||||
"opencode": run_opencode_agent,
|
||||
"cline": run_cline_agent,
|
||||
}
|
||||
runner = runners.get(agent_target.agent)
|
||||
if runner is None:
|
||||
@@ -1493,6 +1500,16 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
preview = content[:300] if content else ""
|
||||
await publish_event(
|
||||
EVENTS.CHAT_FINISHED,
|
||||
actor={"id": user_id},
|
||||
subject_id=chat_id,
|
||||
subject_type="chat",
|
||||
source="chat_task",
|
||||
data={"workspace": event_workspace, "preview": preview},
|
||||
message=preview,
|
||||
)
|
||||
return
|
||||
|
||||
flushed_item = _flush_text()
|
||||
@@ -1501,6 +1518,16 @@ async def run_chat_task(
|
||||
await _save_message("agent stream ended", content=content, output=output_items, done=True)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
preview = content[:300] if content else ""
|
||||
await publish_event(
|
||||
EVENTS.CHAT_FINISHED,
|
||||
actor={"id": user_id},
|
||||
subject_id=chat_id,
|
||||
subject_type="chat",
|
||||
source="chat_task",
|
||||
data={"workspace": event_workspace, "preview": preview},
|
||||
message=preview,
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -1776,30 +1803,8 @@ async def run_chat_task(
|
||||
last_usage = usage
|
||||
new_messages_since = 0
|
||||
|
||||
if not pending_calls:
|
||||
# No tool calls — final response, we're done
|
||||
_flush_text()
|
||||
if streamed_reasoning_chars and not response_reasoning_items:
|
||||
logger.warning(
|
||||
"[task %s] reasoning output streamed (%d chars) but no completed reasoning item arrived before usage; DB output may contain only in-progress reasoning",
|
||||
message_id[:8],
|
||||
streamed_reasoning_chars,
|
||||
)
|
||||
await _save_message(
|
||||
"usage",
|
||||
content=content,
|
||||
output=output_items,
|
||||
usage=usage,
|
||||
done=True,
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
return
|
||||
|
||||
elif event["type"] == "done":
|
||||
# Stream ended — if usage already triggered a save+return, we won't
|
||||
# reach here. This is the fallback for providers that don't support
|
||||
# stream_options.include_usage.
|
||||
# Stream ended. Usage may have arrived earlier, multiple times, or never.
|
||||
if not pending_calls:
|
||||
_flush_text()
|
||||
if streamed_reasoning_chars and not response_reasoning_items:
|
||||
@@ -1809,7 +1814,7 @@ async def run_chat_task(
|
||||
streamed_reasoning_chars,
|
||||
)
|
||||
await _save_message(
|
||||
"done fallback",
|
||||
"done",
|
||||
content=content,
|
||||
output=output_items,
|
||||
usage=last_usage,
|
||||
@@ -1817,6 +1822,16 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
preview = content[:300] if content else ""
|
||||
await publish_event(
|
||||
EVENTS.CHAT_FINISHED,
|
||||
actor={"id": user_id},
|
||||
subject_id=chat_id,
|
||||
subject_type="chat",
|
||||
source="chat_task",
|
||||
data={"workspace": event_workspace, "preview": preview},
|
||||
message=preview,
|
||||
)
|
||||
return
|
||||
|
||||
# ── Process collected tool calls ────────────────────
|
||||
@@ -1873,7 +1888,7 @@ async def run_chat_task(
|
||||
)
|
||||
if flushed_item:
|
||||
await emit(output=flushed_item)
|
||||
await emit(output=item)
|
||||
await emit(output=item)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True)
|
||||
return
|
||||
@@ -2028,10 +2043,21 @@ async def run_chat_task(
|
||||
"end",
|
||||
content=content,
|
||||
output=output_items,
|
||||
usage=last_usage,
|
||||
done=True,
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
preview = content[:300] if content else ""
|
||||
await publish_event(
|
||||
EVENTS.CHAT_FINISHED,
|
||||
actor={"id": user_id},
|
||||
subject_id=chat_id,
|
||||
subject_type="chat",
|
||||
source="chat_task",
|
||||
data={"workspace": event_workspace, "preview": preview},
|
||||
message=preview,
|
||||
)
|
||||
return
|
||||
|
||||
# Max iterations reached
|
||||
@@ -2044,6 +2070,15 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await _emit_done()
|
||||
await publish_event(
|
||||
EVENTS.CHAT_FAILED,
|
||||
actor={"id": user_id},
|
||||
subject_id=chat_id,
|
||||
subject_type="chat",
|
||||
source="chat_task",
|
||||
data={"workspace": event_workspace, "preview": "Max iterations reached."},
|
||||
message="Max iterations reached.",
|
||||
)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
_flush_text()
|
||||
@@ -2085,6 +2120,15 @@ async def run_chat_task(
|
||||
)
|
||||
_task_state.pop(message_id, None)
|
||||
await emit(done=True, error=error_msg)
|
||||
await publish_event(
|
||||
EVENTS.CHAT_FAILED,
|
||||
actor={"id": user_id},
|
||||
subject_id=chat_id,
|
||||
subject_type="chat",
|
||||
source="chat_task",
|
||||
data={"workspace": event_workspace, "preview": error_msg[:300] if error_msg else ""},
|
||||
message=error_msg[:300] if error_msg else "",
|
||||
)
|
||||
finally:
|
||||
# Guarantee the gateway SSE stream terminates. If emit()
|
||||
# already pushed a done/error event the sentinel is harmless
|
||||
@@ -2128,18 +2172,6 @@ async def run_chat_task(
|
||||
logger.debug(
|
||||
"[title] Error in title generation for chat %s", chat_id[:8], exc_info=True
|
||||
)
|
||||
# Fire webhook notification if configured
|
||||
try:
|
||||
webhook_url = await Config.get("notifications.webhook_url")
|
||||
if webhook_url:
|
||||
chat_obj = chat_obj or await Chat.get_by_id(chat_id)
|
||||
title = chat_obj.title if chat_obj else "Chat"
|
||||
preview = content[:300] if content else ""
|
||||
from cptr.utils.webhook import post_webhook
|
||||
|
||||
await post_webhook(webhook_url, title, preview)
|
||||
except Exception:
|
||||
logger.debug("[webhook] Error sending webhook for chat %s", chat_id[:8], exc_info=True)
|
||||
# Best-effort post-turn memory review. Runs detached and never competes
|
||||
# with queued user input processing.
|
||||
try:
|
||||
|
||||
@@ -24,7 +24,7 @@ class ApiModelTarget:
|
||||
class AgentModelTarget:
|
||||
kind: Literal["agent"]
|
||||
profile_id: str
|
||||
agent: Literal["codex", "claude_code", "cursor", "grok", "opencode"]
|
||||
agent: Literal["codex", "claude_code", "cursor", "grok", "opencode", "cline"]
|
||||
model: str
|
||||
full_model_id: str
|
||||
config: dict[str, Any]
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
"""User-owned chat notification targets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import socket
|
||||
import time
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
from cptr.events import CHAT_NOTIFICATION_EVENTS, EVENT_DEFINITIONS_BY_NAME, EVENTS, Event
|
||||
from cptr.models import UserStates
|
||||
from cptr.socket.main import is_user_active
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
VALID_EVENTS = {event.name for event in CHAT_NOTIFICATION_EVENTS}
|
||||
VALID_TYPES = {"webhook", "bot"}
|
||||
VALID_DELIVERY = {"away", "always"}
|
||||
|
||||
|
||||
class NotificationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _now() -> int:
|
||||
return int(time.time())
|
||||
|
||||
|
||||
async def _state(user_id: str) -> dict:
|
||||
return dict(await UserStates.get_data(user_id) or {})
|
||||
|
||||
|
||||
async def _save_state(user_id: str, data: dict) -> None:
|
||||
await UserStates.save_data(user_id, data)
|
||||
|
||||
|
||||
def _targets(data: dict) -> list[dict]:
|
||||
notifications = data.setdefault("notifications", {})
|
||||
targets = notifications.setdefault("targets", [])
|
||||
if not isinstance(targets, list):
|
||||
targets = []
|
||||
notifications["targets"] = targets
|
||||
return targets
|
||||
|
||||
|
||||
def _mask_url(url: str) -> str:
|
||||
parsed = urlparse(url)
|
||||
if not parsed.hostname:
|
||||
return "****"
|
||||
path = parsed.path or ""
|
||||
suffix = path[-4:] if len(path) > 4 else path
|
||||
return f"{parsed.scheme}://{parsed.hostname}/...{suffix}"
|
||||
|
||||
|
||||
def _public_target(target: dict) -> dict:
|
||||
public = {**target, "config": dict(target.get("config") or {})}
|
||||
if public.get("type") == "webhook":
|
||||
url = str(public["config"].pop("url", "") or "")
|
||||
public["config"]["url_masked"] = _mask_url(url) if url else ""
|
||||
return public
|
||||
|
||||
|
||||
def _default_target_id(data: dict) -> str:
|
||||
return str((data.get("notifications") or {}).get("default_target_id") or "")
|
||||
|
||||
|
||||
def _validate_events(events) -> list[str]:
|
||||
if events is None:
|
||||
return []
|
||||
if not isinstance(events, list):
|
||||
raise NotificationError("events must be a list")
|
||||
cleaned = []
|
||||
for event in events:
|
||||
if event not in VALID_EVENTS:
|
||||
raise NotificationError(f"unsupported notification event: {event}")
|
||||
if event not in cleaned:
|
||||
cleaned.append(event)
|
||||
return cleaned
|
||||
|
||||
|
||||
def validate_webhook_url(url: str) -> str:
|
||||
url = (url or "").strip()
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
raise NotificationError("webhook URL must be http or https")
|
||||
|
||||
host = parsed.hostname.lower()
|
||||
if host in {"metadata.google.internal"} or host.endswith(".internal"):
|
||||
raise NotificationError("webhook URL host is not allowed")
|
||||
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, parsed.port or (443 if parsed.scheme == "https" else 80))
|
||||
except OSError as exc:
|
||||
raise NotificationError("webhook URL hostname could not be resolved") from exc
|
||||
|
||||
for info in infos:
|
||||
ip = ipaddress.ip_address(info[4][0])
|
||||
if (
|
||||
ip.is_loopback
|
||||
or ip.is_private
|
||||
or ip.is_link_local
|
||||
or ip.is_multicast
|
||||
or ip.is_reserved
|
||||
or ip.is_unspecified
|
||||
):
|
||||
raise NotificationError("webhook URL resolves to a blocked address")
|
||||
return url
|
||||
|
||||
|
||||
async def list_targets(user_id: str) -> list[dict]:
|
||||
data = await _state(user_id)
|
||||
visible = []
|
||||
default_id = _default_target_id(data)
|
||||
for target in _targets(data):
|
||||
if target.get("type") == "bot":
|
||||
try:
|
||||
await _ensure_user_bot(user_id, str((target.get("config") or {}).get("bot_id") or ""))
|
||||
except NotificationError:
|
||||
continue
|
||||
public = _public_target(target)
|
||||
public["is_default"] = target.get("id") == default_id
|
||||
visible.append(public)
|
||||
return visible
|
||||
|
||||
|
||||
async def get_bot_options(user_id: str, bot_manager=None) -> list[dict]:
|
||||
from cptr.utils.bridge import get_bot_configs
|
||||
|
||||
status = bot_manager.get_status() if bot_manager else {}
|
||||
bots = []
|
||||
for bot in await get_bot_configs():
|
||||
if bot.get("user_id") != user_id:
|
||||
continue
|
||||
bots.append(
|
||||
{
|
||||
"id": bot.get("id"),
|
||||
"name": bot.get("name"),
|
||||
"platform": bot.get("platform"),
|
||||
"is_active": bool(bot.get("is_active", True)),
|
||||
"is_running": bool(status.get(bot.get("id"), False)),
|
||||
}
|
||||
)
|
||||
return bots
|
||||
|
||||
|
||||
async def _ensure_user_bot(user_id: str, bot_id: str) -> None:
|
||||
from cptr.utils.bridge import get_bot_by_id
|
||||
|
||||
bot = await get_bot_by_id(bot_id)
|
||||
if not bot or bot.get("user_id") != user_id:
|
||||
raise NotificationError("bot target is not available")
|
||||
|
||||
|
||||
def _validate_config(target_type: str, config: dict) -> dict:
|
||||
if not isinstance(config, dict):
|
||||
raise NotificationError("config must be an object")
|
||||
if target_type == "webhook":
|
||||
return {"url": validate_webhook_url(str(config.get("url") or ""))}
|
||||
if target_type == "bot":
|
||||
bot_id = str(config.get("bot_id") or "").strip()
|
||||
destination = str(config.get("destination_chat_id") or "").strip()
|
||||
if not bot_id:
|
||||
raise NotificationError("bot target requires bot_id")
|
||||
if not destination:
|
||||
raise NotificationError("bot target requires destination_chat_id")
|
||||
return {"bot_id": bot_id, "destination_chat_id": destination}
|
||||
raise NotificationError("unsupported notification target type")
|
||||
|
||||
|
||||
def _validate_target(payload: dict, existing: dict | None = None) -> dict:
|
||||
merged = {**(existing or {}), **payload}
|
||||
target_id = str(merged.get("id") or "").strip()
|
||||
target_type = str(merged.get("type") or "").strip()
|
||||
delivery = str(merged.get("delivery") or "away").strip()
|
||||
if not target_id:
|
||||
raise NotificationError("target id is required")
|
||||
if target_type not in VALID_TYPES:
|
||||
raise NotificationError("target type must be webhook or bot")
|
||||
if delivery not in VALID_DELIVERY:
|
||||
raise NotificationError("delivery must be away or always")
|
||||
config = _validate_config(target_type, dict(merged.get("config") or {}))
|
||||
now = _now()
|
||||
return {
|
||||
"id": target_id,
|
||||
"type": target_type,
|
||||
"enabled": bool(merged.get("enabled", True)),
|
||||
"events": _validate_events(merged.get("events", [])),
|
||||
"delivery": delivery,
|
||||
"config": config,
|
||||
"created_at": int(merged.get("created_at") or now),
|
||||
"updated_at": now,
|
||||
}
|
||||
|
||||
|
||||
def _check_unique_id(targets: list[dict], new_id: str, old_id: str | None = None) -> None:
|
||||
lowered = new_id.lower()
|
||||
for target in targets:
|
||||
if target.get("id") != old_id and str(target.get("id", "")).lower() == lowered:
|
||||
raise NotificationError("notification target id already exists")
|
||||
|
||||
|
||||
async def create_target(user_id: str, payload: dict) -> dict:
|
||||
data = await _state(user_id)
|
||||
targets = _targets(data)
|
||||
payload = dict(payload)
|
||||
if not str(payload.get("id") or "").strip():
|
||||
config = payload.get("config") or {}
|
||||
target_type = str(payload.get("type") or "target").strip() or "target"
|
||||
if target_type == "webhook":
|
||||
base = urlparse(str(config.get("url") or "")).hostname or "webhook"
|
||||
elif target_type == "bot":
|
||||
base = str(config.get("bot_id") or "bot")
|
||||
else:
|
||||
base = target_type
|
||||
base = re.sub(r"[^a-zA-Z0-9_-]+", "-", base).strip("-").lower() or "target"
|
||||
candidate = base
|
||||
suffix = 2
|
||||
while any(str(target.get("id", "")).lower() == candidate.lower() for target in targets):
|
||||
candidate = f"{base}-{suffix}"
|
||||
suffix += 1
|
||||
payload["id"] = candidate
|
||||
target = _validate_target(payload)
|
||||
if target["type"] == "bot":
|
||||
await _ensure_user_bot(user_id, target["config"]["bot_id"])
|
||||
_check_unique_id(targets, target["id"])
|
||||
targets.append(target)
|
||||
notifications = data.setdefault("notifications", {})
|
||||
is_default = False
|
||||
if not notifications.get("default_target_id"):
|
||||
notifications["default_target_id"] = target["id"]
|
||||
is_default = True
|
||||
await _save_state(user_id, data)
|
||||
public = _public_target(target)
|
||||
public["is_default"] = is_default
|
||||
return public
|
||||
|
||||
|
||||
async def update_target(user_id: str, target_id: str, payload: dict) -> dict:
|
||||
data = await _state(user_id)
|
||||
targets = _targets(data)
|
||||
for idx, current in enumerate(targets):
|
||||
if current.get("id") == target_id:
|
||||
target = _validate_target(payload, existing=current)
|
||||
if target["type"] == "bot":
|
||||
await _ensure_user_bot(user_id, target["config"]["bot_id"])
|
||||
_check_unique_id(targets, target["id"], target_id)
|
||||
targets[idx] = target
|
||||
notifications = data.setdefault("notifications", {})
|
||||
if notifications.get("default_target_id") == target_id:
|
||||
notifications["default_target_id"] = target["id"]
|
||||
await _save_state(user_id, data)
|
||||
public = _public_target(target)
|
||||
public["is_default"] = notifications.get("default_target_id") == target["id"]
|
||||
return public
|
||||
raise NotificationError("notification target not found")
|
||||
|
||||
|
||||
async def delete_target(user_id: str, target_id: str) -> bool:
|
||||
data = await _state(user_id)
|
||||
targets = _targets(data)
|
||||
kept = [target for target in targets if target.get("id") != target_id]
|
||||
if len(kept) == len(targets):
|
||||
return False
|
||||
data["notifications"]["targets"] = kept
|
||||
if data["notifications"].get("default_target_id") == target_id:
|
||||
data["notifications"]["default_target_id"] = kept[0]["id"] if kept else None
|
||||
await _save_state(user_id, data)
|
||||
return True
|
||||
|
||||
|
||||
async def set_default_target(user_id: str, target_id: str) -> dict:
|
||||
data = await _state(user_id)
|
||||
for target in _targets(data):
|
||||
if target.get("id") == target_id:
|
||||
data.setdefault("notifications", {})["default_target_id"] = target_id
|
||||
await _save_state(user_id, data)
|
||||
public = _public_target(target)
|
||||
public["is_default"] = True
|
||||
return public
|
||||
raise NotificationError("notification target not found")
|
||||
|
||||
|
||||
async def _find_target(user_id: str, target_id: str) -> dict | None:
|
||||
data = await _state(user_id)
|
||||
needle = target_id.lower()
|
||||
for target in _targets(data):
|
||||
if str(target.get("id", "")).lower() == needle:
|
||||
return target
|
||||
return None
|
||||
|
||||
|
||||
def _webhook_payload(event: str, title: str, message: str, context: dict) -> dict:
|
||||
return {
|
||||
"event": event,
|
||||
"title": title,
|
||||
"message": message,
|
||||
"source": "computer",
|
||||
"chat_id": context.get("chat_id"),
|
||||
"workspace": context.get("workspace"),
|
||||
"created_at": _now(),
|
||||
}
|
||||
|
||||
|
||||
def _sink_payload(url: str, payload: dict) -> dict:
|
||||
title = payload["title"]
|
||||
message = payload["message"]
|
||||
if "hooks.slack.com" in url or "chat.googleapis.com" in url:
|
||||
return {"text": f"*{title}*\n{message}" if title else message}
|
||||
if "discord.com/api/webhooks" in url:
|
||||
content = f"**{title}**\n{message}" if title else message
|
||||
return {"content": content[:1997] + "..." if len(content) > 2000 else content}
|
||||
if "webhook.office.com" in url:
|
||||
return {
|
||||
"@type": "MessageCard",
|
||||
"@context": "http://schema.org/extensions",
|
||||
"themeColor": "0076D7",
|
||||
"summary": title or "Computer",
|
||||
"sections": [
|
||||
{
|
||||
"activityTitle": title or "Computer",
|
||||
"activitySubtitle": "Computer",
|
||||
"facts": [{"name": "Message", "value": message}],
|
||||
"markdown": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
return payload
|
||||
|
||||
|
||||
async def _send_webhook(target: dict, event: str, title: str, message: str, context: dict) -> None:
|
||||
url = validate_webhook_url(str((target.get("config") or {}).get("url") or ""))
|
||||
payload = _webhook_payload(event, title, message, context)
|
||||
async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
|
||||
response = await client.post(url, json=_sink_payload(url, payload))
|
||||
response.raise_for_status()
|
||||
|
||||
|
||||
async def _send_bot(target: dict, title: str, message: str, context: dict) -> None:
|
||||
from cptr.utils.bridge import get_current_bot_manager
|
||||
|
||||
user_id = str(context.get("user_id") or "")
|
||||
if user_id:
|
||||
await _ensure_user_bot(user_id, str((target.get("config") or {}).get("bot_id") or ""))
|
||||
|
||||
manager = get_current_bot_manager()
|
||||
if not manager:
|
||||
raise NotificationError("bot manager is not running")
|
||||
workspace = (context.get("workspace") or {}).get("name") if isinstance(context.get("workspace"), dict) else ""
|
||||
header = f"[{title}] {workspace}".strip() if title else workspace
|
||||
text = f"{header}\n\n{message}".strip() if header else message
|
||||
config = target.get("config") or {}
|
||||
await manager.send_notification(config["bot_id"], config["destination_chat_id"], text)
|
||||
|
||||
|
||||
async def _deliver(target: dict, event: str, title: str, message: str, context: dict) -> None:
|
||||
if target.get("type") == "webhook":
|
||||
await _send_webhook(target, event, title, message, context)
|
||||
elif target.get("type") == "bot":
|
||||
await _send_bot(target, title, message, context)
|
||||
else:
|
||||
raise NotificationError("unsupported notification target type")
|
||||
|
||||
|
||||
async def test_target(user_id: str, target_id: str) -> dict:
|
||||
target = await _find_target(user_id, target_id)
|
||||
if not target:
|
||||
raise NotificationError("notification target not found")
|
||||
await _deliver(
|
||||
target,
|
||||
EVENTS.NOTIFICATION_TEST.name,
|
||||
EVENTS.NOTIFICATION_TEST.label,
|
||||
"Computer can reach this target.",
|
||||
{"chat_id": None, "workspace": None, "user_id": user_id},
|
||||
)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def get_notification_event_catalog() -> list[dict[str, str]]:
|
||||
return [
|
||||
{
|
||||
"event": event.name,
|
||||
"label": event.label,
|
||||
"description": event.description or "",
|
||||
}
|
||||
for event in CHAT_NOTIFICATION_EVENTS
|
||||
]
|
||||
|
||||
|
||||
async def dispatch_notification_event(event: Event) -> None:
|
||||
if event.event not in VALID_EVENTS:
|
||||
return
|
||||
definition = EVENT_DEFINITIONS_BY_NAME[event.event]
|
||||
actor = event.actor or {}
|
||||
subject = event.subject or {}
|
||||
event_data = event.data or {}
|
||||
user_ids = set()
|
||||
if actor.get("id"):
|
||||
user_ids.add(str(actor["id"]))
|
||||
if subject.get("type") == "user" and subject.get("id"):
|
||||
user_ids.add(str(subject["id"]))
|
||||
if event_data.get("user_id"):
|
||||
user_ids.add(str(event_data["user_id"]))
|
||||
for user_id in event_data.get("user_ids") or []:
|
||||
if user_id:
|
||||
user_ids.add(str(user_id))
|
||||
|
||||
message = str(event.message or event_data.get("preview") or event_data.get("message") or "")
|
||||
chat_id = event_data.get("chat_id") or (
|
||||
subject.get("id") if subject.get("type") == "chat" else None
|
||||
)
|
||||
workspace = event_data.get("workspace")
|
||||
|
||||
for user_id in user_ids:
|
||||
data = await _state(user_id)
|
||||
active = is_user_active(user_id)
|
||||
for target in list(_targets(data)):
|
||||
if not target.get("enabled", True):
|
||||
continue
|
||||
if event.event not in target.get("events", []):
|
||||
continue
|
||||
if target.get("delivery", "away") == "away" and active:
|
||||
continue
|
||||
try:
|
||||
await _deliver(
|
||||
target,
|
||||
event.event,
|
||||
definition.label,
|
||||
message,
|
||||
{"chat_id": chat_id, "workspace": workspace, "user_id": user_id},
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"[notifications] failed to deliver %s to %s",
|
||||
event.event,
|
||||
target.get("id"),
|
||||
)
|
||||
|
||||
|
||||
async def notify_target(
|
||||
user_id: str,
|
||||
message: str,
|
||||
target_id: str | None = None,
|
||||
title: str | None = None,
|
||||
) -> str:
|
||||
if not target_id:
|
||||
data = await _state(user_id)
|
||||
target_id = _default_target_id(data)
|
||||
if not target_id:
|
||||
raise NotificationError("no default notification target is set")
|
||||
target = await _find_target(user_id, target_id)
|
||||
if not target:
|
||||
raise NotificationError(f'notification target "{target_id}" was not found')
|
||||
if not target.get("enabled", True):
|
||||
raise NotificationError(f'notification target "{target_id}" is disabled')
|
||||
await _deliver(
|
||||
target,
|
||||
EVENTS.NOTIFICATION_MANUAL.name,
|
||||
title or "",
|
||||
message,
|
||||
{"chat_id": None, "workspace": None, "user_id": user_id},
|
||||
)
|
||||
return f"Notification sent to {target.get('id')}."
|
||||
@@ -1887,6 +1887,26 @@ async def search_chats(
|
||||
)
|
||||
|
||||
|
||||
async def notify(message: str, target: str = "", title: str = "", *, __context__: dict) -> str:
|
||||
"""Send a notification to a user notification target.
|
||||
|
||||
:param message: Message body to send.
|
||||
:param target: Optional notification target ID from Settings > Notifications. Uses the default target when omitted.
|
||||
:param title: Optional notification title.
|
||||
"""
|
||||
user_id = __context__.get("user_id")
|
||||
if not user_id:
|
||||
return "Error: authentication required."
|
||||
try:
|
||||
from cptr.utils.notifications import NotificationError, notify_target
|
||||
|
||||
return await notify_target(user_id, message, target or None, title or None)
|
||||
except NotificationError as exc:
|
||||
return f"Error: {exc}"
|
||||
except Exception as exc:
|
||||
return f"Error: failed to send notification: {exc}"
|
||||
|
||||
|
||||
# ── Registry ────────────────────────────────────────────────
|
||||
|
||||
TOOLS: dict[str, dict] = {
|
||||
@@ -1912,6 +1932,7 @@ TOOLS: dict[str, dict] = {
|
||||
"update_automation": {"fn": update_automation, "auto": False},
|
||||
"toggle_automation": {"fn": toggle_automation, "auto": False},
|
||||
"delete_automation": {"fn": delete_automation, "auto": False},
|
||||
"notify": {"fn": notify, "auto": False},
|
||||
"image_generate": {"fn": image_generate, "auto": False},
|
||||
"update_memory": {"fn": update_memory, "auto": True},
|
||||
}
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
"""Webhook notifications: POST to Slack, Discord, Teams, or generic JSON.
|
||||
|
||||
Adapted from open-webui's webhook.py, using httpx instead of aiohttp.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def post_webhook(url: str, title: str, message: str) -> bool:
|
||||
"""Send a notification to a webhook URL.
|
||||
|
||||
Auto-detects Slack, Discord, Teams, and Google Chat webhook URLs
|
||||
and formats the payload accordingly. Falls back to generic JSON.
|
||||
|
||||
Returns True on success, False on failure (never raises).
|
||||
"""
|
||||
try:
|
||||
payload: dict = {}
|
||||
|
||||
# Slack and Google Chat
|
||||
if "hooks.slack.com" in url or "chat.googleapis.com" in url:
|
||||
payload["text"] = f"*{title}*\n{message}"
|
||||
|
||||
# Discord (2000 char limit)
|
||||
elif "discord.com/api/webhooks" in url:
|
||||
content = f"**{title}**\n{message}"
|
||||
if len(content) > 2000:
|
||||
content = content[:1980] + "... (truncated)"
|
||||
payload["content"] = content
|
||||
|
||||
# Microsoft Teams
|
||||
elif "webhook.office.com" in url:
|
||||
payload = {
|
||||
"@type": "MessageCard",
|
||||
"@context": "http://schema.org/extensions",
|
||||
"themeColor": "0076D7",
|
||||
"summary": title,
|
||||
"sections": [
|
||||
{
|
||||
"activityTitle": title,
|
||||
"activitySubtitle": "cptr",
|
||||
"facts": [{"name": "Message", "value": message}],
|
||||
"markdown": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
# Generic JSON
|
||||
else:
|
||||
payload = {
|
||||
"title": title,
|
||||
"message": message,
|
||||
"source": "cptr",
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.post(url, json=payload)
|
||||
r.raise_for_status()
|
||||
|
||||
logger.info("[webhook] Sent notification to %s", url[:50])
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
logger.exception("[webhook] Failed to send notification to %s", url[:50])
|
||||
return False
|
||||
""", "Description": "Adapted from open-webui's webhook.py — uses httpx, supports Slack/Discord/Teams/generic JSON", "IsArtifact": false, "Overwrite": false, "TargetFile": "/Users/tim/Documents/workspace/computer/cptr/utils/webhook.py
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cptr"
|
||||
version = "0.7.5"
|
||||
version = "0.7.6"
|
||||
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