Commit Graph
771 Commits
Author SHA1 Message Date
viettranx 6ea9b4d762 feat(desktop): add channel management, paired devices, and multiple fixes
Channel Management:
- Add Channels settings tab with full CRUD for Telegram/Discord (Lite: max 1 each)
- Channel detail panel with tabs: General, Credentials, Managers
- Advanced settings dialog (network, limits, streaming, behavior, access control)
- Schema-driven field renderer with Combobox selects, Switch toggles
- Paired Devices section: approve/deny pending, revoke paired, WS event auto-refresh
- Pairing notification badge in sidebar footer with pending count
- i18n support (en/vi/zh) for all channel strings

Bug Fixes:
- Fix Vietnamese slug generation (NFD normalize + đ/Đ handling) in lib/slug.ts
- Make agent key field editable instead of read-only
- Fix trace detail input/output: use MarkdownRenderer with copy button instead of forced-dark CodePreview
- Fix API error parsing to handle both {error: "string"} and {error: {message}} formats
- Add Accept-Language header to desktop API client for i18n error messages
- Wrap raw err.Error() with i18n messages in HTTP handlers (agents, channel_instances)
- Increase SQLite MaxOpenConns from 2 to 4 to reduce SQLITE_BUSY contention
- Add retryOnBusy wrapper for context file seeding writes
- Update EditionCompareModal: channels moved from "false" to "1 Telegram + 1 Discord"
2026-03-27 19:52:28 +07:00
viettranx 2bc0f5f14a fix(telegram): prevent duplicate messages in groups when streaming disabled
When group_stream=false (default), channels implementing StreamingChannel
still processed chunk events, creating stream messages alongside block
replies — causing each intermediate message to appear twice.

Gate the streaming handler on rc.Streaming so it only activates when
streaming is actually enabled for the run.
2026-03-27 19:49:33 +07:00
viettranx d3bf16d2de refactor(bootstrap): separate profile and seeding callbacks, consolidate per-user state
- Split EnsureUserFilesFunc into EnsureUserProfileFunc (profile + workspace)
  and SeedUserFilesFunc (context file seeding) for single-responsibility
- Merge userWorkspaces + userFilesSeeded sync.Maps into unified userSetups
  struct to prevent desync between workspace and seeding state
- Add skipIfAnyExist param to SeedUserFiles to encapsulate the
  "seed only for brand-new users" logic within the bootstrap package
- Extract getOrCreateUserSetup helper for clean per-user initialization
- Add bootstrap state tests covering all 4 system prompt branches
- Keep legacy EnsureUserFilesFunc as fallback for backward compatibility
2026-03-27 19:16:31 +07:00
viettranx 23c43259c9 fix(bootstrap): ensure per-user context files are seeded for all agent types
- Separate file seeding from workspace resolution so agents without
  workspace still get BOOTSTRAP.md and USER.md seeded
- Always seed context files for existing profiles that have zero files
  (handles EnsureUserProfile pre-creation via HTTP API)
- Add persistent "USER PROFILE INCOMPLETE" nudge in system prompt when
  BOOTSTRAP.md is cleaned up but USER.md remains blank
- Move bootstrap auto-cleanup nudge before session flush so the reminder
  is persisted to history
- Add userFilesSeeded sync.Map to avoid redundant seeding calls
- Capture workspace from seeding call to eliminate double DB roundtrip
2026-03-27 18:19:53 +07:00
viettranx 343ad0c2b1 fix(ui): remove USER_PREDEFINED from summoning, refine canvas dots, require team members
- Remove USER_PREDEFINED.md from summoning file list (web + desktop)
- Soften canvas-dots pattern (smaller dots, wider spacing)
- Require at least 1 member when creating a team
- Prevent removing the last non-lead member from team
2026-03-27 18:01:00 +07:00
viettranx 39ffe6e78f fix(teams): update post-turn comment to match simplified auto-complete logic 2026-03-27 17:18:43 +07:00
viettranx 3c1baecef5 feat(desktop): add Storage management tab in Settings
Browse, upload, download, move, and delete workspace files from the
desktop app. File tree with drag-and-drop move (@dnd-kit/core), syntax
highlighting (react-syntax-highlighter), markdown/CSV/image viewers,
upload dialog with drag-drop + validation, and SSE storage size streaming.
2026-03-27 17:16:29 +07:00
viettranx 5ed86b84c0 fix(teams): simplify post-turn task action fallback to auto-complete
The case expression `taskActionFlags.Progressed || ...` always evaluates
to `true/false`, never matching the switch value. Merge it into the
default branch so non-terminal actions consistently auto-complete.
2026-03-27 17:16:16 +07:00
viettranx 22dc87a262 fix(desktop): move version into Lite badge, remove check update button 2026-03-27 15:59:42 +07:00
viettranx 2f31db4c7e fix(vision): restore context fallback for read_image in file-ref mode
PR #511 removed WithMediaImages context in file-ref mode, breaking
read_image when LLM omits the path param. Restore base64 context as
fallback (costs Go memory, not LLM tokens). Also improve error messages
to distinguish missing provider config vs provider failures.
2026-03-27 15:59:42 +07:00
viettranx 7eea004c8d fix(bootstrap): predefined agents now reliably complete USER.md onboarding
- Strengthen FIRST RUN prompt: mandatory write_file calls, no deferring
- Filter BOOTSTRAP.md from system sessions (subagent/cron/heartbeat)
- Remove duplicate bootstrap reminder in buildProjectContextSection
- Fix template: proper tool-calling syntax, step-by-step instructions
2026-03-27 15:59:42 +07:00
Thieu NguyenandGitHub 30bf66d1da fix(docker): remove manual network creation causing Compose label mismatch (#513)
The Makefile `net` target creates goclaw-net via `docker network create`
without the `com.docker.compose.network` label. Docker Compose then rejects
the network on macOS Docker Desktop. Compose already manages this network
automatically with correct labels.

Closes #488
2026-03-27 15:58:34 +07:00
Duy /zuey/andGitHub 231bc9684e fix(vision): file-ref mode + media pipeline fixes for image visibility (#511)
* fix(vision): file-ref mode + media pipeline fixes for image visibility

Replace inline base64 image loading with file path references when
read_image provider is configured. LLM calls read_image(path=...)
instead of receiving 25K-250K tokens of base64 per image.

Changes:
- Agent loop: skip base64 context storage in file-ref mode, only
  load historical images for inline fallback
- New enrichImagePaths() enriches ALL user messages with file paths
  (not just current turn) so historical images are accessible
- System prompt: imperative tool summaries ("REQUIRED when you see
  <media:image> tags") + dedicated "Media Files" section
- Slack: store mediaPaths in pending history + CollectMedia on mention
- Feishu: add CollectMedia for group context history media
- RC-1 fix: save enriched content (with media IDs/paths) to DB
  instead of raw req.Message

Closes #509

* fix(vision): resolve Claude review — Feishu early media + skip loadImages in file-ref mode

- Feishu: download media BEFORE mention gate (step 4) and store file
  paths in pending history via Media field. Reuse early-resolved
  MediaInfo at step 10 to avoid double-download. CollectMedia now
  returns actual paths instead of empty.
- Agent loop: guard loadImages() behind !deferToReadImageTool so
  file-ref mode avoids unnecessary disk I/O + base64 encoding.
2026-03-27 14:20:05 +07:00
Kai (Tam Nhu) TranandGitHub 4dafd70c83 fix(ui): stop logout on method-level UNAUTHORIZED, align TTS route guard (#502)
ws-client.ts treated any UNAUTHORIZED WebSocket response as session
invalidation, triggering full logout. This caused clicking the TTS tab
to log users out because config.get requires owner role while the route
only required admin.

- Remove UNAUTHORIZED from onAuthFailure trigger in handleResponse;
  only TENANT_ACCESS_REVOKED forces logout now
- Change TTS route guard from RequireAdmin to RequireOwner (matches
  backend requireOwner on config.get/config.patch)
- Gate TTS sidebar item behind isOwner so non-owners don't see it

Closes #501
2026-03-27 13:43:25 +07:00
9e74974129 fix: feishu reply context truncation + task events NULL data crash (#508)
* fix(feishu): increase reply context max length from 500 to 2000

500 bytes is too short for CJK/Unicode text (each accented char = 2-3
bytes, so ~250 real characters). Increase to 2000 so reply context is
not aggressively truncated.

* fix(teams): handle NULL data column in task events queries

ListTaskEvents and ListTeamEvents crash with "unsupported Scan,
storing driver.Value type <nil> into type *json.RawMessage" when the
data column is NULL. Use COALESCE(data, '{}') to return an empty JSON
object instead.

---------

Co-authored-by: Luvu182 <208665161+Luvu182@users.noreply.github.com>
2026-03-27 13:42:31 +07:00
viettranx 1efec43df0 feat(desktop): show version + check update button in sidebar header 2026-03-27 13:37:38 +07:00
viettranx 2c94e8070f fix(desktop): image rendering for Windows paths and MEDIA: prefix
- toFileUrl: normalize backslashes, detect Windows drive-letter paths
- resolveFileUrl: strip MEDIA: prefix from tool results, Windows path support
- handleServe: skip prepending "/" for Windows drive-letter URL paths
2026-03-27 13:07:14 +07:00
viettranx 0292440c35 fix(desktop): make update banner action buttons easier to click 2026-03-27 12:33:10 +07:00
viettranx 622e405436 fix(desktop): default theme to light mode for fresh installs 2026-03-27 12:29:06 +07:00
viettranx 4102d4f321 fix(scripts): auto-launch app after install on macOS and Windows 2026-03-27 12:23:29 +07:00
viettranx 07f43cad36 fix(teams): persist leader media as DB attachments on task creation
Leader-created tasks copied media files to workspace and stored paths
in task metadata, but never inserted into team_task_attachments table.
Members got auto-attached via WorkspaceInterceptor context, but leaders
don't run inside a task context. Now explicitly call AttachFileToTask
after CreateTask succeeds. Dedup handled by ON CONFLICT DO NOTHING.
2026-03-27 12:18:01 +07:00
viettranx 5e936ebf8f feat(desktop): team settings modal, task detail attachments, shared icons
- Add TeamSettingsModal: editable name/description, member management
  (add/remove with minimum 1 member guard), notification toggles (5 events
  + direct/leader mode)
- Extend backend teams.update to support name/description fields
- Add gear button + "+" info button to team board header
- Task detail modal: fetch full detail with attachments on open,
  render attachment list with download links (resolved against local gateway)
- Chat view TaskPanel: clicking active tasks opens TaskDetailModal
- KanbanCard: show comment and attachment counts
- Extract 14 shared SVG icons to Icons.tsx, replace all inline SVGs
  in team components (0 remaining)
- Extract TERMINAL_STATUSES and TeamNotifyConfig to shared types
- i18n: en/vi/zh settings, members, notification, attachment keys
2026-03-27 12:18:01 +07:00
viettranx 865f724816 fix(team): improve leader task decomposition guidance for weaker models
Add concrete task sizing rules, skill-based split tests, and 3 decomposition
examples to TEAM.md so non-Claude leaders (Qwen, GPT, MiniMax) create
appropriately scoped tasks instead of monolithic ones. Soft warning in create
response when subject suggests compound deliverables.
2026-03-27 12:12:03 +07:00
viettranx 1c2dd4f1dd fix(gateway): resolve tenant switch mismatch for non-owner users
Non-owner tenant switch set only tenant_hint in localStorage, but WS
Path 1 non-owner and HTTP client only read tenant_id — causing silent
fallback to MasterTenantID.

Frontend: always set TENANT_ID on switch; keep TENANT_HINT for pairing compat.
Backend: WS Path 1 non-owner now falls back to TenantHint before deprecated TenantScope.
2026-03-27 12:07:14 +07:00
viettranx 9d2aeb7c9c fix(sqlitestore): add ListCodexPoolSpans stub for TracingStore interface 2026-03-27 10:50:55 +07:00
viettranx 6de054df33 build: update frontend asset references in index.html and add it to .gitignore. 2026-03-27 10:44:43 +07:00
viettranx f9f63f12a1 docs: update agent teams Section 7 to match task dispatch flow
Replace outdated spawn+team_task_id delegation docs with current
team_tasks(create, assignee) + dispatchTaskToAgent() auto-dispatch model.
2026-03-27 10:43:29 +07:00
viettranx ffb6786ea4 feat(telegram): lazy-resolve media from pending history on mention
When users send media in a group without mentioning the bot, store
Telegram file_ids as lightweight MediaRef in history entries (no
download). When the bot is mentioned, resolve refs by downloading
media and including them in the LLM context.

Safeguards: 5 MB file size cap, max 15 refs per mention, 30s batch
timeout. Mirrors existing CollectMedia pattern from Discord/Zalo.
2026-03-27 10:39:10 +07:00
viettranx 1fdc4d3228 fix(ci): use macos-14 for both arch builds (macos-13 deprecated) 2026-03-27 10:38:42 +07:00
viettranx 65e7eb8a5f docs: add wails dev command to CLAUDE.md 2026-03-27 10:34:58 +07:00
viettranx c43cd0fb5d docs: add desktop edition notes to CLAUDE.md
Desktop tech stack, build commands, edition system, WS param naming,
auto-update flow, release process, lite limits, tool gating, file
serving security model. Add sqliteonly build check to post-impl checklist.
2026-03-27 10:33:24 +07:00
viettranx c2cb37afcf fix(desktop): improve Windows install script error handling
- SilentlyContinue progress preference (10x faster download)
- try/catch on API + download calls with colored error messages
- Non-fatal shortcut creation (works without admin)
- Colored output for better UX
2026-03-27 10:32:10 +07:00
viettranx e5175a044a fix(desktop): install script pipefail on missing release
grep returns exit 1 when no lite-v* tags exist yet, which
pipefail propagates before the -z check. Add || true.
2026-03-27 10:31:03 +07:00
viettranx 74dc086a80 fix(providers): post-merge fixes for Codex OAuth pools (#450)
- fix Rules of Hooks violation in chatgpt-oauth-routing-section
- add stale-while-revalidate with atomic dedup for RouteEligibility
- move raw SQL from HTTP handler to TracingStore.ListCodexPoolSpans
- persist round-robin state in Registry shared counter
- extract duplicated frontend helpers to agent-display-utils
- split oversized frontend files (964→214 lines max)
- add GIN indexes for spans.metadata and sessions.metadata
- fix tenant-aware provider lookup in handleQuota
- separate empty-role vs error handling in resolveTenantHint
- scope pool validation to chatgpt_oauth providers only
- wrap buildEntries in useCallback for stable useMemo deps
- document OAuth concurrent auth limitation and RoleAdmin breaking change
2026-03-27 10:19:16 +07:00
viettranx b9c1731e31 feat(desktop): packaging, auto-update, CI/CD, and install scripts
- GitHub Actions: release-desktop.yaml builds macOS (arm64+amd64) + Windows
  on lite-v* tag push, creates DMG + tar.gz + zip GitHub Release assets
- Install scripts: install-lite.sh (macOS curl) + install-lite.ps1 (Windows PowerShell)
- Auto-update: internal/updater checks GitHub Releases, downloads + atomic
  app swap with path traversal guards, size limits, symlink handling
- UpdateBanner: thin notification bar with download progress + restart
- Wails bindings: CheckForUpdate, ApplyUpdate (server-cached, no URL from JS),
  RestartApp (graceful gateway shutdown before exit)
- AboutTab: dynamic version from backend via GetVersion()
- Windows build assets: icon.ico, info.json, wails.exe.manifest
- Makefile: desktop-dev, desktop-build, desktop-dmg targets
- README: Desktop Edition section with install commands + feature comparison
- .gitignore: desktop packaging artifacts, SQLite DB files, update backups

Security: HTTPS-only downloads, io.LimitReader on all extractions,
zip/tar path traversal validation, symlink target guard, no untrusted
URL from frontend (ApplyUpdate uses server-cached info).
2026-03-27 10:15:15 +07:00
Kai (Tam Nhu) TranandGitHub 30708ae79d feat(providers): support Codex OAuth pools with inherited routing defaults
* feat(auth): support named chatgpt oauth providers

- add provider-scoped ChatGPT OAuth routes and CLI support

- persist refresh tokens per provider and reject provider-type collisions

- wire provider OAuth setup flows in the dashboard and setup UI

Refs #448

* feat(agent): add chatgpt oauth account routing

- add agent other_config routing for manual and round-robin selection

- reuse routed provider resolution across resolver and pending loaders

- add router, parser, and agent advanced dialog coverage for multi-account use

Refs #448

* docs(api): describe chatgpt oauth routing

- document named-provider ChatGPT OAuth auth routes

- describe agent-side account routing and round-robin behavior

- update OpenAPI agent config schema and provider type enum

Refs #448

* fix(store): add missing agent key context helpers

* feat(ui): clarify chatgpt oauth account setup and routing

* docs(providers): align chatgpt oauth alias examples

* feat(agent): add codex pool activity dashboard

* fix(providers): harden codex oauth alias setup

* feat(codex-pool): improve routing dashboard UX

- redesign the Codex/OpenAI pool page around saved-pool checkpoints and live evidence

- add clearer selection, attention, and recent-proof states for pool members

- make the lower panels fill the remaining desktop viewport while staying responsive

* fix(store): resolve context helper merge duplication

* feat(oauth): add codex pool quota and observation APIs

- add quota inspection and observation endpoints for ChatGPT Subscription (OAuth) providers

- teach codex routing to surface pool activity, observation metadata, and quota-aware readiness

- extend tests and HTTP docs/OpenAPI for the new pool monitoring flows

* feat(web): add codex pool quota monitor and controls

- add provider quota fetching, readiness badges, and live routing evidence on the account pool page

- redesign pool setup and activity panels for multi-account management with localized copy updates

- keep the live monitor internally scrollable and compact the account cards for better viewport fit

* fix(web): clarify pool routing labels

- rename the recent request badge from Direct to Selected

- restore compact quota bars in the live pool cards

* feat(codex-pool): add runtime health dashboard

- derive per-provider success and failure health from routed Codex traces

- surface routing, quota, and recent request evidence in the pool UI

- align provider alias guidance and owner access with the dashboard role model

* docs(auth): document tenant scoping and key roles

* fix(auth): harden tenant and codex pool access control

* fix(providers): align codex pool runtime defaults

* feat(ui): tighten codex pool responsive layout

* feat(chatgpt-oauth): refine codex pool management UX

* feat(chatgpt-oauth): surface quota bars on provider pages

- add compact quota bars to Codex provider rows and provider detail

- fetch quota only for ready visible provider rows and ready detail aliases

- fix managed-member detail visibility and tighten provider locale copy
2026-03-27 09:35:57 +07:00
Viet TranandGitHub e183b459c9 feat: SQLite desktop edition — full desktop app with team tasks (#505)
* feat(store): add SQLite backend foundation with build-tag injection

Add sqlitestore package (//go:build sqlite) as alternative to PostgreSQL:
- pool.go: WAL mode, busy_timeout, 4 concurrent read connections
- helpers.go: ? param helpers, JSON array storage, nullable/update utils
- scope.go: tenant scope with ? placeholders (vs PG's $N)
- schema.sql: 1296-line flattened DDL from 29 PG migrations (51 tables)
- schema.go: embedded schema with transactional apply + version tracking
- factory.go: NewSQLiteStores() stub (stores wired in Phase 2)

Build-tag split for store initialization:
- cmd/gateway_stores_pg.go (//go:build !sqlite) — default PG-only
- cmd/gateway_stores_sqlite.go (//go:build sqlite) — runtime PG/SQLite switch
- cmd/gateway_setup.go: extracted wireTracingAndCron() shared helper

Config: GOCLAW_STORAGE_BACKEND + GOCLAW_SQLITE_PATH env vars.
Security: goclaw.db added to DenyPaths (exec, read_file, filesystem tools).

* feat(edition): add centralized edition package for feature tier limits

New internal/edition/ package — single source of truth for all edition limits:
- Edition struct with MaxAgents, MaxTeams, MaxChannels, KGEnabled, TeamFullMode, etc.
- Standard (default, all features) and Lite (desktop, 5 agents, 1 team) presets
- atomic.Pointer for thread-safe Current()/SetCurrent()

Wiring:
- cmd/gateway.go: GOCLAW_EDITION env override (lite/standard) at startup
- cmd/gateway_stores_sqlite.go: auto-set Lite when backend=sqlite
- /v1/edition HTTP endpoint for UI comparison modal (public, no auth)

* feat(sqlitestore): implement Phase 2A core stores + sqliteonly build tag

Implement 12 SQLite store backends (4200+ LOC) mirroring existing PG stores:
- SessionStore, AgentStore, ProviderStore, TracingStore, SnapshotStore
- ConfigSecretsStore, SystemConfigStore, TenantStore, HeartbeatStore
- BuiltinToolStore, BuiltinToolTenantConfigStore, SkillTenantConfigStore

All stores wired in factory.go. Remaining stores (Memory, Cron, Skills,
Teams, etc.) left nil — gateway handles gracefully.

Add sqliteonly build tag for PG-free desktop builds:
- go build .                  → PG only
- go build -tags sqlite .     → PG + SQLite (runtime switch)
- go build -tags sqliteonly .  → SQLite only (no pgx dependency)

Key SQLite adaptations:
- ? placeholders (not $N), json_extract/json_each/json_array_length
- DISTINCT ON → GROUP BY + Go dedup, ANY($1) → IN (?,?...)
- rows.Err() checks on all scan loops, execMapUpdateWhereTenant in helpers
- GetOrCreateUserProfile uses RowsAffected() instead of PG's xmax trick

* feat(sqlitestore): implement Phase 2B feature stores

Port 8 additional store backends to SQLite (19 new files, ~6000 LOC):

Cron: cron.go, cron_crud.go, cron_exec.go, cron_scheduler.go
  - Job scheduling with cache, ListDue, MarkRunning, MarkComplete

Skills: skills.go, skills_crud.go, skills_content.go, skills_grants.go
  - CRUD, grants, content management. LIKE search (no FTS/vector in Lite)

MCP: mcp_servers.go, mcp_servers_access.go, mcp_user_credentials.go
  - Server CRUD, agent/user grants, encrypted credentials

Channels: channel_instances.go, pairing.go, pending_messages.go, contacts.go
  - Channel management, device pairing, message queue, contact store

Teams: teams.go, teams_tasks.go, teams_tasks_lifecycle.go, teams_tasks_activity.go
  - Team/task CRUD, lifecycle transitions, activity log, progress tracking
  - JSON array for members/blocked_by (replaces PG text[])

Remaining nil stores: Memory, AgentLinks, KnowledgeGraph, Activity,
SecureCLI, APIKeys, ConfigPermissions — gateway handles gracefully.

* fix(sqlitestore): fix critical arg ordering + data races in Phase 2B stores

C1: ListTasks arg mismatch — limit+1 in userID slot, wrong results
C2: SearchTasks missing duplicate userID arg for (? = '' OR t.user_id = ?)
H3: cron_crud.go cacheLoaded written without mutex → use InvalidateCache()
H4: cron_exec.go discarded ExecContext error → log warning
H1: Add rows.Err() checks in cron_crud, cron_scheduler, cron_exec, pairing

* feat(sqlitestore): implement Phase 2C — Memory, Activity, APIKeys, ConfigPermissions

Complete remaining essential stores (6 new files, ~900 LOC):

Memory: memory.go, memory_docs.go, memory_search.go
  - Document/chunk CRUD, LIKE-based search (no vector in Lite edition)
  - Embedding methods return empty results gracefully

Activity: activity.go — simple activity logging
APIKeys: api_keys.go — API key CRUD with SHA-256 hash lookup
ConfigPermissions: config_permissions.go — permission rules with TTL cache

24/27 stores now wired. Only AgentLinks, KnowledgeGraph, SecureCLI
remain nil (disabled in Lite edition by design).

Total: 49 files, 11,435 LOC in internal/store/sqlitestore/

* fix(sqlitestore): fix variable shadow in GetDocument + handle chunk delete error

C1: GetDocument scopeClause used := inside if/else blocks, shadowing
outer err variable — query errors silently swallowed. Fixed by renaming
to tcErr matching PG pattern.

H1: IndexDocument chunk deletion ExecContext error was discarded, could
cause duplicate chunks. Now returns error on failure.

* feat(desktop): Phase 3 — Wails v2 desktop app shell with chat UI

Desktop app (ui/desktop/) using Wails v2 + React 19 + Tailwind CSS 4:

Go backend:
- main.go: Wails entry point with embedded frontend assets
- app.go: gateway embedding via goroutine, health check, Wails bindings
- keyring.go: OS keyring secrets with file fallback
- cmd/gateway_export.go: exports RunGateway() for desktop embedding

React frontend:
- WS v3 client: protocol handshake, exponential backoff, call queue
- Chat system: Zustand stores, RAF-batched streaming, 10 event handlers
- Components: MessageBubble, MarkdownRenderer (rehype-sanitize),
  CodeBlock, ToolCallBlock, ThinkingBlock, ActivityIndicator, InputBar
- Layout: AppShell (2-column), Sidebar with agent/session list, TopBar
- Onboarding wizard (5 steps): welcome, gateway, provider, agent, ready
- Magic Blue theme (dark/light), Inter + JetBrains Mono typography

Build: all 3 variants pass (PG, sqlite, sqliteonly)

* chore: ignore Wails build artifacts (wailsjs, build, package.json.md5)

* fix(desktop): correct onboarding provider list and agent creation API contract

- ProviderStep: expand from 3 to 16 providers in 4 groups (Popular, Cloud, Local, Regional)
  with correct provider_type values and api_base defaults
- AgentStep: fix API payload — use agent_key (slug), provider (name string),
  agent_type=predefined with description in other_config
- use-agents: fix field mapping — agent_key, display_name from backend response
- Clean up failed provider on verify error

* fix(desktop): add missing providers — Bailian Coding, Z.ai Coding, Ollama Cloud

* fix(desktop): match web dashboard brand colors + persist onboarding in store

- Replace Magic Blue theme with web dashboard's warm blue OKLCH palette
- Move onboarding state from localStorage to Zustand persist store
- Add "Run Setup Wizard" option in TopBar settings menu to re-trigger onboarding
- Fix light mode theme activation (explicit :root:not(.dark) overrides)

* fix(desktop): apply dark theme before first paint + better error messages

- Add class="dark" default on <html> + inline script to read persisted theme
  before React hydrate (prevents light flash on dark mode)
- Improve provider test error message for network failures

* feat(desktop): add GoClaw logo from web UI to onboarding + topbar

* fix(desktop): add Vite proxy for dev mode to avoid CORS gateway errors

- Proxy /v1, /ws, /health to localhost:18790 in Vite dev server
- Use relative URLs in dev mode (import.meta.env.DEV) so proxy handles CORS
- Production build uses direct gateway URL from Wails binding

* fix(desktop): GoClaw dock icon + fix duplicate provider slug on re-test

- Convert goclaw-icon.svg to 1024x1024 PNG for macOS dock icon
- Fix provider creation: handle existing slug by finding and updating
- Track build/appicon.png in git (exclude only build/bin/)

* fix(sqlitestore): UUID text/blob mismatch in scopeClause breaks all queries

scopeClause passed uuid.UUID (16-byte array) to SQLite ? placeholder,
but tenant_id column stores TEXT strings. SQLite compared BLOB vs TEXT
→ no match → all scoped queries returned empty results.

Fix: pass scope.TenantID.String() to ensure TEXT comparison.

Also includes:
- macOS dock icon (.icns from GoClaw logo)
- Onboarding auto-detect existing providers/agents
- Debug logging for token + API URL

* fix(desktop): CORS for dev mode + direct gateway URL

- Wails dev server (port 34115) doesn't proxy API calls, causing 405
- Frontend now connects directly to gateway URL from Wails binding
- Added GOCLAW_DESKTOP=1 env → enables CORS middleware on gateway
- desktopCORS wraps mux with Access-Control-Allow-* headers + OPTIONS
- Simplified provider test flow: list-then-create/update

* fix(desktop): split onboarding into 6 steps matching web UI flow

Web UI flow: create provider → select model + verify → create agent.
Desktop was incorrectly trying to verify before creating provider.

Changes:
- ProviderStep: now only creates/saves provider (no verify)
- NEW ModelVerifyStep: loads models from provider, test connection
- AgentStep: receives pre-selected model, shows read-only model field
- OnboardingWizard: 6 steps with auto-detect skip logic
- Auto-detect: has agents→Ready, has providers→ModelVerify, nothing→Provider

* feat(desktop): add Combobox component, use searchable model selector

- New Combobox: searchable dropdown with custom value support
- ModelVerifyStep: replace plain input/select with Combobox
- Models loaded from GET /v1/providers/{id}/models API
- Allows typing custom model name if API returns empty list

* fix(desktop): rename icon to iconfile.icns matching Wails convention

* refactor(desktop): overhaul UI/UX, fix onboarding, fix event handling

Desktop app major refactor:

UI/UX:
- Chat-focused layout with floating panels on dotted canvas
- Sidebar: agent list + sessions grouped by date (no resource counts)
- Modern input bar: rounded pill with attach/send buttons
- User bubble: card style matching web UI (not solid color)
- Thinking block: collapsible, max-height, proper label
- ErrorBoundary wrapping app
- Dock icon: regenerated with transparent bg + dark rounded frame

Onboarding:
- 3-step flow matching web UI (Provider → Model → Agent)
- Proper create vs update (check DB before POST)
- SetupStepper with step circles + connectors
- Agent presets from web UI (Fox Spirit, Artisan, Astrologer)
- Auto-detect existing setup via use-bootstrap-status hook

Event handling (verified from Go source):
- chunk: payload.content (not payload.chunk)
- thinking: payload.content (not payload.thinking)
- tool.call: payload.id/name (not toolId/toolName)
- tool.result: payload.is_error/content (not error field)
- run.completed: usage.prompt_tokens/completion_tokens
- New: block.reply, run.retrying handlers

Backend fixes:
- SQLite scanTime helper for modernc.org/sqlite text timestamps
- X-GoClaw-User-Id header in desktop API client (not X-User-ID)
- user_id: system (owner role in desktop single-user mode)
- CORS: allow X-GoClaw-User-Id header
- SQLite busy timeout: 5s → 10s
- Snapshot SQL: cross-DB compatible (FILTER→CASE, ::BIGINT→CAST)
- Promise.allSettled for bootstrap status (one fail doesn't block other)

* feat(desktop): chat polish, SQLite fixes, summoning modal, bootstrap guard

Chat Polish (Phase 1):
- ToolCallBlock: Wrench/Zap icons, phase badges, arg summary, grouped rendering
- ThinkingBlock: auto-expand on stream, Brain icon, cursor pulse
- MessageBubble: isStreaming prop, streaming cursor, grouped tool calls
- ImageLightbox: fullscreen overlay, gallery nav, keyboard shortcuts, download
- MediaBlock: grid layout, click-to-open lightbox, hover overlay
- ActivityIndicator: phase-specific icons (Brain/Wrench/RefreshCw)
- ChatCanvas: track lastAssistantId for streaming, EmptyState with prompts
- Filter [System] nudge messages and tool-role messages from chat history

SQLite Fixes:
- sessions_list: fix time.Time scan failure (3 sites) using sqliteTime scanner
- snapshots: fix ON CONFLICT expression mismatch with unique index
- snapshots: fix GetLatestBucket using nullSqliteTime
- pool: explicit PRAGMAs (busy_timeout=15s, WAL, synchronous=NORMAL)
- schema: seed master tenant (was missing, causing FK violations)
- schema: incremental migration framework (version-gated patches)

Onboarding:
- SummoningModal: port from web UI with framer-motion animations
- AgentStep: show summoning modal after create, continue button
- App: auto-detect empty DB and reset onboarded flag
- ChatCanvas: loading spinner while agent loads after onboarding

Bootstrap Guard:
- After auto-cleanup of BOOTSTRAP.md, check if USER.md is still empty
- Inject reminder if agent cleared BOOTSTRAP but didn't fill USER.md

Session Management:
- Load chat history on session click (was missing useEffect)
- Fix race condition: don't clear messages on session switch (atomic replace)
- SidebarFooter: center New Chat button text

* fix(desktop): session management, delete confirm, event listener race fix

- New Chat: only clears state, no empty session creation (sendMessage auto-creates)
- Delete session: hover X button with ConfirmDialog confirmation
- Event listener: use sessionKeyRef instead of closure to prevent stale events
- Remove "skip to dashboard" link from onboarding
- Add reusable ConfirmDialog + ConfirmDeleteDialog common components

* feat(desktop): settings view with tabbed layout (Phase 4)

- SettingsView: tab container with header, close button, canvas-dots bg
- SettingsTabBar: 9 tabs (Appearance, Providers, Agents, MCP, Skills, Tools, Cron, Traces, About)
- AppearanceTab: dark/light theme toggle, language + timezone placeholders
- AboutTab: version, edition limits, runtime info
- ui-store: activeView, settingsTab, openSettings(), closeSettings()
- AppShell: switch between chat and settings views
- SidebarFooter: gear icon opens settings (was "Run Setup Wizard")
- Keyboard: Cmd+, opens settings, Escape closes
- Branding: "GoClaw Lite" in sidebar header
- Agent status: online (green) instead of idle for desktop
- Tab content wrapped in solid bg card with border

* feat(desktop): provider management CRUD in settings (Phase 5)

- use-providers hook: list, create, update, delete, verify via HTTP API
- ProviderList: list view with Add button, empty state
- ProviderRow: status dot, type badge, edit/delete actions
- ProviderFormDialog: create/edit with type selector, masked API key, test connection
- Wire ProviderList into Settings Providers tab

* fix(desktop): remove Test Connection from provider form (requires model + provider ID)

* feat(desktop): agent management CRUD in settings (Phase 6)

- AgentData/AgentInput types matching web UI contracts
- use-agent-crud hook: list, create, update, delete, resummon (5 agent limit)
- AgentCard: emoji, status dot, provider/model/type badges, edit/delete/resummon
- AgentFormDialog: provider Combobox + model Combobox (from /v1/providers/{id}/models)
  - Create: agent_type selector, "Check & Create" verifies model before create
  - Edit: no type change, no re-verify needed
  - Personality textarea for predefined agents
- AgentList: grid, edition limit warning, create triggers SummoningModal
- Delete uses ConfirmDeleteDialog (type name to confirm)
- Sidebar agent list refreshes after CRUD

* feat(desktop): agent detail panel with full config (Phase 6 polish)

Agent detail panel (fullscreen overlay covering sidebar):
- PersonalitySection: emoji editor, display name, description, status select, default toggle, agent key display
- ModelBudgetSection: provider/model Combobox with verify-before-save, context window, max tool iterations
- EvolutionSection: self_evolve toggle with info callout (predefined agents only)
- Sticky save bar: backdrop blur, cancel/save buttons, spinner on save
- Save blocked if provider/model changed but not verified

AgentList: card click opens detail panel, create dialog separate
AgentFormDialog: create-only, Check & Create with verify

* fix(desktop): resummon confirm, summoning z-index, save bar UX

- Resummon requires confirm dialog before triggering
- SummoningModal z-index z-50 → z-[70] (above detail panel z-[60])
- Save bar: show error inline, "Verify model first" when blocked

* feat(desktop): agent detail quality polish — files tab, memory config, rich cards

Types (synced with web UI):
- AgentData: added owner_id, workspace, restrict_to_workspace, frontmatter, context_window, max_tool_iterations as required fields
- MemoryConfig, CompactionConfig interfaces
- BootstrapFile type for WS file operations

AgentCard (matching web UI agent-card.tsx):
- Star icon for default agent
- Animated pulse badge for summoning status
- Self-evolve sparkle indicator (orange when active)
- Frontmatter/expertise with line-clamp-3
- Context window display (e.g. "200K ctx")
- Safe emoji extraction, UUID name detection

AgentDetailPanel:
- Tab navigation: Overview + Files tabs
- Overview: Personality + ModelBudget + Memory + Evolution sections
- Files tab: WS-based file editor (agents.files.list/get/set)
  - File sidebar with selection
  - Textarea editor with dirty tracking
  - Save button with spinner
- Sticky save bar with backdrop blur (overview only)
- Resummon with confirm dialog

MemorySection (matching web UI memory-section.tsx):
- Enable/disable toggle
- 6 config fields: max_results, min_score, max_chunk_len, chunk_overlap, vector_weight, text_weight
- "Using global defaults" when disabled

* feat(desktop): agent files — hide USER/HEARTBEAT, add Edit with AI

- Hide USER.md, USER_PREDEFINED.md, HEARTBEAT.md from files tab (managed by bootstrap/cron)
- Add "Edit with AI" button → RegenerateDialog → POST /v1/agents/{id}/regenerate
- Auto-select first file on load
- Show file size in sidebar
- Pass agentId to files tab for regenerate API call

* fix(desktop): remove memory config section (no embedding in SQLite)

* fix(desktop): remove misleading bytes display from file sidebar

* fix(desktop): replace native checkboxes/selects with custom Switch + Combobox

- New Switch component matching Radix UI toggle style
- Replace all native <input type="checkbox"> with Switch in agent/provider forms
- Replace native <select> for status with Combobox
- All interactive elements have cursor-pointer

* fix(desktop): evolution callout colors — use opacity-based for both themes

* fix(desktop): global cursor-pointer for all interactive elements

* fix(desktop): improve dark mode contrast for text and status colors

- text-secondary: 0.62 → 0.68 lightness (better readability on dark bg)
- text-muted: 0.52 → 0.58 lightness (was below WCAG AA 4.5:1 minimum)
- success: 0.45 → 0.55 (green was too dim on dark bg)
- warning: 0.65 → 0.70 (slightly brighter)
- idle: 0.52 → 0.58 (match text-muted)

* fix(desktop): revert color values to exact web UI match (0.62/0.52/0.45)

* fix(desktop): agent card badge colors — match web UI badge variants exactly

* feat(desktop): add MCP servers + Builtin Tools settings tabs

Phase 7 implementation:

MCP Tab:
- Full CRUD with 5-server edition limit
- Form dialog with transport-conditional fields (stdio/SSE/streamable-http)
- Test Connection with inline success/error feedback
- Agent grants dialog (grant/revoke per agent)
- Tools discovery dialog (view server tools)
- KeyValueEditor with sensitive field masking (auth/token/secret)

Tools Tab:
- Category-grouped list of 41 seeded builtin tools
- Toggle enable/disable with optimistic update
- Specialized settings forms: web_fetch extractor chain, media provider chain
- Generic JSON editor fallback for other tools
- Provider/model Combobox selection for media tools

Common:
- RefreshButton component with 500ms min spin animation
- KeyValueEditor with password masking for sensitive keys

Fixes:
- SQLite builtin_tools scan: use scanTimePair() for timestamps
- Session click while in settings: now closes settings view
- Dark mode text contrast: bumped text-secondary/text-muted lightness
- Light mode text contrast: darkened text-secondary/text-muted
- Focus ring thickness: ring-2 → ring-1 globally
- Misleading "memory layering (Postgres)" log label

* feat(desktop): add Skills tab, agent skill grants, emoji avatar, agent form redesign

Skills:
- Skills settings tab with upload ZIP, toggle, delete, runtime check
- Agent skill grants section in agent detail panel (toggle per agent)
- SQLite SkillManageStore interface compliance fixes

Agent form:
- 2-column layout, wider modal (max-w-3xl)
- 6 personality presets (Fox Spirit, Artisan, Astrologer, Researcher, Writer, Coder)
- Separate Verify Model + Summon buttons
- Always predefined type (removed open option)

Fixes:
- SQLite time.Time scan: mcp_servers, mcp_grants, activity_logs
- Combobox portal with scroll/resize tracking
- AgentAvatar shows emoji from other_config
- uploadFile sends X-GoClaw-User-Id header + generic type
- isApiClientReady guard prevents ErrorBoundary crash
- Verify model field: valid (not success)

* fix(sqlitestore): comprehensive timestamp scan sweep + UI fixes

SQLite timestamp sweep (13 files, 25+ sites):
All time.Time direct scans replaced with sqliteTime/scanTimePair/nullSqliteTime.
Files: activity, teams, teams_tasks, teams_tasks_activity, config_permissions,
agents_access, tracing_spans, tracing_scan, channel_instances, tenants,
pending_messages, api_keys, heartbeat.

UI fixes:
- Agent switching: clear active session + chat when agent changes
- MCP table: vertical align middle on row cells

* fix(sqlitestore): fix json.RawMessage scan + sqliteVal for dynamic updates

- mcp_servers_access: scan json columns via string intermediates (SQLite
  TEXT → json.RawMessage incompatible, use string then convert)
- helpers: add sqliteVal() to auto-marshal map/slice/struct to JSON
  string in execMapUpdate/execMapUpdateWhereTenant — fixes agent save
  500 error when updating other_config, tools_config, etc.
- Add AgentMcpSection: toggle MCP server grants per agent in detail panel
- Clean up debug logging from McpGrantsDialog

* feat(desktop): add i18n (react-i18next) + toast system + language/timezone pickers

i18n:
- Install react-i18next + i18next
- Copy 12 web locale namespaces (en/vi/zh) + desktop.json namespace
- Create i18n/index.ts with browser language detection + localStorage persist
- Replace ~300 hardcoded strings across 40+ components with t() calls
- Language picker in ChatTopBar (top-right) + Settings > Appearance
- Timezone picker in ChatTopBar with search + Intl.supportedValuesOf fallback
- All 6 agent presets fully translated (vi/zh) with prompts from locale files
- Agent Key never translated (uses stable English slugs)

Toast:
- Zustand toast store (success/error/warning/default, 4s auto-dismiss)
- Toaster component (bottom-right, z-100, slide-in animation)
- Toast calls in all CRUD hooks (agents, providers, MCP, skills, tools)

* feat(desktop): add Cron Jobs + Traces settings tabs with syntax highlighting

Cron Jobs (Phase 8):
- WS RPC hook (cron.list/create/delete/toggle/run/runs)
- CronList table with schedule formatting, status badges, run/toggle/delete
- CronFormDialog with slug name, agent selector, 3-way schedule (every/cron/once)
- CronRunsDialog for execution history

Traces (Phase 9):
- HTTP REST hook (GET /v1/traces with pagination + agent filter)
- TraceList table with duration, tokens, spans, relative time
- TraceDetailDialog with metadata, collapsible input/output, flat span list
- Syntax-highlighted JSON/code previews via react-syntax-highlighter

* fix(sqlitestore): fix tracing scan — endTime *time.Time → nullSqliteTime

Both trace and span scan functions used *time.Time for nullable end_time
column, which fails on SQLite TEXT timestamps. Changed to nullSqliteTime
with Valid check before assigning pointer.

* fix(desktop): fix cron schedule type label — map 'at' kind to 'once' i18n key

* fix(desktop): prevent flash on cron/traces refresh — keep data while refetching

* feat(desktop): add file attachment rendering — FileButton + FilePreviewDialog

- FileButton: compact attachment button with emoji icon, filename, size, download
- FilePreviewDialog: modal with type-detected preview (image/video/audio/markdown/code/text)
- MarkdownRenderer: override a/img for /v1/files/ links → FileButton + resolved URLs
- MediaBlock: non-image files render as FileButton instead of plain links
- api.ts: add getBaseUrl() for file URL resolution

* fix(desktop): resolve file URLs in chat — toFileUrl for media_refs + relative paths

- use-chat: add toFileUrl() to convert raw paths to /v1/files/{basename} URLs
  for both run.completed media and history media_refs
- MarkdownRenderer: detect relative file paths (./path/file.ext) via isFileLink
  in addition to /v1/files/ links, resolve all to gateway URL

* fix(desktop): authenticated file serving — media cache + blob URLs

Security fix: all /v1/files/ requests now use Bearer auth via fetchFile().
No more raw <a href> or <img src> with unauthenticated file URLs.

- Add media-cache.ts (blob cache with 5-min TTL, dedup inflight fetches)
- Add use-media-url.ts hook (returns cached blob URL for authenticated media)
- Add AuthImage component (loads images via auth blob) + downloadFile helper
- Update MarkdownRenderer: file images use AuthImage, downloads use downloadFile
- Update FileButton: authenticated download via blob
- Update FilePreviewDialog: authenticated fetch for text/preview content
- Clean filename display (strip timestamps + query params)

* fix(desktop): fix file attachments — use media_refs.id for URL, auth all media

Root cause: media_refs from backend has {id, mime_type, kind} but no path/url.
The id IS the filename basename. Fixed toFileUrl to use ref.id as fallback.

Also: AuthImage for lightbox, authenticated audio/video in MediaBlock,
clean filename display (strip timestamps).

* fix(desktop): file serving, traces, and media rendering improvements

Backend:
- Store MediaRef.Path in loop_finalize for direct file serving
- Use full path (not basename) in gateway_managed event signing
- Add fuzzyMatchInDir for LLM-hallucinated filenames
- Add findInWorkspace support for agent dirs and ws/ directory
- Add POST /v1/files/sign endpoint for client-side URL signing
- Always save LLM span input_preview (not just verbose mode)
- Truncate previews from tail (keep recent context), limit 2000 chars
- Add exact filename hint to create_image/video/audio tool results

Desktop frontend:
- File attachments: FileButton, FilePreviewDialog, AuthImage with blob cache
- Media cache: sign URLs via API for non-ft URLs, Bearer auth fallback
- Download via Wails SaveFile binding (native Save As dialog)
- OpenFile + DownloadURL Wails Go bindings
- Traces: rewrite with span tree hierarchy, formatTokens (90.8K),
  formatDuration with start/end fallback, expandable spans
- Traces: export via DownloadURL, copy with checkmark state
- Code preview: JSON = oneDark syntax highlight, text = light pre block
- MarkdownRenderer: baseUrl prop for relative image resolution
- ImageLightbox: preventDefault on keyboard nav (no macOS beep)
- ErrorBoundary: reload instead of re-render on retry
- Combobox: compact sizing (py-1.5, text-sm)
- FileButton: fix nested button HTML violation

* feat(desktop): team tasks kanban board + edition policy + file preview fixes

Phase 11 implementation:

Backend:
- TeamActionPolicy interface — lite/full edition gating for team_tasks tool
- Filter blocked actions from schema enum + early guard in Execute()
- System prompt: edition-specific team member guidance
- Skip skill_manage/publish_skill registration + seeding in lite
- teams.create: require at least 1 member
- files.go: 2-layer path isolation (workspace boundary + tenant scope)

Desktop UI:
- Kanban board with 6 status columns + framer-motion layout animation
- Task detail modal with collapsible description/result sections
- Team create dialog with styled member checkboxes
- Sidebar: teams section with create button + Lite edition badge
- Chat TaskPanel: compact active tasks with real-time WS updates
- Real-time: debounced get-light fetch (300ms) + progress patch (1s)
- Edition comparison modal (Lite vs Standard feature table)
- Custom dropdown filter replacing native select
- i18n: teams namespace (en/vi/zh)

Fixes:
- WS params: camelCase (teamId, taskId, sessionKey) matching backend
- FileButton: span wrapper (HTML nesting) + createPortal for dialog
- FilePreviewDialog: defensive filename normalization for extension check
- use-chat: prevSessionRef init null — fix blank chat on view switch
- Scrollbar: 3px auto-hide
- Agent click in sidebar returns to chat view

* feat: Update frontend build assets, change the default agent thinking level to 'low', and update Go module dependencies.
2026-03-27 09:28:42 +07:00
0dab087fa3 feat(telegram): add yield mention mode for multi-bot group support (#471)
* feat(telegram): add yield mention mode for multi-bot group support

- Add "yield" mention_mode: bot responds to all messages unless another
  bot is explicitly @mentioned, enabling shared groups where bots coexist
- Skip messages from other bots (user.IsBot) in yield mode to prevent
  infinite cross-bot loops
- Enter mention gate for yield mode even when require_mention is false
- Add display_name to channel instance update allowlist
- Change default dev postgres port to 5444 to avoid conflicts

* fix(telegram): address yield mode review — pairing guard, mention check, naming

- Add pairing guard to bot-skip path in yield mode (prevent history
  recording in unpaired groups — matches existing security pattern)
- Check detectMention before skipping other bots' messages (allow
  cross-bot @commands like "@my_bot help" from another bot)
- Rename hasOtherBotMention → hasOtherMention (function yields on any
  @mention, not just bots — name now matches behavior)
- Remove dead MentionMode field from SlackConfig (no Slack handler uses it)
- Add mention_mode validation with warning log for unknown values

* fix(ui): swap mention_mode and require_mention field order

* fix(i18n): add translations for require_mention disabled hint

* fix(ui): apply mention_mode disabled hint to group override tab

* fix(i18n): improve mention_mode UI labels for clarity

Replace developer jargon (Strict/Yield) with user-friendly labels:
- "Mention Mode" → "Group Response Behavior"
- "Strict" → "Default (follow @mention setting)"
- "Yield" → "Multi-bot (respond unless another bot is @mentioned)"

---------

Co-authored-by: viettranx <viettranx@gmail.com>
2026-03-26 18:08:36 +07:00
viettranx 731a98221a fix(teams): gracefully handle task status races in progress/complete
- executeProgress: early-exit on terminal tasks using pre-fetched status,
  check TaskActionFlags before re-querying DB, auto re-assign on stale recovery
- executeComplete: handle already-completed/failed/cancelled gracefully,
  auto re-assign pending tasks reset by stale recovery ticker
- Increase taskLockDuration 30min→60min, heartbeat 5min (was 10min)
  for 12x safety margin against stale recovery race conditions
- Add diagnostic logging in UpdateTaskProgress when 0 rows affected
2026-03-26 18:00:09 +07:00
17a7359b1c fix(zalo): panic on sync.Map.CompareAndDelete with uncomparable CancelFunc (#491)
runQRFlow stored context.CancelFunc directly in sync.Map and called
CompareAndDelete on cleanup. Function types are not comparable in Go,
causing a runtime panic: "comparing uncomparable type context.CancelFunc".

Wrap CancelFunc in a *cancelEntry struct pointer so sync.Map can compare
by pointer identity. This preserves the original semantics: CompareAndDelete
only removes the entry if it still belongs to the current QR flow, not a
newer retry.

Co-authored-by: Tobi <thinhdev@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 15:03:54 +07:00
viettranx 9168e4b4a7 fix(skills): enforce tenant isolation in skill upload, versioning, and grants
- Inject WithTenantSlug into both HTTP (enrichContext) and WS (MethodRouter.Handle)
  context — previously WithTenantSlug was defined but never called, causing all
  non-master tenants to share the same filesystem path (data isolation breach)
- Scope GetNextVersion, GetNextVersionLocked, and CreateSkillManaged version
  queries by tenant_id to prevent cross-tenant version collision
- Make advisory lock tenant-aware (hash tenant_id + slug) so different tenants
  uploading the same slug don't contend on the same lock
- Add agent tenant_id validation in GrantToAgent to prevent cross-tenant grant
  injection
- Fix IsSystemSkill to filter by MasterTenantID only
- Fix StoreMissingDeps to work for both system and custom skills
2026-03-26 13:32:28 +07:00
viettranx b178f843c0 fix(channels): inject tenant scope in resolveAgentUUID for Telegram and Discord
GetByKey is fail-closed when tenant_id is missing from context, causing
all bot commands that resolve agents (/writers, /addwriter, /removewriter,
/reset, /tasks) to return "no agent" error.
2026-03-26 12:59:02 +07:00
viettranx 6a1e1b98f6 fix(providers): handle 127.0.0.1 in Docker rewrite and add Ollama host fallback
DockerLocalhost() now rewrites both localhost and 127.0.0.1 to
host.docker.internal. Ollama registerInMemory() defaults to
http://localhost:11434/v1 when APIBase is empty, matching startup code.
2026-03-26 12:47:47 +07:00
Duc NguyenandGitHub 19498bff79 fix(providers): register Ollama in-memory on HTTP create, Docker localhost rewrite (#483)
Closes #470. registerInMemory() skipped Ollama because APIKey was empty.
Add Ollama special case before the key guard (mirrors startup code).

When running in Docker, rewrite localhost → host.docker.internal so the
container can reach the host Ollama instance. Extract InDocker() and
DockerLocalhost() into config/runtime.go for reuse.

Add extra_hosts to docker-compose.yml for Linux compatibility.
2026-03-26 12:45:52 +07:00
Duc NguyenandGitHub 2445192819 fix(http): add missing fields to update allowlists (#479)
Channel display_name and MCP timeout_sec were silently dropped by
filterAllowedKeys, causing updates to return 200 OK without persisting.

Closes #463
2026-03-26 12:41:28 +07:00
viettranx f31b9ebb54 fix(ui): add loading state to trace stop button and reorder hooks
Prevent double-clicks on the stop button by tracking abort-in-progress
state. Move handleAbortRun below hook declarations for readability.
2026-03-26 12:41:12 +07:00
Kai (Tam Nhu) TranandGitHub 6959ea7479 feat(agent): exclude MCP bridge tools from read-only streak detector (#400)
MCP tools (mcp_*) are user-defined external integrations where
read-heavy workflows are expected and legitimate. The read-only
streak detector was designed for filesystem tool loops but caught
MCP tools in the default fallback, triggering false positives on
workflows like "query inbox + read 10 emails + summarize."

Treat mcp_* tools as neutral (same as exec/bash) since GoClaw
cannot determine whether an MCP tool is read or write.

Closes #399
2026-03-26 12:39:50 +07:00
Duc NguyenandGitHub 709d86c701 feat(ui): add stop button for running traces (#481)
* feat(ui): add stop button for running traces on traces page

Allows admins to abort running agent runs directly from the traces page,
useful for stopping channel-originated runs (Telegram, Discord, etc.)
without needing access to the chat page.

* style(ui): match stop button style to chat destructive button

* fix(ui): fix abort response handling and variable declaration order

- Check aborted field from chat.abort response for accurate feedback
- Move useTraces() before handleAbortRun to fix block-scoped variable error
- Add abortNotFound i18n key for when run already finished

* fix(ui): remove invalid pending status check, add cursor-pointer
2026-03-26 12:39:29 +07:00
viettranx 4d31fe0dda fix(workspace): fix file move bugs, migrate DnD to @dnd-kit
- Fix cross-scope move in team workspace "All" view (prevented invalid
  nested paths by detecting mismatched chat_id scopes)
- Add error toast on move failure instead of silent catch
- Auto-create destination subdirectories on move (os.MkdirAll)
- Add admin bypass for team workspace HTTP auth (matching RPC pattern)
- Clear stale activePath after move in storage page
- Migrate file tree DnD from native HTML5 to @dnd-kit with:
  - PointerSensor (distance=8 prevents accidental drags)
  - DragOverlay via portal (fixes offset in Radix Dialog)
  - Folder auto-expand on 800ms hover during drag
- Silent refresh after move to prevent tree flash/scroll loss
2026-03-25 22:17:33 +07:00
viettranx 31c41dac54 fix(skills): per-tenant skill toggle for non-master tenants
Skills page toggle was calling global /toggle endpoint (master-tenant-only),
returning 403 when owner switched to another tenant. Now uses per-tenant
override endpoints (PUT/DELETE /v1/skills/{id}/tenant-config) when scoped
to non-master tenant, matching builtin-tools page pattern.

- Add tenant_enabled merging to WS skills.list handler
- Add setTenantConfig/deleteTenantConfig to use-skills hook
- Add SkillTenantOverride component with badge + switch + reset
- Fix wrong MasterTenantID constant in both skills and builtin-tools pages
- Add i18n keys for en/vi/zh
2026-03-25 22:15:01 +07:00