Compare commits

...
Author SHA1 Message Date
shadow-testandClaude Opus 5 0aa8315514 CI: restore the MSI now that the 32-bit bundlers can resolve their paths
Build App / compute-version (pull_request) Successful in 3s
Build Container / build-container (pull_request) Successful in 32s
Build App / build-macos (pull_request) Successful in 2m26s
Build App / build-windows (pull_request) Successful in 4m51s
Build App / build-linux (pull_request) Successful in 6m11s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
Dropping the MSI did not help: makensis.exe is 32-bit like candle.exe
and failed the same way ("Unable to start child process, error 0x2").
The cause was WOW64 redirection sending 32-bit processes reading
C:\Windows\System32 to SysWOW64, where the toolset directory does not
exist.

The build VM now carries junctions from the SysWOW64 view of
systemprofile\AppData\Local\tauri and systemprofile\.cache to the
System32 originals. Verified on the runner: candle.exe reports WiX
3.14.1.8722 and makensis reports v3.11, both exiting 0 from the path
that previously failed.

Both targets build again, so the .msi comes back. Artifact collection
fails if either installer is missing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 22:34:59 -07:00
shadow-testandClaude Opus 5 fdc161fd9c CI: build NSIS only on Windows, dropping the MSI target
Build App / compute-version (pull_request) Successful in 17s
Build Container / build-container (pull_request) Successful in 1m22s
Build App / build-macos (pull_request) Successful in 2m22s
Build App / build-windows (pull_request) Failing after 4m41s
Build App / build-linux (pull_request) Successful in 5m51s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
WiX's candle.exe/light.exe are 32-bit. On a SYSTEM-run runner Tauri
caches WiX under C:\Windows\system32\config\systemprofile\..., and WOW64
redirection sends 32-bit processes to SysWOW64 where that directory does
not exist, so candle exits 0x80131700. Tauri aborts the whole bundle on
one target's failure, so the MSI was suppressing the NSIS installer too
and Windows produced no artifact at all.

NSIS is what the project already relies on for Windows upgrades. Drops
the .NET 3.5 gate, which existed only for WiX; keeps the MSVC step,
which is what makes the app link. Artifact collection now fails when no
installer is produced rather than tolerating an empty directory.

To restore the MSI, run the runner as a normal user and set
--bundles msi,nsis.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 22:24:42 -07:00
shadow-testandClaude Opus 5 763af91042 Revert: LOCALAPPDATA override does not move Tauri's WiX cache
Build App / compute-version (pull_request) Successful in 3s
Build Container / build-container (pull_request) Successful in 32s
Build App / build-macos (pull_request) Successful in 2m23s
Build App / build-windows (pull_request) Failing after 4m35s
Build App / build-linux (pull_request) Successful in 5m6s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
Rust's `dirs` crate resolves LOCALAPPDATA on Windows through
SHGetKnownFolderPath, which reads the process token rather than the
environment, so the override changed nothing and 32-bit candle.exe still
hit WOW64 redirection under the SYSTEM profile.

Removing it rather than leaving a plausible-looking non-fix in the
workflow.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 22:19:12 -07:00
shadow-testandClaude Opus 5 03384409e7 CI: keep the WiX toolset out of System32 so 32-bit candle.exe can run
Build App / compute-version (pull_request) Successful in 13s
Build Container / build-container (pull_request) Successful in 44s
Build App / build-macos (pull_request) Successful in 2m24s
Build App / build-windows (pull_request) Failing after 4m39s
Build App / build-linux (pull_request) Successful in 6m44s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
WiX's candle.exe/light.exe are 32-bit. A SYSTEM-run runner has
%LOCALAPPDATA% under C:\Windows\system32\config\systemprofile, where
Tauri caches the WiX toolset — and WOW64 redirection sends 32-bit
processes reading System32 to SysWOW64, which has no such directory. The
CLR then fails to start with 0x80131700 and Tauri reports only "failed
to run candle.exe".

Verified: the same binary and identity exits 0 from C:\wixtest and
0x80131700 from the systemprofile path.

Pointing LOCALAPPDATA outside System32 avoids redirection, needs no
stored credential, and is a no-op for runners already running as a
normal user.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 22:12:27 -07:00
shadow-testandClaude Opus 5 c6bb7fdf1d CI: fix the MSVC exit-code check and verify .NET 3.5 before bundling
Build App / compute-version (pull_request) Successful in 6s
Build Container / build-container (pull_request) Successful in 1m48s
Build App / build-windows (pull_request) Failing after 5m14s
Build App / build-linux (pull_request) Successful in 6m2s
Build App / build-macos (pull_request) Successful in 2m24s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
%VSEXIT% and %ERRORLEVEL% inside a parenthesised cmd block are
substituted at parse time, not run time, so the installer's real exit
code was never read. Uses delayed expansion now.

Also checks for the .NET 3.5 runtime before building: WiX candle.exe
needs it, and Tauri aborts the whole bundle when the MSI target fails,
which silently suppresses the NSIS installer too. Fails early with the
exact dism command rather than at bundle time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 21:50:15 -07:00
shadow-testandClaude Opus 5 ca0f944712 CI: install MSVC build tools on Windows runners that lack them
Build App / compute-version (pull_request) Successful in 4s
Build Container / build-container (pull_request) Successful in 30s
Build App / build-linux (pull_request) Successful in 5m24s
Build App / build-windows (pull_request) Failing after 15m29s
Build App / build-macos (pull_request) Successful in 2m24s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
build-windows failed on this PR with "linker `link.exe` not found",
while build-linux and build-container passed — the code was fine, the
runner environment was not.

The job installs Rust and Node conditionally but assumed the MSVC C++
toolchain was hand-provisioned. A runner without it registers normally,
advertises windows-latest, accepts the job, downloads the entire crate
graph and only then fails at link time. That also means a bare runner
coming online turns a job that would have queued for a capable machine
into a failed build.

Installs the VC++ workload when vswhere cannot find it, matching the
existing conditional Rust and Node steps. rustc locates MSVC through
vswhere and the registry rather than PATH, so no dev-shell activation is
needed. Installer exit 3010 (success, reboot pending) is treated as
success.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 19:36:14 -07:00
shadow-testandClaude Opus 5 7d00390e1f Add scheduled task creation, and stop a bad cron unscheduling everything
Build App / compute-version (pull_request) Successful in 4s
Build Container / build-container (pull_request) Successful in 9m35s
Build App / build-linux (pull_request) Successful in 5m35s
Build App / build-windows (pull_request) Failing after 2m26s
Build App / build-macos (pull_request) Successful in 2m49s
Build App / create-tag (pull_request) Skipped
Build App / sync-to-github (pull_request) Skipped
Completes the Automation tab: it could list, toggle, run, log and remove
tasks but not create them, so task creation still meant dropping to the
CLI. Adds add_scheduled_task and update_scheduled_task, plus a task
editor with cron presets and a plain-English reading of the expression.

Every field is free user text, so all of it goes to the scheduler as a
bare argv vector through bollard — no shell, no quoting. Validation is
shape-only rather than metacharacter scrubbing: length caps, no control
characters in single-line fields, no leading-dash name, absolute
working_dir. Verified by round-tripping a prompt containing
`; rm -rf /`, `$(id)`, backticks and newlines: it landed byte-for-byte
in the task JSON with nothing executed.

The scheduler CLI has no `edit`, so update is add-then-remove with the
add first — a rejected edit leaves the original intact. The new id is
surfaced in the editor rather than hidden.

Root-cause fix, and the more serious half of this commit:
triple-c-scheduler never validated --schedule, and rebuild_crontab
regenerates the entire crontab and pipes it to `crontab`, which rejects
the whole file if any line is malformed — with the error thrown away by
`2>/dev/null || true`. A single bad schedule therefore silently
unscheduled every other task in the container while reporting success.
Reproduced directly. It matters because the global CLAUDE.md tells
Claude to drive this CLI, so Claude could trigger it unprompted.

`add` now validates the expression and exits non-zero, and
rebuild_crontab reports a rejected crontab instead of swallowing it,
keeping the offending file for inspection. Verified against the real CLI
in this container: a bad schedule is refused without disturbing an
existing task's crontab entry, and `0 9 * * 1-5`, `*/30 * * * *`,
`0,30 8-17 * * *` and `0 0 1 1 *` are all still accepted. The Rust layer
validates independently, agreeing with vixie cron on 23 probed
expressions including `1/2` and `*/0` being invalid.

121 frontend tests, 44 Rust tests, both builds clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 12:20:52 -07:00
shadow-testandClaude Opus 5 cf3b021c72 Confirm before Reset, and rewrite the docs for the new UI
Reset is destructive in a way its name does not advertise:
rebuild_project_container deletes both project volumes, so it wipes the
claude login, anything installed in the container, and every saved
session transcript. It was a single unconfirmed click in the overflow
menu, while the comparably destructive Remove already confirmed. Adds
ConfirmResetModal, which names each loss and says explicitly that the
host-side mounted folders are untouched.

Docs: the user guides still described the pre-Project-Home UI. Sixteen
factually wrong statements corrected, including "expand the Config
panel" (six sites), the actions table (Reset and Remove are in an
overflow menu, Files is a tab), a progress modal that no longer exists,
a double-click-to-rename gesture ProjectRow never had, the Full
Permissions boolean, an incomplete reserved-env list, and the claim in
TECHNICAL.md that OAuth tokens survive a Reset. Both layout diagrams and
the project tree were rebuilt from the filesystem.

New sections cover permission modes with the exact CLI mapping, Project
Home, Sessions, capability tiles, Automation, shared authentication, the
Auth Bridge and its security posture, and keyboard shortcuts.

Known gap recorded rather than papered over: the Automation tab manages
existing scheduled tasks but cannot create them — no add command is
registered — so task creation remains `triple-c-scheduler add` in the
terminal.

87 frontend tests, 34 Rust tests, both builds clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 12:02:35 -07:00
shadow-testandClaude Opus 5 d95ba54a69 Add shared-auth-token UI and make cancelling actually cancel
UI for the shared Claude token: a Settings section showing token state
with Authenticate and Revoke, an acquisition modal built on the shared
Modal (sign-in link handed to the host browser via the opener plugin,
plus the code input that answers `setup-token`'s stdin prompt — the flow
cannot complete without it), and a per-project opt-out toggle shown only
for the Anthropic backend.

Cancellation: acquire_claude_token previously had only two exits,
completion and a 15-minute timeout, and held the single-flight guard for
the whole time. Closing the dialog therefore locked the user out of
retrying for up to 15 minutes. Adds cancel_claude_token, backed by a
oneshot claimed and released in lockstep with the input guard, selected
on in the run loop so it wins the race and tears the exec down. The
dialog's Cancel now calls it and closes either way.

Also refreshes CLAUDE.md, which had drifted: it documented the deleted
ProjectCard, and asserted that new IPC commands need permission grants
in capabilities/default.json — they do not, that file covers plugin
commands only. Adds the conventions that would otherwise bite:
container_needs_recreation() is purely label-based and never diffs env,
so container-affecting state needs its own label; and #[serde(default)]
on a bool yields false regardless of intent.

Corrects the claim that Reset preserves credentials. Reset calls
remove_project_volumes, which deletes both the home and claude-config
volumes, so it wipes ~/.claude, the OAuth token, installed skills and
session transcripts.

84 frontend tests, 34 Rust tests, both builds clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 11:49:03 -07:00
shadow-testandClaude Opus 5 01a2f6aec8 Add Project Home, Auth Bridge, shared auth token, and Tier-1 polish
Project Home (DESIGN-REVIEW §B2): the project is promoted from a 280px
sidebar card to a first-class main-area view. ProjectCard.tsx (1,257
lines) is replaced by a select-only ProjectRow plus tabs for Overview,
Sessions, Automation, Config and Files. The PortMappings, FileManager
and ContainerProgress modals are absorbed rather than reimplemented.
Config gains a Saved/Saving/Failed indicator — save-on-blur failures
previously reached only console.error.

Tier-1 polish (DESIGN-REVIEW §A): new elevation, muted-accent, disabled
and focus-ring tokens; a global :focus-visible ring with every
focus:outline-none removed; filled buttons moved to --accent-emphasis
and white-on-success toggles retired, fixing three WCAG AA failures
(2.1:1, 2.5:1, 2.4:1); a shared Modal primitive with role="dialog",
focus trap and restore, adopted by all remaining modals; status
indicators that carry a glyph and word rather than colour alone.

Ctrl+Shift+W closes a tab, deliberately not Ctrl+W — that is readline's
kill-word, used constantly in the terminal this app is built around.

Auth Bridge: a general loopback-callback bridge so browser logins run
inside a container (aws sso login, Concourse fly login, claude login)
can complete against the host browser. Listeners are discovered from
/proc/net/tcp{,6} — ss/netstat/lsof are absent from the image — bound on
host 127.0.0.1 only, and tunnelled in over the Docker API via socat,
which keeps working on Docker Desktop where container IPs are not
routable. Falls back to [::1] because Node resolves localhost to IPv6
first, so claude login often binds ::1 alone. Opt-in per project.

This extracts create_attached_exec() and moves the existing terminal
session path onto it, so there is one attached-exec implementation
rather than two.

Shared auth token: `claude setup-token` is run in a container, the token
is stored in the OS keychain and injected as CLAUDE_CODE_OAUTH_TOKEN
into Anthropic-backend projects. Contrary to the initial design note,
setup-token uses an Anthropic-hosted redirect and blocks on a stdin
paste prompt rather than a loopback callback, so a stdin command is
required for the flow to complete.

The token is never logged, never returned to the frontend, and is
redacted from the streamed output with a stateful matcher that withholds
any tail that could still grow into a secret. Change detection uses a
random rotation id rather than a hash, since a hash in a docker-inspect
readable label would be an offline verification oracle.

Frontend 33 -> 51 tests; Rust 34 tests. Both builds clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 11:35:42 -07:00
shadow-testandClaude Opus 5 f68d10d5c2 Add DESIGN-REVIEW.md and ROADMAP.md
DESIGN-REVIEW.md is Fable's review of the v0.3.0 UI: token gaps and three
WCAG AA contrast failures, the modal/accessibility audit, and an IA
proposal that promotes the project from a sidebar card to a tabbed
main-area view.

ROADMAP.md covers Claude Code feature coverage — the five settings.json
keys currently surfaced, the gaps worth closing, the ones deliberately
skipped, the authentication handoff design, and phase sequencing.

Also published as an artifact for easier reading.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:56:26 -07:00
shadow-testandClaude Opus 5 0ac4e5030c Add permission modes and container introspection backend
Permission modes: replaces the binary full_permissions flag with a
PermissionMode enum (Plan/Default/AcceptEdits/Bypass). Flag mapping is
defined once in PermissionMode::cli_args() and used by the terminal, the
web terminal, and the scheduler:
  Plan        -> --permission-mode plan
  Default     -> (no flag)
  AcceptEdits -> --permission-mode acceptEdits
  Bypass      -> --dangerously-skip-permissions
Choices verified against `claude --permission-mode` on 2.1.226.

full_permissions is retained and effective_permission_mode() falls back
to it, so existing projects.json needs no migration.

Bug fix: triple-c-task-runner ran `claude -p ... --dangerously-skip-
permissions` unconditionally, ignoring the project's setting entirely.
It now reads TRIPLE_C_PERMISSION_MODE, which is injected into the
container, added to the reserved env blocklist, propagated through the
entrypoint's cron env filter, and tracked by a new
triple-c.permission-mode label so a change forces recreation.

Introspection: new commands/inspect_commands.rs exposes read-only views
into the container over docker exec — Claude sessions (parsed from
~/.claude/projects/<cwd>/<uuid>.jsonl), installed capabilities (skills,
agents, commands, hooks, plugins, natively-configured MCP servers), and
the triple-c-scheduler task list, logs and notifications.

Task/session ids are validated against a strict allowlist and every
parameterized call runs as a bare argv vector via bollard, so no shell
is involved. Stopped containers return empty results rather than errors.

No UI yet; that lands with the Project Home view.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:51:34 -07:00
shadow-testandClaude Opus 5 d0bb631d4d Remove MCP backend, entrypoint injection, and docs; add migration shim
Completes the removal begun in the previous commit.

Backend: deletes models/mcp_server.rs, storage/mcp_store.rs and
commands/mcp_commands.rs, the McpStore on AppState, the four IPC
handlers, Project::enabled_mcp_servers, build_mcp_servers_json(),
compute_mcp_fingerprint(), the MCP_SERVERS_JSON env injection, the
mcp-fingerprint label, and the whole MCP container lifecycle.
create_container() and container_needs_recreation() lose their
mcp_servers/network_name parameters.

Container: entrypoint.sh no longer merges MCP_SERVERS_JSON into
~/.claude.json. MCP_SERVERS_JSON stays in the reserved env blocklist.

Security: the Docker socket is no longer auto-mounted for stdio+Docker
MCP servers — it now mounts only when allow_docker_access is set.

Migration: old containers were created with
network_mode=triple-c-net-<projectId> and refuse to start once that
network is gone. docker/network.rs becomes docker/legacy_cleanup.rs with
label-driven, best-effort removal of leftover MCP containers and the
per-project network, called on both delete and recreate.
container_needs_recreation() now forces a rebuild for any container
carrying a non-empty triple-c.mcp-fingerprint label or attached to a
triple-c-net-* network, moving it onto the default bridge. Both can be
dropped a release later.

Docs: drops the MCP sections from README/HOW-TO-USE/TECHNICAL and adds a
short note pointing at Claude Code's native `claude mcp` / `/mcp` /
.mcp.json instead.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:31:18 -07:00
shadow-testandClaude Opus 5 657c61939f Remove MCP tab and per-project MCP UI from frontend
Claude Code manages MCP natively now (`claude mcp add/list/remove`,
`.mcp.json`, `/mcp`), so Triple-C's own MCP server library is redundant.

Deletes components/mcp/, hooks/useMcpServers.ts, the MCP sidebar tab and
rail icon, the per-project enable checkboxes on ProjectCard, the
mcpServers slice of the Zustand store, the four IPC wrappers, and the
McpServer/McpTransportType types.

Rust backend is untouched in this commit; the commands simply become
unreachable. Backend removal and the legacy container/network cleanup
follow separately.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 10:04:25 -07:00
jknapp 401e28a658 Merge pull request 'Fix conflicting --global/--file flags in entrypoint git config' (#12) from fix/entrypoint-gitconfig-flags into main
Build Container / build-container (push) Successful in 2m47s
2026-07-27 14:16:17 +00:00
shadow-testandClaude Opus 5 7c39e3cf11 Fix conflicting --global/--file flags in entrypoint git config
Build Container / build-container (pull_request) Successful in 10m15s
git rejects `--global` and `--file` together ("error: only one config
file at a time"), so the credential helper and user.name/user.email
were never written — /home/claude/.gitconfig was left nonexistent and
containers had no git identity or HTTPS token helper.

Drop `--global` and keep `--file /home/claude/.gitconfig`, which is the
intended target: the entrypoint runs as root at that point, so
`--global` would have resolved to /root/.gitconfig, and the existing
`chown claude:claude /home/claude/.gitconfig` already assumes the
--file path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 06:05:06 -07:00
jknapp ccdfc52dce Merge pull request 'docs: document terminal layout & StatusBar control gotchas' (#11) from docs/terminal-layout-gotchas into main 2026-07-19 16:26:02 +00:00
shadow-testandClaude Opus 4.8 2e661979ea docs: document terminal layout & StatusBar control gotchas
Capture the non-obvious implementation gotchas from PR #7
(terminal-layout-statusbar) in TECHNICAL.md: wrapper-vs-host xterm
padding, global StatusBar controls, recordingSessionIdRef transcript
pinning, active-only Jump-to-Current state, and the Zustand
object-merge rule for publishing action callbacks.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 09:12:54 -07:00
jknapp 59d89bcd1b Merge pull request 'Rename backup archive root so extraction dir mode isn't clobbered' (#10) from fix/backup-root-dir-mode into main
Build App / compute-version (push) Successful in 4s
Build App / build-macos (push) Successful in 2m21s
Build App / build-windows (push) Successful in 4m35s
Build App / build-linux (push) Successful in 5m1s
Build App / create-tag (push) Successful in 4s
Build App / sync-to-github (push) Successful in 10s
2026-07-01 13:35:02 +00:00
shadow-testandClaude Opus 4.8 26adccce5b Rename backup archive root so extraction dir mode isn't clobbered
Build App / compute-version (pull_request) Successful in 4s
Build App / build-macos (pull_request) Successful in 2m14s
Build App / build-windows (pull_request) Successful in 4m26s
Build App / build-linux (pull_request) Successful in 5m0s
Build App / create-tag (pull_request) Has been skipped
Build App / sync-to-github (pull_request) Has been skipped
The transform used `s,^\./,workspace/,`, which rewrites the workspace
*contents* (`./foo` -> `workspace/foo`) but leaves tar's root member as a
bare `./`. That `./` entry carries the source root's mode/mtime, and on
extraction tar stamps them onto the extraction directory itself.

Match the leading `.` instead (`s,^\.,workspace,`) so the root member is
renamed `./` -> `workspace`, giving the archive a proper `workspace/`
directory entry and no bare `./`. The extraction directory is left
untouched. Contents, hidden files, excludes, symlink targets and the
`flags=rh` hardlink handling are unchanged.

Verified in-container: archive top level is exactly `workspace/` +
`home-claude/`, no `./` member, node_modules excluded, extraction into a
0755 dir leaves it 0755, workspace/.git preserved.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 06:33:02 -07:00
jknapp 876ba8a8fc Merge pull request 'Nest workspace under workspace/ in project backup' (#9) from fix/backup-workspace-nesting into main
Build App / compute-version (push) Successful in 2s
Build App / build-macos (push) Successful in 2m22s
Build App / build-windows (push) Successful in 4m36s
Build App / build-linux (push) Successful in 5m5s
Build App / create-tag (push) Successful in 3s
Build App / sync-to-github (push) Successful in 12s
2026-07-01 13:23:08 +00:00
shadow-testandClaude Opus 4.8 5cd528a4ef Use flags=rh so intra-workspace hardlinks survive the transform
Build App / compute-version (pull_request) Successful in 3s
Build App / build-macos (pull_request) Successful in 2m15s
Build App / build-windows (pull_request) Successful in 4m24s
Build App / build-linux (pull_request) Successful in 5m3s
Build App / create-tag (pull_request) Has been skipped
Build App / sync-to-github (pull_request) Has been skipped
Review caught that `flags=r` disables rewriting of both symlink AND
hardlink target names. Leaving symlink targets alone is intended, but a
hardlink's stored target is an archive-internal reference to another
member's name — when member names become `workspace/...` but the
hardlink target stays `./hard_link`, extraction fails hard:

  tar: workspace/file.txt: Cannot hard link to './hard_link':
       No such file or directory

`flags=rh` rewrites regular member names and hardlink target names
together (keeping the pair consistent) while still leaving symlink
targets untouched. Verified in-container: extract exit 0, symlink target
preserved, hardlink pair shares one inode, nesting under workspace/ intact.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 06:22:14 -07:00
shadow-testandClaude Opus 4.8 c3fc029b1d Nest workspace under workspace/ in project backup
Build App / compute-version (pull_request) Successful in 4s
Build App / build-macos (pull_request) Successful in 2m17s
Build App / build-linux (pull_request) Successful in 5m7s
Build App / build-windows (pull_request) Successful in 5m9s
Build App / create-tag (pull_request) Has been skipped
Build App / sync-to-github (pull_request) Has been skipped
The backup archive placed the workspace at the archive root (`./...`)
while the sanitized home config sat under `home-claude/`. On extraction
the workspace files scattered loose into the extraction directory and
only `home-claude/` showed up as a distinct folder, so the backup read
as "config only, workspace missing" — and some archive viewers didn't
surface the root-level entries at all.

Add `--transform='flags=r;s,^\./,workspace/,'` so the workspace nests
under `workspace/`, parallel to `home-claude/`. `flags=r` scopes the
rewrite to member names only, leaving symlink targets (relative and
absolute) intact. Excludes still match the pre-transform names.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 06:18:08 -07:00
jknapp dc253e8da0 Merge pull request 'Fix backend-switch AWS auth + add /workspace backup and terminal file drag-and-drop' (#8) from fix/backend-switch-aws-creds into main
Build App / compute-version (push) Successful in 3s
Build Container / build-container (push) Successful in 34s
Build App / build-macos (push) Successful in 2m23s
Build App / build-windows (push) Successful in 3m14s
Build App / build-linux (push) Successful in 6m22s
Build App / create-tag (push) Successful in 5s
Build App / sync-to-github (push) Successful in 10s
2026-06-30 22:20:00 +00:00
120 changed files with 14312 additions and 4737 deletions
+53 -3
View File
@@ -357,6 +357,44 @@ jobs:
(Get-Content app/src-tauri/Cargo.toml) -replace '^version = ".*?"', "version = `"$version`"" | Set-Content app/src-tauri/Cargo.toml (Get-Content app/src-tauri/Cargo.toml) -replace '^version = ".*?"', "version = `"$version`"" | Set-Content app/src-tauri/Cargo.toml
Write-Host "Patched version to $version" Write-Host "Patched version to $version"
- name: Install MSVC C++ build tools
shell: cmd
run: |
rem Tauri links with MSVC, so rustc needs link.exe and the Windows SDK.
rem This job previously assumed a hand-provisioned runner; a runner
rem without them registers fine, advertises windows-latest, accepts the
rem job, downloads the whole crate graph and only then fails at link
rem time with "linker `link.exe` not found".
rem
rem rustc finds MSVC via vswhere and the registry rather than PATH, so
rem installing is enough - no dev-shell activation needed here.
rem
rem Delayed expansion is required: %VAR% inside a parenthesised block
rem is substituted when the block is PARSED, not when it runs, so both
rem %ERRORLEVEL% and %VSEXIT% would read as their pre-block values.
setlocal enabledelayedexpansion
set "VCPATH="
set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
if exist "%VSWHERE%" (
for /f "usebackq delims=" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VCPATH=%%i"
)
if defined VCPATH (
echo MSVC build tools already present at !VCPATH!
) else (
echo MSVC build tools not found - installing Visual Studio Build Tools
curl -fSL -o "%TEMP%\vs_BuildTools.exe" https://aka.ms/vs/17/release/vs_BuildTools.exe || exit /b 1
"%TEMP%\vs_BuildTools.exe" --quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended
set "VSEXIT=!ERRORLEVEL!"
del "%TEMP%\vs_BuildTools.exe" 2>nul
rem 3010 means installed, reboot pending - a success for our purposes.
if not "!VSEXIT!"=="0" if not "!VSEXIT!"=="3010" (
echo Visual Studio Build Tools installer failed with exit code !VSEXIT!
exit /b 1
)
echo Visual Studio Build Tools installed
)
endlocal
- name: Install Rust stable - name: Install Rust stable
run: | run: |
where rustup >nul 2>&1 && ( where rustup >nul 2>&1 && (
@@ -416,14 +454,26 @@ jobs:
TAURI_CONFIG: "{\"build\":{\"beforeBuildCommand\":\"\"}}" TAURI_CONFIG: "{\"build\":{\"beforeBuildCommand\":\"\"}}"
run: | run: |
set "PATH=%USERPROFILE%\.cargo\bin;C:\Program Files\nodejs;%PATH%" set "PATH=%USERPROFILE%\.cargo\bin;C:\Program Files\nodejs;%PATH%"
cargo tauri build rem Every Tauri bundler it downloads - candle.exe, light.exe and
rem makensis.exe - is 32-bit. A runner running as SYSTEM has
rem %LOCALAPPDATA% under C:\Windows\system32\config\systemprofile, and
rem WOW64 redirection sends 32-bit processes reading System32 to
rem SysWOW64, so they cannot see their own directory: candle exits
rem 0x80131700 and makensis reports "Unable to start child process,
rem error 0x2".
rem
rem The build VM carries junctions from the SysWOW64 view of
rem systemprofile\AppData\Local\tauri and systemprofile\.cache to the
rem System32 originals, which makes the redirected view resolve. A
rem runner running as a normal user needs no such patch.
cargo tauri build --bundles msi,nsis
- name: Collect artifacts - name: Collect artifacts
run: | run: |
set "PATH=%USERPROFILE%\.cargo\bin;C:\Program Files\nodejs;%PATH%" set "PATH=%USERPROFILE%\.cargo\bin;C:\Program Files\nodejs;%PATH%"
mkdir artifacts mkdir artifacts
copy app\src-tauri\target\release\bundle\msi\*.msi artifacts\ 2>nul copy app\src-tauri\target\release\bundle\msi\*.msi artifacts\ || exit /b 1
copy app\src-tauri\target\release\bundle\nsis\*.exe artifacts\ 2>nul copy app\src-tauri\target\release\bundle\nsis\*.exe artifacts\ || exit /b 1
dir artifacts\ dir artifacts\
- name: Upload to Gitea release - name: Upload to Gitea release
+58 -8
View File
@@ -56,22 +56,56 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
### Frontend Structure (`app/src/`) ### Frontend Structure (`app/src/`)
- **`store/appState.ts`** — Single Zustand store for all app state (projects, sessions, UI) - **`store/appState.ts`** — Single Zustand store for all app state (projects, sessions, UI). The
main area is a single ordered tab strip holding two tab kinds, keyed `term:<id>` and
`home:<id>`; `activeSessionId` is *derived* from `activeTabKey` so exactly one thing is current.
- **`hooks/`** — All Tauri IPC calls are encapsulated in hooks (`useTerminal`, `useProjects`, `useDocker`, `useSettings`) - **`hooks/`** — All Tauri IPC calls are encapsulated in hooks (`useTerminal`, `useProjects`, `useDocker`, `useSettings`)
- **`lib/tauri-commands.ts`** — Typed `invoke()` wrappers; TypeScript types in `lib/types.ts` must match Rust models - **`lib/tauri-commands.ts`** — Typed `invoke()` wrappers; TypeScript types in `lib/types.ts` must match Rust models
- **`components/terminal/TerminalView.tsx`** — xterm.js integration with WebGL rendering, URL detection for OAuth flow - **`components/terminal/TerminalView.tsx`** — xterm.js integration with WebGL rendering, URL detection for OAuth flow
- **`components/layout/`** — TopBar (tabs + status), Sidebar (project list), StatusBar - **`components/layout/`** — TopBar, MainTabs (the unified tab strip), Sidebar, StatusBar
- **`components/projects/`** — ProjectCard, ProjectList, AddProjectDialog - **`components/projects/`** — `ProjectRow` (select-only list row), `ProjectList`, `AddProjectDialog`,
- **`components/settings/`** — Settings panels for API keys, Docker, AWS, Web Terminal and the editors reused by Project Home
- **`components/projects/home/`** — **Project Home**, the main-area view for a project:
Overview / Sessions / Automation / Config / Files. Per-project configuration lives here, not in
modals — see "UI conventions" below.
- **`components/settings/`** — Host-level settings: Docker, AWS, Web Terminal, STT, shared auth
- **`components/ui/`** — Shared primitives. **Use these; do not hand-roll replacements.**
`Modal` (the only correct way to build a dialog — it supplies `role="dialog"`, `aria-modal`,
focus trap and restore), `Button`, `Toggle`, `Field`, `SegmentedControl`, `StatusIndicator`,
`SaveIndicator`, `OverflowMenu`, `ToastHost`, `Tooltip`
### UI conventions
- **Project config belongs in Project Home's Config tab, not a modal.** Modals are reserved for
short, genuinely modal tasks (add project, confirm removal, token acquisition). The app
previously had ~12 hand-rolled modals; they were consolidated deliberately.
- **Never bypass the design tokens.** All colour comes from CSS custom properties in `index.css`.
Filled buttons use `--accent-emphasis` (not `--accent`, which fails WCAG AA against white).
Use `--text-disabled` rather than `disabled:opacity-50`.
- **Never write `focus:outline-none`.** A global `:focus-visible` ring is defined in `index.css`.
- **Status must not be encoded in colour alone** — `StatusIndicator` pairs a glyph with a word.
- Keyboard: `Ctrl+T` new terminal, `Ctrl+Shift+W` close tab, `Ctrl+Tab` cycle, `Ctrl+1..9` jump.
`Ctrl+W` is intentionally left alone — it is readline's `kill-word` inside the terminal.
### Backend Structure (`app/src-tauri/src/`) ### Backend Structure (`app/src-tauri/src/`)
- **`commands/`** — Tauri command handlers (docker, project, settings, terminal). These are the IPC entry points called by `invoke()`. - **`commands/`** — Tauri command handlers. These are the IPC entry points called by `invoke()`.
Beyond docker/project/settings/terminal: `inspect_commands.rs` (read-only views into a
container — Claude sessions, installed capabilities, scheduler tasks), `auth_bridge_commands.rs`,
`auth_token_commands.rs`.
- **`auth_bridge/`** — Host-side loopback bridge so browser logins run *inside* a container can
complete against the host browser. Discovers listeners by parsing `/proc/net/tcp{,6}` (the image
has no `ss`/`netstat`/`lsof`), binds host `127.0.0.1` **only**, and tunnels in over the Docker
API via `socat`. Opt-in per project.
- **`docker/`** — Docker API layer using bollard: - **`docker/`** — Docker API layer using bollard:
- `client.rs` — Singleton Docker connection via `OnceLock` - `client.rs` — Singleton Docker connection via `OnceLock`
- `container.rs` — Container lifecycle (create, start, stop, remove, inspect) - `container.rs` — Container lifecycle (create, start, stop, remove, inspect)
- `exec.rs`PTY exec sessions with bidirectional stdin/stdout streaming - `exec.rs`Attached exec streaming. `create_attached_exec()` is the **single** place an
attached exec is opened; terminal sessions and the auth bridge both go through it.
- `image.rs` — Image build/pull with progress streaming - `image.rs` — Image build/pull with progress streaming
- `legacy_cleanup.rs` — One-release migration shim removing leftovers from the deleted MCP
feature (containers labelled `triple-c.mcp-server`, `triple-c-net-*` networks). Deletable once
users have migrated.
- **`web_terminal/`** — Remote terminal access via axum HTTP+WebSocket server: - **`web_terminal/`** — Remote terminal access via axum HTTP+WebSocket server:
- `server.rs` — Axum server lifecycle (start/stop), serves embedded HTML and handles WS upgrades - `server.rs` — Axum server lifecycle (start/stop), serves embedded HTML and handles WS upgrades
- `ws_handler.rs` — Per-connection WebSocket handler with JSON protocol, session management, cleanup on disconnect - `ws_handler.rs` — Per-connection WebSocket handler with JSON protocol, session management, cleanup on disconnect
@@ -87,7 +121,13 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
### Container Lifecycle ### Container Lifecycle
Containers use a **stop/start** model (not create/destroy). Installed packages persist across stops. The `.claude` config dir uses a named Docker volume (`triple-c-claude-config-{projectId}`) so OAuth tokens survive even container resets. Containers use a **stop/start** model (not create/destroy). Installed packages persist across stops. The `.claude` config dir uses a named Docker volume (`triple-c-claude-config-{projectId}`), nested inside the home volume (`triple-c-home-{projectId}`), so OAuth tokens and Claude Code config survive container stop/start *and* container recreation.
**Reset is the exception and it is destructive.** `rebuild_project_container` calls
`remove_project_volumes`, which deletes *both* volumes — so a Reset wipes `~/.claude`,
`~/.claude.json`, the OAuth credential, installed skills, and session transcripts. That is
intentional (Reset exists to get back to a clean base image), but do not describe Reset as
preserving credentials.
### Authentication ### Authentication
@@ -108,8 +148,18 @@ Per-project, independently configured:
- Frontend types in `lib/types.ts` must stay in sync with Rust structs in `models/` - Frontend types in `lib/types.ts` must stay in sync with Rust structs in `models/`
- Tauri commands are registered in `lib.rs` via `.invoke_handler(tauri::generate_handler![...])` - Tauri commands are registered in `lib.rs` via `.invoke_handler(tauri::generate_handler![...])`
- Tauri v2 permissions are declared in `capabilities/default.json` — new IPC commands need permission grants there - `capabilities/default.json` grants permissions for **plugin** commands only (`core:`, `dialog:`,
`store:`, `opener:`). Application commands registered through `generate_handler!` do **not**
need an entry there — adding one is not required and none exists for any app command.
- The `projects.json` file uses atomic writes (write to `.tmp`, then `rename()`). Corrupted files are backed up to `.bak`. - The `projects.json` file uses atomic writes (write to `.tmp`, then `rename()`). Corrupted files are backed up to `.bak`.
- **Adding project state that changes the container?** `container_needs_recreation()` is entirely
**label-based** — it does not diff the container's env. If a new setting affects the container's
environment or configuration, you must also write a corresponding `triple-c.*` label at creation
and compare it there, or the change will silently not take effect until some unrelated setting
forces a rebuild. Never put a secret in a label; labels are readable via `docker inspect`.
- **New model fields need an explicit serde default when the correct default isn't the zero value.**
`#[serde(default)]` on a `bool` yields `false`; follow the `default_full_permissions` pattern in
`models/project.rs` for anything that should default to true.
- Cross-platform paths: Docker socket is `/var/run/docker.sock` on Linux/macOS, `//./pipe/docker_engine` on Windows - Cross-platform paths: Docker socket is `/var/run/docker.sock` on Linux/macOS, `//./pipe/docker_engine` on Windows
## Testing ## Testing
+337
View File
@@ -0,0 +1,337 @@
# Triple-C Design & Product Review
**Date:** 2026-08-09 · **Version reviewed:** 0.3.0 · **Reviewer:** Fable 5
Scope: `app/src/` (App, layout, projects, settings, terminal, ui, store, index.css),
README/CLAUDE.md/TODO.md, the four repo screenshots, and `triple-c-app-logov2.png`.
---
## Summary verdict
The bones are good. The floating-panel layout reads clean, the GitHub-dark palette is
inoffensive, and terminal-as-centerpiece is correct for this product.
The two real problems are structural, and they are the same problem seen from two sides:
**the project — the app's actual unit of work — has no room to live.** Everything about a
project (backend auth, mounts, git identity, env vars, ports, Claude settings, file
manager) is stuffed into a ~280px sidebar card (`ProjectCard.tsx`, 1,257 lines) that
sprays out seven modals to compensate.
`screenshot_for_fix/project_config_run_off.png` is not a bug to patch. It is the
architecture reporting that the config does not fit where it lives. Fixing that one thing
also solves the modal pile, the density problems, *and* creates the surface where newer
Claude Code concepts belong.
---
## Part A — Visual & interaction design
### A1. Tokens: coherent but thin, with one real contrast failure
`index.css` is GitHub Primer dark, verbatim (`#0d1117 / #161b22 / #21262d / #30363d /
#8b949e / #58a6ff`). Defensible — familiar, calm, terminal-adjacent — but the token layer
stops at 11 variables. Roles the code is already faking ad hoc:
- **No elevation/overlay token.** Modals reuse `--bg-secondary`, so a modal over the
sidebar is the same color as the sidebar. Add `--bg-overlay: #1c2128` and
`--shadow-overlay`.
- **No muted-accent tokens.** The code hand-rolls `bg-yellow-500/20 text-yellow-400`,
`bg-blue-500/20 text-blue-400`, `--warning/15`, `--error/10`. Add `--accent-muted`,
`--warning-muted`, `--error-muted`, `--success-muted`. Those raw Tailwind palette colors
are the only two places the token system leaks.
- **Radius drift:** `rounded` (4px), `rounded-lg` (8px), plus hardcoded 3px/6px in help
styles. Pick two: 6px controls, 8px panels.
**Contrast bug (concrete):** white text on `--accent #58a6ff` is ~**2.5:1** — fails WCAG
AA. That is the primary button ("Add Project"), the "Update" pill, and more. Primer solves
this with two accents: keep `#58a6ff` as the *foreground/link* accent and add
`--accent-emphasis: #1f6feb` for filled buttons (white on `#1f6feb` ≈ 4.7:1).
Same story for `bg-[var(--success)] text-white` ON toggles — `#3fb950` + white ≈ **2.1:1**,
the worst offender in the app.
What passes: `--text-secondary #8b949e` on `#161b22` ≈ 5.8:1, fine even at 12px.
`--warning #d29922` ≈ 7:1. But `disabled:opacity-50` on secondary text drops to ~2.4:1 —
and since the entire config form is disabled while the container runs, **the most common
state of the form is illegible.** Use a dedicated `--text-disabled: #6e7681` instead of
opacity.
### A2. Type and density: everything is 12px
Roughly 90% of the UI is `text-xs`. Hierarchy is carried almost entirely by weight plus a
single `text-lg` modal title. Forms feel cramped rather than dense — density is
information per pixel, not small type.
Proposed scale with roles: **11px** uppercase section labels (already used, keep) ·
**12px** secondary/meta · **13px** default UI/body/form values · **14px** panel headers ·
**16px** view titles.
Path strings in mono are a nice identity touch — extend mono to all machine values (model
IDs, ports, digests), which the Bedrock/Ollama forms currently render in the UI face.
The outer chrome spends generously while content starves: `App.tsx` wraps everything in
`p-6 gap-4`, then the config form gets ~180px-wide inputs for AWS secret keys. Keep the
floating-island look; `p-3 gap-3` buys content ~24px horizontally and the terminal two
more rows.
### A3. The project card is three components wearing one div
`ProjectCard` is simultaneously a list row, a command strip, and the entire settings form.
- **Selection and disclosure are conflated.** Clicking a row both selects it and expands an
accordion in place, shoving the other projects down. The 06-28 screenshot shows 18
projects — this jank is daily.
- **Actions are unstyled text links.** `ActionButton` renders `text-xs px-2 py-0.5` colored
text with no border or background, so Start/Stop/Terminal/Shell/Files/Backup/Config/Remove
read as a wrapping line of links. Worse, **Remove (destructive, red) wraps directly next
to Config** with a ~20px hit target.
- **Double-click-to-rename** is undiscoverable and keyboard/touch-inaccessible.
- **27 hover-only `<Tooltip>` markers in ProjectCard alone.** When a form needs 27 tooltips,
the form is the problem.
### A4. Modals: eight is a pattern smell, and none are real dialogs
Hanging off ProjectCard: EnvVars, PortMappings, ClaudeInstructions, ClaudeCodeSettings,
ContainerProgress, FileManager, ConfirmRemove — plus AddProject, three reused from
SettingsPanel, and Update/ImageUpdate/Help from TopBar.
Each reimplements the overlay div, Escape handler, and click-outside logic by hand. **None
has `role="dialog"`, `aria-modal`, a focus trap, or focus restore** — zero hits for
`role=`, `aria-modal`, or `tabIndex` across `components/`.
The pattern is wrong not because modals are bad, but because these are not modal *tasks*.
Env vars, ports, instructions, and Claude settings are all "edit part of the project
config" — a detail view's job.
- Legitimately modal: **ConfirmRemove**, **AddProject**.
- **FileManager** wants to be a main-area tab, not a 42rem popup.
- **ContainerProgressModal actively hurts:** starting a container blocks the entire app
behind an overlay for an operation designed to be routine. Replace with inline row state
plus an error toast.
- Whatever survives should be one shared `<Modal>` primitive with focus trap + ARIA.
### A5. Keyboard and focus: currently unsupported
For a tool whose centerpiece is a keyboard-driven terminal, the chrome is mouse-only.
- Inputs use `focus:outline-none` with only a low-contrast border swap; **buttons have no
focus style at all** — tabbing through the sidebar is invisible.
- One-line fix: add `--focus-ring: #58a6ff` and
`:focus-visible { outline: 2px solid var(--focus-ring); outline-offset: 1px; }`
- No shortcuts for constant actions: `Ctrl+T` new terminal, `Ctrl+Tab`/`Ctrl+1..9` switch,
`Ctrl+W` close, `Ctrl+P` project switcher. The only shortcut in the app is the STT mic.
- Hit targets below 24px: tab close "×" (~14px), Tooltip "?" (14px), Browse "...". The
status bar is `h-6` yet hosts two interactive controls.
### A6. Status communication
Three disconnected dot systems (TopBar Docker/Image, per-project status, StatusBar counts),
all 8px and color-only.
- **Stopped (gray) and error (red) differ only by hue**, and Docker-unavailable renders the
same gray as Docker-still-being-checked (`dockerAvailable === null` and `false` both fall
through). An outage should be loud; unknown should pulse.
- Color-only encoding fails colorblind users. Add shape or text — `● Running`, `○ Stopped`,
`⚠ Error`. The words are already in the model.
- Raw `String(e)` errors dumped into a 12px card line; bollard errors are long. Errors need
a home: toast plus expandable detail.
- The TopBar tab strip is visually disconnected from the terminal it controls. Move tabs
onto the terminal panel's top edge so the active tab connects to its content.
### A7. Empty and first-run states
`WelcomeScreen` is three lines of gray text with no affordance — "Add a project from the
sidebar" *describes* a button instead of *being* one. This is also where brand could exist:
the orange sun-gear logo appears nowhere in the UI and shares no DNA with the blue-on-
graphite chrome.
Make it an onboarding checklist reusing state already tracked:
✓ Docker detected → ✓ Image pulled → **[ Add your first project ]** → open terminal.
The same pattern fixes the "image missing" case, today just a gray dot in the corner.
### A8. Dark-only: keep it
Right call. Terminal-first developer tool, xterm content is dark, audience expects it. The
tokens make a light theme cheap later. Don't spend on it now — but keep discipline that no
color bypasses the token layer.
### A9. Iconography
Mixed: hand-inlined Feather-style SVGs in the sidebar rail, text glyphs elsewhere ("×",
"?", "...", "+", "✓", "✕"). Adopt `lucide-react` — same stroke style already being
imitated, tree-shakeable — and replace the text glyphs. It also supplies the per-concept
icons Part B needs.
---
## Part B — Information architecture & product concepts
### B1. The diagnosis
Current IA: `Projects | MCP | Settings` in a sidebar, terminal in main, project detail
crammed into the list.
Deleting the MCP tab was correct — but **the lesson matters more than the freed slot.
MCP died as a Triple-C feature because Claude Code absorbed it.** Hooks, skills, agents,
plugins, output styles, and statusline are all the same species: files under `.claude/`
that Claude Code manages natively with its own TUIs (`/agents`, `/hooks`, `/plugins`). If
Triple-C builds form editors for them, it loses the same race again and becomes exactly
what it should fear — a settings-file editor with a GUI skin.
What Claude Code *cannot* do is what Triple-C uniquely owns: **the container boundary and
what persists behind it.** The config volume, the workspace mounts, the lifecycle, the
scheduler already shipping in every image, and the fleet view across many projects.
> **Principle: Triple-C shows state and launches things. Claude Code edits its own config.**
Sessions, checkpoints, background tasks, scheduled tasks, capability inventory → surface
them, read from the volume, launch into the terminal. Hook/skill/agent *editing*
deep-link into the terminal, don't rebuild.
### B2. Proposed IA: three nouns
**Project** (a sandboxed workspace) · **Session** (a resumable conversation) ·
**Library** (reusable capabilities pushed into projects). Everything is one of these, or
Settings.
```
┌────────────────────────────────────────────────────────────────────┐
│ TopBar: ⌂ api-server │ ▣ api-server ✕ │ ▣ api (bash) ✕ │ ● ● ? │
├─────────────┬──────────────────────────────────────────────────────┤
│ ◤ Projects │ MAIN AREA — a tab strip of two tab kinds: │
│ ● api-serv │ ⌂ project-home tabs ▣ terminal tabs │
│ ○ blog │ │
│ ● data-pipe│ ⌂ api-server ● Running · 2h 14m │
│ … │ ┌─────────┬──────────┬────────────┬────────┐ │
│ ◧ Library │ │Overview │ Sessions │ Automation │ Config │ │
│ ⚙ Settings │ └─────────┴──────────┴────────────┴────────┘ │
├─────────────┴──────────────────────────────────────────────────────┤
│ StatusBar: 18 projects · 8 running · 4 terminals 🎤 ↓Jump │
└────────────────────────────────────────────────────────────────────┘
```
- **Sidebar** becomes a pure list plus nav rail. Rows carry name, path, status dot, and on
hover a play/stop and terminal button. Clicking opens (or focuses) that project's
**Project Home** tab. The freed MCP slot becomes **Library**.
- **Main area** hosts two tab kinds: terminals (as today) and project-home tabs, like VS
Code's Settings tab. The terminal stays the centerpiece; Project Home is one keystroke
away rather than a layer on top.
- **All seven config modals dissolve** into the Config tab, full-width, grouped:
*Workspace* (folders/mounts), *Model* (backend + auth), *Access* (git/SSH/env/ports),
*Runtime* (docker access, sandbox, permission mode, Mission Control). Room for visible
helper text kills most of the 27 tooltips. Save-on-blur stays but gains a visible
"Saved ✓ / Failed" indicator — today failures go only to `console.error`, which is
silent data loss.
#### Project Home — Overview tab
```
api-server ● Running · started 2h ago
[ Stop ] [ Open Claude Terminal ] [ Shell ] [ Files ] [⋯ menu]
Permission mode ( Plan ) ( Default ) ( Accept Edits ) (▮ Bypass ▮)
Sandbox ON — bubblewrap isolation Backend Anthropic
CAPABILITIES (read from container volume)
◆ Skills 7 ◆ Agents 3 ◆ Hooks 2 ◆ Plugins 1 ◆ Commands 5
└ click any → drawer listing names/descriptions,
[Manage in terminal] → opens claude with /agents etc.
RECENT SESSIONS SCHEDULED TASKS
"Refactor OAuth flow" 2h ago [Resume] nightly-review 0 3 * * *
"Fix flaky CI test" 1d ago [Resume] [2 notifications]
```
### B3. The four concepts worth building
**1. Sessions & Resume — the flagship.** The stop/start container model creates a problem
plain Claude Code doesn't have: stop a container, come back Tuesday, and "which
conversation was I in?" is buried in the volume. Read session metadata via `docker exec`
(the exec and tar plumbing already exists), list sessions with summary and age, and make
**[Resume]** open a terminal running `claude --resume <id>`. Closing a terminal tab today
silently abandons a session; it should say "Session saved — resume from Project Home."
This turns the biggest architectural quirk into the best feature.
Do **not** build a checkpoint browser. Mention rewind (`Esc Esc`) in Help and stop there.
**2. Library — the MCP tab's successor.** The pattern was already invented three times:
global MCP servers with per-project checkboxes, global Claude instructions, and Mission
Control's bundled skill install. Generalize it once: a Library of **skills, agents, and
slash commands** defined globally with per-project enable, synced into the container's
`.claude` volume by the entrypoint. Across many projects, "write a skill once, enable it in
twelve sandboxes" is genuinely differentiated. Keep the editor minimal — name plus markdown
textarea, or "import from folder." Not a structured form per frontmatter field.
**3. Permission mode as the hero control.** The whole pitch is "sandbox so you can safely
go fast," yet that pitch is expressed as a scary boolean buried in a config accordion.
Replace it with Claude Code's real vocabulary — a segmented control (**Plan / Default /
Accept Edits / Bypass**) on Overview, echoed as a badge on terminal tabs, with sandbox
state beside it. When sandbox is ON, Bypass loses its red paint ("contained by sandbox");
when sandbox is OFF *and* Bypass is on, that is when caution color earns its place. This
reframes the product's core value in the product's own UI.
**4. Automation tab.** `triple-c-scheduler` ships in every container with
add/list/logs/notifications — and its only UI is a CLAUDE.md paragraph telling Claude to
run it. Wrap it: task list (name, cron, last run, enabled), toggle/run-now/view-log, and a
notification badge on the project row. "Your nightly agent left you a note" is a reason to
open the app in the morning. Fleet-of-scheduled-agents management across projects is
something the Claude Code TUI does not offer.
**Explicitly skip:** status line builder, output-styles editor, hook *editors* (surface the
count, deep-link to the terminal), checkpoint browser, marketplace browser. Each is niche,
natively handled, or a settings-editor trap.
### B4. Coherence test
Every screen answers exactly one question:
| Screen | Question |
|---|---|
| Sidebar | What projects exist and are they up? |
| Project Home | What can this sandbox do, and where did I leave off? |
| Terminal | Do the work. |
| Library | What capabilities do I reuse? |
| Settings | How does the host behave? |
Anything that doesn't answer one of those doesn't get a nav slot.
---
## Priorities
### Tier 1 — high impact, cheap
1. `:focus-visible` ring and stop stripping outlines (one CSS rule + token). Add
`Ctrl+T` / `Ctrl+W` / `Ctrl+1..9` / `Ctrl+Tab`.
2. Contrast: `--accent-emphasis: #1f6feb` for filled buttons; kill white-on-`#3fb950`;
`--text-disabled` instead of `opacity-50`.
3. Real buttons for project actions; Remove into an overflow menu; primary action filled.
4. Inline start/stop progress and an error toast; delete `ContainerProgressModal`.
5. Status dots get labels or shapes; Docker-down turns red; null state pulses.
6. Welcome screen becomes an onboarding checklist with a real button, plus the logo.
7. One shared `<Modal>` with focus trap and ARIA for the modals that remain.
8. Permission-mode segmented control replacing the boolean.
9. `lucide-react` icons; move the tab strip onto the terminal panel.
### Tier 2 — high impact, expensive
1. **Project Home tabbed view** — the structural fix that dissolves the modal pile and the
1,257-line ProjectCard. The forms already exist; this is mostly moving and splitting.
2. **Sessions tab** with `claude --resume`.
3. **Library** — generalize global→per-project sync to skills/agents/commands.
4. **Automation tab** wrapping `triple-c-scheduler`, with notification badges.
### Tier 3 — skip
- Light theme (dark-only is right; tokens keep the door open).
- Editors for hooks, statusline, output styles; checkpoint browser; marketplace browser.
- Any new global sidebar tab beyond Library.
- Rebuilding MCP management in any form. Let the deletion be a lesson, not a vacancy.
---
**One sentence:** promote the project from a sidebar card to a first-class workspace view,
use the volume you already own to surface sessions/capabilities/automation instead of
building config editors, and spend a focused week on focus rings, contrast, and button
affordances — the visual layer needs sanding, not redesign.
+458 -194
View File
@@ -9,17 +9,22 @@ Triple-C (Claude-Code-Container) is a desktop application that runs Claude Code
- [Prerequisites](#prerequisites) - [Prerequisites](#prerequisites)
- [First Launch](#first-launch) - [First Launch](#first-launch)
- [The Interface](#the-interface) - [The Interface](#the-interface)
- [Project Home](#project-home)
- [Project Management](#project-management) - [Project Management](#project-management)
- [Permission Modes](#permission-modes)
- [Project Configuration](#project-configuration) - [Project Configuration](#project-configuration)
- [MCP Servers (Beta)](#mcp-servers-beta) - [Shared Claude Authentication](#shared-claude-authentication)
- [Browser Logins Inside the Container (Auth Bridge)](#browser-logins-inside-the-container-auth-bridge)
- [AWS Bedrock Configuration](#aws-bedrock-configuration) - [AWS Bedrock Configuration](#aws-bedrock-configuration)
- [Ollama Configuration](#ollama-configuration) - [Ollama Configuration](#ollama-configuration)
- [OpenAI Compatible Configuration](#openai-compatible-configuration) - [OpenAI Compatible Configuration](#openai-compatible-configuration)
- [Settings](#settings) - [Settings](#settings)
- [Web Terminal (Remote Access)](#web-terminal-remote-access) - [Web Terminal (Remote Access)](#web-terminal-remote-access)
- [Terminal Features](#terminal-features) - [Terminal Features](#terminal-features)
- [Scheduled Tasks (Inside the Container)](#scheduled-tasks-inside-the-container) - [Automation & Scheduled Tasks](#automation--scheduled-tasks)
- [Keyboard Shortcuts](#keyboard-shortcuts)
- [What's Inside the Container](#whats-inside-the-container) - [What's Inside the Container](#whats-inside-the-container)
- [Claude Code Tips](#claude-code-tips)
- [Troubleshooting](#troubleshooting) - [Troubleshooting](#troubleshooting)
--- ---
@@ -79,7 +84,7 @@ Click **Pull Image** (for Registry/Custom) or **Build Image** (for Local Build).
### 2. Create Your First Project ### 2. Create Your First Project
Switch to the **Projects** tab in the sidebar and click the **+** button. Switch to the **Projects** tab in the sidebar and click **+ Add**.
1. **Project Name** — Give it a meaningful name (e.g., "my-web-app"). 1. **Project Name** — Give it a meaningful name (e.g., "my-web-app").
2. **Folders** — Click **Browse** to select a directory on your host machine. This directory will be mounted into the container at `/workspace/<folder-name>`. You can add multiple folders with the **+** button at the bottom of the folder list. 2. **Folders** — Click **Browse** to select a directory on your host machine. This directory will be mounted into the container at `/workspace/<folder-name>`. You can add multiple folders with the **+** button at the bottom of the folder list.
@@ -87,42 +92,61 @@ Switch to the **Projects** tab in the sidebar and click the **+** button.
### 3. Start the Container ### 3. Start the Container
Select your project in the sidebar and click **Start**. A progress modal appears showing real-time status as the container starts. The status dot changes from gray (stopped) to orange (starting) to green (running). The modal auto-closes on success. Click the project in the sidebar. Its **Project Home** opens as a tab in the main area. Click
**Start** in the Project Home header (or use the play control that appears when you hover the
sidebar row).
Progress is reported inline — the sidebar row and the Project Home header show messages like
"Creating container…" and "Starting container…" while the status moves from Stopped (`○`) to
Starting (`◐`) to Running (`●`). Nothing blocks the rest of the app; if something fails you get a
toast with the full detail behind a **Details** disclosure.
### 4. Open a Terminal ### 4. Open a Terminal
Click the **Terminal** button to open an interactive terminal session. A new tab appears in the top bar and an xterm.js terminal loads in the main area. Click **Open Claude Terminal** in the Project Home header, or press **Ctrl+T**. A new tab appears
in the main tab strip and an xterm.js terminal loads.
Claude Code launches automatically. By default, it runs in standard permission mode and will ask for your approval before executing commands or editing files. To enable auto-approval of all actions within the sandbox, enable **Full Permissions** in the project configuration. Claude Code launches automatically. The project's **permission mode** decides how much it asks
before acting — the default is to prompt before each tool call. See
[Permission Modes](#permission-modes).
### 5. Authenticate ### 5. Authenticate
**Anthropic (OAuth) — default:** **Anthropic — shared token (recommended):**
Run `claude setup-token` once from **Settings → Claude Authentication** in the sidebar, and every
Anthropic-backend project uses that token without its own login. See
[Shared Claude Authentication](#shared-claude-authentication).
**Anthropic — per-container OAuth:**
1. Type `claude login` or `/login` in the terminal. 1. Type `claude login` or `/login` in the terminal.
2. Claude prints an OAuth URL. Triple-C detects long URLs and shows a clickable toast at the top of the terminal — click **Open** to open it in your browser. 2. Claude prints an OAuth URL. Triple-C detects long URLs and shows a clickable toast at the top of the terminal — click **Open** to open it in your browser.
3. Complete the login in your browser. The token is saved and persists across container stops and resets. 3. Complete the login in your browser. The token is saved and persists across container stops, starts and recreations. A **Reset** deletes it — see below.
> If the login hangs after the browser step, the callback could not reach the container. Enable the
> [Auth Bridge](#browser-logins-inside-the-container-auth-bridge) for that project.
**AWS Bedrock:** **AWS Bedrock:**
1. Stop the container first (settings can only be changed while stopped). 1. Stop the container first (most settings can only be changed while stopped).
2. In the project card, switch the backend to **Bedrock**. 2. Open the project's **Config** tab and, under **Model**, set **Backend** to **Bedrock**.
3. Expand the **Config** panel and fill in your AWS credentials (see [AWS Bedrock Configuration](#aws-bedrock-configuration) below). 3. Fill in your AWS credentials in the same section (see [AWS Bedrock Configuration](#aws-bedrock-configuration) below).
4. Start the container again. 4. Start the container again.
**Ollama:** **Ollama:**
1. Stop the container first (settings can only be changed while stopped). 1. Stop the container first (most settings can only be changed while stopped).
2. In the project card, switch the backend to **Ollama**. 2. Open the project's **Config** tab and, under **Model**, set **Backend** to **Ollama**.
3. Expand the **Config** panel and set the base URL of your Ollama server (defaults to `http://host.docker.internal:11434` for a local instance). Set the **Model ID** to the model you want to use (required). 3. Set the base URL of your Ollama server (defaults to `http://host.docker.internal:11434` for a local instance). Set the **Model** to the model you want to use (required).
4. Make sure the model has been pulled in Ollama (e.g., `ollama pull qwen3.5:27b`) or used via Ollama cloud before starting. 4. Make sure the model has been pulled in Ollama (e.g., `ollama pull qwen3.5:27b`) or used via Ollama cloud before starting.
5. Start the container again. 5. Start the container again.
**OpenAI Compatible:** **OpenAI Compatible:**
1. Stop the container first (settings can only be changed while stopped). 1. Stop the container first (most settings can only be changed while stopped).
2. In the project card, switch the backend to **OpenAI Compatible**. 2. Open the project's **Config** tab and, under **Model**, set **Backend** to **OpenAI Compatible**.
3. Expand the **Config** panel and set the base URL of your OpenAI-compatible endpoint (defaults to `http://host.docker.internal:4000` as an example). Optionally set an API key and model ID. 3. Set the base URL of your OpenAI-compatible endpoint (defaults to `http://host.docker.internal:4000` as an example). Optionally set an API key and model.
4. Start the container again. 4. Start the container again.
--- ---
@@ -130,23 +154,97 @@ Claude Code launches automatically. By default, it runs in standard permission m
## The Interface ## The Interface
``` ```
┌─────────────────────────────────────────────────────┐ ┌──────────────────────────────────────────────────────────────────────
TopBar [ Terminal Tabs ] Docker ● Image ●│ [⌂ my-app] [▣ my-app ask] [▣ my-app (bash)] Docker ● Image ● ?
├────────────────────────────────────────────────────┤ ├─────────────┬────────────────────────────────────────────────────────┤
│ Sidebar │ │ Sidebar ┌──────────────────────────────────────────────────┐
│ │ Terminal View │ my-app ● Running · up 2h 5m
│ Projects │ (xterm.js) │ Projects [Open Claude Terminal] [Shell] [Files]
MCP Settings [Stop] [⋯]
Settings │ │ ├──────────────────────────────────────────────────┤
├────────────┴────────────────────────────────────────┤ │ ● my-app │ │ Overview · Sessions · Automation · Config · Files│ │
StatusBar X projects · X running · X terminals ○ other │ ├──────────────────────────────────────────────────┤
└─────────────────────────────────────────────────────┘ │ │ │ │ │
│ │ │ (Project Home, or a terminal view) │ │
│ │ │ │ │
│ │ └──────────────────────────────────────────────────┘ │
├─────────────┴────────────────────────────────────────────────────────┤
│ 2 project(s) · 1 running · 2 terminal(s) Jump to Current ↓ │
└──────────────────────────────────────────────────────────────────────┘
``` ```
- **TopBar** — Terminal tabs for switching between sessions. Bash shell tabs show a "(bash)" suffix. Status dots on the right show Docker connection (green = connected) and image availability (green = ready). - **Tab strip (top)** — One strip holds every open tab, in the order you opened them. There are two
- **Sidebar** — Toggle between the **Projects** list, **MCP** server configuration, and **Settings** panel. kinds: **Project Home** tabs (`⌂` glyph, project name, status glyph) and **terminal** tabs (`▣`
- **Terminal View** — Interactive terminal powered by xterm.js with WebGL rendering. Includes a **Jump to Current** button that appears when you scroll up, so you can quickly return to the latest output. glyph, plus a small badge showing the permission mode the terminal was launched with —
- **StatusBar** — Counts of total projects, running containers, and open terminal sessions. `plan`, `ask`, `edits` or `bypass`). Bash shell tabs show a "(bash)" suffix. Right-click a
terminal tab to rename it, jump to its project home, or close it; double-click to rename inline.
There is no separate terminal tab bar and no "+" button — tabs appear when you open a project or
a terminal.
- **Status indicators (top right)** — Docker connection and container image availability. Each pairs
a coloured dot with a word, so status is never conveyed by colour alone. The **?** button opens
the built-in help.
- **Sidebar** — Toggle between the **Projects** list and the **Settings** panel. It collapses to a
narrow icon rail with the chevron button, and remembers that choice.
- **Main area** — Shows the active tab: a Project Home view or an xterm.js terminal. With no tabs
open you get a welcome screen with Docker/image/project readiness checks.
- **StatusBar** — Counts of total projects, running containers and open terminal sessions; the
**Jump to Current ↓** button when a terminal is scrolled up; and the microphone button when
speech-to-text is enabled.
---
## Project Home
Clicking a project in the sidebar opens **Project Home** in the main area. The sidebar row is only
for selecting a project and for two quick controls that appear on hover — start/stop, and open a
Claude terminal. Everything else about a project lives in Project Home.
The header shows the project name, its status, how long the container has been up, and the action
buttons. Below that are five tabs:
| Tab | What it's for |
|---|---|
| **Overview** | The permission mode control, a summary of the backend and sandbox settings, capability tiles, recent sessions and scheduled tasks |
| **Sessions** | Past Claude Code conversations stored on this project's config volume, each with a **Resume** button |
| **Automation** | The scheduled tasks running inside this container — see [Automation & Scheduled Tasks](#automation--scheduled-tasks) |
| **Config** | All per-project configuration — see [Project Configuration](#project-configuration) |
| **Files** | Browse, download and upload files inside the container |
### Sessions
Claude Code records each conversation on the project's config volume. The **Sessions** tab lists
them with a name or summary, the session id, its working directory, its age, size and message
count. **Refresh** re-reads the list.
**Resume** opens a new shell tab and runs `claude --resume <session-id>` for you, with the
project's current permission-mode flags applied. The Overview tab shows the four most recent
sessions with the same Resume action.
Sessions can only be read while the container is running, and they are stored on the config volume
— so a **Reset** deletes them.
### Capability Tiles
The Overview tab shows read-only counts of what Claude Code has available **inside this container**:
| Tile | What is counted |
|---|---|
| **Skills** | Directories under `.claude/skills/` that contain a `SKILL.md` |
| **Agents** | `.md` files under `.claude/agents/` |
| **Commands** | `.md` files under `.claude/commands/` |
| **Hooks** | Hook handlers configured in `.claude/settings.json` / `settings.local.json` |
| **Plugins** | Installed and enabled Claude Code plugins |
| **MCP servers** | Servers in `~/.claude.json` and in any `.mcp.json` under `/workspace` |
Both user scope (`/home/claude/.claude`) and project scope (`/workspace/<folder>/.claude`) are
included, and each tile opens a list of what it found.
> **Triple-C does not edit any of this.** Claude Code owns skills, agents, commands, hooks, plugins
> and MCP servers, and it has good built-in tooling for them. The tiles are a window, not an editor:
> **Manage in terminal** opens a terminal in the container so you can use `/agents`, `/hooks`,
> `/plugins`, `/mcp` and friends directly.
The counts are only available while the container is running.
--- ---
@@ -154,59 +252,135 @@ Claude Code launches automatically. By default, it runs in standard permission m
### Project Status ### Project Status
Each project shows a colored status dot: Each project shows a status glyph paired with a word, so it is readable without relying on colour:
| Color | Status | Meaning | | Glyph | Status | Meaning |
|-------|--------|---------| |-------|--------|---------|
| Gray | Stopped | Container is not running | | `○` | Stopped | Container is not running |
| Orange | Starting / Stopping | Container is transitioning | | `◐` | Starting / Stopping | Container is transitioning (the glyph pulses) |
| Green | Running | Container is active, ready for terminals | | `●` | Running | Container is active, ready for terminals |
| Red | Error | Something went wrong (check error message) | | `▲` | Error | Something went wrong (check the toast for detail) |
While a container is starting or stopping, the status line is replaced by the live progress message.
### Project Actions ### Project Actions
Select a project in the sidebar to see its action buttons: Most actions live in the **Project Home header**; two live behind the **⋯** overflow menu next to
it. The sidebar row carries only the two hover controls.
| Button | When Available | What It Does | | Action | Where | When Available | What It Does |
|--------|---------------|--------------| |--------|-------|---------------|--------------|
| **Start** | Stopped | Creates (if needed) and starts the container | | **Start** | Project Home header; sidebar hover control | Stopped | Creates (if needed) and starts the container |
| **Stop** | Running | Stops the container but preserves its state | | **Stop** | Project Home header; sidebar hover control | Running | Stops the container but preserves its state |
| **Terminal** | Running | Opens a new Claude Code terminal session | | **Force stop** | Project Home header | Starting / Stopping | Interrupts a transition that is stuck |
| **Shell** | Running | Opens a bash login shell in the container (no Claude Code) | | **Open Claude Terminal** | Project Home header; sidebar hover control; `Ctrl+T` | Running | Opens a new Claude Code terminal tab |
| **Files** | Running | Opens the file manager to browse, download, and upload files | | **Shell** | Project Home header | Running | Opens a bash login shell tab in the container (no Claude Code) |
| **Reset** | Stopped | Destroys and recreates the container from scratch | | **Files** | Project Home header, and the **Files** tab | Running | Switches to the Files tab to browse, download and upload files |
| **Config** | Always | Toggles the configuration panel | | **Config** | The **Config** tab | Always | Per-project configuration (most fields need the container stopped) |
| **Remove** | Stopped | Deletes the project and its container (with confirmation) | | **Back up container** | **⋯** overflow menu | A container exists | Saves a `.tar.gz` archive of the container to a location you choose |
| **Reset container…** | **⋯** overflow menu | Stopped or Error | Destroys the container, snapshot image and both volumes, then recreates from the base image (wipes `~/.claude`) — asks first |
| **Remove project…** | **⋯** overflow menu | Always | Deletes the project, its container, its volumes and its stored credentials — asks first |
> Both destructive actions confirm before acting, and the Reset dialog spells out what you
> lose: your `claude login`, anything installed inside the container, and every saved
> session transcript. Your mounted project folders live on the host and are not touched.
> The backup archive includes the Claude config volume, which may contain API keys. Keep it private.
### Renaming a Project ### Renaming a Project
Double-click the project name in the sidebar to rename it inline. Press **Enter** to confirm or **Escape** to cancel. Rename a project in its **Config** tab, under **Workspace → Project name**. Press **Enter** to save
and leave the field, or **Escape** to revert. (Double-clicking a *terminal tab* renames that tab —
that is a different thing.)
### Container Lifecycle ### Container Lifecycle
Containers use a **stop/start** model. When you stop a container, everything inside it is preserved — installed packages, modified files, downloaded tools. Starting it again resumes where you left off. Containers use a **stop/start** model. When you stop a container, everything inside it is preserved — installed packages, modified files, downloaded tools. Starting it again resumes where you left off.
**Reset** removes the container and creates a fresh one. However, your Claude Code configuration (including OAuth tokens from `claude login`) is stored in a separate Docker volume and survives resets. **Reset container** removes the container, its snapshot image **and both of its named volumes**
(`triple-c-home-<project-id>` and `triple-c-claude-config-<project-id>`), then creates a fresh one
from the clean base image. This is destructive: `~/.claude` and `~/.claude.json` go with the
volumes, so your per-container OAuth login, any skills or agents you installed, your session
transcripts and your scheduled tasks are all lost.
Only **Remove** deletes everything, including the config volume and any stored credentials. What Reset keeps: your host folders (they are bind mounts and are never touched), the project's
configuration in Triple-C, and anything stored in your OS keychain — including the shared Claude
authentication token. If the project uses that shared token, it re-authenticates by itself after a
Reset; if it relies on `claude login`, you will need to log in again.
Apart from **Remove project…**, Reset is the only action that deletes the volumes. Stopping and
starting preserves them, and so does the automatic container recreation that happens when you
change a setting that affects the container — in both cases your Claude Code configuration
survives.
**Remove project…** deletes everything Reset does, plus the project record itself and its stored
credentials.
### Container Progress Feedback ### Container Progress Feedback
When starting, stopping, or resetting a container, a progress modal shows real-time status messages (e.g., "Setting up MCP network...", "Starting MCP containers...", "Creating container..."). If an error occurs, the modal displays the error with a **Close** button. A **Force Stop** option is available if the operation stalls. The modal auto-closes on success. When starting, stopping, or resetting a container, progress is shown inline on the project row and in the Project Home header (e.g., "Creating container...", "Starting container..."), so the rest of the app stays usable. If an error occurs it is raised as a toast with the full detail behind a **Details** disclosure. There is no blocking progress modal.
---
## Permission Modes
Every project has a **permission mode** that decides how much Claude Code does without asking. It
is a segmented control on the **Overview** tab (and again under **Config → Runtime**), and it
replaces the old Full Permissions on/off switch.
| Mode | What Claude does | What Triple-C passes to `claude` |
|------|------------------|----------------------------------|
| **Plan** | Proposes a plan and makes no changes | `--permission-mode plan` |
| **Default** | Asks before each tool call | *(nothing — Claude Code's own default)* |
| **Accept Edits** | Auto-approves file edits; other tools still prompt | `--permission-mode acceptEdits` |
| **Bypass** | Auto-approves every tool call | `--dangerously-skip-permissions` |
New projects start in **Default**. Projects created before permission modes existed keep behaving
the way they did: one that had Full Permissions on becomes **Bypass**, one that had it off becomes
**Default**.
> **CAUTION:** In **Bypass**, Claude can execute any command inside the container without asking.
> The container sandbox limits the blast radius, but think carefully — especially if the container
> has Docker socket access or reaches services on your network. The Overview tab tells you whether
> the in-container sandbox is also on.
### When a change takes effect
- **Terminals** — the mode is applied when a terminal is opened, so it affects terminals you open
from then on. A Claude session that is already running keeps the permissions it started with;
close the tab and open a new terminal to change it. The badge on each terminal tab shows the mode
that terminal was launched with (`plan`, `ask`, `edits`, `bypass`).
- **Resumed sessions** — a session resumed from the **Sessions** tab uses the project's current
mode.
- **Scheduled tasks** — these now honour the permission mode too (they previously always ran with
`--dangerously-skip-permissions`). The mode reaches them through the container's environment,
which can only change when the container is recreated, so **stop and start the project** for a
mode change to reach the scheduler.
> Scheduled tasks run headless (`claude -p`) and cannot answer a permission prompt. In any mode
> other than **Bypass**, a task may simply stop early when Claude Code asks for approval. Its run
> log records which mode it used.
--- ---
## Project Configuration ## Project Configuration
Click **Config** on a selected project to expand the configuration panel. Settings can only be changed when the container is **stopped** (an orange warning box appears if the container is running). Open a project's **Config** tab in Project Home. Configuration is grouped into four sections —
**Workspace**, **Model**, **Access** and **Runtime** — plus **Claude instructions** and **Claude
Code settings**.
Changes save automatically when a field loses focus, and a Saved / Saving… / Failed indicator in
the corner tells you what happened. Most settings can only be changed when the container is
**stopped**; a warning chip appears at the top of the tab if it is running. (The project name and
the permission mode can be changed at any time.)
### Mounted Folders ### Mounted Folders
Each project mounts one or more host directories into the container. The mount appears at `/workspace/<mount-name>` inside the container. Each project mounts one or more host directories into the container. The mount appears at `/workspace/<mount-name>` inside the container.
- Click **Browse** ("...") to change the host path - Click **Browse** to change the host path
- Edit the mount name to control where it appears inside `/workspace/` - Edit the mount name to control where it appears inside `/workspace/`
- Click **+** to add more folders, or **x** to remove one - Click **+ Add folder** to add more, or **Remove** to drop one (the last remaining folder cannot be removed)
- Mount names must be unique and use only letters, numbers, dashes, underscores, and dots - Mount names must be unique and use only letters, numbers, dashes, underscores, and dots
### SSH Keys ### SSH Keys
@@ -237,27 +411,31 @@ Available skills include `/mission`, `/flight`, `/leg`, `/agentic-workflow`, `/f
> This setting can only be changed when the container is stopped. Toggling it triggers a container recreation on the next start. > This setting can only be changed when the container is stopped. Toggling it triggers a container recreation on the next start.
### Full Permissions ### Permission Mode
Toggle **Full Permissions** to allow Claude Code to run with `--dangerously-skip-permissions` inside the container. This is **off by default**. The **Runtime** section repeats the permission mode control from the Overview tab — see
[Permission Modes](#permission-modes) for what each mode does and when a change takes effect.
When **enabled**, Claude auto-approves all tool calls (file edits, shell commands, etc.) without prompting you. This is the fastest workflow since you won't be interrupted for approvals, and the Docker container provides isolation. ### Sandbox Mode
When **disabled** (default), Claude prompts you for approval before executing each action, giving you fine-grained control over what it does. Toggles Claude Code's in-container bubblewrap isolation. The Overview tab shows the current state
next to the permission mode, because the two together decide how contained a Bypass-mode session
> **CAUTION:** Enabling full permissions means Claude can execute any command inside the container without asking. While the container sandbox limits the blast radius, make sure you understand the implications — especially if the container has Docker socket access or network connectivity. really is.
> This setting can only be changed when the container is stopped. It takes effect the next time you open a terminal session.
### Environment Variables ### Environment Variables
Click **Edit** to open the environment variables modal. Add key-value pairs that will be injected into the container. Per-project variables override global variables with the same key. Add key-value pairs under **Access → Environment variables**; they are injected into the container.
Per-project variables override global variables with the same key.
> Reserved prefixes (`ANTHROPIC_`, `AWS_`, `GIT_`, `HOST_`, `TRIPLE_C_`) and specific internal variables (`CLAUDE_INSTRUCTIONS`, `MCP_SERVERS_JSON`, etc.) are filtered out to prevent conflicts. `CLAUDE_CODE_*` variables are now allowed, so you can set Claude Code feature flags directly (e.g., `CLAUDE_CODE_DISABLE_TERMINAL_TITLE=1`). > Reserved prefixes (`ANTHROPIC_`, `AWS_`, `GIT_`, `HOST_`, `TRIPLE_C_`) are filtered out to prevent
> conflicts, along with the exact names Triple-C manages itself: `CLAUDE_INSTRUCTIONS`,
> `CLAUDE_CODE_SETTINGS_JSON`, `CLAUDE_CODE_OAUTH_TOKEN`, `MISSION_CONTROL_ENABLED`,
> `TRIPLE_C_PERMISSION_MODE` and `MCP_SERVERS_JSON`. Other `CLAUDE_CODE_*` variables are allowed, so
> you can set Claude Code feature flags directly (e.g., `CLAUDE_CODE_DISABLE_TERMINAL_TITLE=1`).
### Port Mappings ### Port Mappings
Click **Edit** to map host ports to container ports. This is useful when Claude Code starts a web server or other service inside the container and you want to access it from your host browser. Under **Access → Port mappings**, map host ports to container ports. This is useful when Claude Code starts a web server or other service inside the container and you want to access it from your host browser.
Each mapping specifies: Each mapping specifies:
- **Host Port** — The port on your machine (1-65535) - **Host Port** — The port on your machine (1-65535)
@@ -266,11 +444,11 @@ Each mapping specifies:
### Claude Instructions ### Claude Instructions
Click **Edit** to write per-project instructions for Claude Code. These are written to `~/.claude/CLAUDE.md` inside the container and provide project-specific context. If you also have global instructions (in Settings), the global instructions come first, followed by the per-project instructions. The **Claude instructions** editor at the bottom of the Config tab holds per-project instructions for Claude Code. These are written to `~/.claude/CLAUDE.md` inside the container and provide project-specific context. If you also have global instructions (in Settings), the global instructions come first, followed by the per-project instructions.
### Claude Code Settings ### Claude Code Settings
Click **Edit** next to "Claude Code Settings" to configure Claude Code CLI behavior for this project. These settings control how Claude Code operates inside the container: The **Claude Code settings** editor, also at the bottom of the Config tab, configures Claude Code CLI behavior for this project. These settings control how Claude Code operates inside the container:
| Setting | What It Does | | Setting | What It Does |
|---------|-------------| |---------|-------------|
@@ -287,146 +465,127 @@ Per-project settings override global defaults set in Settings. If all settings a
> These settings map to Claude Code environment variables and `~/.claude/settings.json` entries. Changes require stopping and restarting the container to take effect. > These settings map to Claude Code environment variables and `~/.claude/settings.json` entries. Changes require stopping and restarting the container to take effect.
### MCP Servers
Triple-C no longer manages [MCP](https://modelcontextprotocol.io/) servers itself. Configure them with Claude Code's own tooling from a terminal inside the container:
- `claude mcp add` — register a server
- `claude mcp list` — show configured servers
- `claude mcp remove` — delete a server
- `/mcp` — slash command inside a Claude Code session for MCP status and authentication
- A project-level `.mcp.json` in `/workspace` — checked into your repo and shared with anyone who opens the project
Your MCP configuration persists across container stop/start because `~/.claude.json` and `~/.claude` live on named Docker volumes. A **Reset** wipes them, so you would need to re-add your servers afterwards.
--- ---
## MCP Servers (Beta) ## Shared Claude Authentication
Triple-C supports [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers, which extend Claude Code with access to external tools and data sources. MCP servers are configured in a **global library** and **enabled per-project**. Instead of running `claude login` separately in every container, you can authenticate once and
share the result across projects. Claude Code's `claude setup-token` mints a long-lived token
(roughly a year) that Triple-C stores in your **OS keychain** and injects into containers as
`CLAUDE_CODE_OAUTH_TOKEN`.
### How It Works This lives in the sidebar under **Settings → Claude Authentication**.
There are two dimensions to MCP server configuration: ### Signing in
| | **Manual** (no Docker image) | **Docker** (Docker image specified) | 1. Start at least one project whose container is running — the flow borrows that container as a
|---|---|---| place to run the CLI. The token it produces is global, not tied to that project.
| **Stdio** | Command runs inside the project container | Command runs in a separate MCP container via `docker exec` | 2. Start the sign-in. Triple-C runs `claude setup-token` inside the container and streams its
| **HTTP** | Connects to a URL you provide | Runs in a separate container, reached by hostname on a shared Docker network | output.
3. Claude Code prints an authorization URL. Open it, sign in, and Anthropic's page gives you a
code to copy — this flow finishes on an Anthropic-hosted page, not a local callback.
4. Paste the code back into Triple-C. The token is captured and written straight to the keychain.
**Docker images are pulled automatically** if not already present when the project starts. Only one sign-in can run at a time, and the whole flow times out after 15 minutes. A long-lived
token requires a Claude subscription; without one, `setup-token` finishes without printing a token
and nothing is stored.
### Accessing MCP Configuration ### How the token is used
Click the **MCP** tab in the sidebar to open the MCP server library. This is where you define all available MCP servers. - It is injected only into projects whose backend is **Anthropic** — it means nothing to Bedrock,
Ollama or an OpenAI-compatible endpoint.
- Each project can opt out under **Config → Model** ("Use the shared Claude token"). Projects are
opted **in** by default, so a single sign-in covers your whole fleet; opt a project out if you
want it pinned to its own `claude login` identity.
- `CLAUDE_CODE_OAUTH_TOKEN` is reserved — you cannot set it yourself as a custom environment
variable, because a hand-set value would silently outrank the stored token.
- A container picks the token up when it is **next started**: acquiring, re-acquiring, revoking or
opting out changes an internal marker that triggers a container recreation on the next start.
Restart your Anthropic-backend containers after signing in.
### Adding an MCP Server ### Revoking
1. Type a name in the input field and click **Add**. Revoking deletes the token from your keychain. Containers keep the value they were given until each
2. Expand the server card and configure it. is next started, at which point the same recreation clears the variable.
The key decision is whether to set a **Docker Image**: > The token is never shown in the app, never written to a log, and never sent to the frontend.
- **With Docker image** — The MCP server runs in its own isolated container. Best for servers that need specific dependencies or system-level packages. > While `setup-token` is running, its output is filtered so anything resembling an `sk-ant-`
- **Without Docker image** (manual) — The command runs directly inside your project container. Best for lightweight npx-based servers that just need Node.js. > secret is masked before it reaches the screen — including a secret split across two chunks of
> output.
Then choose the **Transport Type**: ---
- **Stdio** — The MCP server communicates over stdin/stdout. This is the most common type.
- **HTTP** — The MCP server exposes an HTTP endpoint (streamable HTTP transport).
### Configuration Examples ## Browser Logins Inside the Container (Auth Bridge)
#### Example 1: Filesystem Server (Stdio, Manual) Some CLIs log you in by opening a browser and waiting for the browser to call back to a temporary
web server they started on `localhost`. `claude login`, `aws sso login` and Concourse's
`fly login` all work this way. When the CLI runs inside a container, that `localhost` is the
*container's* — the browser on your host calls back into nothing and the login hangs forever.
A simple npx-based server that runs inside the project container. No Docker image needed since Node.js is already installed. The **Auth Bridge** fixes this. It is **opt-in per project** and **off by default**.
| Field | Value | ### What it does
|-------|-------|
| **Docker Image** | *(empty)* |
| **Transport** | Stdio |
| **Command** | `npx` |
| **Arguments** | `-y @modelcontextprotocol/server-filesystem /workspace` |
This gives Claude Code access to browse and read files via MCP. The command runs directly inside the project container using the pre-installed Node.js. - Every couple of seconds it looks inside the container for programs listening on the container's
loopback address, and binds **the same port number** on your host. That is the whole trick: the
redirect URL the login provider was handed resolves correctly on both sides.
- Connections are carried into the container over the Docker API, which keeps working on Docker
Desktop where container IP addresses are not reachable from the host.
- It follows whichever address family the container program actually used. This matters in
practice: Node resolves `localhost` to IPv6 first on Linux, so `claude login` frequently listens
on `::1` and nothing else.
- Ports you have already configured as port mappings are left alone. If a host port is already
taken, the bridge reports a conflict and leaves it alone rather than fighting for it — it will
retry on a later pass.
- The bridge is entirely host-side, so turning it on or off never recreates the container. It stops
by itself when the container stops.
#### Example 2: GitHub Server (Stdio, Manual) ### Security
Another npx-based server, with an environment variable for authentication. The host side binds **loopback only**`127.0.0.1` and `[::1]`, never a wildcard address. Nothing
on your network can reach a bridged port. Within your own machine, though, a bridged port is
reachable by any local process for as long as the in-container listener exists, and the services
behind it are unauthenticated: they bound loopback precisely because they expected to be reachable
from nowhere else. Only container programs that bound loopback are bridged; anything listening on
all interfaces is deliberately ignored (publishing those is what port mappings are for).
| Field | Value | Leave it off unless you need it, and it will not be running.
|-------|-------|
| **Docker Image** | *(empty)* |
| **Transport** | Stdio |
| **Command** | `npx` |
| **Arguments** | `-y @modelcontextprotocol/server-github` |
| **Environment Variables** | `GITHUB_PERSONAL_ACCESS_TOKEN` = `ghp_your_token` |
#### Example 3: Custom MCP Server (HTTP, Docker)
An MCP server packaged as a Docker image that exposes an HTTP endpoint.
| Field | Value |
|-------|-------|
| **Docker Image** | `myregistry/my-mcp-server:latest` |
| **Transport** | HTTP |
| **Container Port** | `8080` |
| **Environment Variables** | `API_KEY` = `your_key` |
Triple-C will:
1. Pull the image automatically if not present
2. Start the container on the project's bridge network
3. Configure Claude Code to reach it at `http://triple-c-mcp-{id}:8080/mcp`
The hostname is the MCP container's name on the Docker network — **not** `localhost`.
#### Example 4: Database Server (Stdio, Docker)
An MCP server that needs its own runtime environment, communicating over stdio.
| Field | Value |
|-------|-------|
| **Docker Image** | `mcp/postgres-server:latest` |
| **Transport** | Stdio |
| **Command** | `node` |
| **Arguments** | `dist/index.js` |
| **Environment Variables** | `DATABASE_URL` = `postgresql://user:pass@host:5432/db` |
Triple-C will:
1. Pull the image and start it on the project network
2. Configure Claude Code to communicate via `docker exec -i triple-c-mcp-{id} node dist/index.js`
3. Automatically enable Docker socket access on the project container (required for `docker exec`)
### Enabling MCP Servers Per-Project
In a project's configuration panel (click **Config**), the **MCP Servers** section shows checkboxes for all globally defined servers. Toggle each server on or off for that project. Changes take effect on the next container start.
### How Docker-Based MCP Works
When a project with Docker-based MCP servers starts:
1. Missing Docker images are **automatically pulled** (progress shown in the progress modal)
2. A dedicated **bridge network** is created for the project (`triple-c-net-{projectId}`)
3. Each enabled Docker MCP server gets its own container on that network
4. The main project container is connected to the same network
5. MCP server configuration is written to `~/.claude.json` inside the container
**Networking**: Docker-based MCP containers are reached by their container name as a hostname (e.g., `triple-c-mcp-{serverId}`), not by `localhost`. Docker DNS resolves these names automatically on the shared bridge network.
**Stdio + Docker**: The project container uses `docker exec` to communicate with the MCP container over stdin/stdout. This automatically enables Docker socket access on the project container.
**HTTP + Docker**: The project container connects to the MCP container's HTTP endpoint using the container hostname and port (e.g., `http://triple-c-mcp-{serverId}:3000/mcp`).
**Manual (no Docker image)**: Stdio commands run directly inside the project container. HTTP URLs connect to wherever you point them (could be an external service or something running on the host).
### Configuration Change Detection
MCP server configuration is tracked via SHA-256 fingerprints stored as Docker labels. If you add, remove, or modify MCP servers for a project, the container is automatically recreated on the next start to apply the new configuration. The container filesystem is snapshotted first, so installed packages are preserved.
--- ---
## AWS Bedrock Configuration ## AWS Bedrock Configuration
To use Claude via AWS Bedrock instead of Anthropic's API, switch the backend to **Bedrock** on the project card. To use Claude via AWS Bedrock instead of Anthropic's API, set **Backend** to **Bedrock** under
**Config → Model**.
### Authentication Methods ### Authentication Methods
| Method | Fields | Use Case | | Method | Fields | Use Case |
|--------|--------|----------| |--------|--------|----------|
| **Keys** | Access Key ID, Secret Access Key, Session Token (optional) | Direct credentials — simplest setup | | **Static keys** | Access Key ID, Secret Access Key, Session Token (optional) | Direct credentials — simplest setup |
| **Profile** | AWS Profile name | Uses `~/.aws/config` and `~/.aws/credentials` on the host | | **Named profile** | AWS Profile name | Uses `~/.aws/config` and `~/.aws/credentials` on the host |
| **Token** | Bearer Token | Temporary bearer token authentication | | **Bearer token** | Bearer Token | Temporary bearer token authentication |
With **Named profile**, the SSO session is validated before Claude Code launches, so an expired
session is caught at the start of a terminal rather than mid-task.
### Additional Bedrock Settings ### Additional Bedrock Settings
- **AWS Region** — Required. The region where your Bedrock models are deployed (e.g., `us-east-1`). - **AWS Region** — Required. The region where your Bedrock models are deployed (e.g., `us-east-1`).
- **Model ID** — Optional. Override the default Claude model (e.g., `anthropic.claude-sonnet-4-20250514-v1:0`). - **Model ID** — Optional. Override the default Claude model (e.g., `anthropic.claude-sonnet-4-20250514-v1:0`).
- **Service tier** — Optional. Selects a Bedrock service tier.
### Global AWS Defaults ### Global AWS Defaults
@@ -442,7 +601,7 @@ Per-project settings always override these global defaults.
## Ollama Configuration ## Ollama Configuration
To use Claude Code with a local or remote Ollama server, switch the backend to **Ollama** on the project card. To use Claude Code with a local or remote Ollama server, set **Backend** to **Ollama** under **Config → Model**.
### Settings ### Settings
@@ -461,7 +620,7 @@ Triple-C sets `ANTHROPIC_BASE_URL` to point Claude Code at your Ollama server in
## OpenAI Compatible Configuration ## OpenAI Compatible Configuration
To use Claude Code through any OpenAI API-compatible endpoint, switch the backend to **OpenAI Compatible** on the project card. This works with any server that exposes an OpenAI-compatible API, including LiteLLM, OpenRouter, vLLM, text-generation-inference, LocalAI, and others. To use Claude Code through any OpenAI API-compatible endpoint, set **Backend** to **OpenAI Compatible** under **Config → Model**. This works with any server that exposes an OpenAI-compatible API, including LiteLLM, OpenRouter, vLLM, text-generation-inference, LocalAI, and others.
### Settings ### Settings
@@ -479,7 +638,14 @@ Triple-C sets `ANTHROPIC_BASE_URL` to point Claude Code at your OpenAI-compatibl
## Settings ## Settings
Access global settings via the **Settings** tab in the sidebar. Access global settings via the **Settings** tab in the sidebar. The panel is a set of collapsible
sections: **General**, **Claude Authentication**, **Backends**, **Container**, **Git / SSH**,
**Tools** and **Updates**.
### Claude Authentication
Acquire or revoke the shared Claude authentication token — see
[Shared Claude Authentication](#shared-claude-authentication).
### Docker Settings ### Docker Settings
@@ -574,7 +740,14 @@ The web terminal UI mirrors the desktop app's terminal experience:
### Multiple Sessions ### Multiple Sessions
You can open multiple terminal sessions (even for the same project). Each session gets its own tab in the top bar. Click a tab to switch, or click the **x** on a tab to close it. Tabs show the project name (or custom session name if provided), with a "(bash)" suffix for shell sessions. You can open multiple terminal sessions (even for the same project). Each session gets its own tab
in the main tab strip, alongside any open Project Home tabs. Click a tab to switch, or click the
**×** on a tab to close it. Tabs show the project name (or a custom session name if you set one),
with a "(bash)" suffix for shell sessions and a badge for the permission mode the session was
launched with.
Right-click a terminal tab for **Rename tab**, **Reset name**, **Open project home** and
**Close tab**; double-click it to rename inline.
### Bash Shell Sessions ### Bash Shell Sessions
@@ -602,16 +775,16 @@ You can paste images from your clipboard into the terminal (Ctrl+V / Cmd+V). The
When you scroll up in the terminal to review previous output, a **Jump to Current** button appears in the bottom-right corner. Click it to scroll back to the latest output. When you scroll up in the terminal to review previous output, a **Jump to Current** button appears in the bottom-right corner. Click it to scroll back to the latest output.
### File Manager ### Files
Click the **Files** button on a running project to open the file manager modal. You can: The **Files** tab of Project Home browses inside a running container. You can:
- **Browse** the container filesystem starting from `/workspace`, with breadcrumb navigation - **Browse** the container filesystem, starting at `/workspace`, with breadcrumb navigation
- **Download** any file to your host machine via the download button on each file entry - **Download** any file to your host machine via the **Download** button on each file entry
- **Upload** files from your host into the current container directory - **Upload file** from your host into the current container directory
- **Refresh** the directory listing at any time - **Refresh** the directory listing at any time
The file manager shows file names, sizes, and modification dates. The listing shows file names, sizes, and modification dates.
### Terminal Rendering ### Terminal Rendering
@@ -619,9 +792,48 @@ The terminal uses WebGL for hardware-accelerated rendering of the active tab. In
--- ---
## Scheduled Tasks (Inside the Container) ## Automation & Scheduled Tasks
Once inside a running container terminal, you can set up recurring or one-time tasks using `triple-c-scheduler`. Tasks run as separate Claude Code sessions. Each container can run Claude Code on a schedule — recurring or one-time — through a small
scheduler called `triple-c-scheduler` that lives inside the image. Tasks run as separate,
headless Claude Code invocations (`claude -p "<your prompt>"`) driven by cron.
The **Automation** tab in Project Home is the place to watch and control them; tasks are created
from inside the container with the `triple-c-scheduler` CLI.
### The Automation Tab
With the container running, the Automation tab lists every task the scheduler knows about. For each
one you get its name, whether it is recurring or one-time, its cron expression or scheduled time,
and when it last ran. For each task you can:
| Control | What it does |
|---------|--------------|
| **Toggle** | Enable or disable the task without deleting it |
| **Run now** | Trigger the task immediately, outside its schedule |
| **Log** | Show the tail of that task's run log (last 200 lines) |
| **Remove** | Delete the task, after a confirmation |
**Refresh** re-reads everything from the container.
When tasks finish they leave **notifications**. If any are waiting, a panel appears at the top of
the tab listing each one with its task name, whether it succeeded or failed, how long ago it ran
and a summary. **Clear all** dismisses them. The Overview tab also shows a notification count and
the next few scheduled tasks.
### Permission mode
Scheduled runs use the project's [permission mode](#permission-modes) — they no longer always run
with `--dangerously-skip-permissions`. Because the mode travels into the container as an
environment variable, **stop and start the project** after changing it for the scheduler to see the
change. Remember that a headless run cannot answer a permission prompt, so in any mode other than
**Bypass** a task may stop early when Claude Code asks for approval; the run log records the mode
that was used.
### Creating Tasks (In the Container)
There is no "add task" form in the app. Create tasks from a terminal in the container — either type
the commands yourself in a **Shell** session, or just ask Claude to do it.
### Create a Recurring Task ### Create a Recurring Task
@@ -637,7 +849,9 @@ triple-c-scheduler add --name "migrate-db" --at "2026-03-05 14:00" --prompt "Run
One-time tasks automatically remove themselves after execution. One-time tasks automatically remove themselves after execution.
### Manage Tasks ### Manage Tasks From the CLI
The CLI still works, and does the same things the Automation tab does:
```bash ```bash
triple-c-scheduler list # List all tasks triple-c-scheduler list # List all tasks
@@ -670,6 +884,39 @@ By default, tasks run in `/workspace`. Use `--working-dir` to specify a differen
triple-c-scheduler add --name "test" --schedule "0 */6 * * *" --prompt "Run tests" --working-dir /workspace/my-project triple-c-scheduler add --name "test" --schedule "0 */6 * * *" --prompt "Run tests" --working-dir /workspace/my-project
``` ```
> Scheduled tasks live on the project's config volume, so a **Reset** deletes them along with
> everything else on that volume.
---
## Keyboard Shortcuts
### Application
| Shortcut | Action |
|----------|--------|
| **Ctrl+T** | Open a new Claude terminal for the current project (nothing happens unless its container is running) |
| **Ctrl+Shift+W** | Close the active tab |
| **Ctrl+Tab** | Switch to the next tab |
| **Ctrl+Shift+Tab** | Switch to the previous tab |
| **Ctrl+1****Ctrl+9** | Jump to the first through ninth tab |
> **Why Ctrl+Shift+W and not Ctrl+W?** `Ctrl+W` is readline's `kill-word` — it deletes the word
> before the cursor, and it is used constantly in the terminal this app is built around. Binding it
> to "close tab" would make the shell unusable, so Triple-C deliberately leaves `Ctrl+W` alone.
### In the Terminal
| Shortcut | Action |
|----------|--------|
| **Ctrl+Shift+C** | Copy the selection, with trailing whitespace trimmed |
| **Ctrl+Shift+Alt+C** | Copy the selection exactly as-is |
| **Ctrl+Shift+V** | Paste |
| **Ctrl+V** | Paste an image from the clipboard into the container |
| **Ctrl+Shift+M** | Toggle speech-to-text recording (when enabled) |
Everything else goes straight through to the program running in the container.
--- ---
## What's Inside the Container ## What's Inside the Container
@@ -735,7 +982,7 @@ These features are built into Claude Code and work inside Triple-C containers wi
- Check that the Docker image is "Ready" in Settings. - Check that the Docker image is "Ready" in Settings.
- Verify that the mounted folder paths exist on your host. - Verify that the mounted folder paths exist on your host.
- Look at the error message displayed in the progress modal. - Read the error toast — the full message is behind its **Details** disclosure.
### OAuth Login URL Not Opening ### OAuth Login URL Not Opening
@@ -743,22 +990,39 @@ These features are built into Claude Code and work inside Triple-C containers wi
- If the toast doesn't appear, try scrolling up in the terminal — the URL may have already been printed. - If the toast doesn't appear, try scrolling up in the terminal — the URL may have already been printed.
- You can also manually copy the URL from the terminal output and paste it into your browser. - You can also manually copy the URL from the terminal output and paste it into your browser.
### A Browser Login Never Completes
You opened the URL, signed in successfully, and the CLI in the terminal is still waiting. The
callback from your browser is landing on your host's `localhost` while the CLI is listening on the
*container's*. Enable the
[Auth Bridge](#browser-logins-inside-the-container-auth-bridge) for that project and try again.
For Claude specifically, the simpler answer is usually
[Shared Claude Authentication](#shared-claude-authentication), which finishes on an Anthropic-hosted
page and needs no callback at all.
### A Scheduled Task Stopped Part-Way Through
Scheduled tasks run headless and cannot answer a permission prompt. If the project is not in
**Bypass** mode, a task will stop when Claude Code asks for approval. Check the task's **Log** in
the Automation tab — it records the permission mode the run used.
### A Permission Mode Change Didn't Apply
- **In a terminal:** the mode is set when the terminal opens. Close the tab and open a new one.
- **For scheduled tasks:** the mode reaches the scheduler through the container's environment. Stop
the project and start it again.
### File Permission Issues ### File Permission Issues
- Triple-C automatically remaps the container user's UID/GID to match your host user, so files created inside the container should have the correct ownership on your host. - Triple-C automatically remaps the container user's UID/GID to match your host user, so files created inside the container should have the correct ownership on your host.
- If you see permission errors, try resetting the container (stop, then click **Reset**). - If you see permission errors, try resetting the container: stop it, then choose **Reset container** from the **⋯** menu in the Project Home header. Note that this wipes `~/.claude`.
### Settings Won't Save ### Settings Won't Save
- Most project settings can only be changed when the container is **stopped**. Stop the container first, make your changes, then start it again. - Most project settings can only be changed when the container is **stopped**. Stop the container first, make your changes, then start it again.
- Some changes (like toggling Docker access, Mission Control, or changing mounted folders) trigger an automatic container recreation on the next start. - Some changes (like toggling Docker access, Mission Control, or changing mounted folders) trigger an automatic container recreation on the next start.
### MCP Containers Not Starting
- Ensure the Docker image for the MCP server exists (pull it first if needed).
- Check that Docker socket access is available (stdio + Docker MCP servers auto-enable this).
- Try resetting the project container to force a clean recreation.
### "Failed to install Anthropic marketplace" Error ### "Failed to install Anthropic marketplace" Error
If Claude Code shows **"Failed to install Anthropic marketplace - Will retry on next startup"** repeatedly, the marketplace metadata in `~/.claude.json` may be corrupted. To fix this, open a **Shell** session in the project and run: If Claude Code shows **"Failed to install Anthropic marketplace - Will retry on next startup"** repeatedly, the marketplace metadata in `~/.claude.json` may be corrupted. To fix this, open a **Shell** session in the project and run:
+174 -61
View File
@@ -1,6 +1,6 @@
# Triple-C (Claude-Code-Container) # Triple-C (Claude-Code-Container)
Triple-C is a cross-platform desktop application that sandboxes Claude Code inside Docker containers. Each project can optionally enable full permissions mode (`--dangerously-skip-permissions`), giving Claude unrestricted access within the sandbox. Triple-C is a cross-platform desktop application that sandboxes Claude Code inside Docker containers. Each project chooses its own **permission mode** — from Plan (read-only) through to Bypass (`--dangerously-skip-permissions`), which gives Claude unrestricted access within the sandbox.
## Architecture ## Architecture
@@ -13,41 +13,160 @@ Triple-C is a cross-platform desktop application that sandboxes Claude Code insi
``` ```
┌─────────────────────────────────────────────────────┐ ┌─────────────────────────────────────────────────────┐
│ TopBar (terminal tabs + Docker/Image status) │ TopBar (MainTabs strip + Docker/Image status + ?)
├────────────┬────────────────────────────────────────┤ ├────────────┬────────────────────────────────────────┤
│ Sidebar │ Main Content (terminal views) │ Sidebar │ Main Content
│ (25% w, │ │ (25% w, │ · Project Home views, or
│ responsive│ │ responsive│ · terminal views (xterm.js)
│ min/max) │ │ │ min/max) │ │
├────────────┴────────────────────────────────────────┤ ├────────────┴────────────────────────────────────────┤
│ StatusBar (project/terminal counts) │ StatusBar (project/terminal counts, STT, scroll)
└─────────────────────────────────────────────────────┘ └─────────────────────────────────────────────────────┘
``` ```
The main area is driven by **one ordered tab strip** (`components/layout/MainTabs.tsx`) holding
two tab kinds: `home:<projectId>` (Project Home) and `term:<sessionId>` (a terminal). There is no
separate terminal tab bar. `activeSessionId` is derived from the active tab key, so exactly one
thing is current at a time.
### Keyboard Shortcuts
Implemented in `hooks/useKeyboardShortcuts.ts` (document-level, capture phase):
| Shortcut | Action |
|---|---|
| `Ctrl+T` | New Claude terminal for the current project (no-op unless it is running) |
| `Ctrl+Shift+W` | Close the active tab |
| `Ctrl+Tab` / `Ctrl+Shift+Tab` | Cycle tabs forward / backward |
| `Ctrl+1``Ctrl+9` | Jump to the nth tab |
`Ctrl+W` is deliberately **not** bound: it is readline's `kill-word`, used constantly in the
terminal this app is built around. Terminal-scoped keys (`Ctrl+Shift+C`, `Ctrl+Shift+Alt+C`,
`Ctrl+Shift+M`) are handled in `TerminalView.tsx`.
### Project Home
Clicking a project row in the sidebar opens **Project Home** in the main area — the per-project
view, with tabs **Overview · Sessions · Automation · Config · Files**. The sidebar row itself is
select-only (plus hover controls for start/stop and opening a terminal); it holds no configuration.
Per-project configuration lives in the Config tab rather than in modals.
| Tab | Contents |
|---|---|
| **Overview** | Permission mode control, sandbox/backend/Docker-access summary, capability tiles, recent sessions, scheduled tasks |
| **Sessions** | Past Claude Code conversations read from the config volume, with **Resume** |
| **Automation** | The container's `triple-c-scheduler` tasks — enable/disable, run now, read logs, remove, and completion notifications |
| **Config** | Workspace (name, folders), Model (backend), Access (SSH, git, env vars, port mappings), Runtime (permission mode, sandbox, Docker access, Mission Control, instructions, Claude Code settings) |
| **Files** | Browse, download and upload files inside the container |
Container start/stop progress is reported inline (on the sidebar row and in the Project Home
header) via the `container-progress` event, and failures surface as toasts. There is no blocking
progress modal.
### Permission Modes
`PermissionMode` in `models/project.rs` replaces the old `full_permissions` boolean. Four states,
mapped to CLI flags by `PermissionMode::cli_args()`:
| Mode | Serialized | CLI args passed to `claude` |
|---|---|---|
| **Plan** | `plan` | `--permission-mode plan` |
| **Default** | `default` | *(none)* |
| **Accept Edits** | `acceptEdits` | `--permission-mode acceptEdits` |
| **Bypass** | `bypass` | `--dangerously-skip-permissions` |
`Project.permission_mode` is `Option<PermissionMode>`; `effective_permission_mode()` falls back to
the legacy `full_permissions` flag (`true` → Bypass) for records written before the change. Changing
the mode affects terminals opened **from then on** — a running `claude` process keeps the argv it
was launched with.
Scheduled tasks honour it too. The mode is injected as `TRIPLE_C_PERMISSION_MODE` (via
`as_env_value()`) and written as the `triple-c.permission-mode` container label; the entrypoint
snapshots it into `~/.claude/scheduler/.env`, and `container/triple-c-task-runner` translates it
back into flags for its headless `claude -p` run. Because it travels as container env, a mode change
only reaches the scheduler after the container is recreated on its next start (the label mismatch
forces that).
### Container Introspection (Capability Tiles)
`list_container_capabilities` (`commands/inspect_commands.rs`) runs a read-only `find`/`jq` script
inside a running container and returns counts plus item lists for **skills, agents, commands, hooks,
plugins and MCP servers**, at user scope (`/home/claude/.claude`) and project scope
(`/workspace/*/.claude`, `/workspace/*/.mcp.json`). Overview renders these as tiles.
Triple-C does not create or edit any of them — Claude Code owns that configuration, and the tiles
link out to a terminal where `/agents`, `/hooks`, `/plugins` and `/mcp` do the real work.
### Auth Bridge
Browser-based logins run *inside* a container (`claude login`, `aws sso login`, Concourse
`fly login`) start an ephemeral HTTP listener on the container's loopback and expect the host
browser's redirect to reach it. `auth_bridge/` closes that gap:
- Listeners are discovered by parsing `/proc/net/tcp{,6}` every 2 seconds — the image ships no
`ss`, `netstat` or `lsof`. Only `TCP_LISTEN` rows bound to loopback are considered; wildcard
binds are deliberately ignored (that is the port-mappings feature's job).
- Each discovered port is bound on the host at **the same port number**, on `127.0.0.1` (required)
and `[::1]` (best effort) — never a wildcard address. Node resolves `localhost` to IPv6 first, so
`claude login` often binds `::1` alone; the bridge follows the family it actually finds.
- Traffic is carried in over the Docker API by an attached exec running `socat`, because container
IPs are not routable from the host on Docker Desktop.
- Ports already covered by the project's port mappings are skipped, and a host port that is already
in use is reported as a conflict rather than fought over.
Opt-in per project (`auth_bridge_enabled`, default `false`), purely host-side, so toggling it never
recreates the container. The poller stops on its own when the container stops.
**Security posture:** the host side binds loopback only. Everything reachable through it is an
unauthenticated service inside the container, so widening those addresses would publish container
internals to the LAN. Nothing else on the network can reach a bridged port.
### Shared Claude Authentication Token
Rather than running `claude login` in every container, `claude setup-token` can be run once
(`commands/auth_token_commands.rs`). The flow borrows a running container, runs the CLI on a PTY,
and the long-lived token it prints is stored in the OS keychain — it is never returned to the
frontend and never logged. Streamed output passes through a chunk-boundary-safe redactor that masks
anything resembling an `sk-ant-` secret.
The token is injected as `CLAUDE_CODE_OAUTH_TOKEN` into every project where the backend is
Anthropic, the project has not opted out (`use_shared_auth_token`, default `true`), and a token is
actually stored. It is a reserved env key, so it cannot be hand-set as a custom variable.
Rotation is tracked with a random id (not a hash of the token) mirrored into the
`triple-c.claude-token-version` label — a hash in a `docker inspect`-readable label would be an
offline verification oracle. Acquiring, rotating, revoking or opting out changes that label, which
forces a container recreation on the next start; that is when a container picks the token up or has
it cleared.
### Container Lifecycle ### Container Lifecycle
1. **Create**: New container created with bind mounts, env vars, and labels 1. **Create**: New container created with bind mounts, named volumes, env vars, and labels
2. **Start**: Container started, entrypoint remaps UID/GID, sets up SSH, configures Docker group, sets up MCP servers, injects Claude Code settings 2. **Start**: Container started, entrypoint remaps UID/GID, sets up SSH, configures Docker group, injects Claude Code settings, rebuilds the scheduler crontab
3. **Terminal**: `docker exec` launches Claude Code (or bash shell) with a PTY 3. **Terminal**: `docker exec` launches Claude Code (with the project's permission-mode flags) or a bash login shell, with a PTY
4. **Stop**: Container halted (filesystem persists in named volume); MCP containers stopped 4. **Stop**: Container halted (its filesystem layer and both named volumes persist)
5. **Restart**: Existing container restarted; recreated if settings changed (detected via SHA-256 fingerprint) 5. **Restart**: Existing container restarted; if any `triple-c.*` label no longer matches the project's settings, the container is committed to a snapshot image, removed, and recreated from that snapshot — so installed packages survive
6. **Reset**: Container removed and recreated from scratch (named volume preserved) 6. **Reset**: Container, snapshot image **and both named volumes** all removed, then recreated from the clean base image. `remove_project_volumes` deletes `triple-c-home-{projectId}` and `triple-c-claude-config-{projectId}`, so `~/.claude`, `~/.claude.json`, the OAuth login, installed skills, session transcripts and the scheduler's tasks are all lost.
### Mounts ### Mounts
| Target in Container | Source | Type | Notes | | Target in Container | Source | Type | Notes |
|---|---|---|---| |---|---|---|---|
| `/workspace` | Project directory | Bind | Read-write | | `/workspace/<mount-name>` | Each configured project folder | Bind | Read-write; one per folder |
| `/home/claude/.claude` | `triple-c-claude-config-{projectId}` | Named Volume | Persists across container recreation | | `/home/claude` | `triple-c-home-{projectId}` | Named Volume | Home directory; survives stop/start and recreation |
| `/home/claude/.claude` | `triple-c-claude-config-{projectId}` | Named Volume | Nested inside the home volume; Docker gives the more specific mount precedence |
| `/tmp/.host-ssh` | SSH key directory | Bind | Read-only; entrypoint copies to `~/.ssh` | | `/tmp/.host-ssh` | SSH key directory | Bind | Read-only; entrypoint copies to `~/.ssh` |
| `/home/claude/.aws` | AWS config directory | Bind | Read-only; for Bedrock auth | | `/home/claude/.aws` | AWS config directory | Bind | Read-only; for Bedrock auth |
| `/var/run/docker.sock` | Host Docker socket | Bind | If "Allow container spawning" is ON, or auto-enabled by stdio+Docker MCP servers | | `/var/run/docker.sock` | Host Docker socket | Bind | If "Allow container spawning" is ON |
These two named volumes are the only ones a project owns. Both are removed by Reset and by project
removal, and by nothing else.
### Authentication Modes ### Authentication Modes
Each project can independently use one of: Each project can independently use one of:
- **Anthropic** (OAuth): User runs `claude login` inside the terminal on first use. Token persisted in the config volume across restarts and resets. - **Anthropic** (OAuth or shared token): either the shared `claude setup-token` token injected as `CLAUDE_CODE_OAUTH_TOKEN` (see below), or a per-container `claude login`. An interactive login's token lives in the config volume and survives container stop/start and recreation — but **not** a Reset, which deletes the volumes.
- **AWS Bedrock**: Per-project AWS credentials (static keys, profile, or bearer token). SSO sessions are validated before launching Claude for Profile auth. - **AWS Bedrock**: Per-project AWS credentials (static keys, profile, or bearer token). SSO sessions are validated before launching Claude for Profile auth.
- **Ollama**: Connect to a local or remote Ollama server via `ANTHROPIC_BASE_URL` (e.g., `http://host.docker.internal:11434`). Requires a model ID, and the model must be pulled (or used via Ollama cloud) before starting the container. - **Ollama**: Connect to a local or remote Ollama server via `ANTHROPIC_BASE_URL` (e.g., `http://host.docker.internal:11434`). Requires a model ID, and the model must be pulled (or used via Ollama cloud) before starting the container.
- **OpenAI Compatible**: Connect through any OpenAI API-compatible endpoint (LiteLLM, OpenRouter, vLLM, text-generation-inference, LocalAI, etc.) via `ANTHROPIC_BASE_URL` + `ANTHROPIC_AUTH_TOKEN`. API key stored securely in OS keychain. - **OpenAI Compatible**: Connect through any OpenAI API-compatible endpoint (LiteLLM, OpenRouter, vLLM, text-generation-inference, LocalAI, etc.) via `ANTHROPIC_BASE_URL` + `ANTHROPIC_AUTH_TOKEN`. API key stored securely in OS keychain.
@@ -60,27 +179,6 @@ When "Allow container spawning" is enabled per-project, the host Docker socket i
If the Docker access setting is toggled after a container already exists, the container is automatically recreated on next start to apply the mount change. The named config volume (keyed by project ID) is preserved across recreation. If the Docker access setting is toggled after a container already exists, the container is automatically recreated on next start to apply the mount change. The named config volume (keyed by project ID) is preserved across recreation.
### MCP Server Architecture
Triple-C supports [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers as a Beta feature. MCP servers extend Claude Code with external tools and data sources.
**Modes**: Each MCP server operates in one of four modes based on transport type and whether a Docker image is specified:
| Mode | Where It Runs | How It Communicates |
|------|--------------|---------------------|
| Stdio + Manual | Inside the project container | Direct stdin/stdout (e.g., `npx -y @mcp/server`) |
| Stdio + Docker | Separate MCP container | `docker exec -i <mcp-container> <command>` from the project container |
| HTTP + Manual | External / user-provided | Connects to the URL you specify |
| HTTP + Docker | Separate MCP container | `http://<mcp-container>:<port>/mcp` via Docker DNS on a shared bridge network |
**Key behaviors**:
- **Global library**: MCP servers are defined globally in the MCP sidebar tab and stored in `mcp_servers.json`
- **Per-project toggles**: Each project enables/disables individual servers via checkboxes
- **Auto-pull**: Docker images for MCP servers are pulled automatically if not present when the project starts
- **Docker networking**: Docker-based MCP containers run on a per-project bridge network (`triple-c-net-{projectId}`), reachable by container name — not localhost
- **Auto-detection**: Config changes are detected via SHA-256 fingerprints and trigger automatic container recreation
- **Config injection**: MCP server configuration is written to `~/.claude.json` inside the container via the `MCP_SERVERS_JSON` environment variable, merged by the entrypoint using `jq`
### Mission Control Integration ### Mission Control Integration
Optional per-project integration with Flight Control — an AI-first development methodology bundled with Triple-C. When enabled, the bundled files are installed into the container, skills are installed, and workflow instructions are injected into CLAUDE.md. Optional per-project integration with Flight Control — an AI-first development methodology bundled with Triple-C. When enabled, the bundled files are installed into the container, skills are installed, and workflow instructions are injected into CLAUDE.md.
@@ -99,7 +197,7 @@ The web terminal shares the existing `ExecSessionManager` via `Arc`-wrapped stor
### Speech-to-Text (Voice Mode) ### Speech-to-Text (Voice Mode)
Triple-C includes optional speech-to-text powered by [Faster Whisper](https://github.com/SYSTRAN/faster-whisper) running in a separate Docker container. When enabled, a microphone button appears in the bottom-left corner of each terminal view. Triple-C includes optional speech-to-text powered by [Faster Whisper](https://github.com/SYSTRAN/faster-whisper) running in a separate Docker container. When enabled, a microphone button appears in the StatusBar whenever a terminal session is active.
- **Hotkey**: `Ctrl+Shift+M` to toggle recording - **Hotkey**: `Ctrl+Shift+M` to toggle recording
- **Models**: `tiny`, `small`, or `medium` (configurable in Settings) - **Models**: `tiny`, `small`, or `medium` (configurable in Settings)
@@ -122,52 +220,67 @@ Users can override this in Settings via the global `docker_socket_path` option.
| File | Purpose | | File | Purpose |
|---|---| |---|---|
| `app/src/App.tsx` | Root layout (TopBar + Sidebar + Main + StatusBar) | | `app/src/App.tsx` | Root layout (TopBar + Sidebar + Main + StatusBar + ToastHost) |
| `app/src/index.css` | Global CSS variables, dark theme, `color-scheme: dark` | | `app/src/index.css` | Global CSS variables, dark theme, `color-scheme: dark`, `:focus-visible` ring |
| `app/src/components/layout/TopBar.tsx` | Terminal tabs + Docker/Image status indicators | | `app/src/components/layout/TopBar.tsx` | Hosts MainTabs + Docker/Image status indicators + Help |
| `app/src/components/layout/Sidebar.tsx` | Responsive sidebar (25% width, min 224px, max 320px) | | `app/src/components/layout/MainTabs.tsx` | The single main-area tab strip (Project Home + terminal tabs) |
| `app/src/components/layout/StatusBar.tsx` | Running project/terminal counts | | `app/src/components/layout/Sidebar.tsx` | Responsive sidebar (25% width, min 224px, max 320px), collapsible to an icon rail |
| `app/src/components/projects/ProjectCard.tsx` | Project config, backend selector, action buttons | | `app/src/components/layout/StatusBar.tsx` | Project/terminal counts, Jump to Current, STT mic |
| `app/src/components/projects/ClaudeCodeSettingsModal.tsx` | Claude Code CLI settings modal (TUI mode, effort, focus, caching) | | `app/src/components/projects/ProjectRow.tsx` | Select-only sidebar row; opens Project Home, with hover start/stop and terminal controls |
| `app/src/components/projects/ProjectList.tsx` | Project list in sidebar | | `app/src/components/projects/ProjectList.tsx` | Project list in sidebar |
| `app/src/components/projects/FileManagerModal.tsx` | File browser modal (browse, download, upload) | | `app/src/components/projects/PermissionModeControl.tsx` | Plan / Default / Accept Edits / Bypass segmented control |
| `app/src/components/projects/ContainerProgressModal.tsx` | Real-time container operation progress | | `app/src/components/projects/home/ProjectHome.tsx` | Project Home shell: header actions, overflow menu, tab strip |
| `app/src/components/mcp/McpPanel.tsx` | MCP server library (global configuration) | | `app/src/components/projects/home/OverviewTab.tsx` | Permission mode, summary, capability tiles, recent sessions and tasks |
| `app/src/components/mcp/McpServerCard.tsx` | Individual MCP server configuration card | | `app/src/components/projects/home/SessionsTab.tsx` | Past Claude sessions with Resume |
| `app/src/components/settings/SettingsPanel.tsx` | Docker, AWS, timezone, web terminal, and global settings | | `app/src/components/projects/home/AutomationTab.tsx` | Scheduler tasks: toggle, run now, logs, remove, notifications |
| `app/src/components/projects/home/ConfigTab.tsx` | Config sections (Workspace, Model, Access, Runtime) |
| `app/src/components/projects/home/FilesTab.tsx` | File browser (browse, download, upload) |
| `app/src/components/projects/home/CapabilityTiles.tsx` | Read-only skills/agents/commands/hooks/plugins/MCP counts |
| `app/src/components/projects/ClaudeCodeSettingsEditor.tsx` | Claude Code CLI settings (TUI mode, effort, focus, caching) |
| `app/src/components/ui/` | Shared primitives: `Modal`, `Button`, `Toggle`, `Field`, `SegmentedControl`, `StatusIndicator`, `SaveIndicator`, `OverflowMenu`, `ToastHost`, `Tooltip` |
| `app/src/hooks/useKeyboardShortcuts.ts` | `Ctrl+T`, `Ctrl+Shift+W`, `Ctrl+Tab`, `Ctrl+1..9` |
| `app/src/hooks/useContainerProgress.ts` | `container-progress` event → inline progress lines |
| `app/src/components/settings/SettingsPanel.tsx` | Docker, AWS, timezone, web terminal, shared auth, and global settings |
| `app/src/components/settings/SharedAuthSettings.tsx` | Acquire / revoke the shared Claude authentication token |
| `app/src/components/settings/WebTerminalSettings.tsx` | Web terminal toggle, URL, token management | | `app/src/components/settings/WebTerminalSettings.tsx` | Web terminal toggle, URL, token management |
| `app/src/components/settings/SttSettings.tsx` | STT settings panel (model, port, language, container controls) | | `app/src/components/settings/SttSettings.tsx` | STT settings panel (model, port, language, container controls) |
| `app/src/components/terminal/TerminalView.tsx` | xterm.js terminal with WebGL, URL detection, OSC 52 clipboard, image paste | | `app/src/components/terminal/TerminalView.tsx` | xterm.js terminal with WebGL, URL detection, OSC 52 clipboard, image paste |
| `app/src/components/terminal/SttButton.tsx` | Mic button overlay with on-demand container start | | `app/src/components/terminal/SttButton.tsx` | Mic button with on-demand STT container start |
| `app/src/components/terminal/TerminalTabs.tsx` | Tab bar for multiple terminal sessions (claude + bash) |
| `app/src/hooks/useTerminal.ts` | Terminal session management (claude and bash modes) | | `app/src/hooks/useTerminal.ts` | Terminal session management (claude and bash modes) |
| `app/src/hooks/useProjectActions.ts` | Start/stop/reset/backup and terminal-opening helpers |
| `app/src/hooks/useFileManager.ts` | File manager operations (list, download, upload) | | `app/src/hooks/useFileManager.ts` | File manager operations (list, download, upload) |
| `app/src/hooks/useMcpServers.ts` | MCP server CRUD operations | | `app/src/hooks/useClaudeAuth.ts` | Shared-token status and acquisition |
| `app/src/hooks/useSTT.ts` | Speech-to-text recording, transcription, and container management | | `app/src/hooks/useSTT.ts` | Speech-to-text recording, transcription, and container management |
| `app/src-tauri/src/docker/container.rs` | Container creation, mounts, env vars, MCP injection, fingerprinting | | `app/src-tauri/src/docker/container.rs` | Container creation, mounts, env vars, labels, recreation checks, `remove_project_volumes` |
| `app/src-tauri/src/docker/exec.rs` | PTY exec sessions, file upload/download via tar | | `app/src-tauri/src/docker/exec.rs` | `create_attached_exec()` — the single attached-exec path; file upload/download via tar |
| `app/src-tauri/src/docker/image.rs` | Image building/pulling | | `app/src-tauri/src/docker/image.rs` | Image building/pulling |
| `app/src-tauri/src/docker/network.rs` | Per-project bridge networks for MCP containers | | `app/src-tauri/src/docker/stt.rs` | Speech-to-text container lifecycle |
| `app/src-tauri/src/docker/legacy_cleanup.rs` | One-release migration shim removing leftovers from the deleted MCP feature |
| `app/src-tauri/src/auth_bridge/` | Loopback callback bridge (`mod.rs`, `proc_net.rs`, `tunnel.rs`) |
| `app/src-tauri/src/commands/project_commands.rs` | Start/stop/rebuild Tauri command handlers | | `app/src-tauri/src/commands/project_commands.rs` | Start/stop/rebuild Tauri command handlers |
| `app/src-tauri/src/commands/inspect_commands.rs` | Read-only container views: sessions, capabilities, scheduler tasks |
| `app/src-tauri/src/commands/auth_token_commands.rs` | `claude setup-token` flow, redaction, keychain storage |
| `app/src-tauri/src/commands/auth_bridge_commands.rs` | Auth bridge enable/status commands |
| `app/src-tauri/src/commands/file_commands.rs` | File manager Tauri commands (list, download, upload) | | `app/src-tauri/src/commands/file_commands.rs` | File manager Tauri commands (list, download, upload) |
| `app/src-tauri/src/commands/mcp_commands.rs` | MCP server CRUD Tauri commands | | `app/src-tauri/src/models/project.rs` | Project struct (backend, `PermissionMode`, Docker access, Claude Code settings, Mission Control, auth bridge, shared-token opt-out) |
| `app/src-tauri/src/models/project.rs` | Project struct (backend, Docker access, Claude Code settings, MCP servers, Mission Control) |
| `app/src-tauri/src/models/mcp_server.rs` | MCP server struct (transport, Docker image, env vars) |
| `app/src-tauri/src/models/app_settings.rs` | Global settings (image source, Docker socket, AWS, Claude Code settings, web terminal, STT) | | `app/src-tauri/src/models/app_settings.rs` | Global settings (image source, Docker socket, AWS, Claude Code settings, web terminal, STT) |
| `app/src-tauri/src/web_terminal/server.rs` | Axum HTTP+WS server for remote terminal access | | `app/src-tauri/src/web_terminal/server.rs` | Axum HTTP+WS server for remote terminal access |
| `app/src-tauri/src/web_terminal/ws_handler.rs` | WebSocket connection handler and session management | | `app/src-tauri/src/web_terminal/ws_handler.rs` | WebSocket connection handler and session management |
| `app/src-tauri/src/web_terminal/terminal.html` | Embedded web UI (xterm.js, project picker, tabs) | | `app/src-tauri/src/web_terminal/terminal.html` | Embedded web UI (xterm.js, project picker, tabs) |
| `app/src-tauri/src/commands/stt_commands.rs` | STT start/stop/transcribe Tauri commands | | `app/src-tauri/src/commands/stt_commands.rs` | STT start/stop/transcribe Tauri commands |
| `app/src-tauri/src/commands/web_terminal_commands.rs` | Web terminal start/stop/status Tauri commands | | `app/src-tauri/src/commands/web_terminal_commands.rs` | Web terminal start/stop/status Tauri commands |
| `app/src-tauri/src/storage/mcp_store.rs` | MCP server persistence (JSON with atomic writes) |
| `app/src-tauri/src/docker/stt.rs` | STT Docker container lifecycle (create, start, stop, build, pull) | | `app/src-tauri/src/docker/stt.rs` | STT Docker container lifecycle (create, start, stop, build, pull) |
| `app/src/lib/wav.ts` | WAV audio encoding for STT transcription | | `app/src/lib/wav.ts` | WAV audio encoding for STT transcription |
| `stt-container/Dockerfile` | Faster Whisper STT container image (Python 3.11 + FastAPI) | | `stt-container/Dockerfile` | Faster Whisper STT container image (Python 3.11 + FastAPI) |
| `stt-container/server.py` | STT HTTP server (POST /transcribe endpoint) | | `stt-container/server.py` | STT HTTP server (POST /transcribe endpoint) |
| `container/Dockerfile` | Ubuntu 24.04 sandbox image with Claude Code + dev tools + clipboard/audio shims | | `container/Dockerfile` | Ubuntu 24.04 sandbox image with Claude Code + dev tools + clipboard/audio shims |
| `container/entrypoint.sh` | UID/GID remap, SSH setup, Docker group config, MCP injection, Claude Code settings injection, Mission Control setup | | `container/entrypoint.sh` | UID/GID remap, SSH setup, Docker group config, Claude Code settings injection, Mission Control setup |
| `container/osc52-clipboard` | Clipboard shim (xclip/xsel/pbcopy via OSC 52) | | `container/osc52-clipboard` | Clipboard shim (xclip/xsel/pbcopy via OSC 52) |
| `container/audio-shim` | Audio capture shim (rec/arecord via FIFO) for voice mode | | `container/audio-shim` | Audio capture shim (rec/arecord via FIFO) for voice mode |
| `container/triple-c-scheduler` | Bash CLI managing scheduled task JSON and the crontab |
| `container/triple-c-task-runner` | Cron entry point; maps `TRIPLE_C_PERMISSION_MODE` to flags and runs `claude -p` |
| `container/triple-c-sso-refresh` | AWS SSO session refresh helper |
| `app/src-tauri/src/storage/secure.rs` | OS keychain access (per-project secrets, shared token, rotation id) |
## CSS / Styling Notes ## CSS / Styling Notes
+250
View File
@@ -0,0 +1,250 @@
# Triple-C Roadmap — Claude Code Feature Parity
**Date:** 2026-08-09 · **Baseline:** v0.3.0 · **Claude Code reference:** 2.1.226
Companion to [DESIGN-REVIEW.md](DESIGN-REVIEW.md), which covers visual design and
information architecture. This document covers *which Claude Code capabilities Triple-C
should surface, and why.*
---
## Guiding principle
> **Triple-C shows state and launches things. Claude Code edits its own config.**
Triple-C's built-in MCP server management was removed in this cycle because Claude Code
absorbed the capability natively (`claude mcp add/list/remove`, `.mcp.json`, `/mcp`).
Hooks, skills, agents, plugins, output styles, and statusline are the same species: files
under `.claude/` with first-class Claude Code TUIs. Building GUI form editors for them
means losing the same race again.
What Claude Code cannot do is what Triple-C uniquely owns: **the container boundary and
what persists behind it** — the config volume, workspace mounts, lifecycle, the bundled
scheduler, and the fleet view across many projects.
---
## Current coverage (v0.3.0)
Triple-C sets exactly five `settings.json` keys, plus a sandbox block:
| Key | Surfaced as |
|---|---|
| `tui` | TUI Mode select (`fullscreen`) |
| `effort` | Effort Level select (`low`/`medium`/`high`) |
| `autoScrollEnabled` | Auto-Scroll Disabled toggle |
| `focusMode` | Focus Mode toggle |
| `showThinkingSummaries` | Thinking Summaries toggle |
| `sandbox.*` | Sandbox toggle (`enabled`, `enableWeakerNestedSandbox`, `allowUnsandboxedCommands`) |
Plus four env feature flags — `CLAUDE_CODE_NO_FLICKER`, `CLAUDE_CODE_ENABLE_AWAY_SUMMARY`,
`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`, `ENABLE_PROMPT_CACHING_1H` — and arbitrary user-set
`CLAUDE_CODE_*` vars via the Env Vars modal.
Also covered: per-project auth backends (Anthropic OAuth, Bedrock incl. SSO refresh,
Ollama, OpenAI-compatible), user-level `CLAUDE.md` composition, `claude update` on every
container start, terminal ergonomics (OAuth URL detection, OSC 52 clipboard, image paste,
file drag-drop, STT), the web terminal, and workspace backup.
---
## Gap analysis
### Committed for this cycle
| # | Gap | Today | Plan |
|---|---|---|---|
| 1 | **Permission modes** | one boolean → `--dangerously-skip-permissions` | Four-state control (Plan / Default / Accept Edits / Bypass) → `--permission-mode`. Verified choices on 2.1.226: `acceptEdits`, `auto`, `bypassPermissions`, `manual`, `dontAsk`, `plan`. |
| 2 | **Session resume** | none | List sessions from the config volume; `[Resume]` opens a terminal on `claude --resume <id>`. |
| 3 | **Capability inventory** | none | Read-only counts + names for skills / agents / hooks / plugins / commands / native MCP servers. Deep-link to the terminal to manage. |
| 4 | **Automation** | `triple-c-scheduler` ships in every container with *zero* UI | Task list, cron editor, run-now, logs, notification badges. |
| 5 | **Container auth handoff** | manual code paste | See "Authentication handoff" below — design decision pending. |
### Deliberately skipped
Status line builder · output-styles editor · hook *editors* · checkpoint/rewind browser ·
plugin marketplace browser. Each is niche, natively handled by Claude Code's own TUI, or a
settings-editor trap. Surface counts and deep-link instead.
### Not yet scheduled
- Granular `permissions.allow` / `ask` / `deny` rules and `additionalDirectories`
- Sandbox detail settings (`filesystem.allowRead/allowWrite`, `allowedDomains`,
`excludedCommands`) — currently documented for hand-editing via `SANDBOX_INSTRUCTIONS`
- Project-level `.claude/settings.json` vs user-level settings hierarchy
- A model picker. **Note:** the only model strings in the app today are stale placeholders
(`anthropic.claude-sonnet-4-20250514-v1:0` in `AwsSettings.tsx` and `ProjectCard.tsx`,
`qwen3.5:27b`, `gpt-4o / gemini-pro / etc.`). These are free-text placeholders, not
dropdowns, but they should be refreshed to current model identifiers regardless.
- The container's settings.json merge is **shallow** (`jq -s '.[0] * .[1]'`), so a
user-authored nested block such as `sandbox.filesystem.allowWrite` is replaced wholesale
on every container start. Worth deepening to `*` recursive merge.
---
## Authentication handoff
**Goal:** stop making users hand-copy an auth code into every container.
**Constraint discovered during research:** `claude login`'s callback server uses an
**ephemeral port** and its redirect URI is **not configurable** for the main login flow
(`--callback-port` and `oauth.callbackPort` apply to *MCP server* OAuth only). So a design
that pre-assigns each container a fixed callback port and routes to it cannot work as
stated — there is no fixed port to route.
There is also a known container gotcha: on Linux, Node resolves `localhost` to IPv6 first,
so the callback server may bind `[::1]:PORT` only and be unreachable over IPv4
([anthropics/claude-code#44844](https://github.com/anthropics/claude-code/issues/44844)).
Two viable options:
### Option A — long-lived token injection (simple)
`claude setup-token` (verified present on 2.1.226: *"Set up a long-lived authentication
token (requires Claude subscription)"*) returns a ~1-year OAuth token. Triple-C runs it in
a running container, stores the token in the OS keychain via the existing `secure.rs`, and
injects `CLAUDE_CODE_OAUTH_TOKEN` into every container on the Anthropic backend.
**Correction to an earlier assumption in this document.** `setup-token` does *not* start a
loopback callback listener, so it does not need the Auth Bridge. Verified by running it
under a pty: its `redirect_uri` is Anthropic-hosted
(`https://platform.claude.com/oauth/code/callback`), the user copies a code off that page,
and the CLI blocks at a `Paste code here if prompted >` prompt on **stdin**. A stdin path
is therefore mandatory — the flow cannot complete without one.
- No routing, no ports, no proxy.
- One auth event covers every project.
- Cost: small. Reuses existing keychain and env-injection plumbing.
- Limits: token is subscription-scoped and expires annually; per the docs a `setup-token`
token cannot drive Remote Control sessions or claude.ai connector fetches.
Change detection uses a **random rotation id** in the `triple-c.claude-token-version`
label, not a hash of the token. Labels are readable by anything that can run
`docker inspect`, so a hash would be an offline verification oracle — given a candidate
token you could confirm it. A presence boolean would instead miss rotations and silently
leave containers on a stale token.
### Option B — the Auth Bridge (general loopback-callback bridge)
Option A only solves Claude Code. The same problem affects every CLI that authenticates by
starting a temporary loopback listener and opening a browser at a URL that redirects back
to it — Concourse `fly login` (random loopback port serving `/auth/callback`),
`aws sso login`, and many others. Inside a container the host browser cannot reach that
listener, so login stalls.
Because the ports are ephemeral and unconfigurable, nothing can be pre-assigned. The bridge
**discovers** listeners instead:
1. While enabled for a running project, poll the container for loopback TCP listeners by
reading `/proc/net/tcp` and `/proc/net/tcp6` over `docker exec` — no dependency on
`ss`/`netstat`/`lsof`, which aren't guaranteed in the image.
2. For each newly-appeared loopback listener, bind **the same port on the host's
`127.0.0.1`** (never `0.0.0.0` — that would expose container internals to the LAN).
3. Proxy each accepted connection into the container over the Docker API via
`socat - TCP:127.0.0.1:<port>` (socat already ships in the image), reusing the existing
attached-exec streaming in `docker/exec.rs`. Going through the Docker API rather than a
container IP keeps this working on Docker Desktop, where container IPs are not routable
from the host.
4. Fall back to `TCP6:[::1]:<port>` when the listener appeared only on IPv6 — on Linux,
Node resolves `localhost` to IPv6 first, so `claude login` frequently binds `::1` only
([anthropics/claude-code#44844](https://github.com/anthropics/claude-code/issues/44844)).
5. Tear down when the listener vanishes, the container stops, the bridge is disabled, or
the app exits. Ports already covered by the project's explicit port mappings are skipped;
host-side conflicts are reported rather than silently swallowed.
Opt-in per project (`auth_bridge_enabled`, default off), since it makes container-internal
loopback services reachable from the host.
**Plan:** ship **A** for Claude Code specifically — it removes the pain for the common case
at a fraction of the cost — and **B** as the general mechanism covering every other CLI.
They compose: A means most users never trigger a browser login at all; B catches AWS SSO,
Concourse, and anything else that needs a real callback.
---
## Sequencing
**Phase 0 — done.** Remove MCP (frontend, backend, entrypoint, docs) with a self-healing
migration for containers created against the old per-project Docker network.
**Phase 1 — foundations.** Permission modes end-to-end (including the scheduler bug fix
below). Read-only introspection backend: sessions, capabilities, scheduler.
**Phase 2 — Tier-1 polish.** Focus rings, contrast fixes, real buttons, inline start/stop
progress, status labels, onboarding welcome screen, shared accessible `<Modal>`.
**Phase 3 — Project Home.** Move project config out of the sidebar card into a tabbed
main-area view (Overview / Sessions / Automation / Config), dissolving the modal pile and
splitting the 1,257-line `ProjectCard`.
**Phase 4 — authentication handoff.** Option A, then evaluate B.
**Phase 5 — Library.** Global skills/agents/commands with per-project enable, synced into
the config volume by the entrypoint. Generalizes the pattern the MCP tab was reaching for.
---
## Bugs found during this review
1. **Scheduled tasks ignore the project's permission setting.**
`container/triple-c-task-runner:69` runs
`claude -p "$PROMPT" --dangerously-skip-permissions` unconditionally, regardless of the
project's Full Permissions toggle. Being fixed as part of Phase 1.
2. **Docs claim Reset preserves credentials; it does not.**
`rebuild_project_container` calls `remove_project_volumes`, which deletes both
`triple-c-home-{id}` (holding `~/.claude.json`) and `triple-c-claude-config-{id}`
(holding `~/.claude`). README.md, HOW-TO-USE.md, and CLAUDE.md all still state that
OAuth tokens survive a Reset. Pre-existing; not yet corrected.
3. **An invalid cron expression silently unscheduled every task.** Found while adding
task creation to the Automation tab, and the most serious bug in this review.
`triple-c-scheduler` never validated `--schedule`, and `rebuild_crontab` regenerates the
*entire* crontab and pipes it to `crontab`, which rejects the whole file if any single
line is malformed — with the error discarded by `2>/dev/null || true`. So one bad
schedule silently unscheduled every other task in the container, reporting success.
Reproduced directly. This mattered because the global CLAUDE.md instructs Claude to use
this CLI, so Claude itself could trigger it. Fixed at the root: `add` now validates the
expression and exits non-zero, and `rebuild_crontab` reports a rejected crontab instead
of swallowing it. The Rust `add_scheduled_task` command validates independently.
4. **Reset was destructive with no confirmation.** It deletes both volumes — the login,
installed skills, all session transcripts — from a single unconfirmed click, while the
comparably destructive Remove already confirmed. Now gated by a dialog that names each
loss. Fixed.
5. **Cancelling authentication did not cancel.** Fixed — see the handoff section above.
6. **Stale model placeholders** — see "Not yet scheduled" above.
7. **Silent save failures.** Project config saves on blur; failures went only to
`console.error`. Fixed in Phase 3 — `useProjectSave` now renders a
Saved / Saving / Save failed indicator and raises a toast.
---
## Known gaps left by Phase 23
- **Editing a scheduled task changes its id.** `triple-c-scheduler` has no `edit`
subcommand, and hand-editing its JSON behind its back would desync the crontab, so edit is
implemented as add-then-remove. The add runs first, so a rejected edit leaves the original
intact. The task gets a new id and its older logs stay under the old one; the editor says
so before saving.
- **`open_terminal_session` takes no command argument.** "Resume session" and
"Manage in terminal" therefore open a bash tab and *type* the command after a
fixed prompt delay. It works, but it is timing-dependent and will misfire on a
slow container start. The fix is a `command: Option<String>` parameter on the
Tauri command so the exec launches the process directly.
- **Uptime is observed, not reported.** `get_container_info` returns a status enum
with no start time, so Project Home records "running since" when the app *sees*
the transition. A container already running when the app launches shows
`● Running` with no elapsed time. Surfacing Docker's `State.StartedAt` would fix it.
- **`lucide-react` was not adopted** (DESIGN-REVIEW Tier-1 #9) — no package-registry
access in the build environment used for this cycle. The existing inline SVGs and
text glyphs remain.
- **The tab strip stayed in the TopBar** rather than moving onto the terminal panel's
top edge. DESIGN-REVIEW §A6 asks for the move but its own §B2 layout diagram puts
the tabs in the TopBar; the diagram won. Worth revisiting.
- **`Ctrl+Shift+W`, not `Ctrl+W`, closes a tab.** Plain `Ctrl+W` is readline's
`kill-word`, used constantly inside the terminal this app is built around;
intercepting it globally would break word-erase in every shell.
+249 -47
View File
@@ -2,7 +2,7 @@
## Overview ## Overview
Triple-C (Claude-Code-Container) sandboxes Claude Code inside Docker containers so that when running with `--dangerously-skip-permissions`, Claude only has access to files and projects you explicitly provide. The project consists of two components: a **Docker container image** pre-loaded with development tools, and a **cross-platform desktop application** for managing project containers, terminal sessions, and authentication. Triple-C (Claude-Code-Container) sandboxes Claude Code inside Docker containers so that even in its most permissive mode — `--dangerously-skip-permissions` Claude only has access to files and projects you explicitly provide. The project consists of two components: a **Docker container image** pre-loaded with development tools, and a **cross-platform desktop application** for managing project containers, terminal sessions, and authentication.
--- ---
@@ -57,6 +57,16 @@ Tauri uses a Rust backend paired with a web-based frontend rendered by the OS-na
- **Web links addon**`@xterm/addon-web-links` makes URLs in terminal output clickable. Combined with `tauri-plugin-opener`, clicked URLs open in the host browser — essential for the `claude login` OAuth flow where Claude prints an authentication URL that must be opened on the host. - **Web links addon**`@xterm/addon-web-links` makes URLs in terminal output clickable. Combined with `tauri-plugin-opener`, clicked URLs open in the host browser — essential for the `claude login` OAuth flow where Claude prints an authentication URL that must be opened on the host.
- **Bidirectional data flow** — xterm.js exposes `term.onData()` for user keystrokes and `term.write()` for incoming data. This maps directly to our Tauri event-based streaming architecture. - **Bidirectional data flow** — xterm.js exposes `term.onData()` for user keystrokes and `term.write()` for incoming data. This maps directly to our Tauri event-based streaming architecture.
#### Terminal Layout & StatusBar Controls
Implementation gotchas for the terminal view and its global controls (merged in PR #7, `terminal-layout-statusbar`):
- **xterm padding lives on a wrapper, never the host.** FitAddon measures the same element that `term.open()` mounts into, so any padding on that host element makes the grid overhang and clip its rightmost column / bottom row. Padding must live on a **wrapper `div`**; the xterm host fills it with no padding of its own. Do not reintroduce padding on the host element in `TerminalView.tsx`.
- **STT mic and "Jump to Current" live in the global `StatusBar`, not per-terminal overlays.** There is a single `useSTT` instance in `App.tsx` bound to the active session. `Ctrl+Shift+M` routes through the Zustand store (`sttToggle`).
- **Recording is pinned to where it started.** The STT transcript targets `recordingSessionIdRef` (the session recording began in), **not** the live active session — switching tabs mid-recording must not misroute the transcript.
- **"Jump to Current" state is written only by the active terminal.** The active `TerminalView` surfaces `terminalAtBottom` and `scrollActiveToBottom` through the store; only the active terminal writes them, and they are cleared on its unmount.
- **Set store function values via object-merge, not the updater form**`set({ fn: value })`, not `set(state => ...)` — when publishing action callbacks (like `scrollActiveToBottom`) into the Zustand store.
### bollard (Docker API) ### bollard (Docker API)
**Chosen over:** Shelling out to the `docker` CLI, dockerode (Node.js), docker-api (Python) **Chosen over:** Shelling out to the `docker` CLI, dockerode (Node.js), docker-api (Python)
@@ -113,7 +123,8 @@ Tauri uses a Rust backend paired with a web-based frontend rendered by the OS-na
┌──────────────────────────────────────────────────────────┐ ┌──────────────────────────────────────────────────────────┐
│ Docker Container (per project) │ │ Docker Container (per project) │
│ │ │ │
│ /workspace ←─ bind mount ─► Host project directory │ /workspace/<name> ←─ bind mount ─► Host project folder
│ /home/claude ←── named volume (home dir) │
│ /home/claude/.claude ←── named volume (persists config) │ │ /home/claude/.claude ←── named volume (persists config) │
│ /tmp/.host-ssh ←── read-only bind mount (SSH keys) │ │ /tmp/.host-ssh ←── read-only bind mount (SSH keys) │
│ /var/run/docker.sock ←── optional (sibling containers) │ │ /var/run/docker.sock ←── optional (sibling containers) │
@@ -150,22 +161,143 @@ Terminal resize follows the same pattern: `ResizeObserver` detects container siz
Containers follow a **stop/start** model, not create/destroy: Containers follow a **stop/start** model, not create/destroy:
1. **First start**: A new container is created with bind mounts, environment variables, and labels. The entrypoint remaps UID/GID, configures SSH and git, then runs `sleep infinity` to keep the container alive. 1. **First start**: A new container is created with bind mounts, named volumes, environment variables, and labels. The entrypoint remaps UID/GID, configures SSH and git, rebuilds the scheduler crontab, then runs `sleep infinity` to keep the container alive.
2. **Terminal open**: `docker exec` launches `claude --dangerously-skip-permissions` with a PTY in the running container. 2. **Terminal open**: `docker exec` launches `claude` with a PTY in the running container, with the permission-mode flags from `PermissionMode::cli_args()` (or `bash -l` for a shell session).
3. **Stop**: `docker stop` halts the container but preserves its filesystem. Any packages Claude installed via `apt`, `pip`, `cargo`, etc. survive. 3. **Stop**: `docker stop` halts the container but preserves its filesystem. Any packages Claude installed via `apt`, `pip`, `cargo`, etc. survive.
4. **Restart**: `docker start` resumes the existing container. All installed tools and configuration persist. 4. **Restart**: `docker start` resumes the existing container — unless `container_needs_recreation()` finds a `triple-c.*` label that no longer matches the project's settings, in which case the container is committed to a snapshot image (`triple-c-snapshot-{projectId}:latest`), removed, and recreated from that snapshot. Installed tools survive; the named volumes are untouched.
5. **Reset**: The container is removed and recreated from the image. This is a clean slate — the nuclear option when the container state is corrupted. 5. **Reset**: `rebuild_project_container` closes live exec sessions, removes the container, removes the snapshot image, calls `remove_project_volumes` to delete **both** named volumes, then starts fresh from the clean base image.
The `.claude` configuration directory uses a **named Docker volume** (`triple-c-claude-config-{projectId}`) so OAuth tokens from `claude login` persist even across container resets. Two named volumes exist per project and they are the only ones it owns:
| Volume | Mount point | Purpose |
|---|---|---|
| `triple-c-home-{projectId}` | `/home/claude` | Home directory — `~/.claude.json`, `~/.local`, `~/.ssh`, `~/.aws` |
| `triple-c-claude-config-{projectId}` | `/home/claude/.claude` | Claude Code config: OAuth credential, settings, skills/agents/commands, session transcripts, scheduler state. Nested inside the home volume; Docker gives the more specific mount precedence. |
`remove_project_volumes` names those two volumes explicitly (no prefix sweep) and is called from
exactly two places: `remove_project` and `rebuild_project_container`. Ordinary container removal
passes `v: false`, so stop/start and recreation never touch the volumes — **only Reset and project
removal delete them.** A Reset therefore destroys the `claude login` credential, installed skills,
session transcripts and scheduled tasks; it does not touch host bind mounts, the project record, or
host keychain secrets.
### Permission Modes
`PermissionMode` (`models/project.rs`) is a four-state enum replacing the earlier `full_permissions`
boolean. It reaches Claude Code by two different routes:
| Mode | `cli_args()` — interactive terminals | `as_env_value()` — scheduler |
|---|---|---|
| `Plan` | `--permission-mode plan` | `plan` |
| `Default` | *(no flag)* | `default` |
| `AcceptEdits` | `--permission-mode acceptEdits` | `acceptEdits` |
| `Bypass` | `--dangerously-skip-permissions` | `bypass` |
`Project.permission_mode` is `Option<PermissionMode>`, and `effective_permission_mode()` resolves
`None` from the legacy `full_permissions` flag, so records written before the change keep behaving
the same way.
**Interactive path.** `build_terminal_cmd()` evaluates `cli_args()` when a session is created, so
the flags are fixed for the life of that `claude` process. Changing the mode affects terminals
opened afterwards, not running ones. The same applies to `resume_session_command`, which builds
`claude <flags> --resume <id>` server-side.
**Scheduler path.** Cron jobs run with a minimal environment, so the mode travels as
`TRIPLE_C_PERMISSION_MODE` in the container's env; the entrypoint snapshots the allowlisted
variables into `~/.claude/scheduler/.env`, and `triple-c-task-runner` sources that file and maps the
value back to flags for its `claude -p` run. Container env can only change at create time, so
`container_needs_recreation()` compares a `triple-c.permission-mode` label and forces a recreation
on the next start. A mode change therefore reaches new terminals immediately but the scheduler only
after a stop/start. `TRIPLE_C_PERMISSION_MODE` is a reserved env key so it cannot be hand-set.
### Authentication Modes ### Authentication Modes
Each project independently chooses one of two authentication methods: Each project independently chooses one backend:
| Mode | How It Works | When to Use | | Backend | How It Works | When to Use |
|------|-------------|-------------| |------|-------------|-------------|
| **Anthropic (OAuth)** | User runs `claude login` or `/login` inside the terminal. OAuth URL opens in host browser via URL detection. Token persists in the `.claude` config volume. | Default — personal and team use | | **Anthropic** | Either the shared `CLAUDE_CODE_OAUTH_TOKEN` injected from the OS keychain, or a per-container `claude login` whose credential persists in the `.claude` config volume. The OAuth URL opens in the host browser via URL detection. | Default — personal and team use |
| **AWS Bedrock** | Per-project AWS credentials (static keys, profile, or bearer token) injected as env vars. `~/.aws` config optionally bind-mounted read-only. | Enterprise environments using Bedrock | | **AWS Bedrock** | Per-project AWS credentials (static keys, named profile, or bearer token) injected as env vars. `~/.aws` config optionally bind-mounted read-only; SSO sessions are validated before launching Claude for profile auth. | Enterprise environments using Bedrock |
| **Ollama** | `ANTHROPIC_BASE_URL` points at an Ollama server; `ANTHROPIC_AUTH_TOKEN` is set to a placeholder. | Local models (best-effort) |
| **OpenAI Compatible** | `ANTHROPIC_BASE_URL` plus `ANTHROPIC_AUTH_TOKEN` point at any OpenAI-compatible endpoint (LiteLLM, OpenRouter, vLLM, …). | Gateways and proxies (best-effort) |
### Shared Claude Authentication Token
`commands/auth_token_commands.rs` runs `claude setup-token` on a PTY inside a running container.
Contrary to the loopback pattern most CLI logins use, `setup-token` redirects to an Anthropic-hosted
page and then blocks on a stdin paste prompt, so the flow needs a way to feed the pasted code back
in — hence `submit_claude_token_code`. The flow is single-flight (the token is global, so two
concurrent logins would race to overwrite each other's keychain entry) and times out after 15
minutes.
- **Storage** — the OS keychain, under a dedicated service name; the token is never returned to the
frontend, never written to a log, and no command accepts or returns it.
- **Redaction** — streamed output is stripped of ANSI sequences and passed through a stateful
redactor that masks anything matching `sk-ant-` with a plausible body, withholding any tail that
could still grow into a secret across a chunk boundary.
- **Injection**`CLAUDE_CODE_OAUTH_TOKEN` is set only when the backend is Anthropic, the project
has not opted out (`use_shared_auth_token`, default `true`), and a non-blank token is stored. When
those conditions do not hold, the variable is explicitly set to empty rather than omitted, so a
value baked into a snapshot image by `docker commit` is actively cleared.
- **Rotation** — a random UUID minted on each store is mirrored into the
`triple-c.claude-token-version` label. It is deliberately *not* a hash of the token: labels are
readable by anything that can run `docker inspect`, and a hash would be an offline verification
oracle. A label mismatch forces container recreation on the next start, which is when a container
picks up or loses the token.
### Auth Bridge
CLIs that log in through a browser (`claude login`, `aws sso login`, `fly login`) start an ephemeral
HTTP listener on an unpredictable loopback port and hand the provider a `http://localhost:<port>/…`
redirect. Run inside a container, that listener is unreachable from the host browser and nothing can
be pre-published at container-creation time. `auth_bridge/` bridges it at runtime:
- **Discovery** (`proc_net.rs`) — a `docker exec` reads `/proc/net/tcp` and `/proc/net/tcp6` every
two seconds. The image ships no `ss`, `netstat` or `lsof`. Only rows in state `0A` (`TCP_LISTEN`)
bound to loopback are kept; wildcard binds are ignored on purpose, since publishing those is the
port-mappings feature's job.
- **Family handling** — a `::1`-only listener genuinely cannot be reached over `127.0.0.1`, and Node
resolves `localhost` to IPv6 first on Linux, so `claude login` frequently binds `::1` alone. The
socat target follows the family actually observed; IPv4-mapped rows in `/proc/net/tcp6` are
treated as IPv4.
- **Host bind** (`tunnel.rs`) — the same port number is bound on the host: `127.0.0.1` is required,
`[::1]` is best-effort. **The host side binds loopback only, never a wildcard address**
everything behind it is an unauthenticated in-container service that bound loopback precisely
because it expected to be unreachable.
- **Transport** — each accepted connection is proxied by an attached exec running
`socat - TCP:127.0.0.1:<port>`, because container IPs are not routable from the host under Docker
Desktop. It goes through the same `create_attached_exec()` helper as terminal sessions, with
`tty: false` so socat's stderr is demultiplexed away from the proxied byte stream.
- **Policy** — ports appearing in the project's port mappings are skipped, and a host bind failure
is recorded as a conflict and retried later rather than fought over.
- **Lifecycle** — opt-in per project (`auth_bridge_enabled`, default `false`). It is purely
host-side, so it deliberately has no container-recreation label. The poller stops itself when the
project is gone, the flag is cleared, or the container is no longer running, and `stop()` awaits
it so host ports are provably released.
### Container Introspection
`list_container_capabilities` (`commands/inspect_commands.rs`) executes a read-only shell script in
a running container and returns counts and item lists for skills, agents, commands, hooks, plugins
and MCP servers, across user scope (`/home/claude/.claude`) and project scope
(`/workspace/*/.claude`, `/workspace/*/.mcp.json`). Everything is computed in-container with
`find`/`awk`/`jq`; only the JSON summary crosses the wire, and a stopped container yields zeros
rather than an error.
The script writes nothing. Claude Code owns this configuration and has its own tooling for it
(`/agents`, `/hooks`, `/plugins`, `/mcp`); Triple-C surfaces counts and opens a terminal rather than
rebuilding those editors as forms. `list_claude_sessions` and the scheduler commands
(`list_scheduled_tasks`, `get_scheduled_task_log`, `set_scheduled_task_enabled`,
`run_scheduled_task_now`, `remove_scheduled_task`, `clear_scheduler_notifications`) live in the same
module; the mutating ones shell out to `triple-c-scheduler` rather than editing its state files.
### Main-Area Tab Model
The frontend keeps a single ordered `tabOrder` array in the Zustand store holding two tab kinds,
`home:<projectId>` and `term:<sessionId>`, rendered by `components/layout/MainTabs.tsx`.
`activeSessionId` is *derived* from `activeTabKey`, so exactly one thing is current and a Project
Home tab and a terminal cannot both claim focus. Project configuration is a main-area view
(`components/projects/home/`), not a modal; the sidebar row is select-only.
### UID/GID Remapping ### UID/GID Remapping
@@ -195,10 +327,12 @@ This avoids the common Docker problem where bind-mount permissions can't be chan
| Data | Storage | Location | | Data | Storage | Location |
|------|---------|----------| |------|---------|----------|
| Project configurations | JSON file (atomic writes) | `~/.local/share/triple-c/projects.json` | | Project configurations | JSON file (atomic writes) | `~/.local/share/triple-c/projects.json` |
| API keys | OS keychain | macOS Keychain / Windows Credential Manager / Linux Secret Service | | API keys and per-project secrets | OS keychain | macOS Keychain / Windows Credential Manager / Linux Secret Service |
| Shared Claude token + rotation id | OS keychain | Separate service entries; never on disk, never in a label |
| App settings | Tauri plugin-store | App data directory | | App settings | Tauri plugin-store | App data directory |
| Claude config/tokens | Named Docker volume | `triple-c-claude-config-{projectId}` | | Claude config, sessions, scheduler state | Named Docker volume | `triple-c-claude-config-{projectId}` |
| Container filesystem | Docker container layer | Preserved across stop/start, cleared on reset | | Container home directory | Named Docker volume | `triple-c-home-{projectId}` |
| Container filesystem | Docker container layer, preserved into `triple-c-snapshot-{projectId}:latest` on recreation | Survives stop/start and recreation; destroyed by Reset |
The projects store uses **atomic writes** (write to `.json.tmp`, then `rename()`) to prevent data corruption if the app crashes mid-write. Corrupted files are backed up to `.json.bak` before being replaced. The projects store uses **atomic writes** (write to `.json.tmp`, then `rename()`) to prevent data corruption if the app crashes mid-write. Corrupted files are backed up to `.json.bak` before being replaced.
@@ -220,98 +354,159 @@ The `TerminalView` component works around this with a **URL accumulator**:
triple-c/ triple-c/
├── README.md # Architecture overview ├── README.md # Architecture overview
├── TECHNICAL.md # This document ├── TECHNICAL.md # This document
├── HOW-TO-USE.md # User guide ├── HOW-TO-USE.md # User guide (also served by the in-app Help dialog)
├── BUILDING.md # Build instructions ├── BUILDING.md # Build instructions
├── CLAUDE.md # Claude Code instructions ├── CLAUDE.md # Claude Code instructions
├── DESIGN-REVIEW.md # UI/UX review notes
├── ROADMAP.md # Planned work
├── container/ ├── container/ # Sandbox image
│ ├── Dockerfile # Ubuntu 24.04 + all dev tools + Claude Code │ ├── Dockerfile # Ubuntu 24.04 + all dev tools + Claude Code
│ ├── entrypoint.sh # UID/GID remap, SSH setup, git config, MCP injection │ ├── entrypoint.sh # UID/GID remap, SSH setup, git config, settings injection,
│ │ # scheduler env snapshot + crontab rebuild
│ ├── osc52-clipboard # Clipboard shim (xclip/xsel/pbcopy via OSC 52) │ ├── osc52-clipboard # Clipboard shim (xclip/xsel/pbcopy via OSC 52)
│ ├── audio-shim # Audio capture shim (rec/arecord via FIFO) │ ├── audio-shim # Audio capture shim (rec/arecord via FIFO)
│ ├── triple-c-scheduler # Bash-based cron task system │ ├── triple-c-scheduler # Bash-based cron task system
── triple-c-task-runner # Task execution runner for scheduler ── triple-c-task-runner # Cron entry point; permission mode → flags → `claude -p`
│ ├── triple-c-sso-refresh # AWS SSO session refresh helper
│ └── mission-control/ # Bundled Flight Control methodology (skills, docs, templates)
├── stt-container/ # Speech-to-text image
│ ├── Dockerfile # Faster Whisper (Python 3.11 + FastAPI)
│ └── server.py # POST /transcribe endpoint
├── .gitea/ ├── .gitea/
│ └── workflows/ │ └── workflows/
│ ├── build-app.yml # Build Tauri app (Linux/macOS/Windows) │ ├── build-app.yml # Build Tauri app (Linux/macOS/Windows)
│ ├── build-app-preview.yml # Preview builds
│ ├── build.yml # Build container image (multi-arch) │ ├── build.yml # Build container image (multi-arch)
│ ├── build-stt.yml # Build the STT image
│ ├── sync-release.yml # Mirror releases to GitHub │ ├── sync-release.yml # Mirror releases to GitHub
── backfill-releases.yml # Bulk copy releases to GitHub ── backfill-releases.yml # Bulk copy releases to GitHub
│ └── cleanup-releases.yml # Prune old releases
└── app/ # Tauri v2 desktop application └── app/ # Tauri v2 desktop application
├── package.json # React, xterm.js, zustand, tailwindcss ├── package.json # React, xterm.js, zustand, tailwindcss
├── vite.config.ts # Vite bundler config ├── vite.config.ts # Vite bundler config
├── vitest.config.ts # Vitest (jsdom) config
├── index.html # HTML entry point ├── index.html # HTML entry point
├── src/ # React frontend ├── src/ # React frontend
│ ├── main.tsx # React DOM root │ ├── main.tsx # React DOM root
│ ├── App.tsx # Top-level layout │ ├── App.tsx # Top-level layout + welcome screen
│ ├── index.css # CSS variables, dark theme, scrollbars │ ├── index.css # CSS variables, dark theme, focus ring, scrollbars
│ ├── store/ │ ├── store/
│ │ └── appState.ts # Zustand store (projects, sessions, MCP, UI) │ │ └── appState.ts # Zustand store (projects, sessions, tab strip, toasts)
│ ├── hooks/ │ ├── hooks/
│ │ ├── useClaudeAuth.ts # Shared token status + acquisition
│ │ ├── useContainerProgress.ts # container-progress events → inline progress
│ │ ├── useDocker.ts # Docker status, image build/pull │ │ ├── useDocker.ts # Docker status, image build/pull
│ │ ├── useFileManager.ts # File manager operations │ │ ├── useFileManager.ts # File browser operations
│ │ ├── useMcpServers.ts # MCP server CRUD │ │ ├── useInstallHelper.ts # Guided Docker installation
│ │ ├── useKeyboardShortcuts.ts # Ctrl+T / Ctrl+Shift+W / Ctrl+Tab / Ctrl+1..9
│ │ ├── useProjectActions.ts # Start/stop/reset/backup, open terminals
│ │ ├── useProjects.ts # Project CRUD operations │ │ ├── useProjects.ts # Project CRUD operations
│ │ ├── useSaveState.ts # Saved / Saving / Failed indicator state
│ │ ├── useSettings.ts # App settings │ │ ├── useSettings.ts # App settings
│ │ ├── useSTT.ts # Speech-to-text recording and container control
│ │ ├── useTerminal.ts # Terminal I/O, resize, session events │ │ ├── useTerminal.ts # Terminal I/O, resize, session events
│ │ ├── useUpdates.ts # App update checking │ │ ├── useUpdates.ts # App update checking
│ │ └── useVoice.ts # Voice mode audio capture │ │ └── useVoice.ts # Voice mode audio capture
│ ├── lib/ │ ├── lib/
│ │ ├── types.ts # TypeScript interfaces matching Rust models │ │ ├── types.ts # TypeScript interfaces matching Rust models
│ │ ├── tauri-commands.ts # Typed invoke() wrappers │ │ ├── tauri-commands.ts # Typed invoke() wrappers
│ │ ├── urlDetector.ts # Long-URL reassembly for OAuth flows
│ │ ├── wav.ts # WAV encoding for STT
│ │ └── constants.ts # App-wide constants │ │ └── constants.ts # App-wide constants
│ └── components/ │ └── components/
│ ├── layout/ # Sidebar, TopBar, StatusBar │ ├── DockerInstallDialog.tsx # First-run Docker setup
│ ├── mcp/ # McpPanel, McpServerCard │ ├── layout/ # TopBar, MainTabs (the unified tab strip),
├── projects/ # ProjectCard, ProjectList, AddProjectDialog, # Sidebar, StatusBar, HelpDialog
│ # FileManagerModal, ContainerProgressModal, modals ├── projects/
│ │ ├── home/ # Project Home — the main-area project view
│ │ │ ├── ProjectHome.tsx # Header, actions, overflow menu, tab strip
│ │ │ ├── OverviewTab.tsx # Permission mode, summary, recent activity
│ │ │ ├── SessionsTab.tsx # Past Claude sessions + Resume
│ │ │ ├── AutomationTab.tsx # Scheduler tasks + notifications
│ │ │ ├── ConfigTab.tsx # Config section host
│ │ │ ├── FilesTab.tsx # In-container file browser
│ │ │ ├── CapabilityTiles.tsx # Read-only capability counts
│ │ │ ├── format.ts # Age / size / uptime formatting
│ │ │ └── config/ # WorkspaceSection, ModelSection,
│ │ │ # AccessSection, RuntimeSection
│ │ ├── ProjectRow.tsx # Select-only sidebar row
│ │ ├── ProjectList.tsx # Sidebar project list
│ │ ├── AddProjectDialog.tsx # New-project dialog
│ │ ├── PermissionModeControl.tsx # Plan/Default/Accept Edits/Bypass
│ │ ├── ConfirmRemoveModal.tsx # Project removal confirmation
│ │ └── *Editor.tsx / *Modal.tsx # EnvVars, PortMappings,
│ │ # ClaudeInstructions, ClaudeCodeSettings —
│ │ # editors reused by Project Home
│ ├── settings/ # SettingsPanel, DockerSettings, AwsSettings, │ ├── settings/ # SettingsPanel, DockerSettings, AwsSettings,
│ │ # WebTerminalSettings, UpdateDialog │ │ # OllamaSettings, OpenAiCompatibleSettings,
└── terminal/ # TerminalView (xterm.js), TerminalTabs, UrlToast │ # SharedAuthSettings, ClaudeAuthModal,
│ │ # WebTerminalSettings, SttSettings,
│ │ # MicrophoneSettings, UpdateDialog, ImageUpdateDialog
│ ├── terminal/ # TerminalView (xterm.js), TerminalContextMenu,
│ │ # SttButton, UrlToast, trimSelection
│ └── ui/ # Shared primitives: Modal, Button, Toggle, Field,
│ # SegmentedControl, StatusIndicator, SaveIndicator,
│ # OverflowMenu, ToastHost, Tooltip, AccordionSection
└── src-tauri/ # Rust backend └── src-tauri/ # Rust backend
├── Cargo.toml # Rust dependencies ├── Cargo.toml # Rust dependencies
├── tauri.conf.json # Tauri app configuration ├── tauri.conf.json # Tauri app configuration
├── build.rs # Tauri build script
├── capabilities/ ├── capabilities/
│ └── default.json # Tauri v2 permission grants │ └── default.json # Tauri v2 plugin permission grants
└── src/ └── src/
├── lib.rs # App builder, plugin + command registration ├── lib.rs # App builder, plugin + command registration
├── main.rs # Entry point ├── main.rs # Entry point
├── logging.rs # Log configuration ├── logging.rs # Log configuration
├── commands/ # Tauri command handlers ├── commands/ # Tauri command handlers
│ ├── docker_commands.rs # Docker status, image ops │ ├── auth_bridge_commands.rs # Enable/status for the loopback bridge
│ ├── file_commands.rs # File manager (list/download/upload) │ ├── auth_token_commands.rs # claude setup-token flow, redaction, keychain
│ ├── mcp_commands.rs # MCP server CRUD │ ├── aws_commands.rs # AWS profile/region discovery
│ ├── project_commands.rs # Start/stop/rebuild containers │ ├── docker_commands.rs # Docker status, image ops
│ ├── settings_commands.rs # Settings CRUD │ ├── file_commands.rs # File browser (list/download/upload)
│ ├── terminal_commands.rs # Terminal I/O, resize │ ├── help_commands.rs # Serves HOW-TO-USE.md to the Help dialog
│ ├── update_commands.rs # App update checking │ ├── inspect_commands.rs # Sessions, capabilities, scheduler tasks
│ ├── install_helper_commands.rs # Guided Docker installation
│ ├── project_commands.rs # Start/stop/rebuild/backup containers
│ ├── settings_commands.rs # Settings CRUD
│ ├── stt_commands.rs # STT start/stop/transcribe
│ ├── terminal_commands.rs # Terminal I/O, resize
│ ├── update_commands.rs # App update checking
│ └── web_terminal_commands.rs # Web terminal start/stop/status │ └── web_terminal_commands.rs # Web terminal start/stop/status
├── web_terminal/ # Remote terminal access ├── auth_bridge/ # Host-side loopback callback bridge
│ ├── mod.rs # Per-project poller, status, lifecycle
│ ├── proc_net.rs # /proc/net/tcp{,6} parsing, loopback filtering
│ └── tunnel.rs # Host loopback bind + socat tunnel over the Docker API
├── web_terminal/ # Remote terminal access
│ ├── mod.rs # Module root │ ├── mod.rs # Module root
│ ├── server.rs # Axum HTTP+WS server lifecycle │ ├── server.rs # Axum HTTP+WS server lifecycle
│ ├── ws_handler.rs # WebSocket connection handler │ ├── ws_handler.rs # WebSocket connection handler
│ └── terminal.html # Embedded xterm.js web UI │ └── terminal.html # Embedded xterm.js web UI
├── install_helper/ # Docker installation assistance
│ ├── mod.rs # Install orchestration
│ └── platform.rs # Per-OS install strategies
├── docker/ # Docker API layer ├── docker/ # Docker API layer
│ ├── client.rs # bollard singleton connection │ ├── client.rs # bollard singleton connection
│ ├── container.rs # Create, start, stop, remove, fingerprinting │ ├── container.rs # Create/start/stop/remove, labels, recreation checks,
├── exec.rs # PTY exec sessions with bidirectional streaming │ # remove_project_volumes, snapshot commit
│ ├── exec.rs # create_attached_exec() — the single attached-exec path
│ ├── image.rs # Build from Dockerfile, pull from registry │ ├── image.rs # Build from Dockerfile, pull from registry
── network.rs # Per-project bridge networks for MCP ── stt.rs # Speech-to-text container lifecycle
│ └── legacy_cleanup.rs # Migration shim for the removed MCP feature
├── models/ # Data structures ├── models/ # Data structures
│ ├── project.rs # Project, Backend, BedrockConfig │ ├── project.rs # Project, Backend, PermissionMode, BedrockConfig, …
│ ├── mcp_server.rs # MCP server configuration │ ├── app_settings.rs # Global settings (image source, AWS, STT, web terminal)
│ ├── app_settings.rs # Global settings (image source, AWS, etc.)
│ ├── container_config.rs # Image name resolution │ ├── container_config.rs # Image name resolution
│ └── update_info.rs # Update metadata │ └── update_info.rs # Update metadata
└── storage/ # Persistence └── storage/ # Persistence
├── projects_store.rs # JSON file with atomic writes ├── projects_store.rs # JSON file with atomic writes
├── mcp_store.rs # MCP server persistence
├── settings_store.rs # App settings (Tauri plugin-store) ├── settings_store.rs # App settings (Tauri plugin-store)
└── secure.rs # OS keychain via keyring └── secure.rs # OS keychain via keyring (secrets, shared token)
``` ```
--- ---
@@ -335,6 +530,11 @@ triple-c/
| `tar` | 0.4 | In-memory tar archives for Docker build context | | `tar` | 0.4 | In-memory tar archives for Docker build context |
| `dirs` | 6.x | Cross-platform app data directory paths | | `dirs` | 6.x | Cross-platform app data directory paths |
| `serde` / `serde_json` | 1.x | Serialization for IPC and persistence | | `serde` / `serde_json` | 1.x | Serialization for IPC and persistence |
| `log` / `fern` | 0.4 / 0.7 | Date-based file logging |
| `include_dir` | 0.7 | Embeds the container build context in the binary |
| `reqwest` | 0.12 | HTTPS (rustls) for update checks, help content, STT uploads |
| `iana-time-zone` | 0.1 | Host timezone detection for container `TZ` |
| `sha2` | 0.10 | Settings fingerprints |
| `axum` | 0.8 | HTTP+WebSocket server for web terminal | | `axum` | 0.8 | HTTP+WebSocket server for web terminal |
| `tower-http` | 0.6 | CORS middleware for web terminal | | `tower-http` | 0.6 | CORS middleware for web terminal |
| `base64` | 0.22 | Terminal data encoding over WebSocket | | `base64` | 0.22 | Terminal data encoding over WebSocket |
@@ -357,6 +557,8 @@ triple-c/
| `zustand` | 5.x | Lightweight state management | | `zustand` | 5.x | Lightweight state management |
| `tailwindcss` | 4.x | Utility-first CSS framework | | `tailwindcss` | 4.x | Utility-first CSS framework |
| `vite` | 6.x | Frontend build tool and dev server | | `vite` | 6.x | Frontend build tool and dev server |
| `vitest` | 4.x | Test runner (jsdom environment) |
| `@testing-library/react` | 16.x | Component tests |
### Container Image ### Container Image
+525
View File
@@ -0,0 +1,525 @@
//! Auth Bridge — lets browser-based OAuth logins run by CLIs *inside* a
//! container complete against the browser on the *host*.
//!
//! ## The problem
//!
//! `claude login`, Concourse's `fly login`, `aws sso login` and friends all use
//! the same pattern: start a throwaway HTTP listener on a random loopback port,
//! then open a browser at a provider URL whose redirect points back to
//! `http://localhost:<that port>/callback`. Run inside a container, the listener
//! is on the *container's* loopback, the browser is on the *host's*, and the
//! callback goes nowhere — the login just hangs. The ports are ephemeral and not
//! configurable, so nothing can be pre-published at container creation time.
//!
//! ## The mechanism
//!
//! While the bridge is enabled for a running project, poll the container every
//! [`POLL_INTERVAL`] for loopback TCP listeners (see [`proc_net`]). For each one
//! that appears, bind the *same* port on the host's loopback and proxy each
//! accepted connection into the container over `docker exec … socat` (see
//! [`tunnel`]). When the in-container listener goes away, drop the host
//! listener. The host and container therefore agree on the port number, which is
//! the whole trick: the redirect URL the provider was given resolves correctly
//! on both sides.
//!
//! ## Lifecycle and teardown
//!
//! One poller task per project. It is the only thing that owns
//! [`PortForward`]s, and it always tears them down on its way out, so every way
//! the bridge can end funnels through the same code:
//!
//! | Trigger | Path |
//! |---|---|
//! | Bridge disabled | `set_auth_bridge_enabled(false)` → [`AuthBridgeManager::stop`] |
//! | Container stopped via UI | `stop_project_container` → [`AuthBridgeManager::stop`] |
//! | Container stopped/died another way | poller's own `is_container_running` check → loop exits |
//! | Project deleted | `remove_project` → [`AuthBridgeManager::stop`]; also the poller's `store.get()` check |
//! | Container rebuilt | `rebuild_project_container` → stop, then start re-arms it |
//! | App exit | window `CloseRequested` → [`AuthBridgeManager::stop_all`] |
//!
//! [`AuthBridgeManager::stop`] awaits the poller, so host ports are provably
//! released before it returns. As a backstop for any path that skips all of the
//! above (a panicking poller, an aborted task), `PortForward`'s [`Drop`] aborts
//! the accept loop, which drops the socket.
pub mod proc_net;
pub mod tunnel;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Duration;
use serde::Serialize;
use tauri::{AppHandle, Emitter};
use tokio::sync::{watch, Mutex};
use tokio::task::JoinHandle;
use crate::docker::container::is_container_running;
use crate::docker::exec::exec_oneshot;
use crate::storage::projects_store::ProjectsStore;
use proc_net::PortFamily;
use tunnel::PortForward;
/// How often the container is polled for new/vanished loopback listeners.
/// Short enough that a login redirect isn't left waiting, cheap enough to run
/// continuously (one `cat` of two procfs files per tick).
const POLL_INTERVAL: Duration = Duration::from_secs(2);
/// Emitted whenever the bridged-port set (or the conflict set) changes.
/// Payload: `{ project_id, status: AuthBridgeStatus }`.
const AUTH_BRIDGE_EVENT: &str = "auth-bridge-changed";
// ─────────────────────────────────────────────────────────────────────────────
// IPC response models
// ─────────────────────────────────────────────────────────────────────────────
/// A port currently bound on the host loopback and forwarded into the container.
#[derive(Debug, Clone, Serialize)]
pub struct BridgedPort {
pub port: u16,
pub family: PortFamily,
/// RFC 3339 timestamp of when the host listener was bound.
pub bridged_at: String,
}
/// A loopback listener that was discovered but could not be bridged.
#[derive(Debug, Clone, Serialize)]
pub struct PortConflict {
pub port: u16,
pub reason: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct AuthBridgeStatus {
pub enabled: bool,
pub active_ports: Vec<BridgedPort>,
pub conflicts: Vec<PortConflict>,
}
impl AuthBridgeStatus {
fn disabled() -> Self {
Self {
enabled: false,
active_ports: Vec::new(),
conflicts: Vec::new(),
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Manager
// ─────────────────────────────────────────────────────────────────────────────
/// Everything the poller owns for one project. Live ports and conflicts sit
/// behind an `Arc<Mutex<…>>` so `get_auth_bridge_status` can read them without
/// disturbing the poller.
#[derive(Default)]
struct BridgeState {
forwards: BTreeMap<u16, PortForward>,
conflicts: BTreeMap<u16, String>,
}
impl BridgeState {
fn snapshot(&self, enabled: bool) -> AuthBridgeStatus {
AuthBridgeStatus {
enabled,
active_ports: self
.forwards
.values()
.map(|f| BridgedPort {
port: f.port,
family: f.family,
bridged_at: f.bridged_at.clone(),
})
.collect(),
conflicts: self
.conflicts
.iter()
.map(|(port, reason)| PortConflict {
port: *port,
reason: reason.clone(),
})
.collect(),
}
}
}
struct ProjectBridge {
/// Distinguishes this poller from a later one for the same project, so a
/// poller that exits late can't remove its replacement's map entry.
epoch: u64,
cancel: watch::Sender<bool>,
state: Arc<Mutex<BridgeState>>,
poller: JoinHandle<()>,
}
type BridgeMap = Arc<Mutex<HashMap<String, ProjectBridge>>>;
#[derive(Default)]
pub struct AuthBridgeManager {
bridges: BridgeMap,
next_epoch: AtomicU64,
}
impl AuthBridgeManager {
pub fn new() -> Self {
Self::default()
}
/// Start polling for `project_id`. Idempotent: a call while a live poller
/// already exists for the project is a no-op.
pub async fn start(
&self,
project_id: String,
container_id: String,
app: AppHandle,
store: Arc<ProjectsStore>,
) {
let mut map = self.bridges.lock().await;
// A finished poller has already torn its ports down, so its entry is
// just a husk and can be replaced. A live one means we're already on.
if map
.get(&project_id)
.is_some_and(|b| !b.poller.is_finished())
{
return;
}
let epoch = self.next_epoch.fetch_add(1, Ordering::Relaxed);
let state = Arc::new(Mutex::new(BridgeState::default()));
let (cancel_tx, cancel_rx) = watch::channel(false);
log::info!(
"Auth bridge: starting for project {} (container {})",
project_id,
&container_id[..container_id.len().min(12)]
);
let poller = tokio::spawn(poll_loop(
project_id.clone(),
container_id,
epoch,
app,
store,
state.clone(),
self.bridges.clone(),
cancel_rx,
));
map.insert(
project_id,
ProjectBridge {
epoch,
cancel: cancel_tx,
state,
poller,
},
);
}
/// Stop the bridge for one project and wait until every host port it held
/// has been released.
pub async fn stop(&self, project_id: &str) {
// Remove under the lock, then release it before awaiting: the poller
// takes the same lock to deregister itself on exit.
let bridge = self.bridges.lock().await.remove(project_id);
if let Some(bridge) = bridge {
let _ = bridge.cancel.send(true);
let _ = bridge.poller.await;
log::info!("Auth bridge: stopped for project {}", project_id);
}
}
/// Stop every bridge. Used on app exit.
pub async fn stop_all(&self) {
let bridges: Vec<(String, ProjectBridge)> =
self.bridges.lock().await.drain().collect();
for (project_id, bridge) in bridges {
let _ = bridge.cancel.send(true);
let _ = bridge.poller.await;
log::info!("Auth bridge: stopped for project {}", project_id);
}
}
/// Current status. `enabled` comes from the persisted project record, so a
/// project whose bridge is on but whose container is stopped still reports
/// `enabled: true` with no active ports.
pub async fn status(&self, project_id: &str, enabled: bool) -> AuthBridgeStatus {
let map = self.bridges.lock().await;
match map.get(project_id) {
Some(bridge) => bridge.state.lock().await.snapshot(enabled),
None => AuthBridgeStatus {
enabled,
..AuthBridgeStatus::disabled()
},
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Poller
// ─────────────────────────────────────────────────────────────────────────────
#[allow(clippy::too_many_arguments)]
async fn poll_loop(
project_id: String,
container_id: String,
epoch: u64,
app: AppHandle,
store: Arc<ProjectsStore>,
state: Arc<Mutex<BridgeState>>,
bridges: BridgeMap,
mut cancel: watch::Receiver<bool>,
) {
let mut exec_failures: u32 = 0;
loop {
// Stop conditions checked every tick, so the bridge winds itself down
// even when nothing calls `stop()` (container died, project deleted
// out from under us, flag flipped off by another path).
let project = match store.get(&project_id) {
Some(p) => p,
None => {
log::info!("Auth bridge: project {} is gone — tearing down", project_id);
break;
}
};
if !project.auth_bridge_enabled {
log::info!("Auth bridge: disabled for project {} — tearing down", project_id);
break;
}
if !is_container_running(&container_id).await.unwrap_or(false) {
log::info!(
"Auth bridge: container for project {} is no longer running — tearing down",
project_id
);
break;
}
// One exec per tick reads both procfs files.
let cmd = vec![
"cat".to_string(),
"/proc/net/tcp".to_string(),
"/proc/net/tcp6".to_string(),
];
// Cancellation races the exec, not just the sleep, so disabling the
// bridge or stopping the container doesn't wait out an in-flight poll.
let discovery = tokio::select! {
_ = cancel.changed() => break,
res = exec_oneshot(&container_id, cmd) => res,
};
match discovery {
Ok(text) => {
exec_failures = 0;
let discovered = proc_net::parse_loopback_listeners(&text);
let skip = skipped_ports(&project);
if reconcile(&container_id, &discovered, &skip, &state).await {
emit_status(&app, &project_id, &state, true).await;
}
}
Err(e) => {
exec_failures += 1;
// Transient failures happen (container restarting, engine busy);
// only complain once per streak.
if exec_failures == 1 {
log::warn!(
"Auth bridge: failed to read /proc/net/tcp in container for project {}: {}",
project_id,
e
);
}
}
}
tokio::select! {
_ = cancel.changed() => break,
_ = tokio::time::sleep(POLL_INTERVAL) => {}
}
}
teardown(&project_id, &state).await;
emit_status(
&app,
&project_id,
&state,
store
.get(&project_id)
.is_some_and(|p| p.auth_bridge_enabled),
)
.await;
// Deregister, unless a newer poller has already taken this project's slot.
let mut map = bridges.lock().await;
if map.get(&project_id).is_some_and(|b| b.epoch == epoch) {
map.remove(&project_id);
}
}
/// Ports Docker already handles for this project. A container port that is
/// explicitly published has a host-side path already, and the mapping's host
/// port is a binding we must not fight over.
fn skipped_ports(project: &crate::models::Project) -> HashSet<u16> {
project
.port_mappings
.iter()
.flat_map(|m| [m.container_port, m.host_port])
.collect()
}
/// Bring the set of host listeners in line with what the container is currently
/// listening on. Returns whether anything the UI cares about changed.
async fn reconcile(
container_id: &str,
discovered: &BTreeMap<u16, PortFamily>,
skip: &HashSet<u16>,
state: &Arc<Mutex<BridgeState>>,
) -> bool {
let mut changed = false;
let mut st = state.lock().await;
// Drop host listeners whose container-side counterpart vanished, became
// covered by an explicit port mapping, or changed address family (a family
// change alters the socat target, so it has to be rebound below).
let stale: Vec<u16> = st
.forwards
.iter()
.filter(|(port, forward)| match discovered.get(port) {
None => true,
Some(_) if skip.contains(port) => true,
Some(family) => *family != forward.family,
})
.map(|(port, _)| *port)
.collect();
for port in stale {
if let Some(mut forward) = st.forwards.remove(&port) {
forward.shutdown().await;
log::info!("Auth bridge: released host port {}", port);
changed = true;
}
}
// Forget conflicts for ports that are no longer relevant.
let before = st.conflicts.len();
st.conflicts
.retain(|port, _| discovered.contains_key(port) && !skip.contains(port));
changed |= st.conflicts.len() != before;
for (&port, &family) in discovered {
if skip.contains(&port) || st.forwards.contains_key(&port) {
continue;
}
match PortForward::bind(container_id.to_string(), port, family).await {
Ok(forward) => {
if st.conflicts.remove(&port).is_some() {
log::info!("Auth bridge: host port {} became available", port);
}
log::info!(
"Auth bridge: bridging 127.0.0.1:{} → container {} ({:?})",
port,
family.socat_target(port),
family
);
st.forwards.insert(port, forward);
changed = true;
}
Err(e) => {
// Conflict policy: never fight for a port. Something else on the
// host owns it — another project's bridge, or an unrelated
// process. Skip it, record why so the UI can say so, and retry
// on later ticks in case the owner releases it. Warn only on
// the transition so a long-lived conflict doesn't spam the log.
let reason = format!(
"Host port {} is already in use ({}); not bridged.",
port, e
);
if st.conflicts.get(&port) != Some(&reason) {
log::warn!("Auth bridge: {}", reason);
st.conflicts.insert(port, reason);
changed = true;
}
}
}
}
changed
}
/// Release every host port held for this project. Awaits each shutdown, so on
/// return nothing is bound.
async fn teardown(project_id: &str, state: &Arc<Mutex<BridgeState>>) {
let mut st = state.lock().await;
let forwards = std::mem::take(&mut st.forwards);
st.conflicts.clear();
let count = forwards.len();
for (_, mut forward) in forwards {
forward.shutdown().await;
}
if count > 0 {
log::info!(
"Auth bridge: released {} host port(s) for project {}",
count,
project_id
);
}
}
async fn emit_status(
app: &AppHandle,
project_id: &str,
state: &Arc<Mutex<BridgeState>>,
enabled: bool,
) {
let status = state.lock().await.snapshot(enabled);
let _ = app.emit(
AUTH_BRIDGE_EVENT,
serde_json::json!({
"project_id": project_id,
"status": status,
}),
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{PortMapping, Project, ProjectPath};
fn project_with_mappings(mappings: Vec<(u16, u16)>) -> Project {
let mut p = Project::new(
"test".to_string(),
vec![ProjectPath {
host_path: "/tmp".to_string(),
mount_name: "tmp".to_string(),
}],
);
p.port_mappings = mappings
.into_iter()
.map(|(host_port, container_port)| PortMapping {
host_port,
container_port,
protocol: "tcp".to_string(),
})
.collect();
p
}
#[test]
fn ports_already_published_by_docker_are_skipped() {
let skip = skipped_ports(&project_with_mappings(vec![(3000, 3000), (8081, 8080)]));
assert!(skip.contains(&3000));
// Both ends of an asymmetric mapping are off limits: the container port
// is already reachable, and the host port is Docker's binding.
assert!(skip.contains(&8080));
assert!(skip.contains(&8081));
assert!(!skip.contains(&34567));
}
#[test]
fn no_mappings_means_nothing_is_skipped() {
assert!(skipped_ports(&project_with_mappings(vec![])).is_empty());
}
}
+302
View File
@@ -0,0 +1,302 @@
//! Discovery of loopback TCP listeners by parsing `/proc/net/tcp` and
//! `/proc/net/tcp6` from inside the container.
//!
//! ## Why /proc and not `ss`
//!
//! The container image (`container/Dockerfile`) ships neither `iproute2` (`ss`)
//! nor `net-tools` (`netstat`) nor `lsof`. `/proc/net/tcp{,6}` is part of procfs
//! and needs no package at all, so discovery works in the stock image and in any
//! snapshot derived from it.
//!
//! ## Wire format
//!
//! Both files are fixed-column text with a header line:
//!
//! ```text
//! sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
//! 0: 0100007F:8707 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 27764798 1 ...
//! ```
//!
//! Only two columns matter: `local_address` (index 1) and `st` (index 3).
//! `st == 0A` is `TCP_LISTEN`; every other state is a connection, not a listener.
//!
//! ## Hex and endianness
//!
//! `local_address` is `<address>:<port>`, both hex, but they are *not* encoded
//! the same way:
//!
//! * The **port** is a plain big-endian `%04X` — `8707` is 34567.
//! * The **address** is printed as one `%08X` per 32-bit word *in host byte
//! order*, which is little-endian on every platform this app targets. So each
//! 8-hex-digit group must be parsed as a `u32` and then expanded with
//! [`u32::to_le_bytes`] to recover the address bytes in network order:
//! `0100007F` → `0x0100007F` → `[7F, 00, 00, 01]` → `127.0.0.1`.
//!
//! IPv4 rows have one such group (8 hex digits); IPv6 rows have four (32 hex
//! digits), each converted independently, in order, to fill the 16 address
//! bytes. `::1` is therefore `00000000000000000000000001000000`, and the
//! IPv4-mapped `::ffff:127.0.0.1` is `0000000000000000FFFF00000100007F`.
//!
//! ## What counts as loopback
//!
//! Only `127.0.0.0/8` and `::1` (plus IPv4-mapped loopback, reported as v4).
//! A `0.0.0.0` or `::` listener is a service deliberately published to the
//! outside world — that is the port-mappings feature's job, not the auth
//! bridge's — so those rows are dropped.
use std::collections::BTreeMap;
use std::net::{Ipv4Addr, Ipv6Addr};
use serde::{Deserialize, Serialize};
/// The `st` column value for `TCP_LISTEN`.
const TCP_LISTEN: &str = "0A";
/// Which loopback address family (or families) a container-side listener was
/// found on. Determines the `socat` target address used to reach it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PortFamily {
/// Only `127.0.0.0/8`.
V4,
/// Only `::1`. Common in practice: Node resolves `localhost` to IPv6 first
/// on Linux, so `claude login` frequently binds `::1` and nothing else
/// (anthropics/claude-code#44844).
V6,
/// Both — reachable either way; we use IPv4.
Dual,
}
impl PortFamily {
fn merge(self, other: PortFamily) -> PortFamily {
if self == other {
self
} else {
PortFamily::Dual
}
}
/// The `socat` address that reaches this listener from inside the container.
/// A `::1`-only listener genuinely cannot be reached via `127.0.0.1`
/// (verified: connect gets ECONNREFUSED), hence the split.
pub fn socat_target(&self, port: u16) -> String {
match self {
PortFamily::V4 | PortFamily::Dual => format!("TCP:127.0.0.1:{}", port),
PortFamily::V6 => format!("TCP6:[::1]:{}", port),
}
}
}
/// One parsed LISTEN row that survived the loopback filter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct LoopbackListener {
pub port: u16,
pub family: PortFamily,
}
/// Parse the concatenated contents of `/proc/net/tcp` and `/proc/net/tcp6` into
/// the set of loopback ports being listened on, keyed by port with the families
/// merged (a port bound on both `127.0.0.1` and `::1` yields
/// [`PortFamily::Dual`]).
///
/// Unparseable lines — the two header lines, `cat`'s "No such file" complaint
/// when IPv6 is disabled, anything else that ends up interleaved in the exec's
/// combined output — are silently ignored rather than failing the whole poll.
pub fn parse_loopback_listeners(text: &str) -> BTreeMap<u16, PortFamily> {
let mut ports: BTreeMap<u16, PortFamily> = BTreeMap::new();
for listener in parse_listener_rows(text) {
ports
.entry(listener.port)
.and_modify(|f| *f = f.merge(listener.family))
.or_insert(listener.family);
}
ports
}
/// Row-level parse, before per-port family merging. Split out so tests can
/// assert on the individual rows.
pub fn parse_listener_rows(text: &str) -> Vec<LoopbackListener> {
text.lines().filter_map(parse_listener_row).collect()
}
fn parse_listener_row(line: &str) -> Option<LoopbackListener> {
let mut fields = line.split_whitespace();
let _sl = fields.next()?;
let local_address = fields.next()?;
let _rem_address = fields.next()?;
let state = fields.next()?;
if state != TCP_LISTEN {
return None;
}
let (addr_hex, port_hex) = local_address.split_once(':')?;
// The port is a straightforward big-endian hex u16 — no byte swapping.
let port = u16::from_str_radix(port_hex, 16).ok()?;
if port == 0 {
return None;
}
let family = match addr_hex.len() {
8 => {
let addr = Ipv4Addr::from(parse_le_word(addr_hex)?);
addr.is_loopback().then_some(PortFamily::V4)
}
32 => {
let mut octets = [0u8; 16];
for (i, group) in addr_hex.as_bytes().chunks(8).enumerate() {
let group = std::str::from_utf8(group).ok()?;
octets[i * 4..i * 4 + 4].copy_from_slice(&parse_le_word(group)?);
}
let addr = Ipv6Addr::from(octets);
// An IPv4-mapped row describes a v4 socket, so it is reachable at
// 127.0.0.1 and must be classified as v4, not v6.
match addr.to_ipv4_mapped() {
Some(v4) => v4.is_loopback().then_some(PortFamily::V4),
None => addr.is_loopback().then_some(PortFamily::V6),
}
}
_ => None,
}?;
Some(LoopbackListener { port, family })
}
/// Parse one `%08X` procfs address word into its four address bytes in network
/// order. The kernel prints the word in host byte order, so the recovered bytes
/// are the little-endian expansion of the parsed integer.
fn parse_le_word(hex: &str) -> Option<[u8; 4]> {
Some(u32::from_str_radix(hex, 16).ok()?.to_le_bytes())
}
#[cfg(test)]
mod tests {
use super::*;
/// Verbatim `cat /proc/net/tcp` from a running `triple-c:latest` container
/// with three listeners deliberately started:
/// * `socat TCP4-LISTEN:34567,bind=127.0.0.1` → row 0 (`0100007F:8707`)
/// * `socat TCP4-LISTEN:34569,bind=0.0.0.0` → row 1 (`00000000:8709`)
/// * `node ... .listen(34568, "::1")` → appears in TCP6 only
const REAL_PROC_NET_TCP: &str = concat!(
" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode \n",
" 0: 0100007F:8707 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 27764798 1 0000000000000000 100 0 0 10 0 \n",
" 1: 00000000:8709 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 27758875 1 0000000000000000 100 0 0 10 0 \n",
);
/// Verbatim `cat /proc/net/tcp6` from the same container. The single row is
/// the Node listener bound to `::1` only — the case that motivates the
/// TCP6 socat target.
const REAL_PROC_NET_TCP6: &str = concat!(
" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n",
" 0: 00000000000000000000000001000000:8708 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 27747129 1 0000000000000000 100 0 0 10 0\n",
);
fn both_files() -> String {
format!("{}{}", REAL_PROC_NET_TCP, REAL_PROC_NET_TCP6)
}
#[test]
fn parses_ipv4_loopback_row_with_little_endian_address() {
let rows = parse_listener_rows(REAL_PROC_NET_TCP);
// 0100007F → 127.0.0.1 (kept), 00000000 → 0.0.0.0 (dropped).
assert_eq!(
rows,
vec![LoopbackListener {
port: 0x8707,
family: PortFamily::V4
}]
);
assert_eq!(rows[0].port, 34567);
}
#[test]
fn parses_ipv6_loopback_row() {
let rows = parse_listener_rows(REAL_PROC_NET_TCP6);
assert_eq!(
rows,
vec![LoopbackListener {
port: 34568,
family: PortFamily::V6
}]
);
}
#[test]
fn ignores_wildcard_bind_addresses() {
// 0.0.0.0:34569 is in the fixture and must never be bridged — that is
// the port-mappings feature's territory.
let ports = parse_loopback_listeners(&both_files());
assert!(!ports.contains_key(&34569));
// Same for the IPv6 wildcard and a non-loopback unicast address.
let wildcard_v6 = " 0: 00000000000000000000000000000000:1F90 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 1 1 0 100 0 0 10 0";
let lan_v4 = " 0: 0245A8C0:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 1 1 0 100 0 0 10 0";
assert!(parse_listener_rows(wildcard_v6).is_empty());
assert!(parse_listener_rows(lan_v4).is_empty());
}
#[test]
fn parses_both_files_concatenated_as_one_exec_output() {
let ports = parse_loopback_listeners(&both_files());
assert_eq!(ports.len(), 2);
assert_eq!(ports.get(&34567), Some(&PortFamily::V4));
assert_eq!(ports.get(&34568), Some(&PortFamily::V6));
}
#[test]
fn merges_families_for_a_dual_stack_port() {
let dual = format!(
"{} 1: 00000000000000000000000001000000:8707 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 2 1 0 100 0 0 10 0\n",
both_files()
);
let ports = parse_loopback_listeners(&dual);
assert_eq!(ports.get(&34567), Some(&PortFamily::Dual));
}
#[test]
fn ipv4_mapped_loopback_is_reported_as_v4() {
// ::ffff:127.0.0.1 — a v4 socket surfacing in /proc/net/tcp6.
let row = " 0: 0000000000000000FFFF00000100007F:8707 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 1 1 0 100 0 0 10 0";
assert_eq!(
parse_listener_rows(row),
vec![LoopbackListener {
port: 34567,
family: PortFamily::V4
}]
);
}
#[test]
fn ignores_non_listen_states() {
// Same loopback address, state 01 (ESTABLISHED) instead of 0A.
let established = " 0: 0100007F:8707 0100007F:C350 01 00000000:00000000 00:00000000 00000000 0 0 1 1 0 100 0 0 10 0";
assert!(parse_listener_rows(established).is_empty());
}
#[test]
fn ignores_headers_and_garbage() {
assert!(parse_listener_rows("").is_empty());
assert!(parse_listener_rows(
"cat: /proc/net/tcp6: No such file or directory\n\n sl local_address rem_address st\n"
)
.is_empty());
// Truncated / malformed rows must not panic or be accepted.
assert!(parse_listener_rows(" 0: 0100007F 00000000:0000 0A").is_empty());
assert!(parse_listener_rows(" 0: ZZZZZZZZ:8707 00000000:0000 0A x").is_empty());
assert!(parse_listener_rows(" 0: 0100007F:0000 00000000:0000 0A x").is_empty());
}
#[test]
fn socat_target_matches_family() {
assert_eq!(
PortFamily::V4.socat_target(34567),
"TCP:127.0.0.1:34567"
);
assert_eq!(
PortFamily::Dual.socat_target(34567),
"TCP:127.0.0.1:34567"
);
assert_eq!(PortFamily::V6.socat_target(34568), "TCP6:[::1]:34568");
}
}
+245
View File
@@ -0,0 +1,245 @@
//! Host-side loopback listener for one bridged port, and the per-connection
//! tunnel that carries its bytes into the container.
//!
//! ## Why not connect to the container's IP
//!
//! Container IPs are not routable from the host on Docker Desktop (macOS and
//! Windows run the engine in a VM), so a host→`172.17.x.x` dial cannot be the
//! transport. The Docker API is the only channel guaranteed to reach the
//! container from the host, so each accepted connection is carried by a
//! `docker exec` running `socat - TCP:127.0.0.1:<port>`, with the exec's stdin
//! and stdout wired to the TCP socket. `socat` ships in the container image.
//!
//! The exec plumbing itself is *not* reimplemented here: it comes from
//! [`crate::docker::exec::create_attached_exec`], the same helper the
//! interactive terminal sessions are built on.
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use bollard::container::LogOutput;
use futures_util::StreamExt;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::{JoinHandle, JoinSet};
use crate::docker::exec::{create_attached_exec, AttachedExec};
use super::proc_net::PortFamily;
/// Buffer size for the host→container direction. OAuth callbacks are tiny; this
/// only needs to not be pathological.
const PUMP_BUF: usize = 16 * 1024;
/// Aborts a task when dropped, so a cancelled parent can never leave a detached
/// child running.
struct AbortOnDrop(JoinHandle<()>);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
self.0.abort();
}
}
/// One host loopback port bound and proxied into the container.
///
/// The accept loop owns the [`TcpListener`](tokio::net::TcpListener)s and the
/// [`JoinSet`] of live connection tasks, so aborting the single task handle
/// releases the port *and* tears down every connection under it. [`Drop`] does
/// that as a backstop; [`PortForward::shutdown`] does it deterministically by
/// also awaiting the aborted task, which guarantees the socket is closed before
/// the caller proceeds (important when a port is rebound right after).
pub struct PortForward {
pub port: u16,
pub family: PortFamily,
pub bridged_at: String,
task: JoinHandle<()>,
}
impl Drop for PortForward {
fn drop(&mut self) {
self.task.abort();
}
}
impl PortForward {
/// Bind `port` on the host loopback and start proxying into `container_id`.
///
/// The bind happens before the task is spawned, so an already-taken port is
/// reported to the caller as an error rather than disappearing into a
/// background task.
pub async fn bind(
container_id: String,
port: u16,
family: PortFamily,
) -> Result<Self, std::io::Error> {
// SECURITY BOUNDARY: the host side binds loopback ONLY — 127.0.0.1 and
// ::1, never 0.0.0.0 / ::. Everything reachable through this socket is
// an unauthenticated service inside the container that deliberately
// bound loopback because it expected to be reachable from nowhere else.
// Binding a wildcard address here would publish container internals to
// every host on the LAN. Do not "fix" a connectivity problem by
// widening these addresses.
let v4 = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))).await?;
// Also take ::1 when it is available. Browsers and CLIs resolve
// `localhost` to either family, and the IPv6 answer is often tried
// first, so a v4-only host listener would miss those callbacks. This is
// best-effort: if ::1 is unavailable (no IPv6, or that half is taken)
// the v4 listener alone still works, so it is not treated as a conflict.
let v6 = match TcpListener::bind(SocketAddr::from((Ipv6Addr::LOCALHOST, port))).await {
Ok(l) => Some(l),
Err(e) => {
log::debug!(
"Auth bridge: bound 127.0.0.1:{} but not [::1]:{} ({}) — continuing with IPv4 only",
port,
port,
e
);
None
}
};
let target = family.socat_target(port);
let task = tokio::spawn(accept_loop(container_id, port, target, v4, v6));
Ok(Self {
port,
family,
bridged_at: chrono::Utc::now().to_rfc3339(),
task,
})
}
/// Stop accepting, drop the host socket, and abort every in-flight
/// connection. Awaits the aborted task so the port is provably released
/// when this returns.
pub async fn shutdown(&mut self) {
self.task.abort();
let _ = (&mut self.task).await;
}
}
/// Accept on both loopback listeners until aborted. Dropping this future drops
/// the listeners (freeing the port) and the `JoinSet` (aborting live tunnels).
async fn accept_loop(
container_id: String,
port: u16,
target: String,
v4: TcpListener,
v6: Option<TcpListener>,
) {
let mut conns: JoinSet<()> = JoinSet::new();
loop {
let accepted = tokio::select! {
r = v4.accept() => r,
r = accept_optional(v6.as_ref()) => r,
// Reap finished tunnels so the JoinSet doesn't grow without bound.
// When the set is empty `join_next()` yields None, the pattern fails
// to match, and the branch simply drops out of the select.
Some(_) = conns.join_next() => continue,
};
match accepted {
Ok((stream, peer)) => {
log::debug!("Auth bridge: connection from {} to bridged port {}", peer, port);
let _ = stream.set_nodelay(true);
conns.spawn(tunnel_connection(
container_id.clone(),
target.clone(),
stream,
port,
));
}
Err(e) => {
log::warn!("Auth bridge: accept failed on port {}: {} — stopping listener", port, e);
return;
}
}
}
}
/// `accept()` on an optional listener; never completes when there is none, so it
/// can sit in a `select!` arm unconditionally.
async fn accept_optional(
listener: Option<&TcpListener>,
) -> std::io::Result<(TcpStream, SocketAddr)> {
match listener {
Some(l) => l.accept().await,
None => std::future::pending().await,
}
}
/// Carry one accepted host connection into the container over `socat`.
async fn tunnel_connection(container_id: String, target: String, stream: TcpStream, port: u16) {
let cmd = vec!["socat".to_string(), "-".to_string(), target.clone()];
let AttachedExec {
mut output,
mut input,
..
} = match create_attached_exec(&container_id, cmd, false).await {
Ok(e) => e,
Err(e) => {
log::warn!(
"Auth bridge: failed to open tunnel exec for port {} ({}): {}",
port,
target,
e
);
return;
}
};
let (mut host_rx, mut host_tx) = stream.into_split();
// Host → container. Runs as its own task so the container→host direction is
// never blocked behind a client that has stopped sending. Finishing this
// direction drops `input`, which closes the exec's stdin and lets socat see
// a clean EOF (a half-close, not a teardown of the whole connection).
let upstream = AbortOnDrop(tokio::spawn(async move {
let mut buf = vec![0u8; PUMP_BUF];
loop {
match host_rx.read(&mut buf).await {
Ok(0) => break,
Ok(n) => {
if input.write_all(&buf[..n]).await.is_err() || input.flush().await.is_err() {
break;
}
}
Err(_) => break,
}
}
}));
// Container → host. This direction is authoritative: when the exec's output
// stream ends, socat has exited and the connection is over.
while let Some(chunk) = output.next().await {
match chunk {
// Only stdout is payload. The exec is created with tty = false
// precisely so Docker demultiplexes these, keeping socat's stderr
// diagnostics out of the proxied byte stream.
Ok(LogOutput::StdOut { message }) => {
if host_tx.write_all(&message).await.is_err() {
break;
}
}
Ok(LogOutput::StdErr { message }) => {
log::debug!(
"Auth bridge: socat stderr for port {}: {}",
port,
String::from_utf8_lossy(&message).trim()
);
}
Ok(_) => {}
Err(e) => {
log::debug!("Auth bridge: tunnel stream error on port {}: {}", port, e);
break;
}
}
}
let _ = host_tx.shutdown().await;
// Explicit: stop reading from the host now that the container side is gone.
drop(upstream);
}
@@ -0,0 +1,67 @@
//! IPC surface for the auth bridge. The mechanism lives in
//! [`crate::auth_bridge`]; this file only translates between it and the
//! frontend, and keeps the persisted per-project flag in step.
use tauri::{AppHandle, State};
use crate::auth_bridge::AuthBridgeStatus;
use crate::AppState;
/// Turn the bridge on or off for a project and return the resulting status.
///
/// Enabling starts polling immediately when the container is already running;
/// otherwise the flag is simply persisted and `start_project_container` arms the
/// bridge on the next start. This is a host-side feature, so no container
/// recreation is involved either way.
#[tauri::command]
pub async fn set_auth_bridge_enabled(
project_id: String,
enabled: bool,
app_handle: AppHandle,
state: State<'_, AppState>,
) -> Result<AuthBridgeStatus, String> {
state
.projects_store
.set_auth_bridge_enabled(&project_id, enabled)?;
if enabled {
let project = state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
if let Some(container_id) = project.container_id {
if crate::docker::container::is_container_running(&container_id)
.await
.unwrap_or(false)
{
state
.auth_bridge
.start(
project_id.clone(),
container_id,
app_handle,
state.projects_store.clone(),
)
.await;
}
}
} else {
// Awaits the poller, so every host port is released before we return.
state.auth_bridge.stop(&project_id).await;
}
Ok(state.auth_bridge.status(&project_id, enabled).await)
}
#[tauri::command]
pub async fn get_auth_bridge_status(
project_id: String,
state: State<'_, AppState>,
) -> Result<AuthBridgeStatus, String> {
let enabled = state
.projects_store
.get(&project_id)
.map(|p| p.auth_bridge_enabled)
.unwrap_or(false);
Ok(state.auth_bridge.status(&project_id, enabled).await)
}
@@ -0,0 +1,942 @@
//! Shared Claude Code authentication — one long-lived token for every project.
//!
//! ## Why
//!
//! Without this, every container is its own authentication island: each one
//! needs `claude login`, each one opens a browser flow, each one stores its own
//! credential in its own config volume. `claude setup-token` mints a single
//! ~1-year OAuth token that Claude Code accepts via `CLAUDE_CODE_OAUTH_TOKEN`,
//! so one authentication event can cover the whole fleet.
//!
//! ## How the token is obtained
//!
//! Observed directly against Claude Code 2.1.226, because the flow is not what
//! the design assumed. `claude setup-token` prints an authorization URL whose
//! `redirect_uri` is **Anthropic-hosted**
//! (`https://platform.claude.com/oauth/code/callback`) — it does *not* start a
//! loopback listener. After signing in, the user copies a code off that page
//! and the CLI waits at a `Paste code here if prompted >` prompt on **stdin**.
//! It then prints the token.
//!
//! Two consequences:
//!
//! * The flow needs a way to deliver the pasted code, hence
//! [`submit_claude_token_code`] and the stdin channel below. Without it the
//! command would simply sit at the prompt until it timed out.
//! * [`crate::auth_bridge`] is *not* required for this particular command,
//! since there is no container-local callback to reach. It is still enabled
//! for the duration (and restored afterwards) as designed: it costs nothing
//! here and keeps the flow working if a future CLI version, or the plain
//! `claude login` path, goes back to a loopback redirect.
//!
//! ## Handling of the token itself
//!
//! The token never reaches the frontend. It is parsed out of the command's
//! output, written straight to the OS keychain, and from then on only
//! [`crate::docker::container`] reads it, to inject the env var. Everything
//! streamed to the UI passes through [`SecretRedactor`] first, and no command
//! here returns the token or accepts it as an argument.
use std::sync::OnceLock;
use std::time::Duration;
use futures_util::StreamExt;
use tauri::{AppHandle, Emitter, State};
use tokio::io::AsyncWriteExt;
use tokio::sync::{mpsc, oneshot, Mutex};
use crate::docker::container::is_container_running;
use crate::docker::exec::{create_attached_exec, wait_for_exec_exit, AttachedExec};
use crate::storage::secure;
use crate::AppState;
/// Milestones in the acquisition flow. Payload `{ project_id, message }`,
/// matching the `container-progress` convention.
const PROGRESS_EVENT: &str = "claude-token-progress";
/// Redacted output from `claude setup-token`, so the UI can show the user the
/// URL to visit. Payload `{ project_id, chunk }`.
const OUTPUT_EVENT: &str = "claude-token-output";
/// How long to wait for the whole flow. Generous: the user has to switch to a
/// browser, sign in, and approve. Bounded so a wedged exec can't leak a task.
const SETUP_TIMEOUT: Duration = Duration::from_secs(15 * 60);
/// Documented shape of a `setup-token` credential.
const TOKEN_PREFIX: &str = "sk-ant-oat01-";
/// Minimum number of body characters after [`TOKEN_PREFIX`] for a match to be
/// believed. Real tokens run to ~90 characters; this is set well below that but
/// far above anything prose would produce, so documentation-style decoys like
/// `sk-ant-oat01-...` or `sk-ant-oat01-<your-token>` are rejected.
const MIN_TOKEN_BODY: usize = 32;
/// Redaction is deliberately broader than extraction: anything shaped like an
/// Anthropic credential is masked on its way to the UI, not just `oat01` ones.
const SECRET_MARKER: &str = "sk-ant-";
const SECRET_PLACEHOLDER: &str = "sk-ant-<redacted>";
const MIN_SECRET_BODY: usize = 8;
/// Cap on how much text [`SecretRedactor`] will withhold waiting for a
/// candidate secret to end. Past this, it is not a token — release it (still
/// redacted) rather than swallow the UI's output.
const MAX_HOLDBACK: usize = 4096;
/// Cap on the retained transcript used for parsing. The token is printed at the
/// end, and a re-rendering TUI can repaint many times, so keeping the tail is
/// both sufficient and bounded.
const MAX_TRANSCRIPT: usize = 256 * 1024;
/// Characters that can appear in the body of an Anthropic credential.
fn is_token_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'-' || b == b'_'
}
// ─────────────────────────────────────────────────────────────────────────────
// Token extraction
// ─────────────────────────────────────────────────────────────────────────────
/// Pull the long-lived token out of `claude setup-token`'s output.
///
/// Strict by construction, because the alternative to failing is storing
/// garbage that silently breaks every container:
/// * the value must carry the documented `sk-ant-oat01-` prefix;
/// * the prefix must not be glued to the tail of a longer word;
/// * at least [`MIN_TOKEN_BODY`] token characters must follow it.
///
/// The **last** match wins. The command narrates before it succeeds, and a TUI
/// may repaint the same frame repeatedly, so earlier matches are either prose
/// or superseded repaints of the same value.
pub fn parse_setup_token(output: &str) -> Option<String> {
let bytes = output.as_bytes();
let mut found = None;
let mut cursor = 0usize;
while let Some(offset) = output[cursor..].find(TOKEN_PREFIX) {
let start = cursor + offset;
cursor = start + TOKEN_PREFIX.len();
// `xsk-ant-oat01-…` is not a token, it is a substring of something else.
if start > 0 && is_token_byte(bytes[start - 1]) {
continue;
}
let body_start = start + TOKEN_PREFIX.len();
let mut end = body_start;
while end < bytes.len() && is_token_byte(bytes[end]) {
end += 1;
}
if end - body_start < MIN_TOKEN_BODY {
continue;
}
found = Some(output[start..end].to_string());
}
found
}
// ─────────────────────────────────────────────────────────────────────────────
// Redaction
// ─────────────────────────────────────────────────────────────────────────────
/// Mask every *complete* credential in `text`.
fn redact_complete(text: &str) -> String {
let bytes = text.as_bytes();
let mut out = String::with_capacity(text.len());
let mut copied = 0usize;
let mut cursor = 0usize;
while let Some(offset) = text[cursor..].find(SECRET_MARKER) {
let start = cursor + offset;
cursor = start + SECRET_MARKER.len();
if start > 0 && is_token_byte(bytes[start - 1]) {
continue;
}
let body_start = start + SECRET_MARKER.len();
let mut end = body_start;
while end < bytes.len() && is_token_byte(bytes[end]) {
end += 1;
}
if end - body_start < MIN_SECRET_BODY {
continue;
}
out.push_str(&text[copied..start]);
out.push_str(SECRET_PLACEHOLDER);
copied = end;
cursor = end;
}
out.push_str(&text[copied..]);
out
}
/// Where the tail that might still grow into a credential begins. Everything
/// before this index is safe to emit; everything from it must be withheld until
/// more input arrives. Returns `text.len()` when nothing needs withholding.
fn holdback_index(text: &str) -> usize {
let bytes = text.as_bytes();
// A credential already under way: the last marker with nothing but token
// characters after it. If the *last* marker fails that test, no earlier one
// can pass it either — the disqualifying character lies after them all.
if let Some(start) = text.rfind(SECRET_MARKER) {
let clean_start = start == 0 || !is_token_byte(bytes[start - 1]);
let body_all_token = bytes[start + SECRET_MARKER.len()..]
.iter()
.all(|b| is_token_byte(*b));
if clean_start && body_all_token {
return start;
}
}
// Otherwise: a marker truncated mid-way by the chunk boundary.
for len in (1..SECRET_MARKER.len()).rev() {
if text.len() >= len && text.is_char_boundary(text.len() - len)
&& &text[text.len() - len..] == &SECRET_MARKER[..len]
{
return text.len() - len;
}
}
text.len()
}
/// Masks credentials out of a stream, tolerating a secret split across chunk
/// boundaries by withholding any tail that could still turn into one.
#[derive(Default)]
struct SecretRedactor {
pending: String,
}
impl SecretRedactor {
/// Absorb `chunk` and return the text that is now safe to show.
fn push(&mut self, chunk: &str) -> String {
self.pending.push_str(chunk);
let mut split = holdback_index(&self.pending);
if self.pending.len() - split > MAX_HOLDBACK {
split = self.pending.len();
}
let emit = redact_complete(&self.pending[..split]);
self.pending.drain(..split);
emit
}
/// Release whatever is still withheld. The stream is over, so a partial
/// credential can no longer grow — but it is still redacted on the way out.
fn flush(&mut self) -> String {
let out = redact_complete(&self.pending);
self.pending.clear();
out
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Terminal control-sequence stripping
// ─────────────────────────────────────────────────────────────────────────────
/// Length in bytes of the UTF-8 character starting with `b`.
fn utf8_len(b: u8) -> usize {
if b < 0x80 {
1
} else if b >> 5 == 0b110 {
2
} else if b >> 4 == 0b1110 {
3
} else if b >> 3 == 0b11110 {
4
} else {
1
}
}
/// CSI final bytes that move the cursor. Claude Code's TUI lays text out by
/// jumping to a column (`ESC [ 9 G`) instead of emitting spaces, so deleting
/// these outright would weld neighbouring words together — which at best
/// garbles the URL the user has to read, and at worst welds a preceding word
/// onto the token and makes the parser reject it. They become a space instead:
/// a separator can never fabricate or destroy a match.
const CURSOR_MOVE_FINALS: &[u8] = b"ABCDEFGHd";
/// Strip terminal control sequences from the front of `bytes`, stopping at the
/// first incomplete sequence or truncated character. Returns the clean text and
/// how many bytes were consumed.
fn strip_ansi_prefix(bytes: &[u8]) -> (String, usize) {
let mut out = String::with_capacity(bytes.len());
let mut i = 0usize;
while i < bytes.len() {
match bytes[i] {
0x1b => {
if i + 1 >= bytes.len() {
return (out, i);
}
match bytes[i + 1] {
// CSI: parameter/intermediate bytes, then a final 0x40..=0x7e.
b'[' => {
let mut j = i + 2;
while j < bytes.len() && !(0x40..=0x7e).contains(&bytes[j]) {
j += 1;
}
if j >= bytes.len() {
return (out, i);
}
if CURSOR_MOVE_FINALS.contains(&bytes[j]) {
out.push(' ');
}
i = j + 1;
}
// OSC: runs until BEL or ST (ESC \).
b']' => {
let mut j = i + 2;
loop {
if j >= bytes.len() {
return (out, i);
}
if bytes[j] == 0x07 {
j += 1;
break;
}
if bytes[j] == 0x1b {
if j + 1 >= bytes.len() {
return (out, i);
}
if bytes[j + 1] == b'\\' {
j += 2;
break;
}
}
j += 1;
}
i = j;
}
// Two-byte escapes (charset selection, keypad mode, …).
_ => i += 2,
}
}
// A repaint returns to column 0. Turn that into a line break so the
// old frame's trailing text cannot be glued onto the new frame's
// leading text — which could otherwise fabricate a "token". A run of
// CRs immediately before a LF is just the pty's ONLCR translation,
// so it collapses into that single LF rather than blank lines.
b'\r' => {
let mut j = i;
while j < bytes.len() && bytes[j] == b'\r' {
j += 1;
}
if j >= bytes.len() {
return (out, i);
}
if bytes[j] != b'\n' {
out.push('\n');
}
i = j;
}
b'\n' => {
out.push('\n');
i += 1;
}
b'\t' => {
out.push('\t');
i += 1;
}
0x00..=0x1f | 0x7f => i += 1,
b => {
let len = utf8_len(b);
if i + len > bytes.len() {
return (out, i);
}
if let Ok(s) = std::str::from_utf8(&bytes[i..i + len]) {
out.push_str(s);
}
i += len;
}
}
}
(out, i)
}
/// Stateful wrapper around [`strip_ansi_prefix`] that carries an incomplete
/// trailing sequence over to the next chunk.
#[derive(Default)]
struct AnsiStripper {
carry: Vec<u8>,
}
impl AnsiStripper {
fn push(&mut self, chunk: &[u8]) -> String {
self.carry.extend_from_slice(chunk);
let (out, consumed) = strip_ansi_prefix(&self.carry);
self.carry.drain(..consumed);
out
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Commands
// ─────────────────────────────────────────────────────────────────────────────
/// Stdin of the acquisition currently in flight, so [`submit_claude_token_code`]
/// can answer the CLI's `Paste code here` prompt.
///
/// `Some` exactly while a flow is running, which doubles as the single-flight
/// guard: the token is global, so two concurrent logins would race to overwrite
/// each other's keychain entry and neither could tell which prompt it was
/// feeding.
static PENDING_INPUT: OnceLock<Mutex<Option<mpsc::UnboundedSender<Vec<u8>>>>> = OnceLock::new();
fn pending_input() -> &'static Mutex<Option<mpsc::UnboundedSender<Vec<u8>>>> {
PENDING_INPUT.get_or_init(|| Mutex::new(None))
}
/// Abort channel for the in-flight flow, claimed and released in lockstep with
/// [`PENDING_INPUT`].
///
/// Without this the only exits are "finished" and "timed out", so a user who
/// closes the dialog would be locked out by the single-flight guard until
/// `SETUP_TIMEOUT` elapsed.
static CANCEL_TX: OnceLock<Mutex<Option<oneshot::Sender<()>>>> = OnceLock::new();
fn cancel_slot() -> &'static Mutex<Option<oneshot::Sender<()>>> {
CANCEL_TX.get_or_init(|| Mutex::new(None))
}
fn emit_progress(app: &AppHandle, project_id: &str, message: &str) {
let _ = app.emit(
PROGRESS_EVENT,
serde_json::json!({ "project_id": project_id, "message": message }),
);
}
fn emit_output(app: &AppHandle, project_id: &str, chunk: &str) {
let _ = app.emit(
OUTPUT_EVENT,
serde_json::json!({ "project_id": project_id, "chunk": chunk }),
);
}
/// Shell run inside the container.
///
/// * `stty` widens the pty before Claude Code starts, so its layout engine does
/// not wrap the token or the sign-in URL across lines. Docker's default exec
/// pty is 80 columns; both are longer than that. Setting it here rather than
/// via a post-start resize avoids racing the process's startup.
/// * The `unset` line strips inherited auth so `setup-token` runs against a
/// clean claude.ai login instead of warning about, or deferring to, whatever
/// credential the container is already configured with — including a shared
/// token from a previous run, which is likely the very thing being replaced.
const SETUP_TOKEN_SCRIPT: &str = r#"stty cols 200 rows 50 2>/dev/null || true
unset CLAUDE_CODE_OAUTH_TOKEN ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_BASE_URL \
ANTHROPIC_MODEL CLAUDE_CODE_USE_BEDROCK AWS_BEARER_TOKEN_BEDROCK
exec claude setup-token"#;
/// Run `claude setup-token` in the container and return the token it printed.
/// Streams redacted output as it arrives and forwards anything arriving on
/// `input_rx` (the user's pasted code) to the command's stdin.
async fn run_setup_token(
app: &AppHandle,
project_id: &str,
container_id: &str,
mut input_rx: mpsc::UnboundedReceiver<Vec<u8>>,
mut cancel_rx: oneshot::Receiver<()>,
) -> Result<String, String> {
// A pty (`tty = true`) because `setup-token` renders an interactive TUI and
// reads the pasted code in raw mode, which a plain pipe cannot provide.
let AttachedExec {
exec_id,
mut output,
mut input,
} = create_attached_exec(
container_id,
vec![
"sh".to_string(),
"-c".to_string(),
SETUP_TOKEN_SCRIPT.to_string(),
],
true,
)
.await?;
let mut stripper = AnsiStripper::default();
let mut redactor = SecretRedactor::default();
let mut transcript = String::new();
let deadline = tokio::time::Instant::now() + SETUP_TIMEOUT;
loop {
// Writing stdin and reading stdout are driven from the same loop: with
// a hijacked exec both halves ride one socket, and `input` must stay
// alive for the whole session anyway — dropping it early would tear the
// output stream down with it.
let next = tokio::select! {
// Cancellation wins the race so a user who gives up isn't held by
// the single-flight guard until the timeout. Dropping `input` and
// `output` on return tears the exec down with them.
_ = &mut cancel_rx => {
return Err(
"Authentication cancelled. No token was stored.".to_string()
);
}
Some(data) = input_rx.recv() => {
if let Err(e) = input.write_all(&data).await {
return Err(format!(
"Could not send the code to `claude setup-token`: {}. No token was stored.",
e
));
}
let _ = input.flush().await;
continue;
}
next = tokio::time::timeout_at(deadline, output.next()) => match next {
Ok(next) => next,
Err(_) => {
return Err(format!(
"Timed out after {} minutes waiting for `claude setup-token` to finish. \
No token was stored.",
SETUP_TIMEOUT.as_secs() / 60
))
}
},
};
let frame = match next {
Some(Ok(frame)) => frame,
Some(Err(e)) => {
return Err(format!(
"Lost the connection to `claude setup-token`: {}. No token was stored.",
e
))
}
None => break,
};
let visible = stripper.push(&frame.into_bytes());
if visible.is_empty() {
continue;
}
transcript.push_str(&visible);
if transcript.len() > MAX_TRANSCRIPT {
// Keep the tail: that is where the token lands.
let cut = transcript.len() - MAX_TRANSCRIPT / 2;
let cut = (cut..transcript.len())
.find(|i| transcript.is_char_boundary(*i))
.unwrap_or(transcript.len());
transcript.drain(..cut);
}
let safe = redactor.push(&visible);
if !safe.is_empty() {
emit_output(app, project_id, &safe);
}
}
let tail = redactor.flush();
if !tail.is_empty() {
emit_output(app, project_id, &tail);
}
let exit_code = wait_for_exec_exit(&exec_id).await.unwrap_or(0);
if exit_code != 0 {
return Err(format!(
"`claude setup-token` exited with status {}. No token was stored — \
see the command output above for what went wrong.",
exit_code
));
}
parse_setup_token(&transcript).ok_or_else(|| {
"`claude setup-token` finished but printed no recognisable token. \
Nothing was stored. This usually means the login was cancelled, or the \
account has no Claude subscription (long-lived tokens require one)."
.to_string()
})
}
/// Mint a shared, long-lived Claude Code token by running `claude setup-token`
/// inside `project_id`'s container, and store it in the OS keychain.
///
/// The project only lends its container — a place to run the CLI that already
/// has Claude Code installed. The resulting token is global, and is used by
/// every Anthropic-backend project that has not opted out.
#[tauri::command]
pub async fn acquire_claude_token(
project_id: String,
app_handle: AppHandle,
state: State<'_, AppState>,
) -> Result<(), String> {
let project = state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
let container_id = project.container_id.clone().ok_or_else(|| {
format!(
"Project '{}' has no container yet. Start it, then run authentication again.",
project.name
)
})?;
if !is_container_running(&container_id).await.unwrap_or(false) {
return Err(format!(
"The container for '{}' is not running. Start it, then run authentication again.",
project.name
));
}
// Claim the flow before touching anything else, so a second caller bounces
// off the guard rather than half-configuring the same project.
let (input_tx, input_rx) = mpsc::unbounded_channel::<Vec<u8>>();
let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
{
// Both slots are claimed under the input lock held first, and released
// in the same order below, so the guard and its abort channel can never
// disagree about whether a flow is live.
let mut slot = pending_input().lock().await;
if slot.is_some() {
return Err(
"A Claude authentication flow is already running. Finish or cancel it first."
.to_string(),
);
}
*slot = Some(input_tx);
*cancel_slot().lock().await = Some(cancel_tx);
}
let bridge_was_enabled = project.auth_bridge_enabled;
let result = async {
// See the module docs: 2.1.226's `setup-token` redirects to an
// Anthropic-hosted callback, so no container-local listener needs
// bridging. Enabled anyway, per design, to cover CLI versions and login
// paths that do use a loopback redirect. Temporary elevation — the
// prior setting is restored below whatever happens.
if !bridge_was_enabled {
state
.projects_store
.set_auth_bridge_enabled(&project_id, true)?;
emit_progress(
&app_handle,
&project_id,
"Auth bridge enabled for the duration of login.",
);
}
// Called unconditionally, and idempotent: the flag may already have
// been on while the poller was not running (e.g. enabled before start).
state
.auth_bridge
.start(
project_id.clone(),
container_id.clone(),
app_handle.clone(),
state.projects_store.clone(),
)
.await;
emit_progress(
&app_handle,
&project_id,
"Running `claude setup-token` — sign in at the URL below, then submit the code it gives you.",
);
run_setup_token(&app_handle, &project_id, &container_id, input_rx, cancel_rx).await
}
.await;
// Release the flow, then restore the bridge — both unconditionally, so a
// failed or cancelled login leaves nothing latched on.
*pending_input().lock().await = None;
*cancel_slot().lock().await = None;
if !bridge_was_enabled {
// Stop the poller first: it awaits teardown, so host ports are provably
// released before the flag goes back.
state.auth_bridge.stop(&project_id).await;
if let Err(e) = state
.projects_store
.set_auth_bridge_enabled(&project_id, false)
{
log::warn!(
"Failed to restore the auth bridge setting for project {}: {}",
project_id,
e
);
}
}
let token = result?;
secure::store_claude_oauth_token(&token)?;
log::info!(
"Stored a shared Claude authentication token (acquired via project {})",
project_id
);
emit_progress(
&app_handle,
&project_id,
"Token stored in the OS keychain. Restart your Anthropic-backend containers to use it.",
);
Ok(())
}
/// Answer the `Paste code here if prompted >` prompt of a running
/// [`acquire_claude_token`] with the code shown after signing in.
///
/// Takes no project id: the flow is single-flight and the token is global, so
/// there is only ever one prompt waiting.
#[tauri::command]
pub async fn submit_claude_token_code(code: String) -> Result<(), String> {
let code = code.trim();
if code.is_empty() {
return Err("Enter the code shown after signing in.".to_string());
}
// The code goes to a TUI text input. A newline or escape embedded in it
// would submit early or drive the widget, so reject control characters
// outright rather than trying to sanitise them.
if code.chars().any(char::is_control) {
return Err("That code contains invalid characters. Copy it again and retry.".to_string());
}
let slot = pending_input().lock().await;
let sender = slot.as_ref().ok_or_else(|| {
"No Claude authentication flow is waiting for a code. Start authentication first."
.to_string()
})?;
let mut keystrokes = code.as_bytes().to_vec();
keystrokes.push(b'\r');
sender
.send(keystrokes)
.map_err(|_| "The authentication flow has already ended.".to_string())
}
/// Abort an in-flight [`acquire_claude_token`].
///
/// Tears the `setup-token` exec down and releases the single-flight guard, so
/// the user can immediately try again rather than waiting out `SETUP_TIMEOUT`.
/// A no-op when nothing is running, so closing the dialog twice is harmless.
#[tauri::command]
pub async fn cancel_claude_token() -> Result<(), String> {
let Some(sender) = cancel_slot().lock().await.take() else {
return Ok(());
};
// `Err` only means the flow finished between the take and the send, which
// is exactly the outcome cancelling wanted.
let _ = sender.send(());
Ok(())
}
/// Whether a shared Claude token exists. Deliberately a boolean — no command
/// here ever hands the token itself to the frontend.
#[tauri::command]
pub async fn has_claude_token() -> Result<bool, String> {
Ok(secure::has_claude_oauth_token())
}
/// Forget the shared Claude token. Containers keep the injected value until
/// each is next started, at which point the rotation-id label mismatch forces a
/// recreation that blanks the env var.
#[tauri::command]
pub async fn clear_claude_token() -> Result<(), String> {
secure::delete_claude_oauth_token()?;
log::info!("Cleared the shared Claude authentication token");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// A token-shaped value of realistic length.
fn token(seed: char) -> String {
format!("{}{}", TOKEN_PREFIX, std::iter::repeat(seed).take(90).collect::<String>())
}
#[test]
fn extracts_the_token_from_realistic_output() {
let tok = token('A');
let output = format!(
"Claude Code long-lived token setup\n\
Opening browser to https://claude.ai/oauth/authorize?code=true\n\
Login successful!\n\n\
Your token:\n{}\n\n\
Set CLAUDE_CODE_OAUTH_TOKEN to this value.\n",
tok
);
assert_eq!(parse_setup_token(&output), Some(tok));
}
#[test]
fn ignores_prose_decoys_and_still_finds_the_real_token() {
let tok = token('B');
let output = format!(
"Set the env var like so:\n export CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...\n\
or CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-<your-token-here>\n\
Your token: {}\n",
tok
);
assert_eq!(parse_setup_token(&output), Some(tok));
}
#[test]
fn a_decoy_on_its_own_yields_nothing() {
let output = "Usage: export CLAUDE_CODE_OAUTH_TOKEN=sk-ant-oat01-...\n";
assert_eq!(parse_setup_token(output), None);
}
#[test]
fn no_match_returns_none_rather_than_guessing() {
assert_eq!(parse_setup_token(""), None);
assert_eq!(
parse_setup_token("error: authentication cancelled by the user\n"),
None
);
// Right length, wrong product prefix.
assert_eq!(
parse_setup_token(&format!("sk-ant-api03-{}\n", "C".repeat(90))),
None
);
}
#[test]
fn multiple_matches_take_the_last() {
let old = token('D');
let new = token('E');
let output = format!(
"Replacing existing token {}\n...\nYour new token: {}\n",
old, new
);
assert_eq!(parse_setup_token(&output), Some(new));
}
#[test]
fn a_repainted_tui_frame_yields_the_same_token_once() {
let tok = token('F');
// Same frame drawn three times, as a TUI would.
let output = format!("Your token: {}\n", tok).repeat(3);
assert_eq!(parse_setup_token(&output), Some(tok));
}
#[test]
fn a_prefix_glued_to_a_longer_word_is_not_a_token() {
let output = format!("notasecretsk-ant-oat01-{}\n", "G".repeat(90));
assert_eq!(parse_setup_token(&output), None);
}
#[test]
fn the_token_stops_at_the_first_non_token_character() {
let tok = token('H');
let output = format!("token=\"{}\", expires=2027-08-09\n", tok);
assert_eq!(parse_setup_token(&output), Some(tok));
}
#[test]
fn redaction_masks_a_token_in_one_piece() {
let mut r = SecretRedactor::default();
let mut seen = r.push(&format!("Your token: {}\n", token('I')));
seen.push_str(&r.flush());
assert!(!seen.contains(TOKEN_PREFIX));
assert!(seen.contains(SECRET_PLACEHOLDER));
assert!(seen.contains("Your token: "));
}
#[test]
fn redaction_survives_a_token_split_across_chunks() {
let tok = token('J');
let mut r = SecretRedactor::default();
let mut seen = String::new();
// Split mid-prefix and again mid-body — the worst case for a naive
// per-chunk regex.
seen.push_str(&r.push("Your token: sk-a"));
seen.push_str(&r.push(&tok[4..40]));
seen.push_str(&r.push(&tok[40..]));
seen.push_str(&r.push("\ndone\n"));
seen.push_str(&r.flush());
assert!(!seen.contains(TOKEN_PREFIX), "leaked: {}", seen);
assert!(seen.contains(SECRET_PLACEHOLDER));
assert!(seen.ends_with("\ndone\n"));
}
#[test]
fn redaction_leaves_ordinary_text_alone() {
let mut r = SecretRedactor::default();
let mut seen = r.push("Visit https://claude.ai/oauth/authorize?code=abc-def to continue\n");
seen.push_str(&r.flush());
assert_eq!(
seen,
"Visit https://claude.ai/oauth/authorize?code=abc-def to continue\n"
);
}
#[test]
fn ansi_stripping_recovers_the_token_from_a_styled_frame() {
let tok = token('K');
let framed = format!(
"\x1b[2J\x1b[H\x1b[1;36mYour token:\x1b[0m\r\n\x1b[32m{}\x1b[0m\r\n",
tok
);
let mut s = AnsiStripper::default();
let visible = s.push(framed.as_bytes());
assert!(!visible.contains('\x1b'));
assert_eq!(parse_setup_token(&visible), Some(tok));
}
/// Claude Code's TUI positions words with `ESC [ n G` instead of spaces
/// (verified against 2.1.226). Deleting those would weld words together.
#[test]
fn ansi_stripping_turns_column_jumps_into_separators() {
let mut s = AnsiStripper::default();
let visible = s.push(b"\x1b[38;2;215;119;87mWelcome\x1b[9Gto\x1b[12GClaude\x1b[19GCode\x1b[39m");
assert_eq!(visible, "Welcome to Claude Code");
}
/// The failure this protects against: a column jump immediately before the
/// token would, if simply deleted, glue the preceding word onto the prefix
/// and make `parse_setup_token` reject a perfectly good token.
#[test]
fn a_column_jump_before_the_token_does_not_hide_it() {
let tok = token('L');
let framed = format!("\x1b[2GToken\x1b[8G{}\r\n", tok);
let mut s = AnsiStripper::default();
let visible = s.push(framed.as_bytes());
// The leading jump is an indent, so it becomes a space too.
assert_eq!(visible, format!(" Token {}\n", tok));
assert_eq!(parse_setup_token(&visible), Some(tok));
}
/// A pty with ONLCR emits `\r\r\n` at end of line; that is one break.
#[test]
fn carriage_return_runs_before_a_newline_collapse() {
let mut s = AnsiStripper::default();
let visible = s.push(b"one\r\r\ntwo\r\r\n");
assert_eq!(visible, "one\ntwo\n");
}
/// A bare CR is a repaint, and must still break the line so the old frame's
/// tail cannot be welded onto the new frame's head.
#[test]
fn a_bare_carriage_return_breaks_the_line() {
let mut s = AnsiStripper::default();
let visible = s.push(b"sk-ant-oat01-old\rsk-ant-oat01-new");
assert_eq!(visible, "sk-ant-oat01-old\nsk-ant-oat01-new");
}
#[test]
fn ansi_stripping_removes_osc8_hyperlink_wrappers() {
let mut s = AnsiStripper::default();
let visible = s.push(b"\x1b]8;id=1;https://claude.com/x\x07https://claude.com/x\x1b]8;;\x07");
assert_eq!(visible, "https://claude.com/x");
}
#[test]
fn ansi_stripping_handles_a_sequence_split_across_chunks() {
let mut s = AnsiStripper::default();
let mut visible = s.push(b"a\x1b[3");
visible.push_str(&s.push(b"1mb"));
assert_eq!(visible, "ab");
}
}
+16 -4
View File
@@ -155,11 +155,12 @@ pub async fn download_container_file(
/// Create a `.tar.gz` backup of the container and stream it to a host file. /// Create a `.tar.gz` backup of the container and stream it to a host file.
/// The archive contains: /// The archive contains:
/// - the workspace (default /workspace), minus regenerable build artifacts /// - the workspace (default /workspace), minus regenerable build artifacts
/// (node_modules, target), at the archive root, and /// (node_modules, target), under `workspace/`, and
/// - a sanitized copy of the home config under `home-claude/`: ~/.claude.json /// - a sanitized copy of the home config under `home-claude/`: ~/.claude.json
/// with secret-bearing keys removed (mcpServers/settings kept) and ~/.claude/ /// with secret-bearing keys removed (`mcpServers` — Claude Code's own native
/// minus the OAuth `.credentials.json`, so MCP servers, settings and skills /// MCP config — and `settings` are kept) and ~/.claude/ minus the OAuth
/// set up via Claude Code survive a Reset. /// `.credentials.json`, so settings and skills set up via Claude Code
/// survive a Reset.
/// `.git` is kept in full so the backup faithfully preserves git history, /// `.git` is kept in full so the backup faithfully preserves git history,
/// including unpushed commits. Build + gzip happen inside the container so a /// including unpushed commits. Build + gzip happen inside the container so a
/// large workspace isn't streamed in full. The container must be RUNNING (the /// large workspace isn't streamed in full. The container must be RUNNING (the
@@ -204,6 +205,16 @@ pub async fn download_container_backup(
// transient unreadable file from aborting the whole backup. If jq can't // transient unreadable file from aborting the whole backup. If jq can't
// parse ~/.claude.json we substitute an empty object — never the raw file — // parse ~/.claude.json we substitute an empty object — never the raw file —
// so secrets can't leak through the sanitization fallback. // so secrets can't leak through the sanitization fallback.
// The `--transform` nests the workspace under `workspace/` (parallel to
// `home-claude/`) so an extracted archive has both clearly labeled instead
// of scattering the workspace files into the extraction dir. Rewriting the
// leading `.` (rather than `./`) also renames tar's root member from `./` to
// `workspace`, so the archive carries a proper `workspace/` dir entry rather
// than a bare `./` that would stamp the source root's mode/mtime onto the
// extraction directory. `flags=rh` rewrites regular member names AND
// hardlink target names (so an intra-workspace hardlink pair still resolves
// on extract) while leaving symlink targets untouched (rewriting those would
// corrupt relative/absolute links).
let script = r#"set -e let script = r#"set -e
STAGE=$(mktemp -d) STAGE=$(mktemp -d)
trap 'rm -rf "$STAGE"' EXIT trap 'rm -rf "$STAGE"' EXIT
@@ -221,6 +232,7 @@ if [ -d "$HOME/.claude" ]; then
fi fi
tar czf - --ignore-failed-read \ tar czf - --ignore-failed-read \
--exclude='*/node_modules' --exclude='*/target' \ --exclude='*/node_modules' --exclude='*/target' \
--transform='flags=rh;s,^\.,workspace,' \
-C "$TC_BACKUP_SRC" . \ -C "$TC_BACKUP_SRC" . \
-C "$STAGE" home-claude"#; -C "$STAGE" home-claude"#;
File diff suppressed because it is too large Load Diff
@@ -1,38 +0,0 @@
use tauri::State;
use crate::models::McpServer;
use crate::AppState;
#[tauri::command]
pub async fn list_mcp_servers(state: State<'_, AppState>) -> Result<Vec<McpServer>, String> {
Ok(state.mcp_store.list())
}
#[tauri::command]
pub async fn add_mcp_server(
name: String,
state: State<'_, AppState>,
) -> Result<McpServer, String> {
let name = name.trim().to_string();
if name.is_empty() {
return Err("MCP server name cannot be empty.".to_string());
}
let server = McpServer::new(name);
state.mcp_store.add(server)
}
#[tauri::command]
pub async fn update_mcp_server(
server: McpServer,
state: State<'_, AppState>,
) -> Result<McpServer, String> {
state.mcp_store.update(server)
}
#[tauri::command]
pub async fn remove_mcp_server(
server_id: String,
state: State<'_, AppState>,
) -> Result<(), String> {
state.mcp_store.remove(&server_id)
}
+3 -1
View File
@@ -1,9 +1,11 @@
pub mod auth_bridge_commands;
pub mod auth_token_commands;
pub mod aws_commands; pub mod aws_commands;
pub mod docker_commands; pub mod docker_commands;
pub mod file_commands; pub mod file_commands;
pub mod help_commands; pub mod help_commands;
pub mod inspect_commands;
pub mod install_helper_commands; pub mod install_helper_commands;
pub mod mcp_commands;
pub mod project_commands; pub mod project_commands;
pub mod settings_commands; pub mod settings_commands;
pub mod stt_commands; pub mod stt_commands;
+79 -83
View File
@@ -2,7 +2,7 @@ use tauri::{Emitter, State};
use crate::commands::aws_commands; use crate::commands::aws_commands;
use crate::docker; use crate::docker;
use crate::models::{container_config, Backend, BedrockAuthMethod, McpServer, Project, ProjectPath, ProjectStatus}; use crate::models::{container_config, Backend, BedrockAuthMethod, Project, ProjectPath, ProjectStatus};
use crate::storage::secure; use crate::storage::secure;
use crate::AppState; use crate::AppState;
@@ -63,19 +63,6 @@ fn load_secrets_for_project(project: &mut Project) {
} }
} }
/// Resolve enabled MCP servers and filter to Docker-only ones.
fn resolve_mcp_servers(project: &Project, state: &AppState) -> (Vec<McpServer>, Vec<McpServer>) {
let all_mcp_servers = state.mcp_store.list();
let enabled_mcp: Vec<McpServer> = project.enabled_mcp_servers.iter()
.filter_map(|id| all_mcp_servers.iter().find(|s| &s.id == id).cloned())
.collect();
let docker_mcp: Vec<McpServer> = enabled_mcp.iter()
.filter(|s| s.is_docker())
.cloned()
.collect();
(enabled_mcp, docker_mcp)
}
#[tauri::command] #[tauri::command]
pub async fn list_projects(state: State<'_, AppState>) -> Result<Vec<Project>, String> { pub async fn list_projects(state: State<'_, AppState>) -> Result<Vec<Project>, String> {
Ok(state.projects_store.list()) Ok(state.projects_store.list())
@@ -113,6 +100,10 @@ pub async fn remove_project(
project_id: String, project_id: String,
state: State<'_, AppState>, state: State<'_, AppState>,
) -> Result<(), String> { ) -> Result<(), String> {
// Release any host loopback ports the auth bridge holds for this project
// before the container (and the project record) go away.
state.auth_bridge.stop(&project_id).await;
// Stop and remove container if it exists // Stop and remove container if it exists
if let Some(ref project) = state.projects_store.get(&project_id) { if let Some(ref project) = state.projects_store.get(&project_id) {
if let Some(ref container_id) = project.container_id { if let Some(ref container_id) = project.container_id {
@@ -121,16 +112,10 @@ pub async fn remove_project(
let _ = docker::remove_container(container_id).await; let _ = docker::remove_container(container_id).await;
} }
// Remove MCP containers and network // Legacy MCP cleanup (pre-MCP-removal installs): drop any leftover MCP
let (_enabled_mcp, docker_mcp) = resolve_mcp_servers(project, &state); // containers first, then the per-project network they were attached to.
if !docker_mcp.is_empty() { docker::remove_legacy_mcp_containers(&project.id).await;
if let Err(e) = docker::remove_mcp_containers(&docker_mcp).await { docker::remove_legacy_project_network(&project.id).await;
log::warn!("Failed to remove MCP containers for project {}: {}", project_id, e);
}
}
if let Err(e) = docker::remove_project_network(&project.id).await {
log::warn!("Failed to remove project network for project {}: {}", project_id, e);
}
// Clean up the snapshot image + volumes // Clean up the snapshot image + volumes
if let Err(e) = docker::remove_snapshot_image(project).await { if let Err(e) = docker::remove_snapshot_image(project).await {
@@ -152,10 +137,35 @@ pub async fn remove_project(
#[tauri::command] #[tauri::command]
pub async fn update_project( pub async fn update_project(
project: Project, project: Project,
app_handle: tauri::AppHandle,
state: State<'_, AppState>, state: State<'_, AppState>,
) -> Result<Project, String> { ) -> Result<Project, String> {
store_secrets_for_project(&project)?; store_secrets_for_project(&project)?;
state.projects_store.update(project) let updated = state.projects_store.update(project)?;
// `auth_bridge_enabled` can arrive through this generic save as well as
// through `set_auth_bridge_enabled`, so reconcile the running bridge with
// whatever was just persisted. `start` is idempotent and `stop` is a no-op
// when nothing is running, so this is safe on every project save.
if updated.auth_bridge_enabled {
if let Some(ref container_id) = updated.container_id {
if docker::is_container_running(container_id).await.unwrap_or(false) {
state
.auth_bridge
.start(
updated.id.clone(),
container_id.clone(),
app_handle,
state.projects_store.clone(),
)
.await;
}
}
} else {
state.auth_bridge.stop(&updated.id).await;
}
Ok(updated)
} }
#[tauri::command] #[tauri::command]
@@ -177,9 +187,6 @@ pub async fn start_project_container(
let settings = state.settings_store.get(); let settings = state.settings_store.get();
let image_name = container_config::resolve_image_name(&settings.image_source, &settings.custom_image_name); let image_name = container_config::resolve_image_name(&settings.image_source, &settings.custom_image_name);
// Resolve enabled MCP servers for this project
let (enabled_mcp, docker_mcp) = resolve_mcp_servers(&project, &state);
// Validate backend requirements // Validate backend requirements
if project.backend == Backend::Bedrock { if project.backend == Backend::Bedrock {
let bedrock = project.bedrock_config.as_ref() let bedrock = project.bedrock_config.as_ref()
@@ -300,39 +307,6 @@ pub async fn start_project_container(
// AWS config path from global settings // AWS config path from global settings
let aws_config_path = settings.global_aws.aws_config_path.clone(); let aws_config_path = settings.global_aws.aws_config_path.clone();
// Set up Docker network and MCP containers if needed
let network_name = if !docker_mcp.is_empty() {
// Pull any missing MCP Docker images before starting containers
for server in &docker_mcp {
if let Some(ref image) = server.docker_image {
if !docker::image_exists(image).await.unwrap_or(false) {
emit_progress(
&app_handle,
&project_id,
&format!("Pulling MCP image for '{}'...", server.name),
);
let image_clone = image.clone();
let app_clone = app_handle.clone();
let pid_clone = project_id.clone();
let sname = server.name.clone();
docker::pull_image(&image_clone, move |msg| {
emit_progress(&app_clone, &pid_clone, &format!("[{}] {}", sname, msg));
}).await.map_err(|e| {
format!("Failed to pull MCP image '{}' for '{}': {}", image, server.name, e)
})?;
}
}
}
emit_progress(&app_handle, &project_id, "Setting up MCP network...");
let net = docker::ensure_project_network(&project.id).await?;
emit_progress(&app_handle, &project_id, "Starting MCP containers...");
docker::start_mcp_containers(&docker_mcp, &net).await?;
Some(net)
} else {
None
};
let container_id = if let Some(existing_id) = docker::find_existing_container(&project).await? { let container_id = if let Some(existing_id) = docker::find_existing_container(&project).await? {
// Check if config changed — if so, snapshot + recreate // Check if config changed — if so, snapshot + recreate
let needs_recreate = docker::container_needs_recreation( let needs_recreate = docker::container_needs_recreation(
@@ -344,7 +318,6 @@ pub async fn start_project_container(
settings.global_claude_instructions.as_deref(), settings.global_claude_instructions.as_deref(),
&settings.global_custom_env_vars, &settings.global_custom_env_vars,
settings.timezone.as_deref(), settings.timezone.as_deref(),
&enabled_mcp,
settings.global_claude_code_settings.as_ref(), settings.global_claude_code_settings.as_ref(),
settings.default_ssh_key_path.as_deref(), settings.default_ssh_key_path.as_deref(),
settings.default_git_user_name.as_deref(), settings.default_git_user_name.as_deref(),
@@ -362,6 +335,12 @@ pub async fn start_project_container(
let _ = docker::stop_container(&existing_id).await; let _ = docker::stop_container(&existing_id).await;
docker::remove_container(&existing_id).await?; docker::remove_container(&existing_id).await?;
// Legacy MCP cleanup: the old container may have been attached to
// `triple-c-net-<projectId>`. Tear down leftover MCP containers and
// that network now, before the replacement is created without it.
docker::remove_legacy_mcp_containers(&project.id).await;
docker::remove_legacy_project_network(&project.id).await;
// Create from snapshot image (preserves system-level changes) // Create from snapshot image (preserves system-level changes)
let snapshot_image = docker::get_snapshot_image_name(&project); let snapshot_image = docker::get_snapshot_image_name(&project);
let create_image = if docker::image_exists(&snapshot_image).await.unwrap_or(false) { let create_image = if docker::image_exists(&snapshot_image).await.unwrap_or(false) {
@@ -381,8 +360,6 @@ pub async fn start_project_container(
settings.global_claude_instructions.as_deref(), settings.global_claude_instructions.as_deref(),
&settings.global_custom_env_vars, &settings.global_custom_env_vars,
settings.timezone.as_deref(), settings.timezone.as_deref(),
&enabled_mcp,
network_name.as_deref(),
settings.global_claude_code_settings.as_ref(), settings.global_claude_code_settings.as_ref(),
settings.default_ssh_key_path.as_deref(), settings.default_ssh_key_path.as_deref(),
settings.default_git_user_name.as_deref(), settings.default_git_user_name.as_deref(),
@@ -420,8 +397,6 @@ pub async fn start_project_container(
settings.global_claude_instructions.as_deref(), settings.global_claude_instructions.as_deref(),
&settings.global_custom_env_vars, &settings.global_custom_env_vars,
settings.timezone.as_deref(), settings.timezone.as_deref(),
&enabled_mcp,
network_name.as_deref(),
settings.global_claude_code_settings.as_ref(), settings.global_claude_code_settings.as_ref(),
settings.default_ssh_key_path.as_deref(), settings.default_ssh_key_path.as_deref(),
settings.default_git_user_name.as_deref(), settings.default_git_user_name.as_deref(),
@@ -454,6 +429,20 @@ pub async fn start_project_container(
state.projects_store.set_container_id(&project_id, Some(container_id.clone()))?; state.projects_store.set_container_id(&project_id, Some(container_id.clone()))?;
state.projects_store.update_status(&project_id, ProjectStatus::Running)?; state.projects_store.update_status(&project_id, ProjectStatus::Running)?;
// Arm the auth bridge if this project opted in. Purely host-side, so it
// happens after the container is up and never affects the start itself.
if project.auth_bridge_enabled {
state
.auth_bridge
.start(
project_id.clone(),
container_id.clone(),
app_handle.clone(),
state.projects_store.clone(),
)
.await;
}
project.container_id = Some(container_id); project.container_id = Some(container_id);
project.status = ProjectStatus::Running; project.status = ProjectStatus::Running;
Ok(project) Ok(project)
@@ -472,6 +461,9 @@ pub async fn stop_project_container(
state.projects_store.update_status(&project_id, ProjectStatus::Stopping)?; state.projects_store.update_status(&project_id, ProjectStatus::Stopping)?;
// Drop host listeners first: they only make sense while the container runs.
state.auth_bridge.stop(&project_id).await;
if let Some(ref container_id) = project.container_id { if let Some(ref container_id) = project.container_id {
// Close exec sessions for this project // Close exec sessions for this project
emit_progress(&app_handle, &project_id, "Stopping container..."); emit_progress(&app_handle, &project_id, "Stopping container...");
@@ -482,15 +474,6 @@ pub async fn stop_project_container(
} }
} }
// Stop MCP containers (best-effort)
let (_enabled_mcp, docker_mcp) = resolve_mcp_servers(&project, &state);
if !docker_mcp.is_empty() {
emit_progress(&app_handle, &project_id, "Stopping MCP containers...");
if let Err(e) = docker::stop_mcp_containers(&docker_mcp).await {
log::warn!("Failed to stop MCP containers for project {}: {}", project_id, e);
}
}
state.projects_store.update_status(&project_id, ProjectStatus::Stopped)?; state.projects_store.update_status(&project_id, ProjectStatus::Stopped)?;
Ok(()) Ok(())
} }
@@ -506,6 +489,10 @@ pub async fn rebuild_project_container(
.get(&project_id) .get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?; .ok_or_else(|| format!("Project {} not found", project_id))?;
// The bridge is bound to the container that is about to be destroyed;
// `start_project_container` below re-arms it against the new one.
state.auth_bridge.stop(&project_id).await;
// Remove existing container // Remove existing container
if let Some(ref container_id) = project.container_id { if let Some(ref container_id) = project.container_id {
state.exec_manager.close_sessions_for_container(container_id).await; state.exec_manager.close_sessions_for_container(container_id).await;
@@ -514,14 +501,6 @@ pub async fn rebuild_project_container(
state.projects_store.set_container_id(&project_id, None)?; state.projects_store.set_container_id(&project_id, None)?;
} }
// Remove MCP containers before rebuild
let (_enabled_mcp, docker_mcp) = resolve_mcp_servers(&project, &state);
if !docker_mcp.is_empty() {
if let Err(e) = docker::remove_mcp_containers(&docker_mcp).await {
log::warn!("Failed to remove MCP containers for project {}: {}", project_id, e);
}
}
// Remove snapshot image + volumes so Reset creates from the clean base image // Remove snapshot image + volumes so Reset creates from the clean base image
if let Err(e) = docker::remove_snapshot_image(&project).await { if let Err(e) = docker::remove_snapshot_image(&project).await {
log::warn!("Failed to remove snapshot image for project {}: {}", project_id, e); log::warn!("Failed to remove snapshot image for project {}: {}", project_id, e);
@@ -540,6 +519,7 @@ pub async fn rebuild_project_container(
/// to Stopped. /// to Stopped.
#[tauri::command] #[tauri::command]
pub async fn reconcile_project_statuses( pub async fn reconcile_project_statuses(
app_handle: tauri::AppHandle,
state: State<'_, AppState>, state: State<'_, AppState>,
) -> Result<Vec<Project>, String> { ) -> Result<Vec<Project>, String> {
let projects = state.projects_store.list(); let projects = state.projects_store.list();
@@ -561,6 +541,22 @@ pub async fn reconcile_project_statuses(
project.name, project.name,
project.id project.id
); );
// The app may have restarted while the container kept running; the
// bridge lives in this process, so re-arm it here. `start` is
// idempotent, so a bridge that is already polling is untouched.
if project.auth_bridge_enabled {
if let Some(ref container_id) = project.container_id {
state
.auth_bridge
.start(
project.id.clone(),
container_id.clone(),
app_handle.clone(),
state.projects_store.clone(),
)
.await;
}
}
} else { } else {
log::info!( log::info!(
"Project '{}' ({}) container is not running — setting to Stopped", "Project '{}' ({}) container is not running — setting to Stopped",
@@ -17,11 +17,11 @@ fn build_terminal_cmd(project: &Project, state: &AppState, session_name: Option<
.map(|b| b.auth_method == BedrockAuthMethod::Profile) .map(|b| b.auth_method == BedrockAuthMethod::Profile)
.unwrap_or(false); .unwrap_or(false);
let permission_args = project.effective_permission_mode().cli_args();
if !is_bedrock_profile { if !is_bedrock_profile {
let mut cmd = vec!["claude".to_string()]; let mut cmd = vec!["claude".to_string()];
if project.full_permissions { cmd.extend(permission_args);
cmd.push("--dangerously-skip-permissions".to_string());
}
if let Some(name) = session_name { if let Some(name) = session_name {
if !name.is_empty() { if !name.is_empty() {
cmd.push("-n".to_string()); cmd.push("-n".to_string());
@@ -42,11 +42,13 @@ fn build_terminal_cmd(project: &Project, state: &AppState, session_name: Option<
.filter(|n| !n.is_empty()) .filter(|n| !n.is_empty())
.map(|n| format!(" -n '{}'", n.replace('\'', "'\\''"))) .map(|n| format!(" -n '{}'", n.replace('\'', "'\\''")))
.unwrap_or_default(); .unwrap_or_default();
let claude_cmd = if project.full_permissions { // The args are interpolated into a shell script string, so single-quote
format!("exec claude --dangerously-skip-permissions{}", name_flag) // each one (same escaping style as name_flag above).
} else { let permission_flags: String = permission_args
format!("exec claude{}", name_flag) .iter()
}; .map(|a| format!(" '{}'", a.replace('\'', "'\\''")))
.collect();
let claude_cmd = format!("exec claude{}{}", permission_flags, name_flag);
let script = format!( let script = format!(
r#" r#"
+162 -287
View File
@@ -8,7 +8,7 @@ use std::collections::HashMap;
use sha2::{Sha256, Digest}; use sha2::{Sha256, Digest};
use super::client::get_docker; use super::client::get_docker;
use crate::models::{Backend, BedrockAuthMethod, ClaudeCodeSettings, ContainerInfo, EnvVar, GlobalAwsSettings, GlobalOllamaSettings, GlobalOpenAiCompatibleSettings, McpServer, McpTransportType, PortMapping, Project, ProjectPath}; use crate::models::{Backend, BedrockAuthMethod, ClaudeCodeSettings, ContainerInfo, EnvVar, GlobalAwsSettings, GlobalOllamaSettings, GlobalOpenAiCompatibleSettings, PortMapping, Project, ProjectPath};
const SCHEDULER_INSTRUCTIONS: &str = r#"## Scheduled Tasks const SCHEDULER_INSTRUCTIONS: &str = r#"## Scheduled Tasks
@@ -171,21 +171,45 @@ fn build_claude_instructions(
combined combined
} }
/// The env var Claude Code reads a long-lived `claude setup-token` credential
/// from. Named once so injection, the reserved-name blocklist, and the
/// stale-value neutralization pass can never disagree about the spelling.
pub const CLAUDE_OAUTH_TOKEN_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN";
/// Env var name prefixes Triple-C manages itself; users cannot set these by hand.
const RESERVED_ENV_PREFIXES: &[&str] = &["ANTHROPIC_", "AWS_", "GIT_", "HOST_", "TRIPLE_C_"];
/// Exact env var names Triple-C manages itself. Not covered by
/// [`RESERVED_ENV_PREFIXES`] because they don't share those prefixes.
///
/// `MCP_SERVERS_JSON` is reserved for legacy reasons: the built-in MCP feature
/// was removed, but the name stays blocked so users cannot hand-set it.
/// `CLAUDE_CODE_OAUTH_TOKEN` is reserved because Triple-C owns it — a hand-set
/// value would silently outrank the keychain-held shared token and be invisible
/// to the auth UI.
const RESERVED_ENV_EXACT: &[&str] = &[
"CLAUDE_INSTRUCTIONS",
"MCP_SERVERS_JSON",
"CLAUDE_CODE_SETTINGS_JSON",
"MISSION_CONTROL_ENABLED",
"TRIPLE_C_PERMISSION_MODE",
CLAUDE_OAUTH_TOKEN_ENV,
];
/// Whether `key` is an env var name Triple-C reserves for itself.
fn is_reserved_env_key(key: &str) -> bool {
let upper = key.to_uppercase();
RESERVED_ENV_PREFIXES.iter().any(|p| upper.starts_with(p))
|| RESERVED_ENV_EXACT.iter().any(|e| upper == *e)
}
/// Compute a fingerprint string for the custom environment variables. /// Compute a fingerprint string for the custom environment variables.
/// Sorted alphabetically so order changes do not cause spurious recreation. /// Sorted alphabetically so order changes do not cause spurious recreation.
fn compute_env_fingerprint(custom_env_vars: &[EnvVar]) -> String { fn compute_env_fingerprint(custom_env_vars: &[EnvVar]) -> String {
let reserved_prefixes = ["ANTHROPIC_", "AWS_", "GIT_", "HOST_", "TRIPLE_C_"];
let reserved_exact = ["CLAUDE_INSTRUCTIONS", "MCP_SERVERS_JSON", "CLAUDE_CODE_SETTINGS_JSON", "MISSION_CONTROL_ENABLED"];
let mut parts: Vec<String> = Vec::new(); let mut parts: Vec<String> = Vec::new();
for env_var in custom_env_vars { for env_var in custom_env_vars {
let key = env_var.key.trim(); let key = env_var.key.trim();
if key.is_empty() { if key.is_empty() || is_reserved_env_key(key) {
continue;
}
let upper = key.to_uppercase();
let is_reserved = reserved_prefixes.iter().any(|p| upper.starts_with(p))
|| reserved_exact.iter().any(|e| upper == *e);
if is_reserved {
continue; continue;
} }
parts.push(format!("{}={}", key, env_var.value)); parts.push(format!("{}={}", key, env_var.value));
@@ -194,6 +218,45 @@ fn compute_env_fingerprint(custom_env_vars: &[EnvVar]) -> String {
parts.join(",") parts.join(",")
} }
/// The shared Claude Code OAuth token to inject for this project, paired with
/// its rotation id.
///
/// `None` unless *all* of: the backend is Anthropic (the token is meaningless
/// to Bedrock/Ollama/OpenAI-compatible), the project has not opted out, and a
/// non-blank token is actually in the keychain. Read here rather than passed in
/// because the token is global, not part of the per-project record.
///
/// The returned token is never logged and never leaves this module except as
/// the env var value handed to Docker.
fn shared_claude_auth(project: &Project) -> Option<(String, String)> {
if project.backend != Backend::Anthropic || !project.use_shared_auth_token {
return None;
}
let token = crate::storage::secure::get_claude_oauth_token()
.unwrap_or_else(|e| {
log::warn!("Could not read the shared Claude token from the keychain: {}", e);
None
})
.filter(|t| !t.trim().is_empty())?;
// A token with no rotation id predates versioning (or the id write failed).
// A constant stand-in still differs from the empty "no token" label, so
// presence changes are caught; only rotations could be missed.
let version = crate::storage::secure::get_claude_oauth_token_version()
.unwrap_or(None)
.unwrap_or_else(|| "unversioned".to_string());
Some((token, version))
}
/// Label value tracking which shared Claude token (if any) a container was
/// created with. Empty means "none injected". See
/// [`crate::storage::secure`] for why this is a random rotation id rather than
/// a hash of the token.
fn claude_token_label(project: &Project) -> String {
shared_claude_auth(project)
.map(|(_, version)| version)
.unwrap_or_default()
}
/// Merge global and per-project custom environment variables. /// Merge global and per-project custom environment variables.
/// Per-project variables override global variables with the same key. /// Per-project variables override global variables with the same key.
fn merge_custom_env_vars(global: &[EnvVar], project: &[EnvVar]) -> Vec<EnvVar> { fn merge_custom_env_vars(global: &[EnvVar], project: &[EnvVar]) -> Vec<EnvVar> {
@@ -476,83 +539,6 @@ fn build_claude_code_settings_json(
} }
} }
/// Build the JSON value for MCP servers config to be injected into ~/.claude.json.
/// Produces `{"mcpServers": {"name": {"type": "stdio", ...}, ...}}`.
///
/// Handles 4 modes:
/// - Stdio+Docker: `docker exec -i <mcp-container-name> <command> ...args`
/// - Stdio+Manual: `<command> ...args` (existing behavior)
/// - HTTP+Docker: `streamableHttp` URL pointing to `http://<mcp-container-name>:<port>/mcp`
/// - HTTP+Manual: `streamableHttp` with user-provided URL + headers
fn build_mcp_servers_json(servers: &[McpServer]) -> String {
let mut mcp_map = serde_json::Map::new();
for server in servers {
let mut entry = serde_json::Map::new();
match server.transport_type {
McpTransportType::Stdio => {
entry.insert("type".to_string(), serde_json::json!("stdio"));
if server.is_docker() {
// Stdio+Docker: use `docker exec` to communicate with MCP container
entry.insert("command".to_string(), serde_json::json!("docker"));
let mut args = vec![
"exec".to_string(),
"-i".to_string(),
server.mcp_container_name(),
];
if let Some(ref cmd) = server.command {
args.push(cmd.clone());
}
args.extend(server.args.iter().cloned());
entry.insert("args".to_string(), serde_json::json!(args));
} else {
// Stdio+Manual: existing behavior
if let Some(ref cmd) = server.command {
entry.insert("command".to_string(), serde_json::json!(cmd));
}
if !server.args.is_empty() {
entry.insert("args".to_string(), serde_json::json!(server.args));
}
}
if !server.env.is_empty() {
entry.insert("env".to_string(), serde_json::json!(server.env));
}
}
McpTransportType::Http => {
entry.insert("type".to_string(), serde_json::json!("streamableHttp"));
if server.is_docker() {
// HTTP+Docker: point to MCP container by name on the shared network
let url = format!(
"http://{}:{}/mcp",
server.mcp_container_name(),
server.effective_container_port()
);
entry.insert("url".to_string(), serde_json::json!(url));
} else {
// HTTP+Manual: user-provided URL + headers
if let Some(ref url) = server.url {
entry.insert("url".to_string(), serde_json::json!(url));
}
if !server.headers.is_empty() {
entry.insert("headers".to_string(), serde_json::json!(server.headers));
}
}
}
}
mcp_map.insert(server.name.clone(), serde_json::Value::Object(entry));
}
let wrapper = serde_json::json!({ "mcpServers": mcp_map });
serde_json::to_string(&wrapper).unwrap_or_default()
}
/// Compute a fingerprint for MCP server configuration so we can detect changes.
fn compute_mcp_fingerprint(servers: &[McpServer]) -> String {
if servers.is_empty() {
return String::new();
}
let json = build_mcp_servers_json(servers);
sha256_hex(&json)
}
pub async fn find_existing_container(project: &Project) -> Result<Option<String>, String> { pub async fn find_existing_container(project: &Project) -> Result<Option<String>, String> {
let docker = get_docker()?; let docker = get_docker()?;
let container_name = project.container_name(); let container_name = project.container_name();
@@ -594,8 +580,6 @@ pub async fn create_container(
global_claude_instructions: Option<&str>, global_claude_instructions: Option<&str>,
global_custom_env_vars: &[EnvVar], global_custom_env_vars: &[EnvVar],
timezone: Option<&str>, timezone: Option<&str>,
mcp_servers: &[McpServer],
network_name: Option<&str>,
global_claude_code_settings: Option<&ClaudeCodeSettings>, global_claude_code_settings: Option<&ClaudeCodeSettings>,
default_ssh_key_path: Option<&str>, default_ssh_key_path: Option<&str>,
default_git_user_name: Option<&str>, default_git_user_name: Option<&str>,
@@ -757,6 +741,19 @@ pub async fn create_container(
} }
} }
// Shared Claude Code OAuth token (Anthropic backend only, opt-out per
// project). Injected *before* the neutralization pass below so that pass
// sees it as already-set; when it is absent the pass actively blanks the
// variable instead of leaving a stale one baked into the snapshot image.
let shared_claude = shared_claude_auth(project);
if let Some((ref token, _)) = shared_claude {
env_vars.push(format!("{}={}", CLAUDE_OAUTH_TOKEN_ENV, token));
log::info!(
"Injecting the shared Claude authentication token into the container for project {}",
project.id
);
}
// ── Neutralize stale backend auth env vars ────────────────────────────── // ── Neutralize stale backend auth env vars ──────────────────────────────
// When a project switches backends (e.g. Bedrock → Anthropic) the container // When a project switches backends (e.g. Bedrock → Anthropic) the container
// is recreated *from a snapshot image* committed off the previous container. // is recreated *from a snapshot image* committed off the previous container.
@@ -781,6 +778,11 @@ pub async fn create_container(
"ANTHROPIC_MODEL", "ANTHROPIC_MODEL",
"DISABLE_PROMPT_CACHING", "DISABLE_PROMPT_CACHING",
"ANTHROPIC_BEDROCK_SERVICE_TIER", "ANTHROPIC_BEDROCK_SERVICE_TIER",
// Revoking the shared token, opting a project out, or switching away
// from the Anthropic backend must *clear* this, not merely stop setting
// it — otherwise the value committed into the snapshot image keeps
// authenticating the container with a credential the user removed.
CLAUDE_OAUTH_TOKEN_ENV,
]; ];
let already_set: std::collections::HashSet<String> = env_vars let already_set: std::collections::HashSet<String> = env_vars
.iter() .iter()
@@ -794,17 +796,12 @@ pub async fn create_container(
// Custom environment variables (global + per-project, project overrides global for same key) // Custom environment variables (global + per-project, project overrides global for same key)
let merged_env = merge_custom_env_vars(global_custom_env_vars, &project.custom_env_vars); let merged_env = merge_custom_env_vars(global_custom_env_vars, &project.custom_env_vars);
let reserved_prefixes = ["ANTHROPIC_", "AWS_", "GIT_", "HOST_", "TRIPLE_C_"];
let reserved_exact = ["CLAUDE_INSTRUCTIONS", "MCP_SERVERS_JSON", "CLAUDE_CODE_SETTINGS_JSON", "MISSION_CONTROL_ENABLED"];
for env_var in &merged_env { for env_var in &merged_env {
let key = env_var.key.trim(); let key = env_var.key.trim();
if key.is_empty() { if key.is_empty() {
continue; continue;
} }
let upper = key.to_uppercase(); if is_reserved_env_key(key) {
let is_reserved = reserved_prefixes.iter().any(|p| upper.starts_with(p))
|| reserved_exact.iter().any(|e| upper == *e);
if is_reserved {
log::warn!("Skipping reserved env var: {}", key); log::warn!("Skipping reserved env var: {}", key);
continue; continue;
} }
@@ -825,6 +822,13 @@ pub async fn create_container(
env_vars.push("MISSION_CONTROL_ENABLED=1".to_string()); env_vars.push("MISSION_CONTROL_ENABLED=1".to_string());
} }
// Permission mode — read by triple-c-task-runner for scheduled (headless)
// Claude Code runs. Interactive terminals get the flags directly instead.
env_vars.push(format!(
"TRIPLE_C_PERMISSION_MODE={}",
project.effective_permission_mode().as_env_value()
));
// Claude instructions (global + per-project, plus port mapping info + scheduler docs) // Claude instructions (global + per-project, plus port mapping info + scheduler docs)
let combined_instructions = build_claude_instructions( let combined_instructions = build_claude_instructions(
global_claude_instructions, global_claude_instructions,
@@ -838,12 +842,6 @@ pub async fn create_container(
env_vars.push(format!("CLAUDE_INSTRUCTIONS={}", instructions)); env_vars.push(format!("CLAUDE_INSTRUCTIONS={}", instructions));
} }
// MCP servers config
if !mcp_servers.is_empty() {
let mcp_json = build_mcp_servers_json(mcp_servers);
env_vars.push(format!("MCP_SERVERS_JSON={}", mcp_json));
}
// Claude Code settings (global + per-project merged) // Claude Code settings (global + per-project merged)
let merged_cc_settings = merge_claude_code_settings( let merged_cc_settings = merge_claude_code_settings(
global_claude_code_settings, global_claude_code_settings,
@@ -964,12 +962,8 @@ pub async fn create_container(
} }
} }
// Docker socket (if allowed, or auto-enabled for stdio+Docker MCP servers) // Docker socket (if allowed)
let needs_docker_for_mcp = any_stdio_docker_mcp(mcp_servers); if project.allow_docker_access {
if project.allow_docker_access || needs_docker_for_mcp {
if needs_docker_for_mcp && !project.allow_docker_access {
log::info!("Auto-enabling Docker socket access for stdio+Docker MCP servers");
}
// On Windows, the named pipe (//./pipe/docker_engine) cannot be // On Windows, the named pipe (//./pipe/docker_engine) cannot be
// bind-mounted into a Linux container. Docker Desktop exposes the // bind-mounted into a Linux container. Docker Desktop exposes the
// daemon socket as /var/run/docker.sock for container mounts. // daemon socket as /var/run/docker.sock for container mounts.
@@ -1014,8 +1008,9 @@ pub async fn create_container(
labels.insert("triple-c.ports-fingerprint".to_string(), compute_ports_fingerprint(&project.port_mappings)); labels.insert("triple-c.ports-fingerprint".to_string(), compute_ports_fingerprint(&project.port_mappings));
labels.insert("triple-c.image".to_string(), image_name.to_string()); labels.insert("triple-c.image".to_string(), image_name.to_string());
labels.insert("triple-c.timezone".to_string(), timezone.unwrap_or("").to_string()); labels.insert("triple-c.timezone".to_string(), timezone.unwrap_or("").to_string());
labels.insert("triple-c.mcp-fingerprint".to_string(), compute_mcp_fingerprint(mcp_servers));
labels.insert("triple-c.mission-control".to_string(), project.mission_control_enabled.to_string()); labels.insert("triple-c.mission-control".to_string(), project.mission_control_enabled.to_string());
labels.insert("triple-c.permission-mode".to_string(),
project.effective_permission_mode().as_env_value().to_string());
labels.insert("triple-c.custom-env-fingerprint".to_string(), custom_env_fingerprint.clone()); labels.insert("triple-c.custom-env-fingerprint".to_string(), custom_env_fingerprint.clone());
labels.insert("triple-c.claude-code-settings-fingerprint".to_string(), labels.insert("triple-c.claude-code-settings-fingerprint".to_string(),
compute_claude_code_settings_fingerprint(merged_cc_settings.as_ref(), project.sandbox_mode_enabled)); compute_claude_code_settings_fingerprint(merged_cc_settings.as_ref(), project.sandbox_mode_enabled));
@@ -1025,13 +1020,15 @@ pub async fn create_container(
labels.insert("triple-c.git-user-email".to_string(), effective_git_email.unwrap_or_default().to_string()); labels.insert("triple-c.git-user-email".to_string(), effective_git_email.unwrap_or_default().to_string());
labels.insert("triple-c.git-token-hash".to_string(), labels.insert("triple-c.git-token-hash".to_string(),
project.git_token.as_ref().map(|t| sha256_hex(t)).unwrap_or_default()); project.git_token.as_ref().map(|t| sha256_hex(t)).unwrap_or_default());
// Rotation id, NOT the token and NOT a hash of it — labels are readable by
// anything on the host via `docker inspect`.
labels.insert("triple-c.claude-token-version".to_string(),
shared_claude.as_ref().map(|(_, v)| v.clone()).unwrap_or_default());
let host_config = HostConfig { let host_config = HostConfig {
mounts: Some(mounts), mounts: Some(mounts),
port_bindings: if port_bindings.is_empty() { None } else { Some(port_bindings) }, port_bindings: if port_bindings.is_empty() { None } else { Some(port_bindings) },
init: Some(true), init: Some(true),
// Connect to project network if specified (for MCP container communication)
network_mode: network_name.map(|n| n.to_string()),
..Default::default() ..Default::default()
}; };
@@ -1223,7 +1220,8 @@ chmod 600 "$HOME/.aws/credentials""#;
/// NOTE: `docker commit` always bakes the *running container's* full ENV into /// NOTE: `docker commit` always bakes the *running container's* full ENV into
/// the resulting image — passing an empty Config here does NOT strip it, and /// the resulting image — passing an empty Config here does NOT strip it, and
/// the commit API gives no way to remove env vars. As a result auth vars (e.g. /// the commit API gives no way to remove env vars. As a result auth vars (e.g.
/// CLAUDE_CODE_USE_BEDROCK, AWS_*) are present in this snapshot image's ENV. /// CLAUDE_CODE_USE_BEDROCK, AWS_*, CLAUDE_CODE_OAUTH_TOKEN) are present in this
/// snapshot image's ENV — this image is local and per-project, never pushed.
/// `create_container` defends against that by explicitly overriding every /// `create_container` defends against that by explicitly overriding every
/// managed auth key for the active backend (see MANAGED_AUTH_KEYS), so a /// managed auth key for the active backend (see MANAGED_AUTH_KEYS), so a
/// backend switch does not inherit the previous backend's stale credentials. /// backend switch does not inherit the previous backend's stale credentials.
@@ -1307,7 +1305,6 @@ pub async fn container_needs_recreation(
global_claude_instructions: Option<&str>, global_claude_instructions: Option<&str>,
global_custom_env_vars: &[EnvVar], global_custom_env_vars: &[EnvVar],
timezone: Option<&str>, timezone: Option<&str>,
mcp_servers: &[McpServer],
global_claude_code_settings: Option<&ClaudeCodeSettings>, global_claude_code_settings: Option<&ClaudeCodeSettings>,
default_ssh_key_path: Option<&str>, default_ssh_key_path: Option<&str>,
default_git_user_name: Option<&str>, default_git_user_name: Option<&str>,
@@ -1470,6 +1467,20 @@ pub async fn container_needs_recreation(
return Ok(true); return Ok(true);
} }
// ── Shared Claude Code OAuth token ───────────────────────────────────
// Compares rotation ids, so this fires when the token is first acquired,
// re-acquired (rotated), revoked, or opted out of. Both "" means no token
// is in play, which is also what a container predating this feature reports
// — so existing installs are not recreated until a token actually exists.
// Recreation is the only way to change container env, and it is also what
// makes MANAGED_AUTH_KEYS blank a revoked token out of the snapshot image.
let expected_claude_token = claude_token_label(project);
let container_claude_token = get_label("triple-c.claude-token-version").unwrap_or_default();
if container_claude_token != expected_claude_token {
log::info!("Shared Claude authentication token mismatch — recreating container");
return Ok(true);
}
// ── Custom environment variables (label-based fingerprint) ────────── // ── Custom environment variables (label-based fingerprint) ──────────
let merged_env = merge_custom_env_vars(global_custom_env_vars, &project.custom_env_vars); let merged_env = merge_custom_env_vars(global_custom_env_vars, &project.custom_env_vars);
let expected_fingerprint = compute_env_fingerprint(&merged_env); let expected_fingerprint = compute_env_fingerprint(&merged_env);
@@ -1487,6 +1498,22 @@ pub async fn container_needs_recreation(
return Ok(true); return Ok(true);
} }
// ── Permission mode ────────────────────────────────────────────────────
// The mode is injected as the TRIPLE_C_PERMISSION_MODE env var, and
// container env can only change by recreating the container. A missing
// label means the container predates this feature and therefore has no
// such env var, so it must be recreated too (empty != any valid mode).
let expected_permission_mode = project.effective_permission_mode().as_env_value();
let container_permission_mode = get_label("triple-c.permission-mode").unwrap_or_default();
if container_permission_mode != expected_permission_mode {
log::info!(
"Permission mode mismatch (container={:?}, expected={:?})",
container_permission_mode,
expected_permission_mode
);
return Ok(true);
}
// ── Claude instructions (label-based fingerprint) ───────────────────── // ── Claude instructions (label-based fingerprint) ─────────────────────
let expected_instructions = build_claude_instructions( let expected_instructions = build_claude_instructions(
global_claude_instructions, global_claude_instructions,
@@ -1514,11 +1541,29 @@ pub async fn container_needs_recreation(
return Ok(true); return Ok(true);
} }
// ── MCP servers fingerprint ───────────────────────────────────────── // ── Legacy MCP migration shim ───────────────────────────────────────
let expected_mcp_fp = compute_mcp_fingerprint(mcp_servers); // One-release migration for containers created before the built-in MCP
let container_mcp_fp = get_label("triple-c.mcp-fingerprint").unwrap_or_default(); // feature was removed. Such containers carry a `triple-c.mcp-fingerprint`
if container_mcp_fp != expected_mcp_fp { // label and/or are attached to the per-project `triple-c-net-<id>` network.
log::info!("MCP servers fingerprint mismatch (container={:?}, expected={:?})", container_mcp_fp, expected_mcp_fp); // That user-defined network is deleted during cleanup, and a container
// whose NetworkMode points at a missing network refuses to start — so force
// a recreation to move them onto the default bridge. Containers created by
// the current code never carry the label or the network, so this is a no-op
// for them and can be dropped a release later.
if let Some(fp) = get_label("triple-c.mcp-fingerprint") {
if !fp.is_empty() {
log::info!("Legacy container carries triple-c.mcp-fingerprint label — recreating without MCP");
return Ok(true);
}
}
let legacy_network = info
.host_config
.as_ref()
.and_then(|hc| hc.network_mode.as_deref())
.map(|nm| nm.starts_with("triple-c-net-"))
.unwrap_or(false);
if legacy_network {
log::info!("Legacy container attached to a triple-c-net-* network — recreating without MCP");
return Ok(true); return Ok(true);
} }
@@ -1590,173 +1635,3 @@ pub async fn list_sibling_containers() -> Result<Vec<ContainerSummary>, String>
Ok(siblings) Ok(siblings)
} }
// ── MCP Container Lifecycle ─────────────────────────────────────────────
/// Returns true if any MCP server uses stdio transport with Docker.
pub fn any_stdio_docker_mcp(servers: &[McpServer]) -> bool {
servers.iter().any(|s| s.is_docker() && s.transport_type == McpTransportType::Stdio)
}
/// Find an existing MCP container by its expected name.
pub async fn find_mcp_container(server: &McpServer) -> Result<Option<String>, String> {
let docker = get_docker()?;
let container_name = server.mcp_container_name();
let filters: HashMap<String, Vec<String>> = HashMap::from([
("name".to_string(), vec![container_name.clone()]),
]);
let containers: Vec<ContainerSummary> = docker
.list_containers(Some(ListContainersOptions {
all: true,
filters,
..Default::default()
}))
.await
.map_err(|e| format!("Failed to list MCP containers: {}", e))?;
let expected = format!("/{}", container_name);
for c in &containers {
if let Some(names) = &c.names {
if names.iter().any(|n| n == &expected) {
return Ok(c.id.clone());
}
}
}
Ok(None)
}
/// Create a Docker container for an MCP server.
pub async fn create_mcp_container(
server: &McpServer,
network_name: &str,
) -> Result<String, String> {
let docker = get_docker()?;
let container_name = server.mcp_container_name();
let image = server
.docker_image
.as_ref()
.ok_or_else(|| format!("MCP server '{}' has no docker_image", server.name))?;
let mut env_vars: Vec<String> = Vec::new();
for (k, v) in &server.env {
env_vars.push(format!("{}={}", k, v));
}
// Build command + args as Cmd
let mut cmd: Vec<String> = Vec::new();
if let Some(ref command) = server.command {
cmd.push(command.clone());
}
cmd.extend(server.args.iter().cloned());
let mut labels = HashMap::new();
labels.insert("triple-c.managed".to_string(), "true".to_string());
labels.insert("triple-c.mcp-server".to_string(), server.id.clone());
let host_config = HostConfig {
network_mode: Some(network_name.to_string()),
..Default::default()
};
let config = Config {
image: Some(image.clone()),
env: if env_vars.is_empty() { None } else { Some(env_vars) },
cmd: if cmd.is_empty() { None } else { Some(cmd) },
labels: Some(labels),
host_config: Some(host_config),
..Default::default()
};
let options = CreateContainerOptions {
name: container_name.clone(),
..Default::default()
};
let response = docker
.create_container(Some(options), config)
.await
.map_err(|e| format!("Failed to create MCP container '{}': {}", container_name, e))?;
log::info!(
"Created MCP container {} (image: {}) on network {}",
container_name,
image,
network_name
);
Ok(response.id)
}
/// Start all Docker-based MCP server containers. Finds or creates each one.
pub async fn start_mcp_containers(
servers: &[McpServer],
network_name: &str,
) -> Result<(), String> {
for server in servers {
if !server.is_docker() {
continue;
}
let container_id = if let Some(existing_id) = find_mcp_container(server).await? {
log::debug!("Found existing MCP container for '{}'", server.name);
existing_id
} else {
create_mcp_container(server, network_name).await?
};
// Start the container (ignore already-started errors)
if let Err(e) = start_container(&container_id).await {
let err_str = e.to_string();
if err_str.contains("already started") || err_str.contains("304") {
log::debug!("MCP container '{}' already running", server.name);
} else {
return Err(format!(
"Failed to start MCP container '{}': {}",
server.name, e
));
}
}
log::info!("MCP container '{}' started", server.name);
}
Ok(())
}
/// Stop all Docker-based MCP server containers (best-effort).
pub async fn stop_mcp_containers(servers: &[McpServer]) -> Result<(), String> {
for server in servers {
if !server.is_docker() {
continue;
}
if let Ok(Some(container_id)) = find_mcp_container(server).await {
if let Err(e) = stop_container(&container_id).await {
log::warn!("Failed to stop MCP container '{}': {}", server.name, e);
} else {
log::info!("Stopped MCP container '{}'", server.name);
}
}
}
Ok(())
}
/// Stop and remove all Docker-based MCP server containers (best-effort).
pub async fn remove_mcp_containers(servers: &[McpServer]) -> Result<(), String> {
for server in servers {
if !server.is_docker() {
continue;
}
if let Ok(Some(container_id)) = find_mcp_container(server).await {
let _ = stop_container(&container_id).await;
if let Err(e) = remove_container(&container_id).await {
log::warn!("Failed to remove MCP container '{}': {}", server.name, e);
} else {
log::info!("Removed MCP container '{}'", server.name);
}
}
}
Ok(())
}
+105 -67
View File
@@ -1,13 +1,78 @@
use bollard::container::UploadToContainerOptions; use bollard::container::{LogOutput, UploadToContainerOptions};
use bollard::exec::{CreateExecOptions, ResizeExecOptions, StartExecResults}; use bollard::exec::{CreateExecOptions, ResizeExecOptions, StartExecResults};
use futures_util::StreamExt; use futures_util::{Stream, StreamExt};
use std::collections::HashMap; use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc; use std::sync::Arc;
use tokio::io::AsyncWriteExt; use tokio::io::{AsyncWrite, AsyncWriteExt};
use tokio::sync::{mpsc, Mutex}; use tokio::sync::{mpsc, Mutex};
use super::client::get_docker; use super::client::get_docker;
/// A `docker exec` that has been created and started with stdin/stdout/stderr
/// attached — the raw duplex halves, before any policy about what to do with
/// them.
///
/// This is the single place in the codebase that knows how to open an attached
/// exec. Both consumers are built on it:
/// * [`ExecSessionManager`] — interactive terminals and the audio bridge,
/// which pump bytes through mpsc channels and a callback.
/// * `auth_bridge` — per-connection `socat` tunnels, which pump bytes
/// straight between a host TCP socket and these halves.
///
/// With `tty = false` the output stream is demultiplexed by Docker, so the
/// consumer can tell [`LogOutput::StdOut`] from [`LogOutput::StdErr`]. That
/// distinction matters for the auth bridge: `socat`'s diagnostics must not be
/// spliced into the proxied byte stream.
pub struct AttachedExec {
pub exec_id: String,
pub output: Pin<Box<dyn Stream<Item = Result<LogOutput, bollard::errors::Error>> + Send>>,
pub input: Pin<Box<dyn AsyncWrite + Send>>,
}
/// Create and start an exec with stdin + stdout + stderr attached, returning the
/// raw duplex halves. Runs as `claude` in `/workspace`, like every other exec
/// this app opens.
pub async fn create_attached_exec(
container_id: &str,
cmd: Vec<String>,
tty: bool,
) -> Result<AttachedExec, String> {
let docker = get_docker()?;
let exec = docker
.create_exec(
container_id,
CreateExecOptions {
attach_stdin: Some(true),
attach_stdout: Some(true),
attach_stderr: Some(true),
tty: Some(tty),
cmd: Some(cmd),
user: Some("claude".to_string()),
working_dir: Some("/workspace".to_string()),
..Default::default()
},
)
.await
.map_err(|e| format!("Failed to create exec: {}", e))?;
let exec_id = exec.id.clone();
match docker
.start_exec(&exec_id, None)
.await
.map_err(|e| format!("Failed to start exec: {}", e))?
{
StartExecResults::Attached { output, input } => Ok(AttachedExec {
exec_id,
output,
input,
}),
StartExecResults::Detached => Err("Exec started in detached mode".to_string()),
}
}
pub struct ExecSession { pub struct ExecSession {
pub exec_id: String, pub exec_id: String,
pub container_id: String, pub container_id: String,
@@ -80,82 +145,55 @@ impl ExecSessionManager {
where where
F: Fn(Vec<u8>) + Send + 'static, F: Fn(Vec<u8>) + Send + 'static,
{ {
let docker = get_docker()?; let AttachedExec {
exec_id,
let exec = docker mut output,
.create_exec( mut input,
container_id, } = create_attached_exec(container_id, cmd, tty).await?;
CreateExecOptions {
attach_stdin: Some(true),
attach_stdout: Some(true),
attach_stderr: Some(true),
tty: Some(tty),
cmd: Some(cmd),
user: Some("claude".to_string()),
working_dir: Some("/workspace".to_string()),
..Default::default()
},
)
.await
.map_err(|e| format!("Failed to create exec: {}", e))?;
let exec_id = exec.id.clone();
let result = docker
.start_exec(&exec_id, None)
.await
.map_err(|e| format!("Failed to start exec: {}", e))?;
let (input_tx, mut input_rx) = mpsc::unbounded_channel::<Vec<u8>>(); let (input_tx, mut input_rx) = mpsc::unbounded_channel::<Vec<u8>>();
let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(1); let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(1);
match result { // Output reader task
StartExecResults::Attached { mut output, mut input } => { let session_id_clone = session_id.to_string();
// Output reader task let shutdown_tx_clone = shutdown_tx.clone();
let session_id_clone = session_id.to_string(); tokio::spawn(async move {
let shutdown_tx_clone = shutdown_tx.clone(); loop {
tokio::spawn(async move { tokio::select! {
loop { msg = output.next() => {
tokio::select! { match msg {
msg = output.next() => { Some(Ok(output)) => {
match msg { on_output(output.into_bytes().to_vec());
Some(Ok(output)) => {
on_output(output.into_bytes().to_vec());
}
Some(Err(e)) => {
log::error!("Exec output error for {}: {}", session_id_clone, e);
break;
}
None => {
log::info!("Exec output stream ended for {}", session_id_clone);
break;
}
}
} }
_ = shutdown_rx.recv() => { Some(Err(e)) => {
log::info!("Exec session {} shutting down", session_id_clone); log::error!("Exec output error for {}: {}", session_id_clone, e);
break;
}
None => {
log::info!("Exec output stream ended for {}", session_id_clone);
break; break;
} }
} }
} }
on_exit(); _ = shutdown_rx.recv() => {
let _ = shutdown_tx_clone; log::info!("Exec session {} shutting down", session_id_clone);
}); break;
// Input writer task
tokio::spawn(async move {
while let Some(data) = input_rx.recv().await {
if let Err(e) = input.write_all(&data).await {
log::error!("Failed to write to exec stdin: {}", e);
break;
}
} }
}); }
} }
StartExecResults::Detached => { on_exit();
return Err("Exec started in detached mode".to_string()); let _ = shutdown_tx_clone;
});
// Input writer task
tokio::spawn(async move {
while let Some(data) = input_rx.recv().await {
if let Err(e) = input.write_all(&data).await {
log::error!("Failed to write to exec stdin: {}", e);
break;
}
} }
} });
let session = ExecSession { let session = ExecSession {
exec_id, exec_id,
+137
View File
@@ -0,0 +1,137 @@
//! One-release migration shim for the removed built-in MCP feature.
//!
//! Older releases created a per-project user-defined bridge network
//! (`triple-c-net-<projectId>`) plus one container per Docker-backed MCP
//! server, and attached the project container to that network. Now that MCP
//! support is gone, those leftovers have to be torn down — a container whose
//! `NetworkMode` names a network that no longer exists refuses to start, so
//! the cleanup is paired with a forced container recreation (see
//! `container_needs_recreation`).
//!
//! Everything here is best-effort: failures are logged and never abort the
//! caller, and absent resources are a silent no-op. This module can be deleted
//! a release after all users have migrated.
use bollard::container::{ListContainersOptions, RemoveContainerOptions};
use bollard::network::InspectNetworkOptions;
use std::collections::HashMap;
use super::client::get_docker;
/// Network name used by the old MCP implementation for a project.
fn legacy_network_name(project_id: &str) -> String {
format!("triple-c-net-{}", project_id)
}
/// Force-remove every leftover MCP server container.
///
/// Matched by the `triple-c.mcp-server` label rather than by name, so
/// containers survive even if the MCP server definitions they came from are
/// already gone from storage. Best-effort: errors are logged and skipped.
pub async fn remove_legacy_mcp_containers(project_id: &str) {
let docker = match get_docker() {
Ok(d) => d,
Err(e) => {
log::debug!(
"Skipping legacy MCP container cleanup for project {}: {}",
project_id,
e
);
return;
}
};
let filters: HashMap<String, Vec<String>> = HashMap::from([(
"label".to_string(),
vec!["triple-c.mcp-server".to_string()],
)]);
let containers = match docker
.list_containers(Some(ListContainersOptions {
all: true,
filters,
..Default::default()
}))
.await
{
Ok(c) => c,
Err(e) => {
log::warn!("Failed to list legacy MCP containers: {}", e);
return;
}
};
for container in containers {
let Some(id) = container.id else { continue };
match docker
.remove_container(
&id,
Some(RemoveContainerOptions {
force: true,
..Default::default()
}),
)
.await
{
Ok(_) => log::info!("Removed legacy MCP container {}", id),
Err(e) => log::warn!("Failed to remove legacy MCP container {}: {}", id, e),
}
}
}
/// Remove the old per-project Docker network, disconnecting any remaining
/// members first (a network with attached endpoints cannot be deleted).
///
/// Silent no-op when the network does not exist. Best-effort: errors are
/// logged and never propagated.
pub async fn remove_legacy_project_network(project_id: &str) {
let docker = match get_docker() {
Ok(d) => d,
Err(e) => {
log::debug!(
"Skipping legacy network cleanup for project {}: {}",
project_id,
e
);
return;
}
};
let network_name = legacy_network_name(project_id);
// Inspect to discover connected containers; absence means nothing to do.
let info = match docker
.inspect_network(&network_name, None::<InspectNetworkOptions<String>>)
.await
{
Ok(info) => info,
Err(_) => {
log::debug!("Legacy network {} not present, nothing to do", network_name);
return;
}
};
if let Some(containers) = info.containers {
for container_id in containers.into_keys() {
let disconnect_opts = bollard::network::DisconnectNetworkOptions {
container: container_id.clone(),
force: true,
};
if let Err(e) = docker
.disconnect_network(&network_name, disconnect_opts)
.await
{
log::warn!(
"Failed to disconnect container {} from legacy network {}: {}",
container_id,
network_name,
e
);
}
}
}
match docker.remove_network(&network_name).await {
Ok(_) => log::info!("Removed legacy Docker network {}", network_name),
Err(e) => log::warn!("Failed to remove legacy network {}: {}", network_name, e),
}
}
+2 -2
View File
@@ -2,7 +2,7 @@ pub mod client;
pub mod container; pub mod container;
pub mod image; pub mod image;
pub mod exec; pub mod exec;
pub mod network; pub mod legacy_cleanup;
pub mod stt; pub mod stt;
#[allow(unused_imports)] #[allow(unused_imports)]
@@ -16,4 +16,4 @@ pub use image::*;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use exec::*; pub use exec::*;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use network::*; pub use legacy_cleanup::*;
-129
View File
@@ -1,129 +0,0 @@
use bollard::network::{CreateNetworkOptions, InspectNetworkOptions};
use std::collections::HashMap;
use super::client::get_docker;
/// Network name for a project's MCP containers.
fn project_network_name(project_id: &str) -> String {
format!("triple-c-net-{}", project_id)
}
/// Ensure a Docker bridge network exists for the project.
/// Returns the network name.
pub async fn ensure_project_network(project_id: &str) -> Result<String, String> {
let docker = get_docker()?;
let network_name = project_network_name(project_id);
// Check if network already exists
match docker
.inspect_network(&network_name, None::<InspectNetworkOptions<String>>)
.await
{
Ok(_) => {
log::debug!("Network {} already exists", network_name);
return Ok(network_name);
}
Err(_) => {
// Network doesn't exist, create it
}
}
let options = CreateNetworkOptions {
name: network_name.clone(),
driver: "bridge".to_string(),
labels: HashMap::from([
("triple-c.managed".to_string(), "true".to_string()),
("triple-c.project-id".to_string(), project_id.to_string()),
]),
..Default::default()
};
docker
.create_network(options)
.await
.map_err(|e| format!("Failed to create network {}: {}", network_name, e))?;
log::info!("Created Docker network {}", network_name);
Ok(network_name)
}
/// Connect a container to the project network.
#[allow(dead_code)]
pub async fn connect_container_to_network(
container_id: &str,
network_name: &str,
) -> Result<(), String> {
let docker = get_docker()?;
let config = bollard::network::ConnectNetworkOptions {
container: container_id.to_string(),
..Default::default()
};
docker
.connect_network(network_name, config)
.await
.map_err(|e| {
format!(
"Failed to connect container {} to network {}: {}",
container_id, network_name, e
)
})?;
log::debug!(
"Connected container {} to network {}",
container_id,
network_name
);
Ok(())
}
/// Remove the project network (best-effort). Disconnects all containers first.
pub async fn remove_project_network(project_id: &str) -> Result<(), String> {
let docker = get_docker()?;
let network_name = project_network_name(project_id);
// Inspect to get connected containers
let info = match docker
.inspect_network(&network_name, None::<InspectNetworkOptions<String>>)
.await
{
Ok(info) => info,
Err(_) => {
log::debug!(
"Network {} not found, nothing to remove",
network_name
);
return Ok(());
}
};
// Disconnect all containers
if let Some(containers) = info.containers {
for (container_id, _) in containers {
let disconnect_opts = bollard::network::DisconnectNetworkOptions {
container: container_id.clone(),
force: true,
};
if let Err(e) = docker
.disconnect_network(&network_name, disconnect_opts)
.await
{
log::warn!(
"Failed to disconnect container {} from network {}: {}",
container_id,
network_name,
e
);
}
}
}
// Remove the network
match docker.remove_network(&network_name).await {
Ok(_) => log::info!("Removed Docker network {}", network_name),
Err(e) => log::warn!("Failed to remove network {}: {}", network_name, e),
}
Ok(())
}
+29 -15
View File
@@ -1,3 +1,4 @@
mod auth_bridge;
mod commands; mod commands;
mod docker; mod docker;
mod install_helper; mod install_helper;
@@ -8,18 +9,18 @@ pub mod web_terminal;
use std::sync::Arc; use std::sync::Arc;
use auth_bridge::AuthBridgeManager;
use docker::exec::ExecSessionManager; use docker::exec::ExecSessionManager;
use storage::projects_store::ProjectsStore; use storage::projects_store::ProjectsStore;
use storage::settings_store::SettingsStore; use storage::settings_store::SettingsStore;
use storage::mcp_store::McpStore;
use tauri::Manager; use tauri::Manager;
use web_terminal::WebTerminalServer; use web_terminal::WebTerminalServer;
pub struct AppState { pub struct AppState {
pub projects_store: Arc<ProjectsStore>, pub projects_store: Arc<ProjectsStore>,
pub settings_store: Arc<SettingsStore>, pub settings_store: Arc<SettingsStore>,
pub mcp_store: Arc<McpStore>,
pub exec_manager: Arc<ExecSessionManager>, pub exec_manager: Arc<ExecSessionManager>,
pub auth_bridge: Arc<AuthBridgeManager>,
pub web_terminal_server: Arc<tokio::sync::Mutex<Option<WebTerminalServer>>>, pub web_terminal_server: Arc<tokio::sync::Mutex<Option<WebTerminalServer>>>,
} }
@@ -40,14 +41,8 @@ pub fn run() {
panic!("Failed to initialize settings store: {}", e); panic!("Failed to initialize settings store: {}", e);
} }
}); });
let mcp_store = Arc::new(match McpStore::new() {
Ok(s) => s,
Err(e) => {
log::error!("Failed to initialize MCP store: {}", e);
panic!("Failed to initialize MCP store: {}", e);
}
});
let exec_manager = Arc::new(ExecSessionManager::new()); let exec_manager = Arc::new(ExecSessionManager::new());
let auth_bridge = Arc::new(AuthBridgeManager::new());
// Clone Arcs for the setup closure (web terminal auto-start) // Clone Arcs for the setup closure (web terminal auto-start)
let projects_store_setup = projects_store.clone(); let projects_store_setup = projects_store.clone();
@@ -61,8 +56,8 @@ pub fn run() {
.manage(AppState { .manage(AppState {
projects_store, projects_store,
settings_store, settings_store,
mcp_store,
exec_manager, exec_manager,
auth_bridge,
web_terminal_server: Arc::new(tokio::sync::Mutex::new(None)), web_terminal_server: Arc::new(tokio::sync::Mutex::new(None)),
}) })
.setup(move |app| { .setup(move |app| {
@@ -146,6 +141,8 @@ pub fn run() {
let _ = docker::stt::stop_stt_container().await; let _ = docker::stt::stop_stt_container().await;
// Close all exec sessions // Close all exec sessions
state.exec_manager.close_all_sessions().await; state.exec_manager.close_all_sessions().await;
// Release every host loopback port held by the auth bridge
state.auth_bridge.stop_all().await;
}); });
} }
}) })
@@ -165,6 +162,15 @@ pub fn run() {
commands::project_commands::stop_project_container, commands::project_commands::stop_project_container,
commands::project_commands::rebuild_project_container, commands::project_commands::rebuild_project_container,
commands::project_commands::reconcile_project_statuses, commands::project_commands::reconcile_project_statuses,
// Auth bridge
commands::auth_bridge_commands::set_auth_bridge_enabled,
commands::auth_bridge_commands::get_auth_bridge_status,
// Shared Claude Code auth token
commands::auth_token_commands::acquire_claude_token,
commands::auth_token_commands::submit_claude_token_code,
commands::auth_token_commands::cancel_claude_token,
commands::auth_token_commands::has_claude_token,
commands::auth_token_commands::clear_claude_token,
// Settings // Settings
commands::settings_commands::get_settings, commands::settings_commands::get_settings,
commands::settings_commands::update_settings, commands::settings_commands::update_settings,
@@ -187,11 +193,6 @@ pub fn run() {
commands::file_commands::download_container_file, commands::file_commands::download_container_file,
commands::file_commands::download_container_backup, commands::file_commands::download_container_backup,
commands::file_commands::upload_file_to_container, commands::file_commands::upload_file_to_container,
// MCP
commands::mcp_commands::list_mcp_servers,
commands::mcp_commands::add_mcp_server,
commands::mcp_commands::update_mcp_server,
commands::mcp_commands::remove_mcp_server,
// AWS // AWS
commands::aws_commands::aws_sso_refresh, commands::aws_commands::aws_sso_refresh,
// Updates // Updates
@@ -215,6 +216,19 @@ pub fn run() {
commands::stt_commands::build_stt_image, commands::stt_commands::build_stt_image,
commands::stt_commands::pull_stt_image, commands::stt_commands::pull_stt_image,
commands::stt_commands::transcribe_audio, commands::stt_commands::transcribe_audio,
// Container introspection (sessions / capabilities / scheduler)
commands::inspect_commands::list_claude_sessions,
commands::inspect_commands::resume_session_command,
commands::inspect_commands::list_container_capabilities,
commands::inspect_commands::list_scheduled_tasks,
commands::inspect_commands::add_scheduled_task,
commands::inspect_commands::update_scheduled_task,
commands::inspect_commands::get_scheduled_task_log,
commands::inspect_commands::set_scheduled_task_enabled,
commands::inspect_commands::run_scheduled_task_now,
commands::inspect_commands::remove_scheduled_task,
commands::inspect_commands::get_scheduler_notifications,
commands::inspect_commands::clear_scheduler_notifications,
]) ])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
-70
View File
@@ -1,70 +0,0 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum McpTransportType {
Stdio,
#[serde(alias = "sse")]
Http,
}
impl Default for McpTransportType {
fn default() -> Self {
Self::Stdio
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServer {
pub id: String,
pub name: String,
#[serde(default)]
pub transport_type: McpTransportType,
pub command: Option<String>,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub env: HashMap<String, String>,
pub url: Option<String>,
#[serde(default)]
pub headers: HashMap<String, String>,
#[serde(default)]
pub docker_image: Option<String>,
#[serde(default)]
pub container_port: Option<u16>,
pub created_at: String,
pub updated_at: String,
}
impl McpServer {
pub fn new(name: String) -> Self {
let now = chrono::Utc::now().to_rfc3339();
Self {
id: uuid::Uuid::new_v4().to_string(),
name,
transport_type: McpTransportType::default(),
command: None,
args: Vec::new(),
env: HashMap::new(),
url: None,
headers: HashMap::new(),
docker_image: None,
container_port: None,
created_at: now.clone(),
updated_at: now,
}
}
pub fn is_docker(&self) -> bool {
self.docker_image.is_some()
}
pub fn mcp_container_name(&self) -> String {
format!("triple-c-mcp-{}", self.id)
}
pub fn effective_container_port(&self) -> u16 {
self.container_port.unwrap_or(3000)
}
}
-2
View File
@@ -2,10 +2,8 @@ pub mod project;
pub mod container_config; pub mod container_config;
pub mod app_settings; pub mod app_settings;
pub mod update_info; pub mod update_info;
pub mod mcp_server;
pub use project::*; pub use project::*;
pub use container_config::*; pub use container_config::*;
pub use app_settings::*; pub use app_settings::*;
pub use update_info::*; pub use update_info::*;
pub use mcp_server::*;
+91 -3
View File
@@ -30,6 +30,58 @@ fn default_full_permissions() -> bool {
true true
} }
/// `use_shared_auth_token` defaults to **on**: once the user has run
/// `claude setup-token` once, every existing Anthropic-backend project should
/// pick the token up without being edited one by one. Projects deliberately
/// pinned to their own `claude login` identity opt out.
fn default_use_shared_auth_token() -> bool {
true
}
/// How much autonomy Claude Code is granted inside the container.
///
/// Maps onto Claude Code CLI flags — see [`PermissionMode::cli_args`], which is
/// the single definition of that mapping and must be used by every call site.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "camelCase")]
pub enum PermissionMode {
/// Read-only planning mode.
Plan,
/// Claude Code's own default behavior (prompts for permission).
#[default]
Default,
/// Auto-accept file edits, prompt for everything else.
AcceptEdits,
/// Skip all permission prompts.
Bypass,
}
impl PermissionMode {
/// The CLI flags this mode adds to a `claude` invocation.
/// Defined once here so every call site stays in sync.
pub fn cli_args(&self) -> Vec<String> {
match self {
PermissionMode::Plan => vec!["--permission-mode".to_string(), "plan".to_string()],
PermissionMode::Default => Vec::new(),
PermissionMode::AcceptEdits => {
vec!["--permission-mode".to_string(), "acceptEdits".to_string()]
}
PermissionMode::Bypass => vec!["--dangerously-skip-permissions".to_string()],
}
}
/// The wire value used for the `TRIPLE_C_PERMISSION_MODE` container env var.
/// Matches the serde `camelCase` representation.
pub fn as_env_value(&self) -> &'static str {
match self {
PermissionMode::Plan => "plan",
PermissionMode::Default => "default",
PermissionMode::AcceptEdits => "acceptEdits",
PermissionMode::Bypass => "bypass",
}
}
}
/// Settings for Claude Code CLI behavior inside the container. /// Settings for Claude Code CLI behavior inside the container.
/// These map to Claude Code env vars and ~/.claude/settings.json entries. /// These map to Claude Code env vars and ~/.claude/settings.json entries.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
@@ -78,8 +130,33 @@ pub struct Project {
pub sandbox_mode_enabled: bool, pub sandbox_mode_enabled: bool,
#[serde(default)] #[serde(default)]
pub mission_control_enabled: bool, pub mission_control_enabled: bool,
/// Opt in to the auth bridge: while the container runs, its loopback
/// listeners are mirrored onto the host's loopback so browser OAuth
/// callbacks (`claude login`, `fly login`, `aws sso login`) can reach them.
/// Purely host-side — it deliberately has no container-recreation label,
/// because toggling it changes nothing about the container itself.
#[serde(default)]
pub auth_bridge_enabled: bool,
/// Use the shared, long-lived Claude Code OAuth token (from
/// `claude setup-token`, held in the OS keychain) for this project instead
/// of requiring its own `claude login`. Only consulted when `backend` is
/// [`Backend::Anthropic`] and a token has actually been stored.
///
/// Defaults to **true** so a single `setup-token` run covers every project;
/// turn it off to pin a project to the identity it logged in with inside
/// its own container.
#[serde(default = "default_use_shared_auth_token")]
pub use_shared_auth_token: bool,
/// Legacy binary permission flag. Superseded by `permission_mode`, but kept
/// because it is the value already stored in users' `projects.json`; it is
/// the fallback in `effective_permission_mode()` so old projects keep
/// behaving identically without a data migration.
#[serde(default = "default_full_permissions")] #[serde(default = "default_full_permissions")]
pub full_permissions: bool, pub full_permissions: bool,
/// Per-project permission mode. `None` means "not set yet" → fall back to
/// the legacy `full_permissions` flag.
#[serde(default)]
pub permission_mode: Option<PermissionMode>,
pub ssh_key_path: Option<String>, pub ssh_key_path: Option<String>,
#[serde(skip_serializing, default)] #[serde(skip_serializing, default)]
pub git_token: Option<String>, pub git_token: Option<String>,
@@ -92,8 +169,6 @@ pub struct Project {
#[serde(default)] #[serde(default)]
pub claude_instructions: Option<String>, pub claude_instructions: Option<String>,
#[serde(default)] #[serde(default)]
pub enabled_mcp_servers: Vec<String>,
#[serde(default)]
pub claude_code_settings: Option<ClaudeCodeSettings>, pub claude_code_settings: Option<ClaudeCodeSettings>,
/// User-defined display names for terminal tabs, keyed by session id. /// User-defined display names for terminal tabs, keyed by session id.
#[serde(default)] #[serde(default)]
@@ -212,7 +287,10 @@ impl Project {
allow_docker_access: false, allow_docker_access: false,
sandbox_mode_enabled: false, sandbox_mode_enabled: false,
mission_control_enabled: false, mission_control_enabled: false,
auth_bridge_enabled: false,
use_shared_auth_token: default_use_shared_auth_token(),
full_permissions: false, full_permissions: false,
permission_mode: None,
ssh_key_path: None, ssh_key_path: None,
git_token: None, git_token: None,
git_user_name: None, git_user_name: None,
@@ -220,7 +298,6 @@ impl Project {
custom_env_vars: Vec::new(), custom_env_vars: Vec::new(),
port_mappings: Vec::new(), port_mappings: Vec::new(),
claude_instructions: None, claude_instructions: None,
enabled_mcp_servers: Vec::new(),
claude_code_settings: None, claude_code_settings: None,
renamed_session_names: HashMap::new(), renamed_session_names: HashMap::new(),
created_at: now.clone(), created_at: now.clone(),
@@ -228,6 +305,17 @@ impl Project {
} }
} }
/// The permission mode to actually use for this project.
/// Falls back to the legacy `full_permissions` boolean when the newer
/// `permission_mode` field has never been set.
pub fn effective_permission_mode(&self) -> PermissionMode {
self.permission_mode.unwrap_or(if self.full_permissions {
PermissionMode::Bypass
} else {
PermissionMode::Default
})
}
pub fn container_name(&self) -> String { pub fn container_name(&self) -> String {
format!("triple-c-{}", self.id) format!("triple-c-{}", self.id)
} }
-106
View File
@@ -1,106 +0,0 @@
use std::fs;
use std::path::PathBuf;
use std::sync::Mutex;
use crate::models::McpServer;
pub struct McpStore {
servers: Mutex<Vec<McpServer>>,
file_path: PathBuf,
}
impl McpStore {
pub fn new() -> Result<Self, String> {
let data_dir = dirs::data_dir()
.ok_or_else(|| "Could not determine data directory. Set XDG_DATA_HOME on Linux.".to_string())?
.join("triple-c");
fs::create_dir_all(&data_dir).ok();
let file_path = data_dir.join("mcp_servers.json");
let servers = if file_path.exists() {
match fs::read_to_string(&file_path) {
Ok(data) => {
match serde_json::from_str::<Vec<McpServer>>(&data) {
Ok(parsed) => parsed,
Err(e) => {
log::error!("Failed to parse mcp_servers.json: {}. Starting with empty list.", e);
let backup = file_path.with_extension("json.bak");
if let Err(be) = fs::copy(&file_path, &backup) {
log::error!("Failed to back up corrupted mcp_servers.json: {}", be);
}
Vec::new()
}
}
}
Err(e) => {
log::error!("Failed to read mcp_servers.json: {}", e);
Vec::new()
}
}
} else {
Vec::new()
};
Ok(Self {
servers: Mutex::new(servers),
file_path,
})
}
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<McpServer>> {
self.servers.lock().unwrap_or_else(|e| e.into_inner())
}
fn save(&self, servers: &[McpServer]) -> Result<(), String> {
let data = serde_json::to_string_pretty(servers)
.map_err(|e| format!("Failed to serialize MCP servers: {}", e))?;
// Atomic write: write to temp file, then rename
let tmp_path = self.file_path.with_extension("json.tmp");
fs::write(&tmp_path, data)
.map_err(|e| format!("Failed to write temp MCP servers file: {}", e))?;
fs::rename(&tmp_path, &self.file_path)
.map_err(|e| format!("Failed to rename MCP servers file: {}", e))?;
Ok(())
}
pub fn list(&self) -> Vec<McpServer> {
self.lock().clone()
}
pub fn get(&self, id: &str) -> Option<McpServer> {
self.lock().iter().find(|s| s.id == id).cloned()
}
pub fn add(&self, server: McpServer) -> Result<McpServer, String> {
let mut servers = self.lock();
let cloned = server.clone();
servers.push(server);
self.save(&servers)?;
Ok(cloned)
}
pub fn update(&self, updated: McpServer) -> Result<McpServer, String> {
let mut servers = self.lock();
if let Some(s) = servers.iter_mut().find(|s| s.id == updated.id) {
*s = updated.clone();
self.save(&servers)?;
Ok(updated)
} else {
Err(format!("MCP server {} not found", updated.id))
}
}
pub fn remove(&self, id: &str) -> Result<(), String> {
let mut servers = self.lock();
let initial_len = servers.len();
servers.retain(|s| s.id != id);
if servers.len() == initial_len {
return Err(format!("MCP server {} not found", id));
}
self.save(&servers)?;
Ok(())
}
}
-3
View File
@@ -1,7 +1,6 @@
pub mod projects_store; pub mod projects_store;
pub mod secure; pub mod secure;
pub mod settings_store; pub mod settings_store;
pub mod mcp_store;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use projects_store::*; pub use projects_store::*;
@@ -9,5 +8,3 @@ pub use projects_store::*;
pub use secure::*; pub use secure::*;
#[allow(unused_imports)] #[allow(unused_imports)]
pub use settings_store::*; pub use settings_store::*;
#[allow(unused_imports)]
pub use mcp_store::*;
@@ -177,6 +177,20 @@ impl ProjectsStore {
} }
} }
/// Granular setter for the auth bridge opt-in, so toggling it can't clobber
/// concurrent edits to the rest of the project record.
pub fn set_auth_bridge_enabled(&self, project_id: &str, enabled: bool) -> Result<(), String> {
let mut projects = self.lock();
if let Some(p) = projects.iter_mut().find(|p| p.id == project_id) {
p.auth_bridge_enabled = enabled;
p.updated_at = chrono::Utc::now().to_rfc3339();
self.save(&projects)?;
Ok(())
} else {
Err(format!("Project {} not found", project_id))
}
}
pub fn set_container_id(&self, project_id: &str, container_id: Option<String>) -> Result<(), String> { pub fn set_container_id(&self, project_id: &str, container_id: Option<String>) -> Result<(), String> {
let mut projects = self.lock(); let mut projects = self.lock();
if let Some(p) = projects.iter_mut().find(|p| p.id == project_id) { if let Some(p) = projects.iter_mut().find(|p| p.id == project_id) {
+113
View File
@@ -1,3 +1,31 @@
//! OS keychain access, via the `keyring` crate.
//!
//! Two kinds of secret live here:
//! * **per-project** secrets (git token, AWS keys, …), keyed by project id;
//! * the **shared Claude Code OAuth token**, which is global — one
//! `claude setup-token` run authenticates every Anthropic-backend project.
//!
//! Nothing in this module ever logs a secret or folds one into an error string.
/// Keychain service for the single, global Claude Code OAuth token minted by
/// `claude setup-token` and consumed via `CLAUDE_CODE_OAUTH_TOKEN`.
const CLAUDE_TOKEN_SERVICE: &str = "triple-c-claude-oauth-token";
/// Keychain service for the token's **rotation id** — a fresh random value
/// written every time the token is stored.
///
/// Container recreation is driven off Docker labels, which anything on the host
/// can read with `docker inspect`. The token itself must obviously not go in a
/// label, and neither should a bare hash of it: a hash is a verification oracle
/// (holding a candidate token, you could confirm it). This id is not derived
/// from the token at all — it is unrelated random data that merely *changes*
/// whenever the token does, which is exactly (and only) what change detection
/// needs.
const CLAUDE_TOKEN_VERSION_SERVICE: &str = "triple-c-claude-oauth-token-version";
/// Fixed account name used for every triple-c keychain entry.
const KEYCHAIN_ACCOUNT: &str = "secret";
/// Store a per-project secret in the OS keychain. /// Store a per-project secret in the OS keychain.
pub fn store_project_secret(project_id: &str, key_name: &str, value: &str) -> Result<(), String> { pub fn store_project_secret(project_id: &str, key_name: &str, value: &str) -> Result<(), String> {
let service = format!("triple-c-project-{}-{}", project_id, key_name); let service = format!("triple-c-project-{}-{}", project_id, key_name);
@@ -43,3 +71,88 @@ pub fn delete_project_secrets(project_id: &str) -> Result<(), String> {
} }
Ok(()) Ok(())
} }
// ─────────────────────────────────────────────────────────────────────────────
// Shared Claude Code OAuth token (global, not per project)
// ─────────────────────────────────────────────────────────────────────────────
/// Read a single-value keychain entry. `Ok(None)` when the entry is absent.
/// The error text names the entry, never its value.
fn read_entry(service: &str, label: &str) -> Result<Option<String>, String> {
let entry = keyring::Entry::new(service, KEYCHAIN_ACCOUNT)
.map_err(|e| format!("Keyring error: {}", e))?;
match entry.get_password() {
Ok(value) => Ok(Some(value)),
Err(keyring::Error::NoEntry) => Ok(None),
Err(e) => Err(format!("Failed to retrieve {}: {}", label, e)),
}
}
/// Delete a keychain entry, treating "wasn't there" as success.
fn delete_entry(service: &str, label: &str) -> Result<(), String> {
let entry = keyring::Entry::new(service, KEYCHAIN_ACCOUNT)
.map_err(|e| format!("Keyring error: {}", e))?;
match entry.delete_credential() {
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
Err(e) => Err(format!("Failed to delete {}: {}", label, e)),
}
}
/// Store the shared Claude Code OAuth token, replacing any previous one, and
/// mint a fresh rotation id so containers holding the old token are flagged for
/// recreation. Blank input is rejected rather than silently stored.
pub fn store_claude_oauth_token(token: &str) -> Result<(), String> {
if token.trim().is_empty() {
return Err("Refusing to store an empty Claude authentication token.".to_string());
}
let entry = keyring::Entry::new(CLAUDE_TOKEN_SERVICE, KEYCHAIN_ACCOUNT)
.map_err(|e| format!("Keyring error: {}", e))?;
entry
.set_password(token)
.map_err(|e| format!("Failed to store the Claude authentication token: {}", e))?;
// Rotation id second: if this fails the token is still usable, and the
// stale id only costs one extra container recreation later.
let version = uuid::Uuid::new_v4().to_string();
let version_entry = keyring::Entry::new(CLAUDE_TOKEN_VERSION_SERVICE, KEYCHAIN_ACCOUNT)
.map_err(|e| format!("Keyring error: {}", e))?;
version_entry
.set_password(&version)
.map_err(|e| format!("Failed to store the Claude token rotation id: {}", e))?;
Ok(())
}
/// Retrieve the shared Claude Code OAuth token, if one has been stored.
pub fn get_claude_oauth_token() -> Result<Option<String>, String> {
read_entry(CLAUDE_TOKEN_SERVICE, "the Claude authentication token")
}
/// The rotation id of the currently stored token. Opaque random data — safe to
/// put in a Docker label, unlike the token or any hash of it.
pub fn get_claude_oauth_token_version() -> Result<Option<String>, String> {
read_entry(
CLAUDE_TOKEN_VERSION_SERVICE,
"the Claude token rotation id",
)
}
/// Whether a shared Claude Code OAuth token is currently stored. A keychain
/// failure is reported as "no token" rather than surfacing as an error, so the
/// UI degrades to the un-authenticated state instead of breaking.
pub fn has_claude_oauth_token() -> bool {
matches!(get_claude_oauth_token(), Ok(Some(t)) if !t.trim().is_empty())
}
/// Delete the shared Claude Code OAuth token and its rotation id. Both are
/// attempted even if the first fails, so a partial failure cannot strand the
/// token behind a deleted id.
pub fn delete_claude_oauth_token() -> Result<(), String> {
let token_result = delete_entry(CLAUDE_TOKEN_SERVICE, "the Claude authentication token");
let version_result = delete_entry(
CLAUDE_TOKEN_VERSION_SERVICE,
"the Claude token rotation id",
);
token_result.and(version_result)
}
+10 -8
View File
@@ -205,11 +205,11 @@ fn build_terminal_cmd(project: &Project, settings_store: &crate::storage::settin
.map(|b| b.auth_method == BedrockAuthMethod::Profile) .map(|b| b.auth_method == BedrockAuthMethod::Profile)
.unwrap_or(false); .unwrap_or(false);
let permission_args = project.effective_permission_mode().cli_args();
if !is_bedrock_profile { if !is_bedrock_profile {
let mut cmd = vec!["claude".to_string()]; let mut cmd = vec!["claude".to_string()];
if project.full_permissions { cmd.extend(permission_args);
cmd.push("--dangerously-skip-permissions".to_string());
}
return cmd; return cmd;
} }
@@ -218,11 +218,13 @@ fn build_terminal_cmd(project: &Project, settings_store: &crate::storage::settin
settings_store.get().global_aws.aws_profile.as_deref(), settings_store.get().global_aws.aws_profile.as_deref(),
); );
let claude_cmd = if project.full_permissions { // The args are interpolated into a shell script string below, so
"exec claude --dangerously-skip-permissions" // single-quote each one.
} else { let permission_flags: String = permission_args
"exec claude" .iter()
}; .map(|a| format!(" '{}'", a.replace('\'', "'\\''")))
.collect();
let claude_cmd = format!("exec claude{}", permission_flags);
let script = format!( let script = format!(
r#" r#"
+123 -20
View File
@@ -5,25 +5,38 @@ import TopBar from "./components/layout/TopBar";
import StatusBar from "./components/layout/StatusBar"; import StatusBar from "./components/layout/StatusBar";
import TerminalView from "./components/terminal/TerminalView"; import TerminalView from "./components/terminal/TerminalView";
import DockerInstallDialog from "./components/DockerInstallDialog"; import DockerInstallDialog from "./components/DockerInstallDialog";
import ProjectHome from "./components/projects/home/ProjectHome";
import AddProjectDialog from "./components/projects/AddProjectDialog";
import ToastHost from "./components/ui/ToastHost";
import StatusIndicator from "./components/ui/StatusIndicator";
import Button from "./components/ui/Button";
import { useDocker } from "./hooks/useDocker"; import { useDocker } from "./hooks/useDocker";
import { useSettings } from "./hooks/useSettings"; import { useSettings } from "./hooks/useSettings";
import { useProjects } from "./hooks/useProjects"; import { useProjects } from "./hooks/useProjects";
import { useMcpServers } from "./hooks/useMcpServers";
import { useUpdates } from "./hooks/useUpdates"; import { useUpdates } from "./hooks/useUpdates";
import { useTerminal } from "./hooks/useTerminal"; import { useTerminal } from "./hooks/useTerminal";
import { useSTT } from "./hooks/useSTT"; import { useSTT } from "./hooks/useSTT";
import { useAppState } from "./store/appState"; import { useContainerProgress } from "./hooks/useContainerProgress";
import { useKeyboardShortcuts } from "./hooks/useKeyboardShortcuts";
import { useAppState, isHomeTab, tabKeyId, homeTabKey } from "./store/appState";
import { reconcileProjectStatuses } from "./lib/tauri-commands"; import { reconcileProjectStatuses } from "./lib/tauri-commands";
export default function App() { export default function App() {
const { checkDocker, checkImage, startDockerPolling } = useDocker(); const { checkDocker, checkImage, startDockerPolling } = useDocker();
const { loadSettings } = useSettings(); const { loadSettings } = useSettings();
const { refresh } = useProjects(); const { refresh } = useProjects();
const { refresh: refreshMcp } = useMcpServers();
const { loadVersion, checkForUpdates, checkImageUpdate, startPeriodicCheck } = useUpdates(); const { loadVersion, checkForUpdates, checkImageUpdate, startPeriodicCheck } = useUpdates();
const { sessions, activeSessionId, setProjects, setSttToggle } = useAppState( const { sessions, activeSessionId, tabOrder, activeTabKey, setProjects, setSttToggle } =
useShallow(s => ({ sessions: s.sessions, activeSessionId: s.activeSessionId, setProjects: s.setProjects, setSttToggle: s.setSttToggle })) useAppState(
); useShallow(s => ({
sessions: s.sessions,
activeSessionId: s.activeSessionId,
tabOrder: s.tabOrder,
activeTabKey: s.activeTabKey,
setProjects: s.setProjects,
setSttToggle: s.setSttToggle,
}))
);
const [showInstallDialog, setShowInstallDialog] = useState(false); const [showInstallDialog, setShowInstallDialog] = useState(false);
// Single STT instance bound to the active session. The mic lives in the // Single STT instance bound to the active session. The mic lives in the
@@ -35,6 +48,9 @@ export default function App() {
setSttToggle(stt.toggle); setSttToggle(stt.toggle);
}, [stt.toggle, setSttToggle]); }, [stt.toggle, setSttToggle]);
useContainerProgress();
useKeyboardShortcuts();
// Initialize on mount // Initialize on mount
useEffect(() => { useEffect(() => {
loadSettings(); loadSettings();
@@ -56,7 +72,6 @@ export default function App() {
} }
}); });
refresh(); refresh();
refreshMcp();
// Update detection // Update detection
loadVersion(); loadVersion();
@@ -72,16 +87,25 @@ export default function App() {
}; };
}, []); // eslint-disable-line react-hooks/exhaustive-deps }, []); // eslint-disable-line react-hooks/exhaustive-deps
const homeProjectIds = tabOrder.filter(isHomeTab).map(tabKeyId);
return ( return (
<div className="flex flex-col h-screen p-6 gap-4 bg-[var(--bg-primary)]"> <div className="flex flex-col h-screen p-3 gap-3 bg-[var(--bg-primary)]">
<TopBar /> <TopBar />
<div className="flex flex-1 min-h-0 gap-4"> <div className="flex flex-1 min-h-0 gap-3">
<Sidebar /> <Sidebar />
<main className="flex-1 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg min-w-0 overflow-hidden"> <main className="flex-1 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-panel)] min-w-0 overflow-hidden">
{sessions.length === 0 ? ( {tabOrder.length === 0 ? (
<WelcomeScreen /> <WelcomeScreen />
) : ( ) : (
<div className="w-full h-full"> <div className="w-full h-full">
{homeProjectIds.map((projectId) => (
<ProjectHome
key={projectId}
projectId={projectId}
active={activeTabKey === homeTabKey(projectId)}
/>
))}
{sessions.map((session) => ( {sessions.map((session) => (
<TerminalView <TerminalView
key={session.id} key={session.id}
@@ -94,6 +118,7 @@ export default function App() {
</main> </main>
</div> </div>
<StatusBar stt={stt} /> <StatusBar stt={stt} />
<ToastHost />
{showInstallDialog && ( {showInstallDialog && (
<DockerInstallDialog onClose={() => setShowInstallDialog(false)} /> <DockerInstallDialog onClose={() => setShowInstallDialog(false)} />
)} )}
@@ -101,18 +126,96 @@ export default function App() {
); );
} }
/**
* First run is a checklist, not a paragraph: it reuses state the app already
* tracks and ends in a real button.
*/
function WelcomeScreen() { function WelcomeScreen() {
const { dockerAvailable, imageExists, projects, openProjectHome } = useAppState(
useShallow((s) => ({
dockerAvailable: s.dockerAvailable,
imageExists: s.imageExists,
projects: s.projects,
openProjectHome: s.openProjectHome,
})),
);
const [showAdd, setShowAdd] = useState(false);
const steps: {
label: string;
state: boolean | null;
pendingLabel: string;
failLabel: string;
}[] = [
{
label: "Docker detected",
state: dockerAvailable,
pendingLabel: "Checking for Docker…",
failLabel: "Docker not available",
},
{
label: "Container image ready",
state: imageExists,
pendingLabel: "Checking for the image…",
failLabel: "Image not pulled yet — see Settings Container",
},
{
label: `${projects.length} project${projects.length === 1 ? "" : "s"} configured`,
state: projects.length > 0 ? true : false,
pendingLabel: "",
failLabel: "No projects yet",
},
];
return ( return (
<div className="flex items-center justify-center h-full text-[var(--text-secondary)]"> <div className="flex items-center justify-center h-full p-6">
<div className="text-center"> <div className="w-full max-w-md">
<h1 className="text-3xl font-bold mb-2 text-[var(--text-primary)]"> <h1 className="text-xl font-semibold text-[var(--text-primary)]">Triple-C</h1>
Triple-C <p className="text-[13px] text-[var(--text-secondary)] mb-5">
</h1> Claude Code, sandboxed in a container.
<p className="text-sm mb-4">Claude Code Container</p>
<p className="text-xs max-w-md">
Add a project from the sidebar, start its container, then open a
terminal to begin using Claude Code in a sandboxed environment.
</p> </p>
<ol className="space-y-2 mb-5">
{steps.map((step) => (
<li
key={step.label}
className="flex items-center gap-2 px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)]"
>
<StatusIndicator
tone={step.state === true ? "ok" : step.state === false ? "error" : "unknown"}
label={
step.state === true
? step.label
: step.state === false
? step.failLabel
: step.pendingLabel
}
className="text-[13px]"
/>
</li>
))}
</ol>
<div className="flex items-center gap-2">
<Button size="md" variant="primary" onClick={() => setShowAdd(true)}>
{projects.length === 0 ? "Add your first project" : "Add a project"}
</Button>
{projects.length > 0 && (
<Button size="md" onClick={() => openProjectHome(projects[0].id)}>
Open {projects[0].name}
</Button>
)}
</div>
<p className="mt-4 text-xs text-[var(--text-secondary)]">
Then start its container and press{" "}
<kbd className="px-1 py-0.5 font-mono bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded-[4px]">
Ctrl+T
</kbd>{" "}
to open a Claude terminal.
</p>
{showAdd && <AddProjectDialog onClose={() => setShowAdd(false)} />}
</div> </div>
</div> </div>
); );
+108 -142
View File
@@ -1,7 +1,9 @@
import { useCallback, useEffect, useRef, useState } from "react"; import { useEffect, useState } from "react";
import { openUrl } from "@tauri-apps/plugin-opener"; import { openUrl } from "@tauri-apps/plugin-opener";
import { useInstallHelper } from "../hooks/useInstallHelper"; import { useInstallHelper } from "../hooks/useInstallHelper";
import { useDocker } from "../hooks/useDocker"; import { useDocker } from "../hooks/useDocker";
import Modal from "./ui/Modal";
import Button from "./ui/Button";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
@@ -16,27 +18,11 @@ export default function DockerInstallDialog({ onClose }: Props) {
const [phase, setPhase] = useState<Phase>("idle"); const [phase, setPhase] = useState<Phase>("idle");
const [log, setLog] = useState<string[]>([]); const [log, setLog] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const overlayRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {
loadOptions(); loadOptions();
}, [loadOptions]); }, [loadOptions]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape" && phase !== "installing") onClose();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [onClose, phase]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current && phase !== "installing") onClose();
},
[onClose, phase],
);
const handleInstall = async () => { const handleInstall = async () => {
setPhase("installing"); setPhase("installing");
setLog([]); setLog([]);
@@ -70,142 +56,122 @@ export default function DockerInstallDialog({ onClose }: Props) {
return null; return null;
} }
const installVerb = phase === "installing" ? "Installing…" : `Install ${options.product_name}`; const installVerb =
phase === "installing" ? "Installing…" : `Install ${options.product_name}`;
return ( return (
<div <Modal
ref={overlayRef} title="Docker not detected"
onClick={handleOverlayClick} onClose={onClose}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" widthClassName="w-[34rem]"
// Closing mid-install would orphan a privileged installer.
dismissible={phase !== "installing"}
footer={
phase === "idle" ? (
<Button variant="ghost" onClick={onClose}>
Dismiss
</Button>
) : undefined
}
> >
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[32rem] max-h-[85vh] overflow-y-auto shadow-xl"> <p className="text-[13px] text-[var(--text-secondary)] mb-4">
<h2 className="text-lg font-semibold mb-1">Docker not detected</h2> Triple-C needs a Docker-compatible runtime to manage sandboxed project
<p className="text-sm text-[var(--text-secondary)] mb-4"> containers. We can install{" "}
Triple-C needs a Docker-compatible runtime to manage sandboxed project containers. <span className="text-[var(--text-primary)]">{options.product_name}</span> for
We can install <span className="text-[var(--text-primary)]">{options.product_name}</span>{" "} you, or you can follow the official instructions.
for you, or you can follow the official instructions. </p>
</p>
{phase === "idle" && ( {phase === "idle" && (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
{options.can_auto_install ? ( {options.can_auto_install ? (
<button <Button size="md" variant="primary" onClick={handleInstall}>
onClick={handleInstall} {installVerb} ({options.auto_install_method})
className="px-3 py-2 text-sm bg-[var(--accent)] text-white rounded hover:bg-[var(--accent-hover)] transition-colors" </Button>
> ) : (
{installVerb} ({options.auto_install_method}) <div className="text-xs text-[var(--text-secondary)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] p-2">
</button> One-click install unavailable:{" "}
) : ( <span className="text-[var(--text-primary)]">
<div className="text-xs text-[var(--text-secondary)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded p-2"> {options.auto_install_blocker ?? "required tooling missing."}
One-click install unavailable:{" "} </span>
<span className="text-[var(--text-primary)]">
{options.auto_install_blocker ?? "required tooling missing."}
</span>
</div>
)}
<button
onClick={() => setShowManual((s) => !s)}
className="px-3 py-2 text-sm bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] transition-colors"
>
{showManual ? "Hide manual instructions" : "Show manual instructions"}
</button>
<button
onClick={handleOpenDocs}
className="px-3 py-2 text-sm bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] transition-colors"
>
Open official documentation
</button>
</div>
)}
{phase === "installing" && (
<div className="text-xs text-[var(--text-secondary)]">
Installing a system password prompt may appear. Do not close this window.
</div>
)}
{phase === "done" && (
<div className="flex flex-col gap-2">
<div className="text-sm text-[var(--success)]">Install finished.</div>
{options.post_install_notes.length > 0 && (
<ul className="text-xs text-[var(--text-secondary)] list-disc list-inside space-y-1">
{options.post_install_notes.map((note, i) => (
<li key={i}>{note}</li>
))}
</ul>
)}
<div className="flex gap-2 mt-2">
<button
onClick={handleRecheck}
className="px-3 py-2 text-sm bg-[var(--accent)] text-white rounded hover:bg-[var(--accent-hover)] transition-colors"
>
Re-check Docker
</button>
<button
onClick={onClose}
className="px-3 py-2 text-sm bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] transition-colors"
>
Close
</button>
</div> </div>
</div> )}
)}
{phase === "error" && ( <Button size="md" onClick={() => setShowManual((s) => !s)}>
<div className="flex flex-col gap-2"> {showManual ? "Hide manual instructions" : "Show manual instructions"}
<div className="text-sm text-[var(--error)]">Install failed.</div> </Button>
{error && <div className="text-xs font-mono text-[var(--error)]">{error}</div>}
<div className="flex gap-2 mt-2">
<button
onClick={() => setPhase("idle")}
className="px-3 py-2 text-sm bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] transition-colors"
>
Back
</button>
<button
onClick={handleOpenDocs}
className="px-3 py-2 text-sm bg-[var(--accent)] text-white rounded hover:bg-[var(--accent-hover)] transition-colors"
>
Open official docs
</button>
</div>
</div>
)}
{(showManual || phase === "error") && ( <Button size="md" onClick={handleOpenDocs}>
<div className="mt-4"> Open official documentation
<div className="text-xs font-medium mb-1.5 text-[var(--text-secondary)]"> </Button>
Manual install steps </div>
</div> )}
<ol className="text-xs text-[var(--text-secondary)] list-decimal list-inside space-y-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded p-2">
{options.manual_steps.map((step, i) => ( {phase === "installing" && (
<li key={i}>{step}</li> <div className="text-xs text-[var(--text-secondary)]">
Installing a system password prompt may appear. Do not close this window.
</div>
)}
{phase === "done" && (
<div className="flex flex-col gap-2">
<div className="text-[13px] text-[var(--success)]">Install finished.</div>
{options.post_install_notes.length > 0 && (
<ul className="text-xs text-[var(--text-secondary)] list-disc list-inside space-y-1">
{options.post_install_notes.map((note, i) => (
<li key={i}>{note}</li>
))} ))}
</ol> </ul>
)}
<div className="flex gap-2 mt-2">
<Button size="md" variant="primary" onClick={handleRecheck}>
Re-check Docker
</Button>
<Button size="md" onClick={onClose}>
Close
</Button>
</div> </div>
)} </div>
)}
{log.length > 0 && ( {phase === "error" && (
<div className="mt-4 max-h-48 overflow-y-auto bg-[var(--bg-primary)] border border-[var(--border-color)] rounded p-2 text-xs font-mono text-[var(--text-secondary)]"> <div className="flex flex-col gap-2">
{log.map((line, i) => ( <div className="text-[13px] text-[var(--error)]">Install failed.</div>
<div key={i}>{line}</div> {error && (
<div className="text-xs font-mono text-[var(--error)] break-words">
{error}
</div>
)}
<div className="flex gap-2 mt-2">
<Button size="md" onClick={() => setPhase("idle")}>
Back
</Button>
<Button size="md" variant="primary" onClick={handleOpenDocs}>
Open official docs
</Button>
</div>
</div>
)}
{(showManual || phase === "error") && (
<div className="mt-4">
<div className="text-xs font-medium mb-1.5 text-[var(--text-secondary)]">
Manual install steps
</div>
<ol className="text-xs text-[var(--text-secondary)] list-decimal list-inside space-y-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] p-2">
{options.manual_steps.map((step, i) => (
<li key={i}>{step}</li>
))} ))}
</div> </ol>
)} </div>
)}
{phase === "idle" && ( {log.length > 0 && (
<div className="mt-4 flex justify-end"> <div className="mt-4 max-h-48 overflow-y-auto bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] p-2 text-xs font-mono text-[var(--text-secondary)]">
<button {log.map((line, i) => (
onClick={onClose} <div key={i}>{line}</div>
className="text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)]" ))}
> </div>
Dismiss )}
</button> </Modal>
</div>
)}
</div>
</div>
); );
} }
+20 -49
View File
@@ -1,5 +1,7 @@
import { useEffect, useRef, useCallback, useState } from "react"; import { useEffect, useRef, useCallback, useState } from "react";
import { getHelpContent } from "../../lib/tauri-commands"; import { getHelpContent } from "../../lib/tauri-commands";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
@@ -140,32 +142,16 @@ function renderMarkdown(md: string): string {
} }
export default function HelpDialog({ onClose }: Props) { export default function HelpDialog({ onClose }: Props) {
const overlayRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null); const contentRef = useRef<HTMLDivElement>(null);
const [markdown, setMarkdown] = useState<string | null>(null); const [markdown, setMarkdown] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
useEffect(() => { useEffect(() => {
getHelpContent() getHelpContent()
.then(setMarkdown) .then(setMarkdown)
.catch((e) => setError(String(e))); .catch((e) => setError(String(e)));
}, []); }, []);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
// Handle anchor link clicks to scroll within the dialog // Handle anchor link clicks to scroll within the dialog
const handleContentClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => { const handleContentClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
const target = e.target as HTMLElement; const target = e.target as HTMLElement;
@@ -179,40 +165,25 @@ export default function HelpDialog({ onClose }: Props) {
}, []); }, []);
return ( return (
<div <Modal
ref={overlayRef} title="How to Use Triple-C"
onClick={handleOverlayClick} onClose={onClose}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" widthClassName="w-[48rem]"
footer={<Button onClick={onClose}>Close</Button>}
> >
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg shadow-xl w-[48rem] max-w-[90vw] max-h-[85vh] flex flex-col"> <div ref={contentRef} onClick={handleContentClick} className="help-content">
{/* Header */} {error && (
<div className="flex items-center justify-between px-6 py-4 border-b border-[var(--border-color)] flex-shrink-0"> <p className="text-[var(--error)] text-sm">
<h2 className="text-lg font-semibold">How to Use Triple-C</h2> Failed to load help content: {error}
<button </p>
onClick={onClose} )}
className="px-3 py-1.5 text-xs bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] transition-colors" {!markdown && !error && (
> <p className="text-[var(--text-secondary)] text-sm">Loading</p>
Close )}
</button> {markdown && (
</div> <div dangerouslySetInnerHTML={{ __html: renderMarkdown(markdown) }} />
)}
{/* Scrollable content */}
<div
ref={contentRef}
onClick={handleContentClick}
className="flex-1 overflow-y-auto px-6 py-4 help-content"
>
{error && (
<p className="text-[var(--error)] text-sm">Failed to load help content: {error}</p>
)}
{!markdown && !error && (
<p className="text-[var(--text-secondary)] text-sm">Loading...</p>
)}
{markdown && (
<div dangerouslySetInnerHTML={{ __html: renderMarkdown(markdown) }} />
)}
</div>
</div> </div>
</div> </Modal>
); );
} }
+328
View File
@@ -0,0 +1,328 @@
import { useEffect, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";
import { useTerminal } from "../../hooks/useTerminal";
import { useProjects } from "../../hooks/useProjects";
import {
useAppState,
isHomeTab,
tabKeyId,
terminalTabKey,
} from "../../store/appState";
import { effectivePermissionMode } from "../projects/PermissionModeControl";
import { ProjectStatusIndicator } from "../ui/StatusIndicator";
import type { PermissionMode } from "../../lib/types";
interface ContextMenuState {
sessionId: string;
x: number;
y: number;
}
const MODE_BADGE: Record<PermissionMode, { text: string; className: string }> = {
plan: { text: "plan", className: "bg-[var(--bg-tertiary)] text-[var(--text-secondary)]" },
default: { text: "ask", className: "bg-[var(--bg-tertiary)] text-[var(--text-secondary)]" },
acceptEdits: { text: "edits", className: "bg-[var(--accent-muted)] text-[var(--accent)]" },
bypass: { text: "bypass", className: "bg-[var(--warning-muted)] text-[var(--warning)]" },
};
/**
* One strip for both main-area tab kinds: Project Home views () and
* terminals ().
*/
export default function MainTabs() {
const { sessions, close } = useTerminal();
const { projects, update } = useProjects();
const { tabOrder, activeTabKey, setActiveTabKey, closeHomeTab } = useAppState(
useShallow((s) => ({
tabOrder: s.tabOrder,
activeTabKey: s.activeTabKey,
setActiveTabKey: s.setActiveTabKey,
closeHomeTab: s.closeHomeTab,
})),
);
const [menu, setMenu] = useState<ContextMenuState | null>(null);
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameDraft, setRenameDraft] = useState("");
const renameInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!menu) return;
const dismiss = () => setMenu(null);
window.addEventListener("click", dismiss);
window.addEventListener("scroll", dismiss, true);
return () => {
window.removeEventListener("click", dismiss);
window.removeEventListener("scroll", dismiss, true);
};
}, [menu]);
useEffect(() => {
if (renamingId) {
renameInputRef.current?.focus();
renameInputRef.current?.select();
}
}, [renamingId]);
if (tabOrder.length === 0) {
return (
<div className="px-3 text-xs text-[var(--text-secondary)] leading-10">
No open tabs select a project to open its home view.
</div>
);
}
const getCustomName = (projectId: string, sessionId: string): string | null => {
const project = projects.find((p) => p.id === projectId);
return project?.renamed_session_names?.[sessionId] ?? null;
};
const startRename = (sessionId: string) => {
const session = sessions.find((s) => s.id === sessionId);
if (!session) return;
const current =
getCustomName(session.projectId, sessionId) ??
session.sessionName ??
session.projectName;
setRenameDraft(current);
setRenamingId(sessionId);
setMenu(null);
};
const commitRename = async (sessionId: string) => {
const session = sessions.find((s) => s.id === sessionId);
if (!session) {
setRenamingId(null);
return;
}
const project = projects.find((p) => p.id === session.projectId);
if (!project) {
setRenamingId(null);
return;
}
const trimmed = renameDraft.trim();
const map = { ...(project.renamed_session_names ?? {}) };
if (trimmed) {
map[sessionId] = trimmed;
} else {
delete map[sessionId];
}
try {
await update({ ...project, renamed_session_names: map });
} catch (err) {
console.error("Failed to rename terminal tab:", err);
} finally {
setRenamingId(null);
}
};
const clearCustomName = async (sessionId: string) => {
const session = sessions.find((s) => s.id === sessionId);
if (!session) return;
const project = projects.find((p) => p.id === session.projectId);
if (!project) return;
const map = { ...(project.renamed_session_names ?? {}) };
if (!(sessionId in map)) {
setMenu(null);
return;
}
delete map[sessionId];
try {
await update({ ...project, renamed_session_names: map });
} catch (err) {
console.error("Failed to reset terminal tab name:", err);
} finally {
setMenu(null);
}
};
const tabClass = (active: boolean) =>
`flex items-center gap-1.5 pl-3 pr-1.5 h-full text-xs cursor-pointer border-r border-[var(--border-color)] transition-colors ${
active
? "bg-[var(--bg-primary)] text-[var(--text-primary)]"
: "text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
}`;
return (
<div className="flex items-center h-full" role="tablist" aria-label="Open tabs">
{tabOrder.map((key) => {
const active = activeTabKey === key;
if (isHomeTab(key)) {
const projectId = tabKeyId(key);
const project = projects.find((p) => p.id === projectId);
if (!project) return null;
return (
<div
key={key}
role="tab"
aria-selected={active}
tabIndex={0}
onClick={() => setActiveTabKey(key)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
setActiveTabKey(key);
}
}}
className={tabClass(active)}
>
<span aria-hidden="true" className="text-[var(--text-secondary)]"></span>
<span className="truncate max-w-[160px]" title={`${project.name} — project home`}>
{project.name}
</span>
<ProjectStatusIndicator status={project.status} iconOnly />
<button
type="button"
onClick={(e) => {
e.stopPropagation();
closeHomeTab(projectId);
}}
aria-label={`Close ${project.name} home tab`}
title="Close tab"
className="w-6 h-6 flex items-center justify-center rounded-[var(--radius-control)] text-[var(--text-secondary)] hover:text-[var(--error)] hover:bg-[var(--bg-tertiary)] transition-colors"
>
<span aria-hidden="true">×</span>
</button>
</div>
);
}
const sessionId = tabKeyId(key);
const session = sessions.find((s) => s.id === sessionId);
if (!session) return null;
const project = projects.find((p) => p.id === session.projectId);
const customName = getCustomName(session.projectId, session.id);
const baseLabel =
(session.sessionName ?? session.projectName) +
(session.sessionType === "bash" ? " (bash)" : "");
const displayLabel = customName
? `${session.projectName}: ${customName}`
: baseLabel;
const isRenaming = renamingId === session.id;
const badge = project ? MODE_BADGE[effectivePermissionMode(project)] : null;
return (
<div
key={key}
role="tab"
aria-selected={active}
tabIndex={0}
onClick={() => setActiveTabKey(terminalTabKey(session.id))}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
setActiveTabKey(terminalTabKey(session.id));
}
}}
onContextMenu={(e) => {
e.preventDefault();
setMenu({ sessionId: session.id, x: e.clientX, y: e.clientY });
}}
onDoubleClick={() => startRename(session.id)}
className={tabClass(active)}
>
<span aria-hidden="true" className="text-[var(--text-secondary)]"></span>
{isRenaming ? (
<input
ref={renameInputRef}
value={renameDraft}
aria-label="Rename tab"
onChange={(e) => setRenameDraft(e.target.value)}
onClick={(e) => e.stopPropagation()}
onBlur={() => commitRename(session.id)}
onKeyDown={(e) => {
if (e.key === "Enter") (e.target as HTMLInputElement).blur();
if (e.key === "Escape") setRenamingId(null);
}}
className="max-w-[180px] px-1 py-0 bg-[var(--bg-primary)] border border-[var(--accent)] rounded-[var(--radius-control)] text-xs text-[var(--text-primary)]"
/>
) : (
<span className="truncate max-w-[180px]" title={displayLabel}>
{displayLabel}
</span>
)}
{badge && (
<span
className={`px-1 py-0.5 rounded-[4px] text-[10px] leading-none font-medium ${badge.className}`}
title={`Permission mode: ${badge.text}`}
>
{badge.text}
</span>
)}
<button
type="button"
onClick={(e) => {
e.stopPropagation();
close(session.id);
}}
aria-label={`Close ${displayLabel}`}
title="Close terminal"
className="w-6 h-6 flex items-center justify-center rounded-[var(--radius-control)] text-[var(--text-secondary)] hover:text-[var(--error)] hover:bg-[var(--bg-tertiary)] transition-colors"
>
<span aria-hidden="true">×</span>
</button>
</div>
);
})}
{menu && (() => {
const session = sessions.find((s) => s.id === menu.sessionId);
const hasCustom = session
? !!getCustomName(session.projectId, menu.sessionId)
: false;
return (
<div
role="menu"
className="fixed z-50 min-w-[160px] py-1 bg-[var(--bg-overlay)] border border-[var(--border-color)] rounded-[var(--radius-panel)] text-xs"
style={{ top: menu.y, left: menu.x, boxShadow: "var(--shadow-overlay)" }}
onClick={(e) => e.stopPropagation()}
>
<button
type="button"
role="menuitem"
className="w-full text-left px-3 py-1.5 text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] transition-colors"
onClick={() => startRename(menu.sessionId)}
>
Rename tab
</button>
{hasCustom && (
<button
type="button"
role="menuitem"
className="w-full text-left px-3 py-1.5 text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] transition-colors"
onClick={() => clearCustomName(menu.sessionId)}
>
Reset name
</button>
)}
{session && (
<button
type="button"
role="menuitem"
className="w-full text-left px-3 py-1.5 text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] transition-colors"
onClick={() => {
useAppState.getState().openProjectHome(session.projectId);
setMenu(null);
}}
>
Open project home
</button>
)}
<div className="border-t border-[var(--border-color)] my-1" />
<button
type="button"
role="menuitem"
className="w-full text-left px-3 py-1.5 text-[var(--error)] hover:bg-[var(--bg-tertiary)] transition-colors"
onClick={() => {
close(menu.sessionId);
setMenu(null);
}}
>
Close tab
</button>
</div>
);
})()}
</div>
);
}
+6 -3
View File
@@ -22,9 +22,6 @@ vi.mock("../projects/ProjectList", () => ({
vi.mock("../settings/SettingsPanel", () => ({ vi.mock("../settings/SettingsPanel", () => ({
default: () => <div data-testid="settings-panel">SettingsPanel</div>, default: () => <div data-testid="settings-panel">SettingsPanel</div>,
})); }));
vi.mock("../mcp/McpPanel", () => ({
default: () => <div data-testid="mcp-panel">McpPanel</div>,
}));
describe("Sidebar", () => { describe("Sidebar", () => {
beforeEach(() => { beforeEach(() => {
@@ -37,6 +34,12 @@ describe("Sidebar", () => {
expect(screen.getByText("Settings")).toBeInTheDocument(); expect(screen.getByText("Settings")).toBeInTheDocument();
}); });
it("renders the project list, not a settings form, in the projects view", () => {
render(<Sidebar />);
expect(screen.getByTestId("project-list")).toBeInTheDocument();
expect(screen.queryByTestId("settings-panel")).not.toBeInTheDocument();
});
it("content area has min-w-0 to prevent flex overflow", () => { it("content area has min-w-0 to prevent flex overflow", () => {
const { container } = render(<Sidebar />); const { container } = render(<Sidebar />);
const contentArea = container.querySelector(".overflow-y-auto"); const contentArea = container.querySelector(".overflow-y-auto");
+4 -26
View File
@@ -2,10 +2,9 @@ import type { ReactNode } from "react";
import { useShallow } from "zustand/react/shallow"; import { useShallow } from "zustand/react/shallow";
import { useAppState } from "../../store/appState"; import { useAppState } from "../../store/appState";
import ProjectList from "../projects/ProjectList"; import ProjectList from "../projects/ProjectList";
import McpPanel from "../mcp/McpPanel";
import SettingsPanel from "../settings/SettingsPanel"; import SettingsPanel from "../settings/SettingsPanel";
type SidebarView = "projects" | "mcp" | "settings"; type SidebarView = "projects" | "settings";
const RAIL_ICONS: { view: SidebarView; label: string; icon: ReactNode }[] = [ const RAIL_ICONS: { view: SidebarView; label: string; icon: ReactNode }[] = [
{ {
@@ -17,18 +16,6 @@ const RAIL_ICONS: { view: SidebarView; label: string; icon: ReactNode }[] = [
</svg> </svg>
), ),
}, },
{
view: "mcp",
label: "MCP",
icon: (
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M9 2v6" />
<path d="M15 2v6" />
<path d="M7 8h10v4a5 5 0 0 1-10 0V8z" />
<path d="M12 17v5" />
</svg>
),
},
{ {
view: "settings", view: "settings",
label: "Settings", label: "Settings",
@@ -76,7 +63,7 @@ export default function Sidebar() {
}; };
return ( return (
<div className="flex flex-col h-full w-12 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg overflow-hidden"> <div className="flex flex-col h-full w-12 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-panel)] overflow-hidden">
<button <button
onClick={toggleSidebarCollapsed} onClick={toggleSidebarCollapsed}
title="Expand sidebar" title="Expand sidebar"
@@ -102,15 +89,12 @@ export default function Sidebar() {
}`; }`;
return ( return (
<div className="flex flex-col h-full w-[25%] min-w-56 max-w-80 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg overflow-hidden"> <div className="flex flex-col h-full w-[25%] min-w-56 max-w-80 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-panel)] overflow-hidden">
{/* Nav tabs */} {/* Nav tabs */}
<div className="flex border-b border-[var(--border-color)]"> <div className="flex border-b border-[var(--border-color)]">
<button onClick={() => setSidebarView("projects")} className={tabCls("projects")}> <button onClick={() => setSidebarView("projects")} className={tabCls("projects")}>
Projects Projects
</button> </button>
<button onClick={() => setSidebarView("mcp")} className={tabCls("mcp")}>
MCP <span className="text-[0.6rem] px-1 py-0.5 rounded bg-yellow-500/20 text-yellow-400 ml-0.5">Beta</span>
</button>
<button onClick={() => setSidebarView("settings")} className={tabCls("settings")}> <button onClick={() => setSidebarView("settings")} className={tabCls("settings")}>
Settings Settings
</button> </button>
@@ -128,13 +112,7 @@ export default function Sidebar() {
{/* Content */} {/* Content */}
<div className="flex-1 overflow-y-auto overflow-x-hidden p-1 min-w-0"> <div className="flex-1 overflow-y-auto overflow-x-hidden p-1 min-w-0">
{sidebarView === "projects" ? ( {sidebarView === "projects" ? <ProjectList /> : <SettingsPanel />}
<ProjectList />
) : sidebarView === "mcp" ? (
<McpPanel />
) : (
<SettingsPanel />
)}
</div> </div>
</div> </div>
); );
+1 -1
View File
@@ -25,7 +25,7 @@ export default function StatusBar({ stt }: Props) {
const running = projects.filter((p) => p.status === "running").length; const running = projects.filter((p) => p.status === "running").length;
return ( return (
<div className="flex items-center h-6 px-4 bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded-lg text-xs text-[var(--text-secondary)]"> <div className="flex items-center h-6 px-4 bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded-[var(--radius-panel)] text-xs text-[var(--text-secondary)]">
<span> <span>
{projects.length} project{projects.length !== 1 ? "s" : ""} {projects.length} project{projects.length !== 1 ? "s" : ""}
</span> </span>
+50 -21
View File
@@ -1,11 +1,12 @@
import { useState } from "react"; import { useState } from "react";
import { useShallow } from "zustand/react/shallow"; import { useShallow } from "zustand/react/shallow";
import TerminalTabs from "../terminal/TerminalTabs"; import MainTabs from "./MainTabs";
import { useAppState } from "../../store/appState"; import { useAppState } from "../../store/appState";
import { useSettings } from "../../hooks/useSettings"; import { useSettings } from "../../hooks/useSettings";
import UpdateDialog from "../settings/UpdateDialog"; import UpdateDialog from "../settings/UpdateDialog";
import ImageUpdateDialog from "../settings/ImageUpdateDialog"; import ImageUpdateDialog from "../settings/ImageUpdateDialog";
import HelpDialog from "./HelpDialog"; import HelpDialog from "./HelpDialog";
import StatusIndicator, { type StatusTone } from "../ui/StatusIndicator";
export default function TopBar() { export default function TopBar() {
const { dockerAvailable, imageExists, updateInfo, imageUpdateInfo, appVersion, setUpdateInfo, setImageUpdateInfo } = useAppState( const { dockerAvailable, imageExists, updateInfo, imageUpdateInfo, appVersion, setUpdateInfo, setImageUpdateInfo } = useAppState(
@@ -48,34 +49,48 @@ export default function TopBar() {
return ( return (
<> <>
<div className="flex items-center h-10 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg overflow-hidden"> <div className="flex items-center h-10 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-panel)] overflow-hidden">
<div className="flex-1 overflow-x-auto pl-2"> <div className="flex-1 overflow-x-auto pl-1">
<TerminalTabs /> <MainTabs />
</div> </div>
<div className="flex items-center gap-2 px-4 flex-shrink-0 text-xs text-[var(--text-secondary)]"> <div className="flex items-center gap-3 px-3 flex-shrink-0 text-xs text-[var(--text-secondary)]">
{updateInfo && ( {updateInfo && (
<button <button
type="button"
onClick={() => setShowUpdateDialog(true)} onClick={() => setShowUpdateDialog(true)}
className="px-2 py-0.5 rounded text-xs font-medium bg-[var(--accent)] text-white animate-pulse hover:bg-[var(--accent-hover)] transition-colors" className="h-6 px-2 rounded-[var(--radius-control)] text-xs font-medium bg-[var(--accent-emphasis)] text-white hover:bg-[var(--accent-emphasis-hover)] transition-colors"
> >
Update Update
</button> </button>
)} )}
{imageUpdateInfo && ( {imageUpdateInfo && (
<button <button
type="button"
onClick={() => setShowImageUpdateDialog(true)} onClick={() => setShowImageUpdateDialog(true)}
className="px-2 py-0.5 rounded text-xs font-medium bg-[var(--warning,#f59e0b)] text-white hover:opacity-80 transition-colors" className="h-6 px-2 rounded-[var(--radius-control)] text-xs font-medium bg-[var(--warning-emphasis)] text-white hover:opacity-90 transition-colors"
title="A newer container image is available" title="A newer container image is available"
> >
Image Update Image Update
</button> </button>
)} )}
<StatusDot ok={dockerAvailable === true} label="Docker" /> <HealthDot
<StatusDot ok={imageExists === true} label="Image" /> state={dockerAvailable}
okLabel="Docker"
failLabel="Docker unavailable"
pendingLabel="Docker — checking"
/>
<HealthDot
state={imageExists}
okLabel="Image"
failLabel="Image missing"
pendingLabel="Image — checking"
/>
<button <button
type="button"
onClick={() => setShowHelpDialog(true)} onClick={() => setShowHelpDialog(true)}
title="Help" title="Help"
className="ml-1 w-5 h-5 flex items-center justify-center rounded-full border border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:border-[var(--text-secondary)] transition-colors text-xs font-semibold leading-none" aria-label="Help"
className="w-6 h-6 flex items-center justify-center rounded-[var(--radius-control)] border border-[var(--border-color)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:border-[var(--text-secondary)] transition-colors text-xs font-semibold leading-none"
> >
? ?
</button> </button>
@@ -103,15 +118,29 @@ export default function TopBar() {
); );
} }
function StatusDot({ ok, label }: { ok: boolean; label: string }) { /**
return ( * `null` (still checking) is visually distinct and pulses; `false` is an
<span className="flex items-center gap-1"> * outage and renders red previously both fell through to the same gray dot.
<span */
className={`inline-block w-2 h-2 rounded-full ${ function HealthDot({
ok ? "bg-[var(--success)]" : "bg-[var(--text-secondary)]" state,
}`} okLabel,
/> failLabel,
{label} pendingLabel,
</span> }: {
); state: boolean | null;
okLabel: string;
failLabel: string;
pendingLabel: string;
}) {
let tone: StatusTone = "unknown";
let label = pendingLabel;
if (state === true) {
tone = "ok";
label = okLabel;
} else if (state === false) {
tone = "error";
label = failLabel;
}
return <StatusIndicator tone={tone} label={label} />;
} }
-79
View File
@@ -1,79 +0,0 @@
import { useState, useEffect } from "react";
import { useMcpServers } from "../../hooks/useMcpServers";
import McpServerCard from "./McpServerCard";
export default function McpPanel() {
const { mcpServers, refresh, add, update, remove } = useMcpServers();
const [newName, setNewName] = useState("");
const [error, setError] = useState<string | null>(null);
useEffect(() => {
refresh();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const handleAdd = async () => {
const name = newName.trim();
if (!name) return;
setError(null);
try {
await add(name);
setNewName("");
} catch (e) {
setError(String(e));
}
};
return (
<div className="space-y-3 p-2">
<div>
<h2 className="text-sm font-semibold text-[var(--text-primary)]">
MCP Servers{" "}
<span className="text-xs px-1.5 py-0.5 rounded bg-yellow-500/20 text-yellow-400">Beta</span>
</h2>
<p className="text-xs text-[var(--text-secondary)] mt-0.5">
Define MCP servers globally, then enable them per-project.
</p>
</div>
{/* Add new server */}
<div className="flex gap-1">
<input
value={newName}
onChange={(e) => setNewName(e.target.value)}
onKeyDown={(e) => { if (e.key === "Enter") handleAdd(); }}
placeholder="Server name..."
className="flex-1 px-2 py-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-xs text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)]"
/>
<button
onClick={handleAdd}
disabled={!newName.trim()}
className="px-3 py-1 text-xs bg-[var(--accent)] text-white rounded hover:bg-[var(--accent-hover)] disabled:opacity-50 transition-colors"
>
Add
</button>
</div>
{error && (
<div className="text-xs text-[var(--error)]">{error}</div>
)}
{/* Server list */}
<div className="space-y-2">
{mcpServers.length === 0 ? (
<p className="text-xs text-[var(--text-secondary)] italic">
No MCP servers configured.
</p>
) : (
mcpServers.map((server) => (
<McpServerCard
key={server.id}
server={server}
onUpdate={update}
onRemove={remove}
/>
))
)}
</div>
</div>
);
}
-331
View File
@@ -1,331 +0,0 @@
import { useState, useEffect } from "react";
import type { McpServer, McpTransportType } from "../../lib/types";
interface Props {
server: McpServer;
onUpdate: (server: McpServer) => Promise<McpServer | void>;
onRemove: (id: string) => Promise<void>;
}
export default function McpServerCard({ server, onUpdate, onRemove }: Props) {
const [expanded, setExpanded] = useState(false);
const [name, setName] = useState(server.name);
const [transportType, setTransportType] = useState<McpTransportType>(server.transport_type);
const [command, setCommand] = useState(server.command ?? "");
const [args, setArgs] = useState(server.args.join(" "));
const [envPairs, setEnvPairs] = useState<[string, string][]>(Object.entries(server.env));
const [url, setUrl] = useState(server.url ?? "");
const [headerPairs, setHeaderPairs] = useState<[string, string][]>(Object.entries(server.headers));
const [dockerImage, setDockerImage] = useState(server.docker_image ?? "");
const [containerPort, setContainerPort] = useState(server.container_port?.toString() ?? "3000");
useEffect(() => {
setName(server.name);
setTransportType(server.transport_type);
setCommand(server.command ?? "");
setArgs(server.args.join(" "));
setEnvPairs(Object.entries(server.env));
setUrl(server.url ?? "");
setHeaderPairs(Object.entries(server.headers));
setDockerImage(server.docker_image ?? "");
setContainerPort(server.container_port?.toString() ?? "3000");
}, [server]);
const saveServer = async (patch: Partial<McpServer>) => {
try {
await onUpdate({ ...server, ...patch });
} catch (err) {
console.error("Failed to update MCP server:", err);
}
};
const handleNameBlur = () => {
if (name !== server.name) saveServer({ name });
};
const handleTransportChange = (t: McpTransportType) => {
setTransportType(t);
saveServer({ transport_type: t });
};
const handleCommandBlur = () => {
saveServer({ command: command || null });
};
const handleArgsBlur = () => {
const parsed = args.trim() ? args.trim().split(/\s+/) : [];
saveServer({ args: parsed });
};
const handleUrlBlur = () => {
saveServer({ url: url || null });
};
const handleDockerImageBlur = () => {
saveServer({ docker_image: dockerImage || null });
};
const handleContainerPortBlur = () => {
const port = parseInt(containerPort, 10);
saveServer({ container_port: isNaN(port) ? null : port });
};
const saveEnv = (pairs: [string, string][]) => {
const env: Record<string, string> = {};
for (const [k, v] of pairs) {
if (k.trim()) env[k.trim()] = v;
}
saveServer({ env });
};
const saveHeaders = (pairs: [string, string][]) => {
const headers: Record<string, string> = {};
for (const [k, v] of pairs) {
if (k.trim()) headers[k.trim()] = v;
}
saveServer({ headers });
};
const inputCls = "w-full px-2 py-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-xs text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)]";
const isDocker = !!dockerImage;
const transportBadge = {
stdio: "Stdio",
http: "HTTP",
}[transportType];
const modeBadge = isDocker ? "Docker" : "Manual";
return (
<div className="border border-[var(--border-color)] rounded bg-[var(--bg-primary)]">
{/* Header */}
<div className="flex items-center gap-2 px-3 py-2">
<button
onClick={() => setExpanded(!expanded)}
className="flex-1 flex items-center gap-2 text-left min-w-0"
>
<span className="text-xs text-[var(--text-secondary)]">{expanded ? "\u25BC" : "\u25B6"}</span>
<span className="text-sm font-medium truncate">{server.name}</span>
<span className="text-xs px-1.5 py-0.5 rounded bg-[var(--bg-secondary)] text-[var(--text-secondary)]">
{transportBadge}
</span>
<span className={`text-xs px-1.5 py-0.5 rounded ${isDocker ? "bg-blue-500/20 text-blue-400" : "bg-[var(--bg-secondary)] text-[var(--text-secondary)]"}`}>
{modeBadge}
</span>
</button>
<button
onClick={() => { if (confirm(`Remove MCP server "${server.name}"?`)) onRemove(server.id); }}
className="text-xs px-2 py-0.5 text-[var(--error)] hover:bg-[var(--bg-secondary)] rounded transition-colors"
>
Remove
</button>
</div>
{/* Expanded config */}
{expanded && (
<div className="px-3 pb-3 space-y-2 border-t border-[var(--border-color)] pt-2">
{/* Name */}
<div>
<label className="block text-xs text-[var(--text-secondary)] mb-0.5">Name</label>
<input
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={handleNameBlur}
className={inputCls}
/>
</div>
{/* Docker Image (primary field — determines Docker vs Manual mode) */}
<div>
<label className="block text-xs text-[var(--text-secondary)] mb-0.5">Docker Image</label>
<input
value={dockerImage}
onChange={(e) => setDockerImage(e.target.value)}
onBlur={handleDockerImageBlur}
placeholder="e.g. mcp/filesystem:latest (leave empty for manual mode)"
className={inputCls}
/>
<p className="text-xs text-[var(--text-secondary)] mt-0.5 opacity-60">
Set a Docker image to run this MCP server in its own container. Leave empty to run commands inside the project container. Images are pulled automatically if not present.
</p>
</div>
{/* Transport type */}
<div>
<label className="block text-xs text-[var(--text-secondary)] mb-0.5">Transport</label>
<div className="flex items-center gap-1">
{(["stdio", "http"] as McpTransportType[]).map((t) => (
<button
key={t}
onClick={() => handleTransportChange(t)}
className={`px-2 py-0.5 text-xs rounded transition-colors ${
transportType === t
? "bg-[var(--accent)] text-white"
: "text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)]"
}`}
>
{t === "stdio" ? "Stdio" : "HTTP"}
</button>
))}
</div>
</div>
{/* Mode description */}
<p className="text-xs text-[var(--text-secondary)] opacity-60">
{transportType === "stdio" && isDocker && "Runs via docker exec in a separate MCP container."}
{transportType === "stdio" && !isDocker && "Runs inside the project container (e.g. npx commands)."}
{transportType === "http" && isDocker && "Runs in a separate container, reached by hostname on the project network."}
{transportType === "http" && !isDocker && "Connects to an MCP server at the URL you specify."}
</p>
{/* Container Port (HTTP+Docker only) */}
{transportType === "http" && isDocker && (
<div>
<label className="block text-xs text-[var(--text-secondary)] mb-0.5">Container Port</label>
<input
value={containerPort}
onChange={(e) => setContainerPort(e.target.value)}
onBlur={handleContainerPortBlur}
placeholder="3000"
className={inputCls}
/>
<p className="text-xs text-[var(--text-secondary)] mt-0.5 opacity-60">
Port the MCP server listens on inside its container. The URL is auto-generated as http://&lt;container&gt;:&lt;port&gt;/mcp on the project network.
</p>
</div>
)}
{/* Stdio fields */}
{transportType === "stdio" && (
<>
<div>
<label className="block text-xs text-[var(--text-secondary)] mb-0.5">Command</label>
<input
value={command}
onChange={(e) => setCommand(e.target.value)}
onBlur={handleCommandBlur}
placeholder={isDocker ? "Command inside container" : "npx"}
className={inputCls}
/>
</div>
<div>
<label className="block text-xs text-[var(--text-secondary)] mb-0.5">Arguments (space-separated)</label>
<input
value={args}
onChange={(e) => setArgs(e.target.value)}
onBlur={handleArgsBlur}
placeholder="-y @modelcontextprotocol/server-filesystem /path"
className={inputCls}
/>
</div>
<KeyValueEditor
label="Environment Variables"
pairs={envPairs}
onChange={(pairs) => { setEnvPairs(pairs); }}
onSave={saveEnv}
/>
</>
)}
{/* HTTP fields (only for manual mode — Docker mode auto-generates URL) */}
{transportType === "http" && !isDocker && (
<>
<div>
<label className="block text-xs text-[var(--text-secondary)] mb-0.5">URL</label>
<input
value={url}
onChange={(e) => setUrl(e.target.value)}
onBlur={handleUrlBlur}
placeholder="http://localhost:3000/mcp"
className={inputCls}
/>
</div>
<KeyValueEditor
label="Headers"
pairs={headerPairs}
onChange={(pairs) => { setHeaderPairs(pairs); }}
onSave={saveHeaders}
/>
</>
)}
{/* Environment variables for HTTP+Docker */}
{transportType === "http" && isDocker && (
<KeyValueEditor
label="Environment Variables"
pairs={envPairs}
onChange={(pairs) => { setEnvPairs(pairs); }}
onSave={saveEnv}
/>
)}
</div>
)}
</div>
);
}
function KeyValueEditor({
label,
pairs,
onChange,
onSave,
}: {
label: string;
pairs: [string, string][];
onChange: (pairs: [string, string][]) => void;
onSave: (pairs: [string, string][]) => void;
}) {
const inputCls = "flex-1 min-w-0 px-2 py-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-xs text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)]";
return (
<div>
<label className="block text-xs text-[var(--text-secondary)] mb-0.5">{label}</label>
{pairs.map(([key, value], i) => (
<div key={i} className="flex gap-1 items-center mb-1">
<input
value={key}
onChange={(e) => {
const updated = [...pairs] as [string, string][];
updated[i] = [e.target.value, value];
onChange(updated);
}}
onBlur={() => onSave(pairs)}
placeholder="KEY"
className={inputCls}
/>
<span className="text-xs text-[var(--text-secondary)]">=</span>
<input
value={value}
onChange={(e) => {
const updated = [...pairs] as [string, string][];
updated[i] = [key, e.target.value];
onChange(updated);
}}
onBlur={() => onSave(pairs)}
placeholder="value"
className={inputCls}
/>
<button
onClick={() => {
const updated = pairs.filter((_, j) => j !== i);
onChange(updated);
onSave(updated);
}}
className="flex-shrink-0 px-1.5 py-1 text-xs text-[var(--error)] hover:bg-[var(--bg-secondary)] rounded transition-colors"
>
x
</button>
</div>
))}
<button
onClick={() => {
onChange([...pairs, ["", ""]]);
}}
className="text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors"
>
+ Add
</button>
</div>
);
}
@@ -1,7 +1,10 @@
import { useState, useEffect, useRef, useCallback } from "react"; import { useId, useRef, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog"; import { open } from "@tauri-apps/plugin-dialog";
import { useProjects } from "../../hooks/useProjects"; import { useProjects } from "../../hooks/useProjects";
import type { ProjectPath } from "../../lib/types"; import type { ProjectPath } from "../../lib/types";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
import { inputClass, monoInputClass } from "../ui/Field";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
@@ -25,26 +28,7 @@ export default function AddProjectDialog({ onClose }: Props) {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const nameInputRef = useRef<HTMLInputElement>(null); const nameInputRef = useRef<HTMLInputElement>(null);
const overlayRef = useRef<HTMLDivElement>(null); const formId = useId();
useEffect(() => {
nameInputRef.current?.focus();
}, []);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
const handleBrowse = async (index: number) => { const handleBrowse = async (index: number) => {
const selected = await open({ directory: true, multiple: false }); const selected = await open({ directory: true, multiple: false });
@@ -63,24 +47,12 @@ export default function AddProjectDialog({ onClose }: Props) {
} }
}; };
const updateEntry = ( const updateEntry = (index: number, field: keyof PathEntry, value: string) => {
index: number,
field: keyof PathEntry,
value: string,
) => {
const entries = [...pathEntries]; const entries = [...pathEntries];
entries[index] = { ...entries[index], [field]: value }; entries[index] = { ...entries[index], [field]: value };
setPathEntries(entries); setPathEntries(entries);
}; };
const removeEntry = (index: number) => {
setPathEntries(pathEntries.filter((_, i) => i !== index));
};
const addEntry = () => {
setPathEntries([...pathEntries, { host_path: "", mount_name: "" }]);
};
const handleSubmit = async (e?: React.FormEvent) => { const handleSubmit = async (e?: React.FormEvent) => {
if (e) e.preventDefault(); if (e) e.preventDefault();
if (!name.trim()) { if (!name.trim()) {
@@ -115,98 +87,106 @@ export default function AddProjectDialog({ onClose }: Props) {
}; };
return ( return (
<div <Modal
ref={overlayRef} title="Add Project"
onClick={handleOverlayClick} onClose={onClose}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" widthClassName="w-[30rem]"
initialFocusRef={nameInputRef}
footer={
<>
<Button size="md" variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button size="md" variant="primary" type="submit" form={formId} disabled={loading}>
{loading ? "Adding…" : "Add Project"}
</Button>
</>
}
> >
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[28rem] shadow-xl max-h-[80vh] overflow-y-auto"> <form id={formId} onSubmit={handleSubmit} className="space-y-4">
<h2 className="text-lg font-semibold mb-4">Add Project</h2> <div>
<label
<form onSubmit={handleSubmit}> htmlFor={`${formId}-name`}
<label className="block text-sm text-[var(--text-secondary)] mb-1"> className="block text-[13px] font-medium mb-1"
Project Name >
Project name
</label> </label>
<input <input
id={`${formId}-name`}
ref={nameInputRef} ref={nameInputRef}
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
placeholder="my-project" placeholder="my-project"
className="w-full px-3 py-2 mb-3 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)]" className={inputClass}
/> />
</div>
<label className="block text-sm text-[var(--text-secondary)] mb-1"> <div>
Folders <span className="block text-[13px] font-medium mb-1">Folders</span>
</label> <div className="space-y-2">
<div className="space-y-2 mb-3">
{pathEntries.map((entry, i) => ( {pathEntries.map((entry, i) => (
<div key={i} className="space-y-1 p-2 bg-[var(--bg-primary)] rounded border border-[var(--border-color)]"> <div
<div className="flex gap-1"> key={i}
className="space-y-1.5 p-2 bg-[var(--bg-primary)] rounded-[var(--radius-control)] border border-[var(--border-color)]"
>
<div className="flex gap-1.5">
<input <input
value={entry.host_path} value={entry.host_path}
onChange={(e) => updateEntry(i, "host_path", e.target.value)} onChange={(e) => updateEntry(i, "host_path", e.target.value)}
placeholder="/path/to/folder" placeholder="/path/to/folder"
className="flex-1 px-2 py-1.5 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded text-xs text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)]" aria-label={`Folder ${i + 1} host path`}
className={inputClass}
/> />
<button <Button size="md" onClick={() => handleBrowse(i)}>
type="button"
onClick={() => handleBrowse(i)}
className="px-2 py-1.5 text-xs bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] transition-colors"
>
Browse Browse
</button> </Button>
{pathEntries.length > 1 && ( {pathEntries.length > 1 && (
<button <Button
type="button" size="md"
onClick={() => removeEntry(i)} variant="danger"
className="px-1.5 py-1.5 text-xs text-[var(--error)] hover:bg-[var(--bg-secondary)] rounded transition-colors" aria-label={`Remove folder ${i + 1}`}
onClick={() =>
setPathEntries(pathEntries.filter((_, j) => j !== i))
}
> >
x Remove
</button> </Button>
)} )}
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1.5">
<span className="text-xs text-[var(--text-secondary)] flex-shrink-0">/workspace/</span> <span className="text-xs text-[var(--text-secondary)] flex-shrink-0 font-mono">
/workspace/
</span>
<input <input
value={entry.mount_name} value={entry.mount_name}
onChange={(e) => updateEntry(i, "mount_name", e.target.value)} onChange={(e) => updateEntry(i, "mount_name", e.target.value)}
placeholder="mount-name" placeholder="mount-name"
className="flex-1 px-2 py-1 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded text-xs text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] font-mono" aria-label={`Folder ${i + 1} mount name`}
className={monoInputClass}
/> />
</div> </div>
</div> </div>
))} ))}
</div> </div>
<button <Button
type="button" className="mt-2"
onClick={addEntry} onClick={() =>
className="text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] mb-4 transition-colors" setPathEntries([...pathEntries, { host_path: "", mount_name: "" }])
}
> >
+ Add folder + Add folder
</button> </Button>
</div>
{error && ( {error && (
<div className="text-xs text-[var(--error)] mb-3">{error}</div> <div
)} role="alert"
className="px-2 py-1.5 text-xs text-[var(--error)] bg-[var(--error-muted)] border border-[var(--error)]/30 rounded-[var(--radius-control)]"
<div className="flex justify-end gap-2"> >
<button {error}
type="button"
onClick={onClose}
className="px-4 py-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={loading}
className="px-4 py-2 text-sm bg-[var(--accent)] text-white rounded hover:bg-[var(--accent-hover)] disabled:opacity-50 transition-colors"
>
{loading ? "Adding..." : "Add Project"}
</button>
</div> </div>
</form> )}
</div> </form>
</div> </Modal>
); );
} }
@@ -0,0 +1,151 @@
import { useEffect, useState } from "react";
import type { ClaudeCodeSettings } from "../../lib/types";
import Toggle from "../ui/Toggle";
import { SwitchRow, selectClass } from "../ui/Field";
interface Props {
settings: ClaudeCodeSettings | null;
disabled: boolean;
disabledReason?: string;
onSave: (settings: ClaudeCodeSettings | null) => Promise<unknown>;
}
export const CLAUDE_CODE_DEFAULTS: ClaudeCodeSettings = {
tui_mode: null,
effort: null,
auto_scroll_disabled: false,
focus_mode: false,
show_thinking_summaries: false,
enable_session_recap: false,
env_scrub: false,
prompt_caching_1h: false,
};
function isAllDefaults(s: ClaudeCodeSettings): boolean {
return (
s.tui_mode === null &&
s.effort === null &&
s.auto_scroll_disabled === false &&
s.focus_mode === false &&
s.show_thinking_summaries === false &&
s.enable_session_recap === false &&
s.env_scrub === false &&
s.prompt_caching_1h === false
);
}
const BOOLEAN_FIELDS: {
key: keyof Omit<ClaudeCodeSettings, "tui_mode" | "effort">;
label: string;
hint: string;
}[] = [
{ key: "focus_mode", label: "Focus mode", hint: "Collapses tool output to one-line summaries." },
{
key: "show_thinking_summaries",
label: "Thinking summaries",
hint: "Shows Claude's thinking process as summaries.",
},
{
key: "enable_session_recap",
label: "Session recap",
hint: "Provides context when returning to a session.",
},
{
key: "auto_scroll_disabled",
label: "Auto-scroll disabled",
hint: "Disables auto-scroll when in fullscreen TUI mode.",
},
{
key: "env_scrub",
label: "Env scrub",
hint: "Strips credentials from subprocess environments.",
},
{
key: "prompt_caching_1h",
label: "Prompt caching (1h)",
hint: "Uses a 1-hour prompt cache TTL instead of 5 minutes.",
},
];
export default function ClaudeCodeSettingsEditor({
settings,
disabled,
disabledReason,
onSave,
}: Props) {
const [local, setLocal] = useState<ClaudeCodeSettings>(
settings ?? { ...CLAUDE_CODE_DEFAULTS },
);
useEffect(() => {
setLocal(settings ?? { ...CLAUDE_CODE_DEFAULTS });
}, [settings]);
const apply = (patch: Partial<ClaudeCodeSettings>) => {
const next = { ...local, ...patch };
setLocal(next);
onSave(isAllDefaults(next) ? null : next);
};
return (
<div className="space-y-4">
{disabled && disabledReason && (
<p className="px-2 py-1.5 bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)] text-xs text-[var(--warning)]">
{disabledReason}
</p>
)}
<SwitchRow
label="TUI mode"
hint="Enables flicker-free alt-screen rendering."
control={
<select
value={local.tui_mode ?? ""}
aria-label="TUI mode"
onChange={(e) => apply({ tui_mode: e.target.value || null })}
disabled={disabled}
className={selectClass}
>
<option value="">Default</option>
<option value="fullscreen">Fullscreen</option>
</select>
}
/>
<SwitchRow
label="Effort level"
hint="Controls how much reasoning Claude applies."
control={
<select
value={local.effort ?? ""}
aria-label="Effort level"
onChange={(e) => apply({ effort: e.target.value || null })}
disabled={disabled}
className={selectClass}
>
<option value="">Default</option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</select>
}
/>
{BOOLEAN_FIELDS.map(({ key, label, hint }) => (
<SwitchRow
key={key}
label={label}
hint={hint}
control={
<Toggle
label={label}
checked={local[key]}
disabled={disabled}
onChange={(v) => apply({ [key]: v } as Partial<ClaudeCodeSettings>)}
/>
}
/>
))}
</div>
);
}
@@ -1,5 +1,7 @@
import { useState, useEffect, useRef, useCallback } from "react";
import type { ClaudeCodeSettings } from "../../lib/types"; import type { ClaudeCodeSettings } from "../../lib/types";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
import ClaudeCodeSettingsEditor from "./ClaudeCodeSettingsEditor";
interface Props { interface Props {
settings: ClaudeCodeSettings | null; settings: ClaudeCodeSettings | null;
@@ -8,184 +10,32 @@ interface Props {
onClose: () => void; onClose: () => void;
} }
const DEFAULTS: ClaudeCodeSettings = { /** Global Claude Code settings (Settings). Per-project lives in Config → Runtime. */
tui_mode: null, export default function ClaudeCodeSettingsModal({
effort: null, settings,
auto_scroll_disabled: false, disabled,
focus_mode: false, onSave,
show_thinking_summaries: false, onClose,
enable_session_recap: false, }: Props) {
env_scrub: false,
prompt_caching_1h: false,
};
function isAllDefaults(s: ClaudeCodeSettings): boolean {
return ( return (
s.tui_mode === null && <Modal
s.effort === null && title="Claude Code Settings"
s.auto_scroll_disabled === false && onClose={onClose}
s.focus_mode === false && widthClassName="w-[34rem]"
s.show_thinking_summaries === false && footer={<Button onClick={onClose}>Close</Button>}
s.enable_session_recap === false &&
s.env_scrub === false &&
s.prompt_caching_1h === false
);
}
export default function ClaudeCodeSettingsModal({ settings, disabled, onSave, onClose }: Props) {
const [local, setLocal] = useState<ClaudeCodeSettings>(settings ?? { ...DEFAULTS });
const overlayRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
const update = async (patch: Partial<ClaudeCodeSettings>) => {
const next = { ...local, ...patch };
setLocal(next);
try {
await onSave(isAllDefaults(next) ? null : next);
} catch (err) {
console.error("Failed to save Claude Code settings:", err);
}
};
const toggleButton = (label: string, description: string, value: boolean, onChange: (v: boolean) => void) => (
<div className="flex items-center justify-between gap-4">
<div className="min-w-0">
<div className="text-sm font-medium text-[var(--text-primary)]">{label}</div>
<div className="text-xs text-[var(--text-secondary)]">{description}</div>
</div>
<button
onClick={() => onChange(!value)}
disabled={disabled}
className={`px-2 py-0.5 text-xs rounded transition-colors disabled:opacity-50 shrink-0 ${
value
? "bg-[var(--success)] text-white"
: "bg-[var(--bg-primary)] border border-[var(--border-color)] text-[var(--text-secondary)]"
}`}
>
{value ? "ON" : "OFF"}
</button>
</div>
);
return (
<div
ref={overlayRef}
onClick={handleOverlayClick}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
> >
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[32rem] shadow-xl max-h-[80vh] overflow-y-auto"> <ClaudeCodeSettingsEditor
<h2 className="text-lg font-semibold mb-4">Claude Code Settings</h2> settings={settings}
disabled={disabled}
{disabled && ( disabledReason="Container must be stopped to change Claude Code settings."
<div className="px-2 py-1.5 mb-3 bg-[var(--warning)]/15 border border-[var(--warning)]/30 rounded text-xs text-[var(--warning)]"> onSave={async (next) => {
Container must be stopped to change Claude Code settings. try {
</div> await onSave(next);
)} } catch (err) {
console.error("Failed to save Claude Code settings:", err);
<div className="space-y-4 mb-6"> }
{/* TUI Mode */} }}
<div className="flex items-center justify-between gap-4"> />
<div className="min-w-0"> </Modal>
<div className="text-sm font-medium text-[var(--text-primary)]">TUI Mode</div>
<div className="text-xs text-[var(--text-secondary)]">Enables flicker-free alt-screen rendering</div>
</div>
<select
value={local.tui_mode ?? ""}
onChange={(e) => update({ tui_mode: e.target.value || null })}
disabled={disabled}
className="px-2 py-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] disabled:opacity-50 shrink-0"
>
<option value="">Default</option>
<option value="fullscreen">Fullscreen</option>
</select>
</div>
{/* Effort Level */}
<div className="flex items-center justify-between gap-4">
<div className="min-w-0">
<div className="text-sm font-medium text-[var(--text-primary)]">Effort Level</div>
<div className="text-xs text-[var(--text-secondary)]">Controls how much reasoning Claude applies</div>
</div>
<select
value={local.effort ?? ""}
onChange={(e) => update({ effort: e.target.value || null })}
disabled={disabled}
className="px-2 py-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] disabled:opacity-50 shrink-0"
>
<option value="">Default</option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</select>
</div>
{/* Boolean toggles */}
{toggleButton(
"Focus Mode",
"Collapses tool output to one-line summaries",
local.focus_mode,
(v) => update({ focus_mode: v }),
)}
{toggleButton(
"Thinking Summaries",
"Shows thinking process as summaries",
local.show_thinking_summaries,
(v) => update({ show_thinking_summaries: v }),
)}
{toggleButton(
"Session Recap",
"Provides context when returning to a session",
local.enable_session_recap,
(v) => update({ enable_session_recap: v }),
)}
{toggleButton(
"Auto-Scroll Disabled",
"Disables auto-scroll when in fullscreen TUI mode",
local.auto_scroll_disabled,
(v) => update({ auto_scroll_disabled: v }),
)}
{toggleButton(
"Env Scrub",
"Strips credentials from subprocess environments for security",
local.env_scrub,
(v) => update({ env_scrub: v }),
)}
{toggleButton(
"Prompt Caching (1h)",
"Enables 1-hour prompt cache TTL instead of 5 minutes",
local.prompt_caching_1h,
(v) => update({ prompt_caching_1h: v }),
)}
</div>
<div className="flex justify-end">
<button
onClick={onClose}
className="px-4 py-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
Close
</button>
</div>
</div>
</div>
); );
} }
@@ -0,0 +1,46 @@
import { useEffect, useState } from "react";
interface Props {
instructions: string;
disabled: boolean;
disabledReason?: string;
onSave: (instructions: string) => Promise<unknown>;
rows?: number;
autoFocus?: boolean;
}
export default function ClaudeInstructionsEditor({
instructions: initial,
disabled,
disabledReason,
onSave,
rows = 10,
autoFocus = false,
}: Props) {
const [instructions, setInstructions] = useState(initial);
useEffect(() => {
setInstructions(initial);
}, [initial]);
return (
<div className="space-y-2">
{disabled && disabledReason && (
<p className="px-2 py-1.5 bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)] text-xs text-[var(--warning)]">
{disabledReason}
</p>
)}
<textarea
autoFocus={autoFocus}
value={instructions}
onChange={(e) => setInstructions(e.target.value)}
onBlur={() => onSave(instructions)}
placeholder="Enter instructions for Claude Code in this project's container..."
aria-label="Claude instructions"
disabled={disabled}
rows={rows}
className="w-full px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] text-[13px] text-[var(--text-primary)] focus:border-[var(--accent)] disabled:text-[var(--text-disabled)] disabled:bg-[var(--bg-secondary)] resize-y font-mono transition-colors"
/>
</div>
);
}
@@ -1,4 +1,6 @@
import { useState, useEffect, useRef, useCallback } from "react"; import Modal from "../ui/Modal";
import Button from "../ui/Button";
import ClaudeInstructionsEditor from "./ClaudeInstructionsEditor";
interface Props { interface Props {
instructions: string; instructions: string;
@@ -7,74 +9,35 @@ interface Props {
onClose: () => void; onClose: () => void;
} }
export default function ClaudeInstructionsModal({ instructions: initial, disabled, onSave, onClose }: Props) { /** Global Claude instructions (Settings). Per-project lives in Config → Runtime. */
const [instructions, setInstructions] = useState(initial); export default function ClaudeInstructionsModal({
const overlayRef = useRef<HTMLDivElement>(null); instructions,
const textareaRef = useRef<HTMLTextAreaElement>(null); disabled,
onSave,
useEffect(() => { onClose,
textareaRef.current?.focus(); }: Props) {
}, []);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
const handleBlur = async () => {
try { await onSave(instructions); } catch (err) {
console.error("Failed to update Claude instructions:", err);
}
};
return ( return (
<div <Modal
ref={overlayRef} title="Claude Instructions"
onClick={handleOverlayClick} description="Written to ~/.claude/CLAUDE.md inside containers."
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClose={onClose}
widthClassName="w-[40rem]"
footer={<Button onClick={onClose}>Close</Button>}
> >
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[40rem] shadow-xl max-h-[80vh] flex flex-col"> <ClaudeInstructionsEditor
<h2 className="text-lg font-semibold mb-1">Claude Instructions</h2> instructions={instructions}
<p className="text-xs text-[var(--text-secondary)] mb-4"> disabled={disabled}
Per-project instructions for Claude Code (written to ~/.claude/CLAUDE.md in container) disabledReason="Container must be stopped to change Claude instructions."
</p> rows={14}
autoFocus
{disabled && ( onSave={async (value) => {
<div className="px-2 py-1.5 mb-3 bg-[var(--warning)]/15 border border-[var(--warning)]/30 rounded text-xs text-[var(--warning)]"> try {
Container must be stopped to change Claude instructions. await onSave(value);
</div> } catch (err) {
)} console.error("Failed to update Claude instructions:", err);
}
<textarea }}
ref={textareaRef} />
value={instructions} </Modal>
onChange={(e) => setInstructions(e.target.value)}
onBlur={handleBlur}
placeholder="Enter instructions for Claude Code in this project's container..."
disabled={disabled}
rows={14}
className="w-full flex-1 px-3 py-2 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] disabled:opacity-50 resize-y font-mono"
/>
<div className="flex justify-end mt-4">
<button
onClick={onClose}
className="px-4 py-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
Close
</button>
</div>
</div>
</div>
); );
} }
@@ -1,4 +1,5 @@
import { useEffect, useRef, useCallback } from "react"; import Modal from "../ui/Modal";
import Button from "../ui/Button";
interface Props { interface Props {
projectName: string; projectName: string;
@@ -7,49 +8,31 @@ interface Props {
} }
export default function ConfirmRemoveModal({ projectName, onConfirm, onCancel }: Props) { export default function ConfirmRemoveModal({ projectName, onConfirm, onCancel }: Props) {
const overlayRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onCancel();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onCancel]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onCancel();
},
[onCancel],
);
return ( return (
<div <Modal
ref={overlayRef} title="Remove Project"
onClick={handleOverlayClick} onClose={onCancel}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" widthClassName="w-[26rem]"
> footer={
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[24rem] shadow-xl"> <>
<h2 className="text-lg font-semibold mb-3">Remove Project</h2> <Button size="md" variant="ghost" onClick={onCancel}>
<p className="text-sm text-[var(--text-secondary)] mb-5">
Are you sure you want to remove <strong className="text-[var(--text-primary)]">{projectName}</strong>? This will delete the container, config volume, and stored credentials.
</p>
<div className="flex justify-end gap-2">
<button
onClick={onCancel}
className="px-4 py-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
Cancel Cancel
</button> </Button>
<button <Button
size="md"
onClick={onConfirm} onClick={onConfirm}
className="px-4 py-2 text-sm text-white bg-[var(--error)] hover:opacity-80 rounded transition-colors" className="bg-[var(--error-emphasis)] text-white border border-transparent hover:opacity-90"
> >
Remove Remove
</button> </Button>
</div> </>
</div> }
</div> >
<p className="text-[13px] text-[var(--text-secondary)]">
Are you sure you want to remove{" "}
<strong className="text-[var(--text-primary)]">{projectName}</strong>? This will
delete the container, config volume, and stored credentials.
</p>
</Modal>
); );
} }
@@ -0,0 +1,57 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, fireEvent, act } from "@testing-library/react";
import ConfirmResetModal from "./ConfirmResetModal";
/** Modal focuses via rAF so the panel is laid out first; jsdom needs a flush. */
async function flushFocus() {
await act(async () => {
vi.advanceTimersByTime(20);
});
}
describe("ConfirmResetModal", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["requestAnimationFrame", "setTimeout"] });
});
afterEach(() => {
vi.useRealTimers();
});
async function renderModal() {
const onConfirm = vi.fn();
const onCancel = vi.fn();
render(
<ConfirmResetModal
projectName="api-server"
onConfirm={onConfirm}
onCancel={onCancel}
/>,
);
await flushFocus();
return { onConfirm, onCancel };
}
it("names what will be lost rather than just asking to confirm", async () => {
await renderModal();
// The whole point of the gate: Reset deletes the volumes, and the two
// losses users do not expect are the login and the session transcripts.
expect(screen.getByText(/sign in again/i)).toBeInTheDocument();
expect(screen.getByText(/session transcript/i)).toBeInTheDocument();
// And it must say what is safe, or the warning reads as "you lose everything".
expect(screen.getByText(/mounted project folders/i)).toBeInTheDocument();
});
it("does not reset until confirmed", async () => {
const { onConfirm, onCancel } = await renderModal();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(onCancel).toHaveBeenCalledTimes(1);
expect(onConfirm).not.toHaveBeenCalled();
});
it("resets on confirm", async () => {
const { onConfirm } = await renderModal();
fireEvent.click(screen.getByRole("button", { name: "Reset container" }));
expect(onConfirm).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,66 @@
import Modal from "../ui/Modal";
import Button from "../ui/Button";
interface Props {
projectName: string;
onConfirm: () => void;
onCancel: () => void;
}
/**
* Reset is destructive in a way its name does not advertise.
*
* `rebuild_project_container` calls `remove_project_volumes`, which deletes
* both `triple-c-home-{id}` and `triple-c-claude-config-{id}` so the OAuth
* login, any skills or agents installed in the container, and every session
* transcript go with them. That is intentional (Reset exists to get back to a
* clean base image), but it is not recoverable, so it gets the same
* confirmation gate as Remove.
*/
export default function ConfirmResetModal({ projectName, onConfirm, onCancel }: Props) {
return (
<Modal
title="Reset container"
onClose={onCancel}
widthClassName="w-[28rem]"
footer={
<>
<Button size="md" variant="ghost" onClick={onCancel}>
Cancel
</Button>
<Button
size="md"
onClick={onConfirm}
className="bg-[var(--error-emphasis)] text-white border border-transparent hover:opacity-90"
>
Reset container
</Button>
</>
}
>
<div className="space-y-2.5 text-[13px] text-[var(--text-secondary)]">
<p>
Rebuild{" "}
<strong className="text-[var(--text-primary)]">{projectName}</strong>&rsquo;s
container from the clean base image.
</p>
<p>
This deletes the container&rsquo;s volumes, which means you will lose:
</p>
<ul className="list-disc pl-5 space-y-1">
<li>
your <code className="font-mono">claude login</code> &mdash; you will need to
sign in again
</li>
<li>any skills, agents or plugins installed inside the container</li>
<li>every saved session transcript, so past sessions cannot be resumed</li>
<li>anything installed with <code className="font-mono">apt</code>, <code className="font-mono">pip</code> or <code className="font-mono">npm</code></li>
</ul>
<p>
Your mounted project folders are on the host and are{" "}
<strong className="text-[var(--text-primary)]">not</strong> affected.
</p>
</div>
</Modal>
);
}
@@ -1,109 +0,0 @@
import { useEffect, useRef, useCallback } from "react";
interface Props {
projectName: string;
operation: "starting" | "stopping" | "resetting";
progressMsg: string | null;
error: string | null;
completed: boolean;
onForceStop: () => void;
onClose: () => void;
}
const operationLabels: Record<string, string> = {
starting: "Starting",
stopping: "Stopping",
resetting: "Resetting",
};
export default function ContainerProgressModal({
projectName,
operation,
progressMsg,
error,
completed,
onForceStop,
onClose,
}: Props) {
const overlayRef = useRef<HTMLDivElement>(null);
// Auto-close on success after 800ms
useEffect(() => {
if (completed && !error) {
const timer = setTimeout(onClose, 800);
return () => clearTimeout(timer);
}
}, [completed, error, onClose]);
// Escape to close (only when completed or error)
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape" && (completed || error)) onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [completed, error, onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current && (completed || error)) onClose();
},
[completed, error, onClose],
);
const inProgress = !completed && !error;
return (
<div
ref={overlayRef}
onClick={handleOverlayClick}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
>
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-80 shadow-xl text-center">
<h3 className="text-sm font-semibold mb-4">
{operationLabels[operation]} &ldquo;{projectName}&rdquo;
</h3>
{/* Spinner / checkmark / error icon */}
<div className="flex justify-center mb-3">
{error ? (
<span className="text-3xl text-[var(--error)]"></span>
) : completed ? (
<span className="text-3xl text-[var(--success)]"></span>
) : (
<div className="w-8 h-8 border-2 border-[var(--accent)] border-t-transparent rounded-full animate-spin" />
)}
</div>
{/* Progress message */}
<p className="text-xs text-[var(--text-secondary)] min-h-[1.25rem] mb-4">
{error
? <span className="text-[var(--error)]">{error}</span>
: completed
? "Done!"
: progressMsg ?? `${operationLabels[operation]}...`}
</p>
{/* Buttons */}
<div className="flex justify-center gap-2">
{inProgress && (
<button
onClick={(e) => { e.stopPropagation(); onForceStop(); }}
className="px-3 py-1.5 text-xs text-[var(--error)] border border-[var(--error)]/30 rounded hover:bg-[var(--error)]/10 transition-colors"
>
Force Stop
</button>
)}
{(completed || error) && (
<button
onClick={(e) => { e.stopPropagation(); onClose(); }}
className="px-3 py-1.5 text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)] border border-[var(--border-color)] rounded transition-colors"
>
Close
</button>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,93 @@
import { useEffect, useState } from "react";
import type { EnvVar } from "../../lib/types";
import Button from "../ui/Button";
import { monoInputClass } from "../ui/Field";
interface Props {
envVars: EnvVar[];
disabled: boolean;
disabledReason?: string;
onSave: (vars: EnvVar[]) => Promise<unknown>;
}
/** Env-var table. Used inline in Project Home → Config and in global Settings. */
export default function EnvVarsEditor({
envVars: initial,
disabled,
disabledReason,
onSave,
}: Props) {
const [vars, setVars] = useState<EnvVar[]>(initial);
useEffect(() => {
setVars(initial);
}, [initial]);
const updateVar = (index: number, field: keyof EnvVar, value: string) => {
const updated = [...vars];
updated[index] = { ...updated[index], [field]: value };
setVars(updated);
};
return (
<div className="space-y-2">
{disabled && disabledReason && (
<p className="px-2 py-1.5 bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)] text-xs text-[var(--warning)]">
{disabledReason}
</p>
)}
{vars.length === 0 && (
<p className="text-xs text-[var(--text-secondary)]">
No environment variables configured.
</p>
)}
{vars.map((ev, i) => (
<div key={i} className="flex gap-2 items-center">
<input
value={ev.key}
onChange={(e) => updateVar(i, "key", e.target.value)}
onBlur={() => onSave(vars)}
placeholder="KEY"
aria-label={`Environment variable ${i + 1} name`}
disabled={disabled}
className={`w-2/5 ${monoInputClass}`}
/>
<input
value={ev.value}
onChange={(e) => updateVar(i, "value", e.target.value)}
onBlur={() => onSave(vars)}
placeholder="value"
aria-label={`Environment variable ${i + 1} value`}
disabled={disabled}
className={`flex-1 ${monoInputClass}`}
/>
<Button
variant="danger"
disabled={disabled}
aria-label={`Remove environment variable ${ev.key || i + 1}`}
onClick={() => {
const updated = vars.filter((_, j) => j !== i);
setVars(updated);
onSave(updated);
}}
>
Remove
</Button>
</div>
))}
<Button
disabled={disabled}
onClick={() => {
const updated = [...vars, { key: "", value: "" }];
setVars(updated);
onSave(updated);
}}
>
+ Add variable
</Button>
</div>
);
}
+23 -111
View File
@@ -1,5 +1,7 @@
import { useState, useEffect, useRef, useCallback } from "react";
import type { EnvVar } from "../../lib/types"; import type { EnvVar } from "../../lib/types";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
import EnvVarsEditor from "./EnvVarsEditor";
interface Props { interface Props {
envVars: EnvVar[]; envVars: EnvVar[];
@@ -8,117 +10,27 @@ interface Props {
onClose: () => void; onClose: () => void;
} }
export default function EnvVarsModal({ envVars: initial, disabled, onSave, onClose }: Props) { /** Global env vars (Settings). Per-project vars live inline in Config → Access. */
const [vars, setVars] = useState<EnvVar[]>(initial); export default function EnvVarsModal({ envVars, disabled, onSave, onClose }: Props) {
const overlayRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
const updateVar = (index: number, field: keyof EnvVar, value: string) => {
const updated = [...vars];
updated[index] = { ...updated[index], [field]: value };
setVars(updated);
};
const removeVar = async (index: number) => {
const updated = vars.filter((_, i) => i !== index);
setVars(updated);
try { await onSave(updated); } catch (err) {
console.error("Failed to remove environment variable:", err);
}
};
const addVar = async () => {
const updated = [...vars, { key: "", value: "" }];
setVars(updated);
try { await onSave(updated); } catch (err) {
console.error("Failed to add environment variable:", err);
}
};
const handleBlur = async () => {
try { await onSave(vars); } catch (err) {
console.error("Failed to update environment variables:", err);
}
};
return ( return (
<div <Modal
ref={overlayRef} title="Environment Variables"
onClick={handleOverlayClick} onClose={onClose}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" widthClassName="w-[36rem]"
footer={<Button onClick={onClose}>Close</Button>}
> >
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[36rem] shadow-xl max-h-[80vh] overflow-y-auto"> <EnvVarsEditor
<h2 className="text-lg font-semibold mb-4">Environment Variables</h2> envVars={envVars}
disabled={disabled}
{disabled && ( disabledReason="Container must be stopped to change environment variables."
<div className="px-2 py-1.5 mb-3 bg-[var(--warning)]/15 border border-[var(--warning)]/30 rounded text-xs text-[var(--warning)]"> onSave={async (vars) => {
Container must be stopped to change environment variables. try {
</div> await onSave(vars);
)} } catch (err) {
console.error("Failed to update environment variables:", err);
<div className="space-y-2 mb-4"> }
{vars.length === 0 && ( }}
<p className="text-xs text-[var(--text-secondary)]">No environment variables configured.</p> />
)} </Modal>
{vars.map((ev, i) => (
<div key={i} className="flex gap-2 items-center">
<input
value={ev.key}
onChange={(e) => updateVar(i, "key", e.target.value)}
onBlur={handleBlur}
placeholder="KEY"
disabled={disabled}
className="w-2/5 px-2 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] disabled:opacity-50 font-mono"
/>
<input
value={ev.value}
onChange={(e) => updateVar(i, "value", e.target.value)}
onBlur={handleBlur}
placeholder="value"
disabled={disabled}
className="flex-1 px-2 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] disabled:opacity-50 font-mono"
/>
<button
onClick={() => removeVar(i)}
disabled={disabled}
className="px-2 py-1.5 text-sm text-[var(--error)] hover:bg-[var(--bg-primary)] rounded disabled:opacity-50 transition-colors"
>
x
</button>
</div>
))}
</div>
<div className="flex justify-between items-center">
<button
onClick={addVar}
disabled={disabled}
className="text-sm text-[var(--accent)] hover:text-[var(--accent-hover)] disabled:opacity-50 transition-colors"
>
+ Add variable
</button>
<button
onClick={onClose}
className="px-4 py-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
Close
</button>
</div>
</div>
</div>
); );
} }
@@ -1,197 +0,0 @@
import { useEffect, useRef, useCallback } from "react";
import { useFileManager } from "../../hooks/useFileManager";
interface Props {
projectId: string;
projectName: string;
onClose: () => void;
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}
export default function FileManagerModal({ projectId, projectName, onClose }: Props) {
const {
currentPath,
entries,
loading,
error,
navigate,
goUp,
refresh,
downloadFile,
uploadFile,
} = useFileManager(projectId);
const overlayRef = useRef<HTMLDivElement>(null);
// Load initial directory
useEffect(() => {
navigate("/workspace");
}, [navigate]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
// Build breadcrumbs from current path
const breadcrumbs = currentPath === "/"
? [{ label: "/", path: "/" }]
: currentPath.split("/").reduce<{ label: string; path: string }[]>((acc, part, i) => {
if (i === 0) {
acc.push({ label: "/", path: "/" });
} else if (part) {
const parentPath = acc[acc.length - 1].path;
const fullPath = parentPath === "/" ? `/${part}` : `${parentPath}/${part}`;
acc.push({ label: part, path: fullPath });
}
return acc;
}, []);
return (
<div
ref={overlayRef}
onClick={handleOverlayClick}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
>
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg shadow-xl w-[36rem] max-h-[80vh] flex flex-col">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--border-color)] flex-shrink-0">
<h2 className="text-sm font-semibold">Files {projectName}</h2>
<button
onClick={onClose}
className="text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
×
</button>
</div>
{/* Path bar */}
<div className="flex items-center gap-1 px-4 py-2 border-b border-[var(--border-color)] text-xs overflow-x-auto flex-shrink-0">
{breadcrumbs.map((crumb, i) => (
<span key={crumb.path} className="flex items-center gap-1">
{i > 0 && <span className="text-[var(--text-secondary)]">/</span>}
<button
onClick={() => navigate(crumb.path)}
className="text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors whitespace-nowrap"
>
{crumb.label}
</button>
</span>
))}
<div className="flex-1" />
<button
onClick={refresh}
disabled={loading}
className="text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors disabled:opacity-50 px-1"
title="Refresh"
>
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto min-h-0">
{error && (
<div className="px-4 py-2 text-xs text-[var(--error)]">{error}</div>
)}
{loading && entries.length === 0 ? (
<div className="px-4 py-8 text-center text-xs text-[var(--text-secondary)]">
Loading...
</div>
) : (
<table className="w-full text-xs">
<tbody>
{/* Go up entry */}
{currentPath !== "/" && (
<tr
onClick={() => goUp()}
className="cursor-pointer hover:bg-[var(--bg-tertiary)] transition-colors"
>
<td className="px-4 py-1.5 text-[var(--text-primary)]">..</td>
<td></td>
<td></td>
<td></td>
</tr>
)}
{entries.map((entry) => (
<tr
key={entry.name}
onClick={() => entry.is_directory && navigate(entry.path)}
className={`${
entry.is_directory ? "cursor-pointer" : ""
} hover:bg-[var(--bg-tertiary)] transition-colors`}
>
<td className="px-4 py-1.5">
<span className={entry.is_directory ? "text-[var(--accent)]" : "text-[var(--text-primary)]"}>
{entry.is_directory ? "📁 " : ""}{entry.name}
</span>
</td>
<td className="px-2 py-1.5 text-[var(--text-secondary)] text-right whitespace-nowrap">
{!entry.is_directory && formatSize(entry.size)}
</td>
<td className="px-2 py-1.5 text-[var(--text-secondary)] whitespace-nowrap">
{entry.modified}
</td>
<td className="px-2 py-1.5 text-right">
{!entry.is_directory && (
<button
onClick={(e) => {
e.stopPropagation();
downloadFile(entry);
}}
className="text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors px-1"
title="Download"
>
</button>
)}
</td>
</tr>
))}
{entries.length === 0 && !loading && (
<tr>
<td colSpan={4} className="px-4 py-8 text-center text-[var(--text-secondary)]">
Empty directory
</td>
</tr>
)}
</tbody>
</table>
)}
</div>
{/* Footer */}
<div className="flex items-center justify-between px-4 py-3 border-t border-[var(--border-color)] flex-shrink-0">
<button
onClick={uploadFile}
className="text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors"
>
Upload file
</button>
<button
onClick={onClose}
className="px-4 py-1.5 text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
Close
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,142 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import PermissionModeControl, {
effectivePermissionMode,
permissionModePatch,
} from "./PermissionModeControl";
import type { Project } from "../../lib/types";
const baseProject: Project = {
id: "p1",
name: "api-server",
paths: [{ host_path: "/src/api", mount_name: "api" }],
container_id: null,
status: "running",
backend: "anthropic",
bedrock_config: null,
ollama_config: null,
openai_compatible_config: null,
allow_docker_access: false,
sandbox_mode_enabled: true,
mission_control_enabled: false,
auth_bridge_enabled: false,
use_shared_auth_token: true,
full_permissions: false,
permission_mode: null,
ssh_key_path: null,
git_token: null,
git_user_name: null,
git_user_email: null,
custom_env_vars: [],
port_mappings: [],
claude_instructions: null,
claude_code_settings: null,
renamed_session_names: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
describe("effectivePermissionMode", () => {
it("falls back to the legacy boolean when permission_mode is null", () => {
expect(effectivePermissionMode(baseProject)).toBe("default");
expect(
effectivePermissionMode({ ...baseProject, full_permissions: true }),
).toBe("bypass");
});
it("prefers permission_mode when it is set", () => {
expect(
effectivePermissionMode({
...baseProject,
permission_mode: "plan",
full_permissions: true,
}),
).toBe("plan");
});
});
describe("permissionModePatch", () => {
it("keeps the legacy full_permissions flag in sync", () => {
expect(permissionModePatch("bypass")).toEqual({
permission_mode: "bypass",
full_permissions: true,
});
expect(permissionModePatch("acceptEdits")).toEqual({
permission_mode: "acceptEdits",
full_permissions: false,
});
});
});
describe("PermissionModeControl", () => {
const onChange = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
});
it("renders all four modes as a radio group with the effective one checked", () => {
render(<PermissionModeControl project={baseProject} onChange={onChange} />);
const group = screen.getByRole("radiogroup", { name: "Permission mode" });
expect(group).toBeInTheDocument();
expect(screen.getAllByRole("radio")).toHaveLength(4);
expect(screen.getByRole("radio", { name: "Default" })).toHaveAttribute(
"aria-checked",
"true",
);
});
it("reports the picked mode", () => {
render(<PermissionModeControl project={baseProject} onChange={onChange} />);
fireEvent.click(screen.getByRole("radio", { name: "Accept Edits" }));
expect(onChange).toHaveBeenCalledWith("acceptEdits");
});
it("moves selection with the arrow keys", () => {
render(<PermissionModeControl project={baseProject} onChange={onChange} />);
fireEvent.keyDown(screen.getByRole("radiogroup", { name: "Permission mode" }), {
key: "ArrowRight",
});
expect(onChange).toHaveBeenCalledWith("acceptEdits");
});
it("shows sandbox state beside the control", () => {
render(<PermissionModeControl project={baseProject} onChange={onChange} />);
expect(screen.getByTestId("sandbox-state")).toHaveTextContent(
/Sandbox\s*ON/,
);
});
it("does not paint Bypass as dangerous while the sandbox contains it", () => {
render(
<PermissionModeControl
project={{ ...baseProject, permission_mode: "bypass" }}
onChange={onChange}
/>,
);
const bypass = screen.getByRole("radio", { name: "Bypass" });
expect(bypass.className).toContain("--accent-emphasis");
expect(bypass.className).not.toContain("--warning-emphasis");
expect(screen.getByTestId("permission-mode-hint")).toHaveTextContent(
/contained by the sandbox/i,
);
});
it("uses caution colour only when Bypass runs with the sandbox off", () => {
render(
<PermissionModeControl
project={{
...baseProject,
permission_mode: "bypass",
sandbox_mode_enabled: false,
}}
onChange={onChange}
/>,
);
const bypass = screen.getByRole("radio", { name: "Bypass" });
expect(bypass.className).toContain("--warning-emphasis");
expect(screen.getByTestId("permission-mode-hint")).toHaveTextContent(
/Caution/i,
);
});
});
@@ -0,0 +1,116 @@
import type { PermissionMode, Project } from "../../lib/types";
import SegmentedControl, { type Segment } from "../ui/SegmentedControl";
export const PERMISSION_MODES: Segment<PermissionMode>[] = [
{ value: "plan", label: "Plan", hint: "Claude proposes a plan and makes no changes." },
{ value: "default", label: "Default", hint: "Claude asks before each tool call." },
{
value: "acceptEdits",
label: "Accept Edits",
hint: "File edits are auto-approved; other tools still prompt.",
},
{
value: "bypass",
label: "Bypass",
hint: "Every tool call is auto-approved (--dangerously-skip-permissions).",
},
];
/**
* `permission_mode` is nullable for projects saved before it existed; fall back
* to the legacy boolean.
*/
export function effectivePermissionMode(project: Project): PermissionMode {
return project.permission_mode ?? (project.full_permissions ? "bypass" : "default");
}
/**
* The patch to apply when the user picks a mode. `full_permissions` is kept in
* sync so anything still reading the legacy field cannot drift.
*/
export function permissionModePatch(mode: PermissionMode): Partial<Project> {
return { permission_mode: mode, full_permissions: mode === "bypass" };
}
interface Props {
project: Project;
onChange: (mode: PermissionMode) => void;
disabled?: boolean;
/** Explanation of why the control is disabled, shown beneath it. */
disabledReason?: string;
}
/**
* The hero control. Per §B3.3: Bypass is only painted as caution when the
* sandbox is OFF with the sandbox ON, bypassing prompts is contained.
*/
export default function PermissionModeControl({
project,
onChange,
disabled = false,
disabledReason,
}: Props) {
const mode = effectivePermissionMode(project);
const sandboxOn = project.sandbox_mode_enabled;
const uncontainedBypass = mode === "bypass" && !sandboxOn;
const segments = PERMISSION_MODES.map((segment) =>
segment.value === "bypass" ? { ...segment, caution: !sandboxOn } : segment,
);
const active = PERMISSION_MODES.find((s) => s.value === mode);
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<span className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)]">
Permission mode
</span>
<SegmentedControl
label="Permission mode"
segments={segments}
value={mode}
onChange={onChange}
disabled={disabled}
/>
<span
className="text-xs text-[var(--text-secondary)]"
data-testid="sandbox-state"
>
Sandbox{" "}
<span
className={
sandboxOn ? "text-[var(--success)] font-semibold" : "text-[var(--warning)] font-semibold"
}
>
{sandboxOn ? "ON" : "OFF"}
</span>
{sandboxOn ? " — bubblewrap isolation" : " — no filesystem/network isolation"}
</span>
</div>
<p
className={`text-xs leading-snug ${
uncontainedBypass ? "text-[var(--warning)]" : "text-[var(--text-secondary)]"
}`}
data-testid="permission-mode-hint"
>
{uncontainedBypass
? "Caution: every tool call is auto-approved and the sandbox is off, so nothing contains what Claude runs."
: mode === "bypass"
? "Every tool call is auto-approved — contained by the sandbox."
: (active?.hint ?? "")}
</p>
{project.status === "running" && (
<p className="text-xs text-[var(--text-disabled)]">
Applies to terminals opened from now on.
</p>
)}
{disabled && disabledReason && (
<p className="text-xs text-[var(--text-disabled)]">{disabledReason}</p>
)}
</div>
);
}
@@ -0,0 +1,128 @@
import { useEffect, useState } from "react";
import type { PortMapping } from "../../lib/types";
import Button from "../ui/Button";
import { monoInputClass, selectClass } from "../ui/Field";
interface Props {
portMappings: PortMapping[];
disabled: boolean;
disabledReason?: string;
onSave: (mappings: PortMapping[]) => Promise<unknown>;
}
export default function PortMappingsEditor({
portMappings: initial,
disabled,
disabledReason,
onSave,
}: Props) {
const [mappings, setMappings] = useState<PortMapping[]>(initial);
useEffect(() => {
setMappings(initial);
}, [initial]);
const updatePort = (
index: number,
field: "host_port" | "container_port",
value: string,
) => {
const updated = [...mappings];
const num = parseInt(value, 10);
updated[index] = { ...updated[index], [field]: isNaN(num) ? 0 : num };
setMappings(updated);
};
return (
<div className="space-y-2">
{disabled && disabledReason && (
<p className="px-2 py-1.5 bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)] text-xs text-[var(--warning)]">
{disabledReason}
</p>
)}
{mappings.length === 0 && (
<p className="text-xs text-[var(--text-secondary)]">No port mappings configured.</p>
)}
{mappings.length > 0 && (
<div className="flex gap-2 items-center text-xs text-[var(--text-secondary)] px-0.5">
<span className="w-[28%]">Host port</span>
<span className="w-[28%]">Container port</span>
<span className="w-[22%]">Protocol</span>
<span className="flex-1" />
</div>
)}
{mappings.map((pm, i) => (
<div key={i} className="flex gap-2 items-center">
<input
type="number"
min="1"
max="65535"
value={pm.host_port || ""}
onChange={(e) => updatePort(i, "host_port", e.target.value)}
onBlur={() => onSave(mappings)}
placeholder="8080"
aria-label={`Host port ${i + 1}`}
disabled={disabled}
className={`w-[28%] ${monoInputClass}`}
/>
<input
type="number"
min="1"
max="65535"
value={pm.container_port || ""}
onChange={(e) => updatePort(i, "container_port", e.target.value)}
onBlur={() => onSave(mappings)}
placeholder="8080"
aria-label={`Container port ${i + 1}`}
disabled={disabled}
className={`w-[28%] ${monoInputClass}`}
/>
<select
value={pm.protocol}
aria-label={`Protocol ${i + 1}`}
onChange={(e) => {
const updated = [...mappings];
updated[i] = { ...updated[i], protocol: e.target.value };
setMappings(updated);
onSave(updated);
}}
disabled={disabled}
className={`w-[22%] ${selectClass}`}
>
<option value="tcp">TCP</option>
<option value="udp">UDP</option>
</select>
<Button
variant="danger"
disabled={disabled}
aria-label={`Remove port mapping ${i + 1}`}
onClick={() => {
const updated = mappings.filter((_, j) => j !== i);
setMappings(updated);
onSave(updated);
}}
>
Remove
</Button>
</div>
))}
<Button
disabled={disabled}
onClick={() => {
const updated = [
...mappings,
{ host_port: 0, container_port: 0, protocol: "tcp" },
];
setMappings(updated);
onSave(updated);
}}
>
+ Add port mapping
</Button>
</div>
);
}
@@ -1,157 +0,0 @@
import { useState, useEffect, useRef, useCallback } from "react";
import type { PortMapping } from "../../lib/types";
interface Props {
portMappings: PortMapping[];
disabled: boolean;
onSave: (mappings: PortMapping[]) => Promise<void>;
onClose: () => void;
}
export default function PortMappingsModal({ portMappings: initial, disabled, onSave, onClose }: Props) {
const [mappings, setMappings] = useState<PortMapping[]>(initial);
const overlayRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
const updatePort = (index: number, field: "host_port" | "container_port", value: string) => {
const updated = [...mappings];
const num = parseInt(value, 10);
updated[index] = { ...updated[index], [field]: isNaN(num) ? 0 : num };
setMappings(updated);
};
const updateProtocol = (index: number, value: string) => {
const updated = [...mappings];
updated[index] = { ...updated[index], protocol: value };
setMappings(updated);
};
const removeMapping = async (index: number) => {
const updated = mappings.filter((_, i) => i !== index);
setMappings(updated);
try { await onSave(updated); } catch (err) {
console.error("Failed to remove port mapping:", err);
}
};
const addMapping = async () => {
const updated = [...mappings, { host_port: 0, container_port: 0, protocol: "tcp" }];
setMappings(updated);
try { await onSave(updated); } catch (err) {
console.error("Failed to add port mapping:", err);
}
};
const handleBlur = async () => {
try { await onSave(mappings); } catch (err) {
console.error("Failed to update port mappings:", err);
}
};
return (
<div
ref={overlayRef}
onClick={handleOverlayClick}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
>
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[36rem] shadow-xl max-h-[80vh] overflow-y-auto">
<h2 className="text-lg font-semibold mb-2">Port Mappings</h2>
<p className="text-xs text-[var(--text-secondary)] mb-4">
Map host ports to container ports. Services can be started after the container is running.
</p>
{disabled && (
<div className="px-2 py-1.5 mb-3 bg-[var(--warning)]/15 border border-[var(--warning)]/30 rounded text-xs text-[var(--warning)]">
Container must be stopped to change port mappings.
</div>
)}
<div className="space-y-2 mb-4">
{mappings.length === 0 && (
<p className="text-xs text-[var(--text-secondary)]">No port mappings configured.</p>
)}
{mappings.length > 0 && (
<div className="flex gap-2 items-center text-xs text-[var(--text-secondary)] px-0.5">
<span className="w-[30%]">Host Port</span>
<span className="w-[30%]">Container Port</span>
<span className="w-[25%]">Protocol</span>
<span className="w-[15%]" />
</div>
)}
{mappings.map((pm, i) => (
<div key={i} className="flex gap-2 items-center">
<input
type="number"
min="1"
max="65535"
value={pm.host_port || ""}
onChange={(e) => updatePort(i, "host_port", e.target.value)}
onBlur={handleBlur}
placeholder="8080"
disabled={disabled}
className="w-[30%] px-2 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] disabled:opacity-50 font-mono"
/>
<input
type="number"
min="1"
max="65535"
value={pm.container_port || ""}
onChange={(e) => updatePort(i, "container_port", e.target.value)}
onBlur={handleBlur}
placeholder="8080"
disabled={disabled}
className="w-[30%] px-2 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] disabled:opacity-50 font-mono"
/>
<select
value={pm.protocol}
onChange={(e) => { updateProtocol(i, e.target.value); handleBlur(); }}
disabled={disabled}
className="w-[25%] px-2 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded text-sm text-[var(--text-primary)] focus:outline-none focus:border-[var(--accent)] disabled:opacity-50"
>
<option value="tcp">TCP</option>
<option value="udp">UDP</option>
</select>
<button
onClick={() => removeMapping(i)}
disabled={disabled}
className="w-[15%] px-2 py-1.5 text-sm text-[var(--error)] hover:bg-[var(--bg-primary)] rounded disabled:opacity-50 transition-colors text-center"
>
x
</button>
</div>
))}
</div>
<div className="flex justify-between items-center">
<button
onClick={addMapping}
disabled={disabled}
className="text-sm text-[var(--accent)] hover:text-[var(--accent-hover)] disabled:opacity-50 transition-colors"
>
+ Add port mapping
</button>
<button
onClick={onClose}
className="px-4 py-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
Close
</button>
</div>
</div>
</div>
);
}
@@ -1,140 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, act } from "@testing-library/react";
import ProjectCard from "./ProjectCard";
import type { Project } from "../../lib/types";
// Mock Tauri dialog plugin
vi.mock("@tauri-apps/plugin-dialog", () => ({
open: vi.fn(),
}));
// Mock hooks
const mockUpdate = vi.fn();
const mockStart = vi.fn();
const mockStop = vi.fn();
const mockRebuild = vi.fn();
const mockRemove = vi.fn();
vi.mock("../../hooks/useProjects", () => ({
useProjects: () => ({
start: mockStart,
stop: mockStop,
rebuild: mockRebuild,
remove: mockRemove,
update: mockUpdate,
}),
}));
vi.mock("../../hooks/useTerminal", () => ({
useTerminal: () => ({
open: vi.fn(),
}),
}));
vi.mock("../../hooks/useMcpServers", () => ({
useMcpServers: () => ({
mcpServers: [],
refresh: vi.fn(),
add: vi.fn(),
update: vi.fn(),
remove: vi.fn(),
}),
}));
let mockSelectedProjectId: string | null = null;
vi.mock("../../store/appState", () => ({
useAppState: vi.fn((selector) =>
selector({
selectedProjectId: mockSelectedProjectId,
setSelectedProject: vi.fn(),
})
),
}));
const mockProject: Project = {
id: "test-1",
name: "Test Project",
paths: [{ host_path: "/home/user/project", mount_name: "project" }],
container_id: null,
status: "stopped",
backend: "anthropic",
bedrock_config: null,
allow_docker_access: false,
ssh_key_path: null,
git_token: null,
git_user_name: null,
git_user_email: null,
custom_env_vars: [],
port_mappings: [],
claude_instructions: null,
enabled_mcp_servers: [],
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
describe("ProjectCard", () => {
beforeEach(() => {
vi.clearAllMocks();
mockSelectedProjectId = null;
});
it("renders project name and path", () => {
render(<ProjectCard project={mockProject} />);
expect(screen.getByText("Test Project")).toBeInTheDocument();
expect(screen.getByText("/workspace/project")).toBeInTheDocument();
});
it("card root has min-w-0 and overflow-hidden to contain content", () => {
const { container } = render(<ProjectCard project={mockProject} />);
const card = container.firstElementChild;
expect(card).not.toBeNull();
expect(card!.className).toContain("min-w-0");
expect(card!.className).toContain("overflow-hidden");
});
describe("when selected and showing config", () => {
beforeEach(() => {
mockSelectedProjectId = "test-1";
});
it("expanded area has min-w-0 and overflow-hidden", () => {
const { container } = render(<ProjectCard project={mockProject} />);
// The expanded section (mt-2 ml-4) contains the auth/action/config controls
const expandedSection = container.querySelector(".ml-4.mt-2");
expect(expandedSection).not.toBeNull();
expect(expandedSection!.className).toContain("min-w-0");
expect(expandedSection!.className).toContain("overflow-hidden");
});
it("folder path inputs use min-w-0 to allow shrinking", async () => {
const { container } = render(<ProjectCard project={mockProject} />);
// Click Config button to show config panel
await act(async () => {
fireEvent.click(screen.getByText("Config"));
});
// After config is shown, check the folder host_path input has min-w-0
const hostPathInputs = container.querySelectorAll('input[placeholder="/path/to/folder"]');
expect(hostPathInputs.length).toBeGreaterThan(0);
expect(hostPathInputs[0].className).toContain("min-w-0");
});
it("config panel container has overflow-hidden", async () => {
const { container } = render(<ProjectCard project={mockProject} />);
// Click Config button
await act(async () => {
fireEvent.click(screen.getByText("Config"));
});
// The config panel has border-t and overflow containment classes
const allDivs = container.querySelectorAll("div");
const configPanel = Array.from(allDivs).find(
(div) => div.className.includes("border-t") && div.className.includes("min-w-0")
);
expect(configPanel).toBeDefined();
expect(configPanel!.className).toContain("overflow-hidden");
});
});
});
File diff suppressed because it is too large Load Diff
+12 -15
View File
@@ -1,35 +1,32 @@
import { useState } from "react"; import { useState } from "react";
import { useProjects } from "../../hooks/useProjects"; import { useProjects } from "../../hooks/useProjects";
import ProjectCard from "./ProjectCard"; import ProjectRow from "./ProjectRow";
import AddProjectDialog from "./AddProjectDialog"; import AddProjectDialog from "./AddProjectDialog";
import Button from "../ui/Button";
export default function ProjectList() { export default function ProjectList() {
const { projects } = useProjects(); const { projects } = useProjects();
const [showAdd, setShowAdd] = useState(false); const [showAdd, setShowAdd] = useState(false);
return ( return (
<div className="p-3"> <div className="p-2">
<div className="flex items-center justify-between px-2 py-1 mb-2"> <div className="flex items-center justify-between px-1 py-1 mb-1.5">
<span className="text-xs font-semibold uppercase text-[var(--text-secondary)]"> <span className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)]">
Projects Projects
</span> </span>
<button <Button onClick={() => setShowAdd(true)} aria-label="Add project">
onClick={() => setShowAdd(true)} + Add
className="text-lg leading-none text-[var(--text-secondary)] hover:text-[var(--accent)] transition-colors" </Button>
title="Add project"
>
+
</button>
</div> </div>
{projects.length === 0 ? ( {projects.length === 0 ? (
<p className="px-2 text-sm text-[var(--text-secondary)]"> <p className="px-1 text-xs text-[var(--text-secondary)]">
No projects yet. Click + to add one. No projects yet use + Add to create one.
</p> </p>
) : ( ) : (
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-0.5">
{projects.map((project) => ( {projects.map((project) => (
<ProjectCard key={project.id} project={project} /> <ProjectRow key={project.id} project={project} />
))} ))}
</div> </div>
)} )}
@@ -0,0 +1,148 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import ProjectRow from "./ProjectRow";
import type { Project } from "../../lib/types";
const mockStart = vi.fn();
const mockStop = vi.fn();
const mockOpenClaudeTerminal = vi.fn();
vi.mock("../../hooks/useProjectActions", () => ({
useProjectActions: () => ({
busy: false,
backingUp: false,
handleStart: mockStart,
handleStop: mockStop,
handleReset: vi.fn(),
handleBackup: vi.fn(),
openClaudeTerminal: mockOpenClaudeTerminal,
openShell: vi.fn(),
openTerminalWithCommand: vi.fn(),
}),
}));
const mockOpenProjectHome = vi.fn();
let storeState: Record<string, unknown> = {};
vi.mock("../../store/appState", async () => {
const actual = await vi.importActual<typeof import("../../store/appState")>(
"../../store/appState",
);
return {
...actual,
useAppState: vi.fn((selector: (s: unknown) => unknown) => selector(storeState)),
};
});
const baseProject: Project = {
id: "test-1",
name: "Test Project",
paths: [{ host_path: "/home/user/project", mount_name: "project" }],
container_id: null,
status: "stopped",
backend: "anthropic",
bedrock_config: null,
ollama_config: null,
openai_compatible_config: null,
allow_docker_access: false,
sandbox_mode_enabled: true,
mission_control_enabled: false,
auth_bridge_enabled: false,
use_shared_auth_token: true,
full_permissions: false,
permission_mode: null,
ssh_key_path: null,
git_token: null,
git_user_name: null,
git_user_email: null,
custom_env_vars: [],
port_mappings: [],
claude_instructions: null,
claude_code_settings: null,
renamed_session_names: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
function setStore(overrides: Record<string, unknown> = {}) {
storeState = {
activeTabKey: null,
selectedProjectId: null,
openProjectHome: mockOpenProjectHome,
containerProgress: {},
...overrides,
};
}
describe("ProjectRow", () => {
beforeEach(() => {
vi.clearAllMocks();
setStore();
});
it("renders project name and mount path", () => {
render(<ProjectRow project={baseProject} />);
expect(screen.getByText("Test Project")).toBeInTheDocument();
expect(screen.getByText("/workspace/project")).toBeInTheDocument();
});
it("row root has min-w-0 and overflow-hidden to contain content", () => {
const { container } = render(<ProjectRow project={baseProject} />);
const row = container.firstElementChild;
expect(row).not.toBeNull();
expect(row!.className).toContain("min-w-0");
expect(row!.className).toContain("overflow-hidden");
});
it("communicates status with a word, not colour alone", () => {
render(<ProjectRow project={baseProject} />);
expect(screen.getAllByText("Stopped").length).toBeGreaterThan(0);
render(<ProjectRow project={{ ...baseProject, status: "error" }} />);
expect(screen.getAllByText("Error").length).toBeGreaterThan(0);
});
it("selecting the row opens that project's home tab instead of expanding in place", () => {
render(<ProjectRow project={baseProject} />);
fireEvent.click(screen.getByText("Test Project"));
expect(mockOpenProjectHome).toHaveBeenCalledWith("test-1");
// No config form is rendered in the sidebar any more.
expect(screen.queryByPlaceholderText("/path/to/folder")).toBeNull();
});
it("offers start when stopped and stop when running", () => {
const { unmount } = render(<ProjectRow project={baseProject} />);
fireEvent.click(screen.getByRole("button", { name: "Start Test Project" }));
expect(mockStart).toHaveBeenCalled();
unmount();
render(<ProjectRow project={{ ...baseProject, status: "running" }} />);
fireEvent.click(screen.getByRole("button", { name: "Stop Test Project" }));
expect(mockStop).toHaveBeenCalled();
});
it("only allows opening a terminal while the container runs", () => {
const { unmount } = render(<ProjectRow project={baseProject} />);
expect(
screen.getByRole("button", {
name: "Open a Claude terminal for Test Project",
}),
).toBeDisabled();
unmount();
render(<ProjectRow project={{ ...baseProject, status: "running" }} />);
fireEvent.click(
screen.getByRole("button", {
name: "Open a Claude terminal for Test Project",
}),
);
expect(mockOpenClaudeTerminal).toHaveBeenCalled();
});
it("shows container progress inline rather than in a blocking modal", () => {
setStore({ containerProgress: { "test-1": "Pulling image…" } });
render(<ProjectRow project={{ ...baseProject, status: "starting" }} />);
expect(screen.getByText("Pulling image…")).toBeInTheDocument();
expect(screen.queryByRole("dialog")).toBeNull();
});
});
+140
View File
@@ -0,0 +1,140 @@
import { useShallow } from "zustand/react/shallow";
import type { Project } from "../../lib/types";
import { useAppState, homeTabKey } from "../../store/appState";
import { useProjectActions } from "../../hooks/useProjectActions";
import { ProjectStatusIndicator } from "../ui/StatusIndicator";
interface Props {
project: Project;
}
/**
* Sidebar rows are select-only: name, paths, status, and hover controls.
* Clicking a row opens (or focuses) that project's Project Home tab the
* settings form no longer lives in a 280px accordion.
*/
export default function ProjectRow({ project }: Props) {
const { activeTabKey, selectedProjectId, openProjectHome, progress } = useAppState(
useShallow((s) => ({
activeTabKey: s.activeTabKey,
selectedProjectId: s.selectedProjectId,
openProjectHome: s.openProjectHome,
progress: s.containerProgress[project.id],
})),
);
const { busy, handleStart, handleStop, openClaudeTerminal } =
useProjectActions(project);
const isSelected =
activeTabKey === homeTabKey(project.id) || selectedProjectId === project.id;
const isRunning = project.status === "running";
const isTransitioning =
project.status === "starting" || project.status === "stopping";
return (
<div
className={`group relative px-2 py-1.5 rounded-[var(--radius-control)] transition-colors min-w-0 overflow-hidden ${
isSelected
? "bg-[var(--bg-tertiary)]"
: "hover:bg-[var(--bg-tertiary)]"
}`}
>
<button
type="button"
onClick={() => openProjectHome(project.id)}
aria-current={isSelected ? "true" : undefined}
className="w-full text-left min-w-0"
>
<div className="flex items-center gap-2 min-w-0">
<ProjectStatusIndicator status={project.status} iconOnly />
<span className="text-[13px] font-medium truncate flex-1 text-[var(--text-primary)]">
{project.name}
</span>
{/* Space reserved for the hover controls so the name never jumps. */}
<span className="w-[3.75rem] flex-shrink-0" aria-hidden="true" />
</div>
<div className="mt-0.5 ml-4 space-y-0.5 min-w-0">
{project.paths.map((pp, i) => (
<div
key={i}
className="text-xs text-[var(--text-secondary)] truncate font-mono"
>
/workspace/{pp.mount_name}
</div>
))}
<div className="text-xs">
{isTransitioning ? (
<span className="text-[var(--warning)] truncate block">
{progress ?? `${project.status}`}
</span>
) : (
<ProjectStatusIndicator
status={project.status}
className="text-xs"
/>
)}
</div>
</div>
</button>
{/* Hover / focus-within controls */}
<div className="absolute top-1.5 right-2 flex items-center gap-0.5 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">
<button
type="button"
disabled={busy}
// While a container is mid-transition this stays live so it can act
// as the force-stop that the old progress modal used to offer.
onClick={() => (isRunning || isTransitioning ? handleStop() : handleStart())}
title={
isTransitioning
? `Force stop ${project.name}`
: isRunning
? `Stop ${project.name}`
: `Start ${project.name}`
}
aria-label={
isTransitioning
? `Force stop ${project.name}`
: isRunning
? `Stop ${project.name}`
: `Start ${project.name}`
}
className="w-6 h-6 flex items-center justify-center rounded-[var(--radius-control)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-primary)] disabled:text-[var(--text-disabled)] transition-colors"
>
{isRunning || isTransitioning ? (
<svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<rect x="6" y="6" width="12" height="12" rx="1.5" />
</svg>
) : (
<svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M8 5.5v13l11-6.5z" />
</svg>
)}
</button>
<button
type="button"
disabled={!isRunning}
onClick={() => openClaudeTerminal()}
title={`Open a Claude terminal for ${project.name}`}
aria-label={`Open a Claude terminal for ${project.name}`}
className="w-6 h-6 flex items-center justify-center rounded-[var(--radius-control)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-primary)] disabled:text-[var(--text-disabled)] transition-colors"
>
<svg
className="w-3.5 h-3.5"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<rect x="3" y="4" width="18" height="16" rx="2" />
<polyline points="7 9 10 12 7 15" />
<line x1="13" y1="15" x2="17" y2="15" />
</svg>
</button>
</div>
</div>
);
}
@@ -0,0 +1,287 @@
import { useCallback, useEffect, useState } from "react";
import type { Project, ScheduledTask, SchedulerNotification } from "../../../lib/types";
import {
clearSchedulerNotifications,
getScheduledTaskLog,
getSchedulerNotifications,
listScheduledTasks,
removeScheduledTask,
runScheduledTaskNow,
setScheduledTaskEnabled,
} from "../../../lib/tauri-commands";
import { useAppState } from "../../../store/appState";
import Button from "../../ui/Button";
import Toggle from "../../ui/Toggle";
import Modal from "../../ui/Modal";
import StatusIndicator from "../../ui/StatusIndicator";
import TaskEditorModal from "./TaskEditorModal";
import { formatAge } from "./format";
interface Props {
project: Project;
}
/**
* UI for `triple-c-scheduler`, which ships in every container and until now
* had no interface beyond a CLAUDE.md paragraph.
*/
export default function AutomationTab({ project }: Props) {
const [tasks, setTasks] = useState<ScheduledTask[]>([]);
const [notifications, setNotifications] = useState<SchedulerNotification[]>([]);
const [loading, setLoading] = useState(false);
const [busyTaskId, setBusyTaskId] = useState<string | null>(null);
const [log, setLog] = useState<{ task: ScheduledTask; text: string } | null>(null);
const [confirmRemoveId, setConfirmRemoveId] = useState<string | null>(null);
/** `undefined` = closed, `null` = creating, a task = editing it. */
const [editing, setEditing] = useState<ScheduledTask | null | undefined>(undefined);
const pushToast = useAppState((s) => s.pushToast);
const running = project.status === "running";
const load = useCallback(() => {
if (!running) {
setTasks([]);
setNotifications([]);
return;
}
setLoading(true);
Promise.all([
listScheduledTasks(project.id).catch(() => [] as ScheduledTask[]),
getSchedulerNotifications(project.id).catch(
() => [] as SchedulerNotification[],
),
])
.then(([t, n]) => {
setTasks(t);
setNotifications(n);
})
.finally(() => setLoading(false));
}, [project.id, running]);
useEffect(load, [load]);
const withTask = async (taskId: string, label: string, fn: () => Promise<unknown>) => {
setBusyTaskId(taskId);
try {
await fn();
load();
} catch (e) {
pushToast({ kind: "error", message: `${label} failed`, detail: String(e) });
} finally {
setBusyTaskId(null);
}
};
const openLog = async (task: ScheduledTask) => {
setBusyTaskId(task.id);
try {
const text = await getScheduledTaskLog(project.id, task.id, 200);
setLog({ task, text });
} catch (e) {
pushToast({
kind: "error",
message: `Could not read the log for “${task.name}`,
detail: String(e),
});
} finally {
setBusyTaskId(null);
}
};
const removing = tasks.find((t) => t.id === confirmRemoveId) ?? null;
return (
<div className="p-4 space-y-6 max-w-4xl">
{/* Notifications */}
{notifications.length > 0 && (
<section className="border border-[var(--accent)]/40 bg-[var(--accent-muted)] rounded-[var(--radius-panel)]">
<header className="flex items-center justify-between px-3 py-2 border-b border-[var(--border-color)]">
<h2 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--accent)]">
{notifications.length} notification
{notifications.length === 1 ? "" : "s"}
</h2>
<Button
onClick={async () => {
try {
await clearSchedulerNotifications(project.id);
setNotifications([]);
} catch (e) {
pushToast({
kind: "error",
message: "Could not clear notifications",
detail: String(e),
});
}
}}
>
Clear all
</Button>
</header>
<ul className="divide-y divide-[var(--border-color)]">
{notifications.map((n, i) => (
<li key={`${n.task_id}-${i}`} className="px-3 py-2">
<div className="flex items-center gap-2 text-xs">
<span className="font-medium text-[var(--text-primary)]">
{n.task_name ?? n.task_id}
</span>
{n.status && (
<StatusIndicator
tone={n.status.toLowerCase() === "success" ? "ok" : "error"}
label={n.status}
/>
)}
<span className="text-[var(--text-secondary)] ml-auto">
{formatAge(n.created_at) ?? n.time ?? ""}
</span>
</div>
<p className="mt-0.5 text-xs text-[var(--text-secondary)] whitespace-pre-wrap break-words">
{n.summary ?? n.body}
</p>
</li>
))}
</ul>
</section>
)}
<section>
<div className="flex items-center justify-between mb-3">
<p className="text-xs text-[var(--text-secondary)]">
Recurring Claude Code runs managed by{" "}
<code className="font-mono text-[var(--text-primary)]">
triple-c-scheduler
</code>{" "}
inside the container.
</p>
<div className="flex items-center gap-2">
<Button onClick={load} disabled={!running || loading}>
{loading ? "Refreshing…" : "Refresh"}
</Button>
<Button variant="primary" disabled={!running} onClick={() => setEditing(null)}>
New task
</Button>
</div>
</div>
{!running ? (
<p className="text-[13px] text-[var(--text-secondary)]">
Start the container to list its scheduled tasks.
</p>
) : tasks.length === 0 && !loading ? (
<p className="text-[13px] text-[var(--text-secondary)]">
No scheduled tasks yet. Use <strong>New task</strong>, or ask Claude to add one with{" "}
<code className="font-mono">triple-c-scheduler add</code>.
</p>
) : (
<ul className="space-y-1">
{tasks.map((task) => (
<li
key={task.id}
className="flex items-center gap-3 px-3 py-2 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-control)]"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-[var(--text-primary)] truncate">
{task.name}
</span>
<span className="text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded-[var(--radius-control)] bg-[var(--bg-tertiary)] text-[var(--text-secondary)]">
{task.task_type}
</span>
</div>
<div className="text-xs text-[var(--text-secondary)] font-mono truncate">
{task.at ?? task.schedule}
{task.last_run ? ` · last run ${formatAge(task.last_run) ?? task.last_run}` : ""}
</div>
</div>
<Toggle
label={`${task.name} enabled`}
checked={task.enabled}
disabled={busyTaskId === task.id}
onChange={(v) =>
withTask(task.id, "Toggle task", () =>
setScheduledTaskEnabled(project.id, task.id, v),
)
}
/>
<Button
disabled={busyTaskId === task.id}
onClick={() =>
withTask(task.id, "Run now", () =>
runScheduledTaskNow(project.id, task.id),
)
}
>
Run now
</Button>
<Button disabled={busyTaskId === task.id} onClick={() => setEditing(task)}>
Edit
</Button>
<Button disabled={busyTaskId === task.id} onClick={() => openLog(task)}>
Log
</Button>
<Button
variant="danger"
disabled={busyTaskId === task.id}
onClick={() => setConfirmRemoveId(task.id)}
>
Remove
</Button>
</li>
))}
</ul>
)}
</section>
{editing !== undefined && (
<TaskEditorModal
project={project}
task={editing}
onClose={() => setEditing(undefined)}
onSaved={load}
/>
)}
{log && (
<Modal
title={`Log — ${log.task.name}`}
onClose={() => setLog(null)}
widthClassName="w-[46rem]"
footer={<Button onClick={() => setLog(null)}>Close</Button>}
>
<pre className="whitespace-pre-wrap break-words font-mono text-xs text-[var(--text-secondary)]">
{log.text.trim() || "(empty log)"}
</pre>
</Modal>
)}
{removing && (
<Modal
title="Remove scheduled task"
onClose={() => setConfirmRemoveId(null)}
widthClassName="w-[26rem]"
footer={
<>
<Button variant="ghost" onClick={() => setConfirmRemoveId(null)}>
Cancel
</Button>
<Button
className="bg-[var(--error-emphasis)] text-white border border-transparent hover:opacity-90"
onClick={() => {
setConfirmRemoveId(null);
withTask(removing.id, "Remove task", () =>
removeScheduledTask(project.id, removing.id),
);
}}
>
Remove
</Button>
</>
}
>
<p className="text-[13px] text-[var(--text-secondary)]">
Remove <strong className="text-[var(--text-primary)]">{removing.name}</strong>{" "}
from this container&rsquo;s scheduler?
</p>
</Modal>
)}
</div>
);
}
@@ -0,0 +1,166 @@
import { useEffect, useState } from "react";
import type {
CapabilityGroup,
ContainerCapabilities,
Project,
} from "../../../lib/types";
import { listContainerCapabilities } from "../../../lib/tauri-commands";
import Modal from "../../ui/Modal";
import Button from "../../ui/Button";
/**
* Read-only inventory of what Claude Code can do inside this container.
* Triple-C surfaces counts and launches the real editors in the terminal
* it does not rebuild `/agents`, `/hooks`, or `/plugins` as forms.
*/
const GROUPS: { key: keyof ContainerCapabilities; label: string }[] = [
{ key: "skills", label: "Skills" },
{ key: "agents", label: "Agents" },
{ key: "commands", label: "Commands" },
{ key: "hooks", label: "Hooks" },
{ key: "plugins", label: "Plugins" },
{ key: "mcp_servers", label: "MCP servers" },
];
const SLASH_HINT: Partial<Record<keyof ContainerCapabilities, string>> = {
agents: "/agents",
hooks: "/hooks",
plugins: "/plugins",
mcp_servers: "/mcp",
};
interface Props {
project: Project;
onManageInTerminal: (command: string) => void;
}
export default function CapabilityTiles({ project, onManageInTerminal }: Props) {
const [capabilities, setCapabilities] = useState<ContainerCapabilities | null>(null);
const [loading, setLoading] = useState(false);
const [open, setOpen] = useState<keyof ContainerCapabilities | null>(null);
const running = project.status === "running";
useEffect(() => {
if (!running) {
setCapabilities(null);
return;
}
let cancelled = false;
setLoading(true);
listContainerCapabilities(project.id)
.then((c) => {
if (!cancelled) setCapabilities(c);
})
// Introspection degrades to "nothing found" when the container is
// unreachable — that is an empty state, not an error banner.
.catch(() => {
if (!cancelled) setCapabilities(null);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [project.id, running, project.container_id]);
const openGroup: CapabilityGroup | null =
open && capabilities ? capabilities[open] : null;
const openLabel = GROUPS.find((g) => g.key === open)?.label ?? "";
return (
<section>
<h2 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)] mb-2">
Capabilities
</h2>
{!running ? (
<p className="text-xs text-[var(--text-secondary)]">
Start the container to read its skills, agents, commands, hooks and plugins.
</p>
) : loading && !capabilities ? (
<p className="text-xs text-[var(--text-secondary)]">Reading container volume</p>
) : (
<div className="flex flex-wrap gap-2">
{GROUPS.map(({ key, label }) => {
const count = capabilities?.[key].count ?? 0;
return (
<button
key={key}
type="button"
disabled={count === 0}
onClick={() => setOpen(key)}
className="flex items-baseline gap-2 px-3 py-2 min-w-[7.5rem] text-left bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-panel)] hover:border-[var(--accent)] disabled:hover:border-[var(--border-color)] disabled:cursor-default transition-colors"
>
<span
className={`text-lg font-semibold tabular-nums ${
count === 0 ? "text-[var(--text-disabled)]" : "text-[var(--text-primary)]"
}`}
>
{count}
</span>
<span className="text-xs text-[var(--text-secondary)]">{label}</span>
</button>
);
})}
</div>
)}
{open && openGroup && (
<Modal
title={`${openLabel}${project.name}`}
description={
SLASH_HINT[open]
? `Claude Code manages these with ${SLASH_HINT[open]}.`
: undefined
}
onClose={() => setOpen(null)}
widthClassName="w-[34rem]"
footer={
<>
<Button
variant="primary"
onClick={() => {
setOpen(null);
// Claude Code owns the editors; we just deep-link into them.
onManageInTerminal("claude");
}}
>
Manage in terminal
</Button>
<Button onClick={() => setOpen(null)}>Close</Button>
</>
}
>
{openGroup.items.length === 0 ? (
<p className="text-xs text-[var(--text-secondary)]">Nothing configured.</p>
) : (
<ul className="space-y-2">
{openGroup.items.map((item, i) => (
<li
key={`${item.name}-${i}`}
className="pb-2 border-b border-[var(--border-color)] last:border-b-0"
>
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-[var(--text-primary)] font-mono">
{item.name}
</span>
<span className="text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded-[var(--radius-control)] bg-[var(--accent-muted)] text-[var(--accent)]">
{item.scope}
</span>
</div>
{item.description && (
<p className="mt-0.5 text-xs text-[var(--text-secondary)]">
{item.description}
</p>
)}
</li>
))}
</ul>
)}
</Modal>
)}
</section>
);
}
@@ -0,0 +1,57 @@
import type { Project } from "../../../lib/types";
import type { SaveState } from "../../../hooks/useSaveState";
import SaveIndicator from "../../ui/SaveIndicator";
import WorkspaceSection from "./config/WorkspaceSection";
import ModelSection from "./config/ModelSection";
import AccessSection from "./config/AccessSection";
import RuntimeSection from "./config/RuntimeSection";
interface Props {
project: Project;
save: (patch: Partial<Project>) => Promise<boolean>;
saveState: SaveState;
}
const STOPPED_ONLY =
"Container must be stopped to change this setting.";
/**
* Everything the seven config modals used to hold, full-width and grouped.
* Saves happen on blur; the indicator in the header reports the outcome.
*/
export default function ConfigTab({ project, save, saveState }: Props) {
const isStopped = project.status === "stopped" || project.status === "error";
const disabled = !isStopped;
return (
<div className="p-4 space-y-4 max-w-4xl">
<div className="flex items-center justify-between gap-4 min-h-[1.5rem]">
{disabled ? (
<p className="px-2 py-1 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)]">
Container is {project.status} stop it to change these settings.
</p>
) : (
<p className="text-xs text-[var(--text-secondary)]">
Changes save when a field loses focus.
</p>
)}
<SaveIndicator state={saveState} />
</div>
<WorkspaceSection project={project} save={save} disabled={disabled} />
<ModelSection project={project} save={save} disabled={disabled} />
<AccessSection
project={project}
save={save}
disabled={disabled}
disabledReason={STOPPED_ONLY}
/>
<RuntimeSection
project={project}
save={save}
disabled={disabled}
disabledReason={STOPPED_ONLY}
/>
</div>
);
}
@@ -0,0 +1,162 @@
import { useEffect } from "react";
import type { Project } from "../../../lib/types";
import { useFileManager } from "../../../hooks/useFileManager";
import Button from "../../ui/Button";
import { formatBytes } from "./format";
interface Props {
project: Project;
}
/** The old 42rem FileManager popup, now a main-area section. */
export default function FilesTab({ project }: Props) {
const {
currentPath,
entries,
loading,
error,
navigate,
goUp,
refresh,
downloadFile,
uploadFile,
} = useFileManager(project.id);
const running = project.status === "running";
useEffect(() => {
if (running) navigate("/workspace");
// Re-list when the container comes up.
}, [navigate, running]);
const breadcrumbs =
currentPath === "/"
? [{ label: "/", path: "/" }]
: currentPath
.split("/")
.reduce<{ label: string; path: string }[]>((acc, part, i) => {
if (i === 0) {
acc.push({ label: "/", path: "/" });
} else if (part) {
const parentPath = acc[acc.length - 1].path;
const fullPath = parentPath === "/" ? `/${part}` : `${parentPath}/${part}`;
acc.push({ label: part, path: fullPath });
}
return acc;
}, []);
if (!running) {
return (
<div className="p-4">
<p className="text-[13px] text-[var(--text-secondary)]">
Start the container to browse its files.
</p>
</div>
);
}
return (
<div className="flex flex-col h-full min-h-0">
<div className="flex items-center gap-1 px-4 py-2 border-b border-[var(--border-color)] text-xs overflow-x-auto flex-shrink-0">
<nav aria-label="Path" className="flex items-center gap-1">
{breadcrumbs.map((crumb, i) => (
<span key={crumb.path} className="flex items-center gap-1">
{i > 0 && <span className="text-[var(--text-secondary)]">/</span>}
<button
type="button"
onClick={() => navigate(crumb.path)}
className="text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors whitespace-nowrap font-mono"
>
{crumb.label}
</button>
</span>
))}
</nav>
<div className="flex-1" />
<Button onClick={uploadFile}>Upload file</Button>
<Button onClick={refresh} disabled={loading} className="ml-1">
Refresh
</Button>
</div>
<div className="flex-1 overflow-y-auto min-h-0">
{error && (
<div role="alert" className="px-4 py-2 text-xs text-[var(--error)]">
{error}
</div>
)}
{loading && entries.length === 0 ? (
<div className="px-4 py-8 text-center text-xs text-[var(--text-secondary)]">
Loading
</div>
) : (
<table className="w-full text-xs">
<tbody>
{currentPath !== "/" && (
<tr
onClick={goUp}
className="cursor-pointer hover:bg-[var(--bg-tertiary)] transition-colors"
>
<td className="px-4 py-1.5 text-[var(--text-primary)] font-mono">..</td>
<td colSpan={3} />
</tr>
)}
{entries.map((entry) => (
<tr
key={entry.name}
onClick={() => entry.is_directory && navigate(entry.path)}
className={`${
entry.is_directory ? "cursor-pointer" : ""
} hover:bg-[var(--bg-tertiary)] transition-colors`}
>
<td className="px-4 py-1.5">
<span
className={`font-mono ${
entry.is_directory
? "text-[var(--accent)]"
: "text-[var(--text-primary)]"
}`}
>
{entry.is_directory ? "📁 " : ""}
{entry.name}
</span>
</td>
<td className="px-2 py-1.5 text-[var(--text-secondary)] text-right whitespace-nowrap tabular-nums">
{!entry.is_directory && formatBytes(entry.size)}
</td>
<td className="px-2 py-1.5 text-[var(--text-secondary)] whitespace-nowrap">
{entry.modified}
</td>
<td className="px-2 py-1.5 text-right">
{!entry.is_directory && (
<Button
aria-label={`Download ${entry.name}`}
onClick={(e) => {
e.stopPropagation();
downloadFile(entry);
}}
>
Download
</Button>
)}
</td>
</tr>
))}
{entries.length === 0 && !loading && (
<tr>
<td
colSpan={4}
className="px-4 py-8 text-center text-[var(--text-secondary)]"
>
Empty directory
</td>
</tr>
)}
</tbody>
</table>
)}
</div>
</div>
);
}
@@ -0,0 +1,218 @@
import { useEffect, useState } from "react";
import type { ClaudeSession, Project, ScheduledTask } from "../../../lib/types";
import {
listClaudeSessions,
listScheduledTasks,
getSchedulerNotifications,
resumeSessionCommand,
} from "../../../lib/tauri-commands";
import type { useProjectActions } from "../../../hooks/useProjectActions";
import type { SaveState } from "../../../hooks/useSaveState";
import PermissionModeControl, {
permissionModePatch,
} from "../PermissionModeControl";
import CapabilityTiles from "./CapabilityTiles";
import SaveIndicator from "../../ui/SaveIndicator";
import Button from "../../ui/Button";
import { formatAge } from "./format";
import type { ProjectHomeTabId } from "./ProjectHome";
const BACKEND_LABEL: Record<Project["backend"], string> = {
anthropic: "Anthropic",
bedrock: "AWS Bedrock",
ollama: "Ollama",
open_ai_compatible: "OpenAI Compatible",
};
interface Props {
project: Project;
save: (patch: Partial<Project>) => Promise<boolean>;
saveState: SaveState;
actions: ReturnType<typeof useProjectActions>;
onOpenTab: (tab: ProjectHomeTabId) => void;
}
export default function OverviewTab({
project,
save,
saveState,
actions,
onOpenTab,
}: Props) {
const [sessions, setSessions] = useState<ClaudeSession[]>([]);
const [tasks, setTasks] = useState<ScheduledTask[]>([]);
const [notificationCount, setNotificationCount] = useState(0);
const running = project.status === "running";
useEffect(() => {
if (!running) {
setSessions([]);
setTasks([]);
setNotificationCount(0);
return;
}
let cancelled = false;
// All three degrade to empty when the container is unreachable.
listClaudeSessions(project.id)
.then((s) => !cancelled && setSessions(s.slice(0, 4)))
.catch(() => !cancelled && setSessions([]));
listScheduledTasks(project.id)
.then((t) => !cancelled && setTasks(t))
.catch(() => !cancelled && setTasks([]));
getSchedulerNotifications(project.id)
.then((n) => !cancelled && setNotificationCount(n.length))
.catch(() => !cancelled && setNotificationCount(0));
return () => {
cancelled = true;
};
}, [project.id, running, project.container_id]);
const handleResume = async (session: ClaudeSession) => {
try {
const command = await resumeSessionCommand(project.id, session.id);
await actions.openTerminalWithCommand(command, session.name ?? "resume");
} catch (e) {
console.error("Failed to build the resume command:", e);
}
};
return (
<div className="p-4 space-y-6 max-w-4xl">
{/* Permission mode — the hero control */}
<section className="p-3 border border-[var(--border-color)] rounded-[var(--radius-panel)] bg-[var(--bg-secondary)]">
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
<PermissionModeControl
project={project}
disabled={!running && project.status !== "stopped" && project.status !== "error"}
onChange={(mode) => save(permissionModePatch(mode))}
/>
</div>
<SaveIndicator state={saveState} />
</div>
<div className="mt-3 pt-3 border-t border-[var(--border-color)] flex flex-wrap gap-x-6 gap-y-1 text-xs">
<span className="text-[var(--text-secondary)]">
Backend{" "}
<span className="text-[var(--text-primary)] font-medium">
{BACKEND_LABEL[project.backend]}
</span>
</span>
<span className="text-[var(--text-secondary)]">
Docker access{" "}
<span className="text-[var(--text-primary)] font-medium">
{project.allow_docker_access ? "ON" : "OFF"}
</span>
</span>
<span className="text-[var(--text-secondary)]">
Mission Control{" "}
<span className="text-[var(--text-primary)] font-medium">
{project.mission_control_enabled ? "ON" : "OFF"}
</span>
</span>
<button
type="button"
onClick={() => onOpenTab("config")}
className="text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors"
>
Edit configuration
</button>
</div>
</section>
<CapabilityTiles
project={project}
onManageInTerminal={(command) => actions.openTerminalWithCommand(command)}
/>
<div className="grid gap-6 md:grid-cols-2">
{/* Recent sessions */}
<section>
<div className="flex items-baseline justify-between mb-2">
<h2 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)]">
Recent sessions
</h2>
<button
type="button"
onClick={() => onOpenTab("sessions")}
className="text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors"
>
All sessions
</button>
</div>
{!running ? (
<p className="text-xs text-[var(--text-secondary)]">
Start the container to list saved conversations.
</p>
) : sessions.length === 0 ? (
<p className="text-xs text-[var(--text-secondary)]">No sessions yet.</p>
) : (
<ul className="space-y-1">
{sessions.map((session) => (
<li
key={session.id}
className="flex items-center gap-2 px-2 py-1.5 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-control)]"
>
<span className="flex-1 min-w-0 text-xs text-[var(--text-primary)] truncate">
{session.name ?? session.summary ?? session.id}
</span>
<span className="text-xs text-[var(--text-secondary)] flex-shrink-0">
{formatAge(session.last_modified) ?? ""}
</span>
<Button onClick={() => handleResume(session)}>Resume</Button>
</li>
))}
</ul>
)}
</section>
{/* Scheduled tasks */}
<section>
<div className="flex items-baseline justify-between mb-2">
<h2 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)]">
Scheduled tasks
</h2>
<button
type="button"
onClick={() => onOpenTab("automation")}
className="text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors"
>
Automation
</button>
</div>
{!running ? (
<p className="text-xs text-[var(--text-secondary)]">
Start the container to list scheduled tasks.
</p>
) : tasks.length === 0 ? (
<p className="text-xs text-[var(--text-secondary)]">No scheduled tasks.</p>
) : (
<ul className="space-y-1">
{tasks.slice(0, 4).map((task) => (
<li
key={task.id}
className="flex items-center gap-2 px-2 py-1.5 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-control)]"
>
<span className="flex-1 min-w-0 text-xs text-[var(--text-primary)] truncate">
{task.name}
</span>
<span className="text-xs text-[var(--text-secondary)] font-mono flex-shrink-0">
{task.at ?? task.schedule}
</span>
</li>
))}
</ul>
)}
{notificationCount > 0 && (
<button
type="button"
onClick={() => onOpenTab("automation")}
className="mt-2 inline-flex items-center gap-1.5 px-2 py-1 text-xs rounded-[var(--radius-control)] bg-[var(--accent-muted)] text-[var(--accent)] hover:bg-[var(--bg-tertiary)] transition-colors"
>
{notificationCount} notification{notificationCount === 1 ? "" : "s"}
</button>
)}
</section>
</div>
</div>
);
}
@@ -0,0 +1,241 @@
import { useEffect, useMemo, useState } from "react";
import { useShallow } from "zustand/react/shallow";
import { useAppState } from "../../../store/appState";
import { useProjectActions } from "../../../hooks/useProjectActions";
import { useProjects } from "../../../hooks/useProjects";
import { useProjectSave } from "../../../hooks/useSaveState";
import { ProjectStatusIndicator } from "../../ui/StatusIndicator";
import Button from "../../ui/Button";
import OverflowMenu from "../../ui/OverflowMenu";
import ConfirmRemoveModal from "../ConfirmRemoveModal";
import ConfirmResetModal from "../ConfirmResetModal";
import OverviewTab from "./OverviewTab";
import SessionsTab from "./SessionsTab";
import AutomationTab from "./AutomationTab";
import ConfigTab from "./ConfigTab";
import FilesTab from "./FilesTab";
import { formatUptime } from "./format";
const TABS = [
{ id: "overview", label: "Overview" },
{ id: "sessions", label: "Sessions" },
{ id: "automation", label: "Automation" },
{ id: "config", label: "Config" },
{ id: "files", label: "Files" },
] as const;
export type ProjectHomeTabId = (typeof TABS)[number]["id"];
interface Props {
projectId: string;
active: boolean;
}
/**
* The project promoted from a sidebar card to a first-class main-area view.
* Everything that used to spray out of `ProjectCard` as a modal lives here.
*/
export default function ProjectHome({ projectId, active }: Props) {
const { projects, remove } = useProjects();
const project = projects.find((p) => p.id === projectId);
const [tab, setTab] = useState<ProjectHomeTabId>("overview");
const [confirmRemove, setConfirmRemove] = useState(false);
const [confirmReset, setConfirmReset] = useState(false);
const { runningSince, progress } = useAppState(
useShallow((s) => ({
runningSince: s.runningSince[projectId],
progress: s.containerProgress[projectId],
})),
);
// Re-render once a minute so the uptime line stays honest.
const [, setTick] = useState(0);
useEffect(() => {
if (!active || runningSince === undefined) return;
const timer = setInterval(() => setTick((t) => t + 1), 60_000);
return () => clearInterval(timer);
}, [active, runningSince]);
const actions = useProjectActions(
project ?? ({ id: projectId, name: "", container_id: null } as never),
);
const { save, saveState } = useProjectSave(
project ?? ({ id: projectId, name: "" } as never),
);
const uptime = useMemo(() => formatUptime(runningSince), [runningSince]);
if (!project) {
return (
<div className={`h-full flex items-center justify-center ${active ? "" : "hidden"}`}>
<p className="text-[13px] text-[var(--text-secondary)]">
This project is no longer available.
</p>
</div>
);
}
const isRunning = project.status === "running";
const isTransitioning =
project.status === "starting" || project.status === "stopping";
const isStopped = project.status === "stopped" || project.status === "error";
return (
<div className={`flex flex-col h-full min-h-0 ${active ? "" : "hidden"}`}>
{/* Header */}
<header className="flex-shrink-0 px-4 pt-3 pb-2 border-b border-[var(--border-color)]">
<div className="flex items-start justify-between gap-4 flex-wrap">
<div className="min-w-0">
<h1 className="text-base font-semibold text-[var(--text-primary)] truncate">
{project.name}
</h1>
<div className="mt-0.5 flex items-center gap-2 text-xs">
<ProjectStatusIndicator status={project.status} />
{isRunning && uptime && (
<span className="text-[var(--text-secondary)]">· {uptime}</span>
)}
{isTransitioning && progress && (
<span className="text-[var(--warning)] truncate">· {progress}</span>
)}
</div>
</div>
<div className="flex items-center gap-1.5 flex-wrap">
{isRunning ? (
<Button
size="md"
variant="primary"
disabled={actions.busy}
onClick={actions.openClaudeTerminal}
>
Open Claude Terminal
</Button>
) : (
<Button
size="md"
variant="primary"
disabled={actions.busy || isTransitioning}
onClick={actions.handleStart}
>
Start
</Button>
)}
{isRunning && (
<>
<Button size="md" onClick={actions.openShell}>
Shell
</Button>
<Button size="md" onClick={() => setTab("files")}>
Files
</Button>
<Button size="md" disabled={actions.busy} onClick={actions.handleStop}>
Stop
</Button>
</>
)}
{isTransitioning && (
<Button size="md" variant="danger" onClick={actions.handleStop}>
Force stop
</Button>
)}
<OverflowMenu
items={[
{
label: actions.backingUp ? "Backing up…" : "Back up container",
onSelect: actions.handleBackup,
disabled: actions.backingUp || !project.container_id,
},
{
label: "Reset container…",
onSelect: () => setConfirmReset(true),
disabled: !isStopped || actions.busy,
danger: true,
},
{
label: "Remove project…",
onSelect: () => setConfirmRemove(true),
danger: true,
},
]}
/>
</div>
</div>
{/* Tabs */}
<div role="tablist" aria-label="Project sections" className="flex gap-1 mt-3 -mb-2">
{TABS.map((t) => (
<button
key={t.id}
type="button"
role="tab"
id={`project-tab-${projectId}-${t.id}`}
aria-selected={tab === t.id}
aria-controls={`project-panel-${projectId}-${t.id}`}
onClick={() => setTab(t.id)}
className={`px-3 h-8 text-[13px] font-medium rounded-t-[var(--radius-control)] border-b-2 transition-colors ${
tab === t.id
? "text-[var(--text-primary)] border-[var(--accent)]"
: "text-[var(--text-secondary)] border-transparent hover:text-[var(--text-primary)]"
}`}
>
{t.label}
</button>
))}
</div>
</header>
{/* Panel */}
<div
role="tabpanel"
id={`project-panel-${projectId}-${tab}`}
aria-labelledby={`project-tab-${projectId}-${tab}`}
className="flex-1 min-h-0 overflow-y-auto"
>
{tab === "overview" && (
<OverviewTab
project={project}
save={save}
saveState={saveState}
actions={actions}
onOpenTab={setTab}
/>
)}
{tab === "sessions" && <SessionsTab project={project} actions={actions} />}
{tab === "automation" && <AutomationTab project={project} />}
{tab === "config" && (
<ConfigTab project={project} save={save} saveState={saveState} />
)}
{tab === "files" && <FilesTab project={project} />}
</div>
{confirmReset && (
<ConfirmResetModal
projectName={project.name}
onCancel={() => setConfirmReset(false)}
onConfirm={() => {
setConfirmReset(false);
actions.handleReset();
}}
/>
)}
{confirmRemove && (
<ConfirmRemoveModal
projectName={project.name}
onCancel={() => setConfirmRemove(false)}
onConfirm={async () => {
setConfirmRemove(false);
try {
await remove(project.id);
} catch (e) {
useAppState.getState().pushToast({
kind: "error",
message: `Could not remove “${project.name}`,
detail: String(e),
});
}
}}
/>
)}
</div>
);
}
@@ -0,0 +1,102 @@
import { useCallback, useEffect, useState } from "react";
import type { ClaudeSession, Project } from "../../../lib/types";
import { listClaudeSessions, resumeSessionCommand } from "../../../lib/tauri-commands";
import type { useProjectActions } from "../../../hooks/useProjectActions";
import { useAppState } from "../../../store/appState";
import Button from "../../ui/Button";
import { formatAge, formatBytes } from "./format";
interface Props {
project: Project;
actions: ReturnType<typeof useProjectActions>;
}
/**
* The stop/start container model buries "which conversation was I in?" in the
* config volume. This lists it and makes [Resume] one click.
*/
export default function SessionsTab({ project, actions }: Props) {
const [sessions, setSessions] = useState<ClaudeSession[]>([]);
const [loading, setLoading] = useState(false);
const pushToast = useAppState((s) => s.pushToast);
const running = project.status === "running";
const load = useCallback(() => {
if (!running) {
setSessions([]);
return;
}
setLoading(true);
listClaudeSessions(project.id)
.then(setSessions)
.catch(() => setSessions([]))
.finally(() => setLoading(false));
}, [project.id, running]);
useEffect(load, [load]);
const resume = async (session: ClaudeSession) => {
try {
const command = await resumeSessionCommand(project.id, session.id);
await actions.openTerminalWithCommand(command, session.name ?? "resume");
} catch (e) {
pushToast({
kind: "error",
message: "Could not resume that session",
detail: String(e),
});
}
};
return (
<div className="p-4 max-w-4xl">
<div className="flex items-center justify-between mb-3">
<p className="text-xs text-[var(--text-secondary)]">
Conversations stored on this project&rsquo;s config volume. Resume opens a
terminal running the resume command.
</p>
<Button onClick={load} disabled={!running || loading}>
{loading ? "Refreshing…" : "Refresh"}
</Button>
</div>
{!running ? (
<p className="text-[13px] text-[var(--text-secondary)]">
Start the container to read its saved sessions.
</p>
) : sessions.length === 0 && !loading ? (
<p className="text-[13px] text-[var(--text-secondary)]">
No sessions recorded yet. Open a Claude terminal to start one.
</p>
) : (
<ul className="space-y-1">
{sessions.map((session) => (
<li
key={session.id}
className="flex items-center gap-3 px-3 py-2 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-[var(--radius-control)]"
>
<div className="flex-1 min-w-0">
<div className="text-[13px] text-[var(--text-primary)] truncate">
{session.name ?? session.summary ?? "(untitled session)"}
</div>
<div className="text-xs text-[var(--text-secondary)] truncate font-mono">
{session.id}
{session.cwd ? ` · ${session.cwd}` : ""}
</div>
</div>
<div className="flex-shrink-0 text-right text-xs text-[var(--text-secondary)] tabular-nums">
<div>{formatAge(session.last_modified) ?? "—"}</div>
<div>
{formatBytes(session.size_bytes)} · {session.message_count} msg
</div>
</div>
<Button variant="primary" onClick={() => resume(session)}>
Resume
</Button>
</li>
))}
</ul>
)}
</div>
);
}
@@ -0,0 +1,202 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, fireEvent, act } from "@testing-library/react";
import TaskEditorModal from "./TaskEditorModal";
import type { Project, ScheduledTask } from "../../../lib/types";
const addScheduledTask = vi.fn(async () => "a1b2c3d4");
const updateScheduledTask = vi.fn(async () => "e5f6a7b8");
vi.mock("../../../lib/tauri-commands", () => ({
addScheduledTask: (...args: unknown[]) => addScheduledTask(...(args as [])),
updateScheduledTask: (...args: unknown[]) => updateScheduledTask(...(args as [])),
}));
/** Modal focuses via rAF; jsdom needs a flush. */
async function flushFocus() {
await act(async () => {
vi.advanceTimersByTime(20);
});
}
const baseProject: Project = {
id: "p1",
name: "api-server",
paths: [{ host_path: "/home/user/api", mount_name: "api" }],
container_id: "c1",
status: "running",
backend: "anthropic",
bedrock_config: null,
ollama_config: null,
openai_compatible_config: null,
allow_docker_access: false,
sandbox_mode_enabled: true,
mission_control_enabled: false,
auth_bridge_enabled: false,
use_shared_auth_token: true,
full_permissions: false,
permission_mode: "bypass",
ssh_key_path: null,
git_token: null,
git_user_name: null,
git_user_email: null,
custom_env_vars: [],
port_mappings: [],
claude_instructions: null,
claude_code_settings: null,
renamed_session_names: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
const existingTask: ScheduledTask = {
id: "a1b2c3d4",
name: "nightly",
prompt: "Run the suite",
schedule: "0 3 * * *",
task_type: "recurring",
at: null,
enabled: false,
working_dir: "/workspace/api",
created_at: null,
last_run: null,
next_run: null,
};
async function renderEditor(task: ScheduledTask | null = null, project = baseProject) {
const onClose = vi.fn();
const onSaved = vi.fn();
render(
<TaskEditorModal project={project} task={task} onClose={onClose} onSaved={onSaved} />,
);
await flushFocus();
return { onClose, onSaved };
}
const field = (name: RegExp) => screen.getByLabelText(name) as HTMLInputElement;
const submit = async () =>
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: /create task|save changes/i }));
});
describe("TaskEditorModal", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers({ toFake: ["requestAnimationFrame", "setTimeout"] });
});
afterEach(() => vi.useRealTimers());
it("sends the typed values through as data, untouched", async () => {
await renderEditor();
fireEvent.change(field(/^name$/i), { target: { value: " nightly " } });
// A prompt full of shell syntax must reach the backend verbatim.
fireEvent.change(field(/^prompt$/i), {
target: { value: 'echo "hi"; rm -rf / $(id)\nsecond line' },
});
fireEvent.change(field(/cron expression/i), { target: { value: "0 3 * * *" } });
await submit();
expect(addScheduledTask).toHaveBeenCalledWith("p1", {
name: "nightly",
prompt: 'echo "hi"; rm -rf / $(id)\nsecond line',
scheduleKind: "recurring",
schedule: "0 3 * * *",
workingDir: "/workspace",
});
});
it("refuses to submit an invalid cron expression and says why", async () => {
const { onSaved } = await renderEditor();
fireEvent.change(field(/^name$/i), { target: { value: "nightly" } });
fireEvent.change(field(/^prompt$/i), { target: { value: "do the thing" } });
fireEvent.change(field(/cron expression/i), { target: { value: "99 * * * *" } });
await submit();
expect(addScheduledTask).not.toHaveBeenCalled();
expect(onSaved).not.toHaveBeenCalled();
expect(screen.getByRole("alert")).toHaveTextContent(/out of range for the minute field/i);
});
it("refuses a relative working directory", async () => {
await renderEditor();
fireEvent.change(field(/^name$/i), { target: { value: "nightly" } });
fireEvent.change(field(/^prompt$/i), { target: { value: "do the thing" } });
fireEvent.change(field(/working directory/i), { target: { value: "relative/path" } });
await submit();
expect(addScheduledTask).not.toHaveBeenCalled();
expect(screen.getByRole("alert")).toHaveTextContent(/absolute path/i);
});
it("reads the cron expression back in English", async () => {
await renderEditor();
fireEvent.change(field(/cron expression/i), { target: { value: "0 9 * * 1-5" } });
expect(screen.getByText("At 09:00, on Monday to Friday.")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Hourly" }));
expect(field(/cron expression/i).value).toBe("0 * * * *");
expect(screen.getByText("At :00 past every hour, every day.")).toBeInTheDocument();
});
it("switches to a one-shot time and validates its format", async () => {
await renderEditor();
fireEvent.change(field(/^name$/i), { target: { value: "one-off" } });
fireEvent.change(field(/^prompt$/i), { target: { value: "commit" } });
fireEvent.click(screen.getByRole("radio", { name: "Once" }));
fireEvent.change(field(/run at/i), { target: { value: "tomorrow" } });
await submit();
expect(addScheduledTask).not.toHaveBeenCalled();
expect(screen.getByRole("alert")).toHaveTextContent(/YYYY-MM-DD HH:MM/);
fireEvent.change(field(/run at/i), { target: { value: "2099-12-25 09:05" } });
await submit();
expect(addScheduledTask).toHaveBeenCalledWith(
"p1",
expect.objectContaining({ scheduleKind: "once", schedule: "2099-12-25 09:05" }),
);
});
it("warns that a headless run cannot answer a permission prompt", async () => {
// Bypass is the only mode where an unattended run is safe from stalling.
await renderEditor(null, { ...baseProject, permission_mode: "bypass" });
expect(screen.getByText(/headless/i)).toBeInTheDocument();
expect(screen.queryByText(/cannot answer a permission prompt/i)).toBeNull();
});
it("spells out the stall risk in any non-Bypass mode", async () => {
await renderEditor(null, { ...baseProject, permission_mode: "default" });
expect(screen.getByText(/cannot answer a permission prompt/i)).toBeInTheDocument();
});
it("edits an existing task, carrying its enabled state and warning about the new id", async () => {
const { onSaved, onClose } = await renderEditor(existingTask);
expect(field(/^name$/i).value).toBe("nightly");
expect(field(/cron expression/i).value).toBe("0 3 * * *");
expect(field(/working directory/i).value).toBe("/workspace/api");
// The id changes on edit; the user is told before they save.
expect(screen.getByText(/re-creates this task under a new id/i)).toBeInTheDocument();
fireEvent.change(field(/^name$/i), { target: { value: "nightly-v2" } });
await submit();
expect(updateScheduledTask).toHaveBeenCalledWith(
"p1",
"a1b2c3d4",
expect.objectContaining({ name: "nightly-v2", workingDir: "/workspace/api" }),
false, // the task was disabled and must not come back enabled
);
expect(onSaved).toHaveBeenCalled();
expect(onClose).toHaveBeenCalled();
});
it("surfaces a backend rejection instead of closing", async () => {
addScheduledTask.mockRejectedValueOnce(new Error("Container is not running"));
const { onClose } = await renderEditor();
fireEvent.change(field(/^name$/i), { target: { value: "nightly" } });
fireEvent.change(field(/^prompt$/i), { target: { value: "do the thing" } });
await submit();
expect(screen.getByRole("alert")).toHaveTextContent(/Container is not running/);
expect(onClose).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,329 @@
import { useId, useMemo, useRef, useState } from "react";
import type { Project, ScheduledTask, ScheduledTaskInput, ScheduleKind } from "../../../lib/types";
import { addScheduledTask, updateScheduledTask } from "../../../lib/tauri-commands";
import { effectivePermissionMode, PERMISSION_MODES } from "../PermissionModeControl";
import Button from "../../ui/Button";
import Modal from "../../ui/Modal";
import SegmentedControl from "../../ui/SegmentedControl";
import { inputClass, monoInputClass } from "../../ui/Field";
import {
atTimestampIsPast,
CRON_PRESETS,
DEFAULT_WORKING_DIR,
describeCron,
MAX_TASK_PROMPT_LEN,
validateAtTimestamp,
validateCronExpression,
validateTaskName,
validateTaskPrompt,
validateWorkingDir,
} from "./taskValidation";
interface Props {
project: Project;
/** `null` creates a new task; a task edits it in place. */
task: ScheduledTask | null;
onClose: () => void;
/** Called after the scheduler accepted the change, to refresh the list. */
onSaved: () => void;
}
const DEFAULT_CRON = "0 9 * * *";
/** `YYYY-MM-DD HH:MM`, one hour from now, as the one-shot default. */
function defaultAtTimestamp(now = new Date()): string {
const at = new Date(now.getTime() + 60 * 60 * 1000);
at.setSeconds(0, 0);
const pad = (n: number) => String(n).padStart(2, "0");
return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${pad(
at.getHours(),
)}:${pad(at.getMinutes())}`;
}
/**
* Create or edit a `triple-c-scheduler` task.
*
* Validation here mirrors the backend so mistakes surface before a round trip;
* the backend re-checks everything regardless.
*/
export default function TaskEditorModal({ project, task, onClose, onSaved }: Props) {
const formId = useId();
const nameRef = useRef<HTMLInputElement>(null);
const [name, setName] = useState(task?.name ?? "");
const [prompt, setPrompt] = useState(task?.prompt ?? "");
const [workingDir, setWorkingDir] = useState(task?.working_dir ?? DEFAULT_WORKING_DIR);
const [kind, setKind] = useState<ScheduleKind>(
task?.task_type === "once" ? "once" : "recurring",
);
const [cron, setCron] = useState(
task && task.task_type !== "once" ? task.schedule : DEFAULT_CRON,
);
const [at, setAt] = useState(task?.at ?? defaultAtTimestamp());
const [showAllErrors, setShowAllErrors] = useState(false);
const [touched, setTouched] = useState<Record<string, boolean>>({});
const [saving, setSaving] = useState(false);
const [submitError, setSubmitError] = useState<string | null>(null);
const errors = {
name: validateTaskName(name),
prompt: validateTaskPrompt(prompt),
workingDir: validateWorkingDir(workingDir),
schedule: kind === "recurring" ? validateCronExpression(cron) : validateAtTimestamp(at),
};
const hasErrors = Object.values(errors).some(Boolean);
const show = (field: keyof typeof errors) =>
(showAllErrors || touched[field]) && errors[field] ? errors[field] : null;
const cronReading = useMemo(() => describeCron(cron), [cron]);
const atIsPast = kind === "once" && atTimestampIsPast(at);
const mode = effectivePermissionMode(project);
const modeLabel = PERMISSION_MODES.find((m) => m.value === mode)?.label ?? mode;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setShowAllErrors(true);
setSubmitError(null);
if (hasErrors) return;
const input: ScheduledTaskInput = {
name: name.trim(),
prompt: prompt.trim(),
scheduleKind: kind,
schedule: kind === "recurring" ? cron.trim() : at.trim(),
workingDir: workingDir.trim() || DEFAULT_WORKING_DIR,
};
setSaving(true);
try {
if (task) {
await updateScheduledTask(project.id, task.id, input, task.enabled);
} else {
await addScheduledTask(project.id, input);
}
onSaved();
onClose();
} catch (err) {
setSubmitError(String(err));
} finally {
setSaving(false);
}
};
const errorText = (message: string | null) =>
message ? (
<p role="alert" className="mt-1 text-xs text-[var(--error)]">
{message}
</p>
) : null;
return (
<Modal
title={task ? `Edit task — ${task.name}` : "New scheduled task"}
onClose={onClose}
widthClassName="w-[40rem]"
initialFocusRef={nameRef}
footer={
<>
<Button size="md" variant="ghost" onClick={onClose} disabled={saving}>
Cancel
</Button>
<Button size="md" variant="primary" type="submit" form={formId} disabled={saving}>
{saving ? "Saving…" : task ? "Save changes" : "Create task"}
</Button>
</>
}
>
<form id={formId} onSubmit={handleSubmit} className="space-y-4">
{/* Name */}
<div>
<label
htmlFor={`${formId}-name`}
className="block text-[13px] font-medium text-[var(--text-primary)] mb-1"
>
Name
</label>
<input
id={`${formId}-name`}
ref={nameRef}
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={() => setTouched((t) => ({ ...t, name: true }))}
placeholder="nightly-tests"
aria-invalid={show("name") ? true : undefined}
className={inputClass}
/>
{errorText(show("name"))}
</div>
{/* Prompt */}
<div>
<label
htmlFor={`${formId}-prompt`}
className="block text-[13px] font-medium text-[var(--text-primary)]"
>
Prompt
</label>
<p className="mt-0.5 mb-1 text-xs text-[var(--text-secondary)] leading-snug">
What Claude Code is asked to do on each run.
</p>
<textarea
id={`${formId}-prompt`}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
onBlur={() => setTouched((t) => ({ ...t, prompt: true }))}
rows={4}
maxLength={MAX_TASK_PROMPT_LEN}
placeholder="Run the test suite and summarise any failures."
aria-invalid={show("prompt") ? true : undefined}
className={`${inputClass} resize-y`}
/>
{errorText(show("prompt"))}
</div>
{/* Schedule */}
<div>
<span className="block text-[13px] font-medium text-[var(--text-primary)] mb-1">
Schedule
</span>
<SegmentedControl
label="Schedule kind"
segments={[
{ value: "recurring", label: "Recurring" },
{ value: "once", label: "Once" },
]}
value={kind}
onChange={(v) => {
setKind(v);
setSubmitError(null);
}}
/>
{kind === "recurring" ? (
<div className="mt-2 space-y-2">
<div className="flex flex-wrap gap-1">
{CRON_PRESETS.map((preset) => (
<Button
key={preset.expression}
onClick={() => {
setCron(preset.expression);
setTouched((t) => ({ ...t, schedule: true }));
}}
>
{preset.label}
</Button>
))}
</div>
<input
id={`${formId}-cron`}
value={cron}
onChange={(e) => setCron(e.target.value)}
onBlur={() => setTouched((t) => ({ ...t, schedule: true }))}
placeholder="0 9 * * 1-5"
aria-label="Cron expression"
aria-describedby={`${formId}-cron-reading`}
aria-invalid={show("schedule") ? true : undefined}
className={monoInputClass}
/>
<p
id={`${formId}-cron-reading`}
aria-live="polite"
className="text-xs text-[var(--text-secondary)]"
>
<span className="font-mono">minute hour day-of-month month day-of-week</span> ·{" "}
{cronReading ? (
<span className="text-[var(--text-primary)]">{cronReading}</span>
) : (
<span>not a valid schedule yet</span>
)}
</p>
{errorText(show("schedule"))}
</div>
) : (
<div className="mt-2 space-y-1">
<input
id={`${formId}-at`}
value={at}
onChange={(e) => setAt(e.target.value)}
onBlur={() => setTouched((t) => ({ ...t, schedule: true }))}
placeholder="2026-12-25 09:05"
aria-label="Run at (YYYY-MM-DD HH:MM)"
aria-invalid={show("schedule") ? true : undefined}
className={monoInputClass}
/>
<p className="text-xs text-[var(--text-secondary)]">
Container local time, as <code className="font-mono">YYYY-MM-DD HH:MM</code>. The
task removes itself after it runs.
</p>
{atIsPast && (
<p className="text-xs text-[var(--warning)]">
That time has already passed. A one-shot task is stored as a cron entry without a
year, so it would next fire on that date next year.
</p>
)}
{errorText(show("schedule"))}
</div>
)}
</div>
{/* Working directory */}
<div>
<label
htmlFor={`${formId}-wd`}
className="block text-[13px] font-medium text-[var(--text-primary)]"
>
Working directory
</label>
<p className="mt-0.5 mb-1 text-xs text-[var(--text-secondary)] leading-snug">
Absolute path inside the container. Project folders are mounted under{" "}
<code className="font-mono">/workspace</code>.
</p>
<input
id={`${formId}-wd`}
value={workingDir}
onChange={(e) => setWorkingDir(e.target.value)}
onBlur={() => setTouched((t) => ({ ...t, workingDir: true }))}
placeholder={DEFAULT_WORKING_DIR}
aria-invalid={show("workingDir") ? true : undefined}
className={monoInputClass}
/>
{errorText(show("workingDir"))}
</div>
{/* How a scheduled run actually behaves. */}
<div className="rounded-[var(--radius-control)] border border-[var(--border-color)] bg-[var(--bg-secondary)] px-3 py-2 space-y-1">
<p className="text-xs text-[var(--text-secondary)]">
Scheduled runs are <strong className="text-[var(--text-primary)]">headless</strong>
the container executes <code className="font-mono">claude -p "…"</code> with no
terminal attached, using this project&rsquo;s permission mode (
<strong className="text-[var(--text-primary)]">{modeLabel}</strong>).
</p>
{mode !== "bypass" && (
<p className="text-xs text-[var(--warning)]">
A headless run cannot answer a permission prompt. In {modeLabel} mode the task may
stall and produce an empty log; set the mode to Bypass in the Config tab for
unattended runs.
</p>
)}
</div>
{task && (
<p className="text-xs text-[var(--text-secondary)]">
The scheduler has no edit command, so saving re-creates this task under a new id and
removes <code className="font-mono">{task.id}</code>. Its previous run logs stay under
the old id.
</p>
)}
{submitError && (
<p role="alert" className="text-xs text-[var(--error)] whitespace-pre-wrap break-words">
{submitError}
</p>
)}
</form>
</Modal>
);
}
@@ -0,0 +1,150 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import type { Project } from "../../../../lib/types";
import Button from "../../../ui/Button";
import Field, { ConfigGroup, inputClass } from "../../../ui/Field";
import EnvVarsEditor from "../../EnvVarsEditor";
import PortMappingsEditor from "../../PortMappingsEditor";
interface Props {
project: Project;
save: (patch: Partial<Project>) => Promise<boolean>;
disabled: boolean;
disabledReason?: string;
}
export default function AccessSection({
project,
save,
disabled,
disabledReason,
}: Props) {
const [sshKeyPath, setSshKeyPath] = useState(project.ssh_key_path ?? "");
const [gitName, setGitName] = useState(project.git_user_name ?? "");
const [gitEmail, setGitEmail] = useState(project.git_user_email ?? "");
const [gitToken, setGitToken] = useState(project.git_token ?? "");
useEffect(() => {
setSshKeyPath(project.ssh_key_path ?? "");
setGitName(project.git_user_name ?? "");
setGitEmail(project.git_user_email ?? "");
setGitToken(project.git_token ?? "");
}, [project]);
return (
<ConfigGroup
title="Access"
description="Credentials, environment, and networking the container is given."
>
<Field
label="SSH key directory"
hint="Mounted into the container so Claude can authenticate with Git remotes over SSH."
>
{(id) => (
<div className="flex gap-1.5">
<input
id={id}
value={sshKeyPath}
onChange={(e) => setSshKeyPath(e.target.value)}
onBlur={() => save({ ssh_key_path: sshKeyPath || null })}
placeholder="~/.ssh"
disabled={disabled}
className={inputClass}
/>
<Button
size="md"
disabled={disabled}
onClick={async () => {
const selected = await open({ directory: true, multiple: false });
if (typeof selected === "string") {
setSshKeyPath(selected);
save({ ssh_key_path: selected });
}
}}
>
Browse
</Button>
</div>
)}
</Field>
<Field label="Git name" hint="Sets git user.name inside the container for commit authorship.">
{(id) => (
<input
id={id}
value={gitName}
onChange={(e) => setGitName(e.target.value)}
onBlur={() => save({ git_user_name: gitName || null })}
placeholder="Your Name"
disabled={disabled}
className={inputClass}
/>
)}
</Field>
<Field label="Git email" hint="Sets git user.email inside the container for commit authorship.">
{(id) => (
<input
id={id}
value={gitEmail}
onChange={(e) => setGitEmail(e.target.value)}
onBlur={() => save({ git_user_email: gitEmail || null })}
placeholder="you@example.com"
disabled={disabled}
className={inputClass}
/>
)}
</Field>
<Field
label="Git HTTPS token"
hint="A personal access token (e.g. a GitHub PAT) for HTTPS git operations inside the container."
>
{(id) => (
<input
id={id}
type="password"
value={gitToken}
onChange={(e) => setGitToken(e.target.value)}
onBlur={() => save({ git_token: gitToken || null })}
placeholder="ghp_…"
disabled={disabled}
className={inputClass}
/>
)}
</Field>
<div className="pt-2 border-t border-[var(--border-color)]">
<span className="block text-[13px] font-medium text-[var(--text-primary)]">
Environment variables
</span>
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
Injected into this project&rsquo;s container. These override global variables
with the same key.
</p>
<EnvVarsEditor
envVars={project.custom_env_vars ?? []}
disabled={disabled}
disabledReason={disabledReason}
onSave={(vars) => save({ custom_env_vars: vars })}
/>
</div>
<div className="pt-2 border-t border-[var(--border-color)]">
<span className="block text-[13px] font-medium text-[var(--text-primary)]">
Port mappings
</span>
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
Expose container ports on the host so you can reach dev servers running inside
the sandbox.
</p>
<PortMappingsEditor
portMappings={project.port_mappings ?? []}
disabled={disabled}
disabledReason={disabledReason}
onSave={(mappings) => save({ port_mappings: mappings })}
/>
</div>
</ConfigGroup>
);
}
@@ -0,0 +1,95 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import ModelSection from "./ModelSection";
import type { Backend, Project } from "../../../../lib/types";
const baseProject: Project = {
id: "p1",
name: "api-server",
paths: [{ host_path: "/src/api", mount_name: "api" }],
container_id: null,
status: "stopped",
backend: "anthropic",
bedrock_config: null,
ollama_config: null,
openai_compatible_config: null,
allow_docker_access: false,
sandbox_mode_enabled: true,
mission_control_enabled: false,
auth_bridge_enabled: false,
use_shared_auth_token: true,
full_permissions: false,
permission_mode: null,
ssh_key_path: null,
git_token: null,
git_user_name: null,
git_user_email: null,
custom_env_vars: [],
port_mappings: [],
claude_instructions: null,
claude_code_settings: null,
renamed_session_names: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
const TOGGLE = "Use the shared Claude token";
const save = vi.fn().mockResolvedValue(true);
function renderSection(over: Partial<Project> = {}, disabled = false) {
return render(
<ModelSection
project={{ ...baseProject, ...over }}
save={save}
disabled={disabled}
/>,
);
}
describe("ModelSection — shared auth token toggle", () => {
beforeEach(() => vi.clearAllMocks());
it("renders for the Anthropic backend", () => {
renderSection();
expect(screen.getByRole("switch", { name: TOGGLE })).toBeInTheDocument();
});
it.each<Backend>(["bedrock", "ollama", "open_ai_compatible"])(
"is hidden for the %s backend",
(backend) => {
renderSection({ backend });
expect(screen.queryByRole("switch", { name: TOGGLE })).not.toBeInTheDocument();
},
);
it("defaults to on, including for data written before the field existed", () => {
renderSection();
expect(screen.getByRole("switch", { name: TOGGLE })).toHaveAttribute(
"aria-checked",
"true",
);
const legacy = { ...baseProject } as Partial<Project>;
delete legacy.use_shared_auth_token;
renderSection(legacy);
expect(screen.getAllByRole("switch", { name: TOGGLE })[1]).toHaveAttribute(
"aria-checked",
"true",
);
});
it("saves the opt-out and explains the consequence", () => {
renderSection();
fireEvent.click(screen.getByRole("switch", { name: TOGGLE }));
expect(save).toHaveBeenCalledWith({ use_shared_auth_token: false });
renderSection({ use_shared_auth_token: false });
expect(screen.getByText(/needs its own `claude login`/)).toBeInTheDocument();
});
it("follows the container-stopped rule like the rest of the group", () => {
renderSection({}, true);
expect(screen.getByRole("switch", { name: TOGGLE })).toBeDisabled();
});
});
@@ -0,0 +1,420 @@
import { useEffect, useState } from "react";
import type {
Backend,
BedrockAuthMethod,
BedrockConfig,
OllamaConfig,
OpenAiCompatibleConfig,
Project,
} from "../../../../lib/types";
import Field, {
ConfigGroup,
SwitchRow,
monoInputClass,
selectClass,
} from "../../../ui/Field";
import Toggle from "../../../ui/Toggle";
export const DEFAULT_BEDROCK_CONFIG: BedrockConfig = {
auth_method: "static_credentials",
aws_region: "us-east-1",
aws_access_key_id: null,
aws_secret_access_key: null,
aws_session_token: null,
aws_profile: null,
aws_bearer_token: null,
model_id: null,
disable_prompt_caching: false,
service_tier: null,
};
export const DEFAULT_OLLAMA_CONFIG: OllamaConfig = {
base_url: "http://host.docker.internal:11434",
model_id: null,
};
export const DEFAULT_OPENAI_COMPATIBLE_CONFIG: OpenAiCompatibleConfig = {
base_url: "http://host.docker.internal:4000",
api_key: null,
model_id: null,
};
interface Props {
project: Project;
save: (patch: Partial<Project>) => Promise<boolean>;
disabled: boolean;
}
export default function ModelSection({ project, save, disabled }: Props) {
const bedrock = project.bedrock_config ?? DEFAULT_BEDROCK_CONFIG;
// Local text state — saved on blur, not on every keystroke.
const [bedrockRegion, setBedrockRegion] = useState(bedrock.aws_region);
const [accessKeyId, setAccessKeyId] = useState(bedrock.aws_access_key_id ?? "");
const [secretKey, setSecretKey] = useState(bedrock.aws_secret_access_key ?? "");
const [sessionToken, setSessionToken] = useState(bedrock.aws_session_token ?? "");
const [profile, setProfile] = useState(bedrock.aws_profile ?? "");
const [bearerToken, setBearerToken] = useState(bedrock.aws_bearer_token ?? "");
const [bedrockModelId, setBedrockModelId] = useState(bedrock.model_id ?? "");
const [serviceTier, setServiceTier] = useState(bedrock.service_tier ?? "");
const [ollamaBaseUrl, setOllamaBaseUrl] = useState(
project.ollama_config?.base_url ?? DEFAULT_OLLAMA_CONFIG.base_url,
);
const [ollamaModelId, setOllamaModelId] = useState(
project.ollama_config?.model_id ?? "",
);
const [oaiBaseUrl, setOaiBaseUrl] = useState(
project.openai_compatible_config?.base_url ??
DEFAULT_OPENAI_COMPATIBLE_CONFIG.base_url,
);
const [oaiApiKey, setOaiApiKey] = useState(
project.openai_compatible_config?.api_key ?? "",
);
const [oaiModelId, setOaiModelId] = useState(
project.openai_compatible_config?.model_id ?? "",
);
useEffect(() => {
const bc = project.bedrock_config ?? DEFAULT_BEDROCK_CONFIG;
setBedrockRegion(bc.aws_region);
setAccessKeyId(bc.aws_access_key_id ?? "");
setSecretKey(bc.aws_secret_access_key ?? "");
setSessionToken(bc.aws_session_token ?? "");
setProfile(bc.aws_profile ?? "");
setBearerToken(bc.aws_bearer_token ?? "");
setBedrockModelId(bc.model_id ?? "");
setServiceTier(bc.service_tier ?? "");
setOllamaBaseUrl(project.ollama_config?.base_url ?? DEFAULT_OLLAMA_CONFIG.base_url);
setOllamaModelId(project.ollama_config?.model_id ?? "");
setOaiBaseUrl(
project.openai_compatible_config?.base_url ??
DEFAULT_OPENAI_COMPATIBLE_CONFIG.base_url,
);
setOaiApiKey(project.openai_compatible_config?.api_key ?? "");
setOaiModelId(project.openai_compatible_config?.model_id ?? "");
}, [project]);
const saveBedrock = (patch: Partial<BedrockConfig>) =>
save({ bedrock_config: { ...bedrock, ...patch } });
const saveOllama = (patch: Partial<OllamaConfig>) =>
save({
ollama_config: { ...(project.ollama_config ?? DEFAULT_OLLAMA_CONFIG), ...patch },
});
const saveOpenAi = (patch: Partial<OpenAiCompatibleConfig>) =>
save({
openai_compatible_config: {
...(project.openai_compatible_config ?? DEFAULT_OPENAI_COMPATIBLE_CONFIG),
...patch,
},
});
// Defaults to on: projects created before the field existed, and any data
// that predates it, should still pick the shared token up.
const useSharedToken = project.use_shared_auth_token !== false;
const handleBackendChange = (mode: Backend) => {
const patch: Partial<Project> = { backend: mode };
if (mode === "bedrock" && !project.bedrock_config)
patch.bedrock_config = DEFAULT_BEDROCK_CONFIG;
if (mode === "ollama" && !project.ollama_config)
patch.ollama_config = DEFAULT_OLLAMA_CONFIG;
if (mode === "open_ai_compatible" && !project.openai_compatible_config)
patch.openai_compatible_config = DEFAULT_OPENAI_COMPATIBLE_CONFIG;
save(patch);
};
return (
<ConfigGroup title="Model" description="Which provider serves this project's Claude.">
<Field
label="Backend"
hint="Anthropic connects directly via OAuth (run `claude login` in a terminal). Bedrock routes through AWS. Ollama and OpenAI Compatible point at any compatible endpoint."
>
{(id) => (
<select
id={id}
value={project.backend}
onChange={(e) => handleBackendChange(e.target.value as Backend)}
disabled={disabled}
className={selectClass}
>
<option value="anthropic">Anthropic</option>
<option value="bedrock">Bedrock</option>
<option value="ollama">Ollama</option>
<option value="open_ai_compatible">OpenAI Compatible</option>
</select>
)}
</Field>
{/* Only Anthropic reads CLAUDE_CODE_OAUTH_TOKEN; the other backends
authenticate through their own credentials entirely. */}
{project.backend === "anthropic" && (
<div className="pt-2 border-t border-[var(--border-color)]">
<SwitchRow
label="Use the shared Claude token"
hint={
useSharedToken
? "Signs in with the shared token from Settings → Claude Authentication, so this container needs no `claude login` of its own."
: "This project is opted out: it ignores the shared token and needs its own `claude login` inside the container."
}
control={
<Toggle
label="Use the shared Claude token"
checked={useSharedToken}
onChange={(value) => save({ use_shared_auth_token: value })}
disabled={disabled}
/>
}
/>
</div>
)}
{project.backend === "bedrock" && (
<div className="space-y-4 pt-2 border-t border-[var(--border-color)]">
<Field label="Authentication method" hint="How the container proves its identity to Bedrock.">
{(id) => (
<select
id={id}
value={bedrock.auth_method}
onChange={(e) =>
saveBedrock({ auth_method: e.target.value as BedrockAuthMethod })
}
disabled={disabled}
className={selectClass}
>
<option value="static_credentials">Static keys</option>
<option value="profile">Named profile</option>
<option value="bearer_token">Bearer token</option>
</select>
)}
</Field>
<Field label="AWS region" hint="Region where your Bedrock endpoint is available.">
{(id) => (
<input
id={id}
value={bedrockRegion}
onChange={(e) => setBedrockRegion(e.target.value)}
onBlur={() => saveBedrock({ aws_region: bedrockRegion })}
placeholder="us-east-1"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
{bedrock.auth_method === "static_credentials" && (
<>
<Field label="Access key ID" hint="IAM access key used for Bedrock API calls.">
{(id) => (
<input
id={id}
value={accessKeyId}
onChange={(e) => setAccessKeyId(e.target.value)}
onBlur={() => saveBedrock({ aws_access_key_id: accessKeyId || null })}
placeholder="AKIA…"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
<Field
label="Secret access key"
hint="Stored locally and injected as an env var into the container."
>
{(id) => (
<input
id={id}
type="password"
value={secretKey}
onChange={(e) => setSecretKey(e.target.value)}
onBlur={() =>
saveBedrock({ aws_secret_access_key: secretKey || null })
}
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
<Field
label="Session token"
hint="Optional — for assumed-role or MFA-based credentials."
>
{(id) => (
<input
id={id}
type="password"
value={sessionToken}
onChange={(e) => setSessionToken(e.target.value)}
onBlur={() =>
saveBedrock({ aws_session_token: sessionToken || null })
}
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
</>
)}
{bedrock.auth_method === "profile" && (
<Field
label="AWS profile"
hint="Named profile from your AWS config/credentials files."
>
{(id) => (
<input
id={id}
value={profile}
onChange={(e) => setProfile(e.target.value)}
onBlur={() => saveBedrock({ aws_profile: profile || null })}
placeholder="default"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
)}
{bedrock.auth_method === "bearer_token" && (
<Field
label="Bearer token"
hint="SSO or identity-center token for Bedrock authentication."
>
{(id) => (
<input
id={id}
type="password"
value={bearerToken}
onChange={(e) => setBearerToken(e.target.value)}
onBlur={() => saveBedrock({ aws_bearer_token: bearerToken || null })}
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
)}
<Field label="Model ID" hint="Optional override. Leave blank for Claude's default.">
{(id) => (
<input
id={id}
value={bedrockModelId}
onChange={(e) => setBedrockModelId(e.target.value)}
onBlur={() => saveBedrock({ model_id: bedrockModelId || null })}
placeholder="anthropic.claude-sonnet-4-20250514-v1:0"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
<Field
label="Service tier"
hint="Optional — sets ANTHROPIC_BEDROCK_SERVICE_TIER (e.g. “priority”)."
>
{(id) => (
<input
id={id}
value={serviceTier}
onChange={(e) => setServiceTier(e.target.value)}
onBlur={() => saveBedrock({ service_tier: serviceTier.trim() || null })}
placeholder="(account default)"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
</div>
)}
{project.backend === "ollama" && (
<div className="space-y-4 pt-2 border-t border-[var(--border-color)]">
<Field
label="Base URL"
hint="Use host.docker.internal to reach the host machine, or an IP/hostname for a remote server."
>
{(id) => (
<input
id={id}
value={ollamaBaseUrl}
onChange={(e) => setOllamaBaseUrl(e.target.value)}
onBlur={() => saveOllama({ base_url: ollamaBaseUrl })}
placeholder="http://host.docker.internal:11434"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
<Field
label="Model"
hint="Required. The model must already be pulled in Ollama before the container starts."
>
{(id) => (
<input
id={id}
value={ollamaModelId}
onChange={(e) => setOllamaModelId(e.target.value)}
onBlur={() => saveOllama({ model_id: ollamaModelId || null })}
placeholder="qwen3.5:27b"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
</div>
)}
{project.backend === "open_ai_compatible" && (
<div className="space-y-4 pt-2 border-t border-[var(--border-color)]">
<Field
label="Base URL"
hint="Any OpenAI API-compatible endpoint — LiteLLM, OpenRouter, vLLM, and so on."
>
{(id) => (
<input
id={id}
value={oaiBaseUrl}
onChange={(e) => setOaiBaseUrl(e.target.value)}
onBlur={() => saveOpenAi({ base_url: oaiBaseUrl })}
placeholder="http://host.docker.internal:4000"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
<Field label="API key" hint="Authentication key for the endpoint, if it requires one.">
{(id) => (
<input
id={id}
type="password"
value={oaiApiKey}
onChange={(e) => setOaiApiKey(e.target.value)}
onBlur={() => saveOpenAi({ api_key: oaiApiKey || null })}
placeholder="sk-…"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
<Field label="Model" hint="Optional — model identifier as configured by your provider.">
{(id) => (
<input
id={id}
value={oaiModelId}
onChange={(e) => setOaiModelId(e.target.value)}
onBlur={() => saveOpenAi({ model_id: oaiModelId || null })}
placeholder="gpt-4o / gemini-pro / …"
disabled={disabled}
className={monoInputClass}
/>
)}
</Field>
</div>
)}
</ConfigGroup>
);
}
@@ -0,0 +1,103 @@
import type { Project } from "../../../../lib/types";
import Toggle from "../../../ui/Toggle";
import { ConfigGroup, SwitchRow } from "../../../ui/Field";
import PermissionModeControl, { permissionModePatch } from "../../PermissionModeControl";
import ClaudeInstructionsEditor from "../../ClaudeInstructionsEditor";
import ClaudeCodeSettingsEditor from "../../ClaudeCodeSettingsEditor";
interface Props {
project: Project;
save: (patch: Partial<Project>) => Promise<boolean>;
disabled: boolean;
disabledReason?: string;
}
export default function RuntimeSection({
project,
save,
disabled,
disabledReason,
}: Props) {
return (
<>
<ConfigGroup
title="Runtime"
description="How much the sandbox lets Claude do, and what contains it."
>
<div className="pb-2 border-b border-[var(--border-color)]">
<PermissionModeControl
project={project}
onChange={(mode) => save(permissionModePatch(mode))}
/>
</div>
<SwitchRow
label="Sandbox mode"
hint="Claude Code's bash sandbox (bubblewrap filesystem and network isolation). Triple-C is the source of truth: toggling this overrides any manual /sandbox configuration in the container's settings.json on next start."
control={
<Toggle
label="Sandbox mode"
checked={project.sandbox_mode_enabled}
disabled={disabled}
onChange={(v) => save({ sandbox_mode_enabled: v })}
/>
}
/>
<SwitchRow
label="Allow container spawning"
hint="Mounts the Docker socket so Claude can build and run Docker containers from inside the sandbox."
control={
<Toggle
label="Allow container spawning"
checked={project.allow_docker_access}
disabled={disabled}
onChange={(v) => save({ allow_docker_access: v })}
/>
}
/>
<SwitchRow
label="Mission Control"
hint="A web dashboard for monitoring and managing Claude sessions remotely."
control={
<Toggle
label="Mission Control"
checked={project.mission_control_enabled}
disabled={disabled}
onChange={(v) => save({ mission_control_enabled: v })}
/>
}
/>
{disabled && disabledReason && (
<p className="text-xs text-[var(--text-disabled)]">{disabledReason}</p>
)}
</ConfigGroup>
<ConfigGroup
title="Claude instructions"
description="Written to ~/.claude/CLAUDE.md inside this project's container."
>
<ClaudeInstructionsEditor
instructions={project.claude_instructions ?? ""}
disabled={disabled}
disabledReason={disabledReason}
onSave={(value) => save({ claude_instructions: value || null })}
/>
</ConfigGroup>
<ConfigGroup
title="Claude Code settings"
description="Per-project CLI behaviour. These override the global defaults in Settings."
>
<ClaudeCodeSettingsEditor
settings={project.claude_code_settings}
disabled={disabled}
disabledReason={disabledReason}
onSave={(settings) => save({ claude_code_settings: settings })}
/>
</ConfigGroup>
</>
);
}
@@ -0,0 +1,145 @@
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import type { Project, ProjectPath } from "../../../../lib/types";
import Button from "../../../ui/Button";
import Field, { ConfigGroup, inputClass, monoInputClass } from "../../../ui/Field";
interface Props {
project: Project;
save: (patch: Partial<Project>) => Promise<boolean>;
disabled: boolean;
}
export default function WorkspaceSection({ project, save, disabled }: Props) {
const [name, setName] = useState(project.name);
const [paths, setPaths] = useState<ProjectPath[]>(project.paths ?? []);
useEffect(() => {
setName(project.name);
setPaths(project.paths ?? []);
}, [project]);
return (
<ConfigGroup
title="Workspace"
description="What this sandbox is called and which host folders it can see."
>
<Field
label="Project name"
hint="Shown in the sidebar and on terminal tabs."
>
{(id) => (
<input
id={id}
value={name}
onChange={(e) => setName(e.target.value)}
onBlur={() => {
const trimmed = name.trim();
if (!trimmed) {
setName(project.name);
return;
}
if (trimmed !== project.name) save({ name: trimmed });
}}
onKeyDown={(e) => {
if (e.key === "Enter") (e.target as HTMLInputElement).blur();
if (e.key === "Escape") setName(project.name);
}}
className={inputClass}
/>
)}
</Field>
<div>
<span className="block text-[13px] font-medium text-[var(--text-primary)]">
Folders
</span>
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
Each host folder is mounted at <span className="font-mono">/workspace/&lt;name&gt;</span>{" "}
inside the container.
</p>
<div className="space-y-3">
{paths.map((pp, i) => (
<div key={i} className="flex flex-col gap-1.5 sm:flex-row sm:items-center">
<input
value={pp.host_path}
aria-label={`Folder ${i + 1} host path`}
onChange={(e) => {
const updated = [...paths];
updated[i] = { ...updated[i], host_path: e.target.value };
setPaths(updated);
}}
onBlur={() => save({ paths })}
placeholder="/path/to/folder"
disabled={disabled}
className={`flex-1 min-w-0 ${inputClass}`}
/>
<div className="flex items-center gap-1.5">
<Button
size="md"
disabled={disabled}
onClick={async () => {
const selected = await open({ directory: true, multiple: false });
if (typeof selected === "string") {
const updated = [...paths];
const basename =
selected.replace(/[/\\]$/, "").split(/[/\\]/).pop() || "";
updated[i] = {
host_path: selected,
mount_name: updated[i].mount_name || basename,
};
setPaths(updated);
save({ paths: updated });
}
}}
>
Browse
</Button>
<span className="text-xs text-[var(--text-secondary)] font-mono flex-shrink-0">
/workspace/
</span>
<input
value={pp.mount_name}
aria-label={`Folder ${i + 1} mount name`}
onChange={(e) => {
const updated = [...paths];
updated[i] = { ...updated[i], mount_name: e.target.value };
setPaths(updated);
}}
onBlur={() => save({ paths })}
placeholder="name"
disabled={disabled}
className={`w-40 ${monoInputClass}`}
/>
{paths.length > 1 && (
<Button
size="md"
variant="danger"
disabled={disabled}
aria-label={`Remove folder ${i + 1}`}
onClick={() => {
const updated = paths.filter((_, j) => j !== i);
setPaths(updated);
save({ paths: updated });
}}
>
Remove
</Button>
)}
</div>
</div>
))}
</div>
<Button
className="mt-2"
disabled={disabled}
onClick={() => setPaths([...paths, { host_path: "", mount_name: "" }])}
>
+ Add folder
</Button>
</div>
</ConfigGroup>
);
}
@@ -0,0 +1,39 @@
/** Shared formatting helpers for the Project Home views. */
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
}
/** "2h ago" / "3d ago". Returns null for unparseable timestamps. */
export function formatAge(iso: string | null | undefined): string | null {
if (!iso) return null;
const then = Date.parse(iso);
if (Number.isNaN(then)) return null;
return formatElapsed(Date.now() - then);
}
export function formatElapsed(ms: number): string {
const seconds = Math.max(0, Math.floor(ms / 1000));
if (seconds < 60) return "just now";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ${minutes % 60}m ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
/** Uptime phrasing for a known start timestamp. */
export function formatUptime(startedAtMs: number | undefined): string | null {
if (startedAtMs === undefined) return null;
const seconds = Math.floor((Date.now() - startedAtMs) / 1000);
if (seconds < 60) return "just started";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `up ${minutes}m`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `up ${hours}h ${minutes % 60}m`;
return `up ${Math.floor(hours / 24)}d`;
}
@@ -0,0 +1,156 @@
import { describe, it, expect } from "vitest";
import {
atTimestampIsPast,
describeCron,
validateAtTimestamp,
validateCronExpression,
validateTaskName,
validateTaskPrompt,
validateWorkingDir,
MAX_TASK_NAME_LEN,
MAX_TASK_PROMPT_LEN,
} from "./taskValidation";
describe("task field validation", () => {
it("requires a name that cannot be read as an option", () => {
expect(validateTaskName("nightly")).toBeNull();
expect(validateTaskName(" nightly ")).toBeNull();
expect(validateTaskName("")).toMatch(/required/i);
expect(validateTaskName(" ")).toMatch(/required/i);
expect(validateTaskName("-id")).toMatch(/cannot start/i);
expect(validateTaskName("--prompt")).toMatch(/cannot start/i);
expect(validateTaskName("two\nlines")).toMatch(/single line/i);
expect(validateTaskName("n".repeat(MAX_TASK_NAME_LEN + 1))).toMatch(/too long/i);
});
it("treats shell syntax in a name or prompt as ordinary text", () => {
// Nothing downstream is a shell, so these must not be rejected —
// over-blocking would be its own bug.
for (const value of ["; rm -rf /", "$(id)", "`id`", "a | b && c", "%pct"]) {
expect(validateTaskName(value)).toBeNull();
expect(validateTaskPrompt(value)).toBeNull();
}
});
it("requires a prompt and allows it to be multi-line", () => {
expect(validateTaskPrompt("Run the tests\nthen report")).toBeNull();
expect(validateTaskPrompt("")).toMatch(/required/i);
expect(validateTaskPrompt(" \n ")).toMatch(/required/i);
expect(validateTaskPrompt("p".repeat(MAX_TASK_PROMPT_LEN + 1))).toMatch(/too long/i);
expect(validateTaskPrompt("bad\u0000nul")).toMatch(/unsupported/i);
});
it("requires an absolute working directory, defaulting when blank", () => {
expect(validateWorkingDir("")).toBeNull();
expect(validateWorkingDir("/workspace/app")).toBeNull();
expect(validateWorkingDir("workspace")).toMatch(/absolute/i);
expect(validateWorkingDir("./rel")).toMatch(/absolute/i);
expect(validateWorkingDir("~/home")).toMatch(/absolute/i);
expect(validateWorkingDir("/workspace/../etc")).toMatch(/\.\./);
});
});
describe("cron validation", () => {
// Every expression below was checked against the container's own
// Debian/vixie `crontab` binary, which is the thing that ultimately accepts
// or rejects the schedule.
it("accepts expressions vixie cron accepts", () => {
for (const good of [
"* * * * *",
"*/30 * * * *",
"0 3 * * *",
"0 9 * * 1-5",
"0,30 9-17 * * 1-5",
"15 0 1 1 *",
"0 9 * * 0",
"0 9 * * 7",
"0 9 * * MON-FRI",
"0 0 1 JAN *",
"0-59/70 * * * *",
"1-5/2 * * * *",
"05 09 * * *",
]) {
expect(validateCronExpression(good), good).toBeNull();
}
});
it("rejects expressions vixie cron rejects", () => {
for (const bad of [
"",
"* * * *",
"* * * * * *",
"@daily",
"not a cron",
"99 * * * *",
"0 24 * * *",
"0 0 0 1 *",
"0 9 * * 8",
"0 9 * 13 *",
"*/0 * * * *",
"1/2 * * * *",
"0 9 * * jan",
"jan 9 * * *",
"0 9 * * mon,",
"0 9 * * 1--5",
"0 9 * * 1-5/x",
"0 9 * * *; rm -rf /",
"$(id) * * * *",
]) {
expect(validateCronExpression(bad), bad).not.toBeNull();
}
});
it("matches the backend's message shape for the field count", () => {
expect(validateCronExpression("* * * *")).toMatch(/exactly 5 fields/);
});
});
describe("describeCron", () => {
const cases: [string, string][] = [
["* * * * *", "Every minute, every day."],
["*/30 * * * *", "Every 30 minutes, every day."],
["0 * * * *", "At :00 past every hour, every day."],
["0,30 * * * *", "At :00 and :30 past every hour, every day."],
["0 9 * * *", "At 09:00, every day."],
["30 9 * * 1-5", "At 09:30, on Monday to Friday."],
["0 8 * * 1", "At 08:00, on Monday."],
["0 9 * * 0", "At 09:00, on Sunday."],
// 7 is Sunday too, and must not read as an eighth day.
["0 9 * * 7", "At 09:00, on Sunday."],
["0 9,17 * * *", "At 09:00 and 17:00, every day."],
["0 9-17 * * *", "At :00 past every hour from 09:00 to 17:00, every day."],
["0 */2 * * *", "At :00 past every 2 hours, every day."],
["0 0 1 * *", "At 00:00, on day 1 of the month."],
["0 0 1 1 *", "At 00:00, on day 1 of the month in January."],
["0 9 * * MON,THU", "At 09:00, on Monday and Thursday."],
];
it.each(cases)("reads %s as %s", (expression, expected) => {
expect(describeCron(expression)).toBe(expected);
});
it("says nothing rather than guessing when the expression is invalid", () => {
expect(describeCron("nope")).toBeNull();
expect(describeCron("99 * * * *")).toBeNull();
});
});
describe("one-shot timestamps", () => {
it("accepts only the scheduler's own format", () => {
expect(validateAtTimestamp("2026-12-25 09:05")).toBeNull();
expect(validateAtTimestamp("")).toMatch(/required/i);
// The scheduler's regex demands two digits everywhere.
expect(validateAtTimestamp("2026-1-5 09:05")).toMatch(/YYYY-MM-DD/);
expect(validateAtTimestamp("2026-12-25T09:05")).toMatch(/YYYY-MM-DD/);
expect(validateAtTimestamp("2026-12-25 09:05:00")).toMatch(/YYYY-MM-DD/);
expect(validateAtTimestamp("2026-02-30 09:05")).toMatch(/not a real/i);
expect(validateAtTimestamp("2026-12-25 25:00")).toMatch(/not a real/i);
});
it("flags a time in the past, because cron would fire it next year", () => {
const now = new Date(2026, 5, 1, 12, 0);
expect(atTimestampIsPast("2026-05-31 09:00", now)).toBe(true);
expect(atTimestampIsPast("2026-06-01 12:01", now)).toBe(false);
expect(atTimestampIsPast("nonsense", now)).toBe(false);
});
});
@@ -0,0 +1,329 @@
/**
* Client-side mirror of the scheduled-task rules in
* `src-tauri/src/commands/inspect_commands.rs`, plus a plain-English reading of
* a cron expression.
*
* The backend remains the authority it re-validates everything and is the
* only thing standing between a prompt and the container. This module exists so
* the form can say what is wrong *before* a round trip, and so the cron field
* can show the user what they actually typed.
*
* The cron rules match Debian/vixie cron, which is what the container runs:
* five fields, names in month and day-of-week only, day-of-week 07, and a
* `/step` only after `*` or a range (vixie rejects `1/2`).
*/
export const MAX_TASK_NAME_LEN = 100;
export const MAX_TASK_PROMPT_LEN = 8000;
export const MAX_WORKING_DIR_LEN = 512;
export const DEFAULT_WORKING_DIR = "/workspace";
const MAX_CRON_LEN = 256;
const MAX_CRON_STEP = 1000;
const MONTH_NAMES = [
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec",
];
const DOW_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
const MONTH_LABELS = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December",
];
const DOW_LABELS = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
];
interface CronFieldSpec {
label: string;
min: number;
max: number;
names: string[];
/** Numeric value of `names[0]` — 1 for January, 0 for Sunday. */
nameBase: number;
}
const CRON_FIELDS: CronFieldSpec[] = [
{ label: "minute", min: 0, max: 59, names: [], nameBase: 0 },
{ label: "hour", min: 0, max: 23, names: [], nameBase: 0 },
{ label: "day of month", min: 1, max: 31, names: [], nameBase: 0 },
{ label: "month", min: 1, max: 12, names: MONTH_NAMES, nameBase: 1 },
{ label: "day of week", min: 0, max: 7, names: DOW_NAMES, nameBase: 0 },
];
/** A handful of schedules that cover most of what people actually want. */
export const CRON_PRESETS: { label: string; expression: string }[] = [
{ label: "Every 30 minutes", expression: "*/30 * * * *" },
{ label: "Hourly", expression: "0 * * * *" },
{ label: "Daily at 09:00", expression: "0 9 * * *" },
{ label: "Weekdays at 09:00", expression: "0 9 * * 1-5" },
{ label: "Mondays at 08:00", expression: "0 8 * * 1" },
];
// ── Field validation ─────────────────────────────────────────────────────────
/** `null` means valid; otherwise the message to show under the field. */
export type FieldError = string | null;
/** C0 and C1 control characters. */
// eslint-disable-next-line no-control-regex
const CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]/;
/** The same, minus tab / LF / CR — a multi-line prompt is normal. */
// eslint-disable-next-line no-control-regex
const CONTROL_CHARS_EXCEPT_WHITESPACE =
/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/;
const hasControlChars = (value: string, allowNewlines: boolean) =>
(allowNewlines ? CONTROL_CHARS_EXCEPT_WHITESPACE : CONTROL_CHARS).test(value);
export function validateTaskName(name: string): FieldError {
const trimmed = name.trim();
if (!trimmed) return "Task name is required.";
if ([...trimmed].length > MAX_TASK_NAME_LEN)
return `Task name is too long (max ${MAX_TASK_NAME_LEN} characters).`;
if (hasControlChars(trimmed, false)) return "Task name must be a single line.";
if (trimmed.startsWith("-")) return "Task name cannot start with “-”.";
return null;
}
export function validateTaskPrompt(prompt: string): FieldError {
const trimmed = prompt.trim();
if (!trimmed) return "Task prompt is required.";
if ([...trimmed].length > MAX_TASK_PROMPT_LEN)
return `Task prompt is too long (max ${MAX_TASK_PROMPT_LEN} characters).`;
if (hasControlChars(trimmed, true)) return "Task prompt contains an unsupported character.";
return null;
}
export function validateWorkingDir(dir: string): FieldError {
const trimmed = dir.trim();
if (!trimmed) return null; // Blank falls back to /workspace, as the CLI does.
if ([...trimmed].length > MAX_WORKING_DIR_LEN)
return `Working directory is too long (max ${MAX_WORKING_DIR_LEN} characters).`;
if (hasControlChars(trimmed, false)) return "Working directory must be a single line.";
if (!trimmed.startsWith("/"))
return "Working directory must be an absolute path inside the container, e.g. /workspace.";
if (trimmed.split("/").includes("..")) return "Working directory cannot contain “..”.";
return null;
}
// ── Cron ─────────────────────────────────────────────────────────────────────
function cronValue(spec: CronFieldSpec, token: string): number | null {
if (token.length > 0 && /^[0-9]+$/.test(token)) {
const value = Number(token);
return value >= spec.min && value <= spec.max ? value : null;
}
const index = spec.names.indexOf(token.toLowerCase());
return index >= 0 ? index + spec.nameBase : null;
}
function validateCronElement(spec: CronFieldSpec, element: string): FieldError {
if (!element) return `Empty value in the ${spec.label} field.`;
const slash = element.indexOf("/");
const base = slash === -1 ? element : element.slice(0, slash);
if (slash !== -1) {
const raw = element.slice(slash + 1);
if (!/^[0-9]{1,4}$/.test(raw))
return `${element}” in the ${spec.label} field: a step must be a number, like */5.`;
const step = Number(raw);
if (step < 1 || step > MAX_CRON_STEP)
return `${element}” in the ${spec.label} field: a step must be between 1 and ${MAX_CRON_STEP}.`;
if (base !== "*" && !base.includes("-"))
return `${element}” in the ${spec.label} field: a step can only follow * or a range, like */5 or 1-5/2.`;
}
if (base === "*") return null;
const dash = base.indexOf("-");
const tokens = dash === -1 ? [base] : [base.slice(0, dash), base.slice(dash + 1)];
for (const token of tokens) {
if (cronValue(spec, token) === null) {
return /^[0-9]+$/.test(token)
? `${token}” is out of range for the ${spec.label} field (${spec.min}${spec.max}).`
: `${token}” is not valid in the ${spec.label} field.`;
}
}
return null;
}
export function validateCronExpression(expression: string): FieldError {
if (expression.length > MAX_CRON_LEN)
return `Cron expression is too long (max ${MAX_CRON_LEN} characters).`;
const fields = expression.trim().split(/\s+/).filter(Boolean);
if (fields.length !== 5)
return `A cron schedule needs exactly 5 fields (minute hour day-of-month month day-of-week); got ${fields.length}.`;
for (let i = 0; i < 5; i++) {
for (const element of fields[i].split(",")) {
const error = validateCronElement(CRON_FIELDS[i], element);
if (error) return error;
}
}
return null;
}
/** Matches the scheduler's own `--at` regex, then checks it is a real instant. */
export function validateAtTimestamp(at: string): FieldError {
const trimmed = at.trim();
if (!trimmed) return "A date and time is required.";
const match = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/.exec(trimmed);
if (!match) return "Use the format YYYY-MM-DD HH:MM, e.g. 2026-12-25 09:05.";
const [, y, mo, d, h, mi] = match.map(Number);
const date = new Date(y, mo - 1, d, h, mi);
const real =
date.getFullYear() === y &&
date.getMonth() === mo - 1 &&
date.getDate() === d &&
date.getHours() === h &&
date.getMinutes() === mi;
return real ? null : "That is not a real date and time.";
}
/** `true` when a valid one-shot time has already passed (a warning, not an error). */
export function atTimestampIsPast(at: string, now: Date = new Date()): boolean {
if (validateAtTimestamp(at)) return false;
const [datePart, timePart] = at.trim().split(" ");
const [y, mo, d] = datePart.split("-").map(Number);
const [h, mi] = timePart.split(":").map(Number);
return new Date(y, mo - 1, d, h, mi).getTime() < now.getTime();
}
// ── Plain-English reading of a cron expression ───────────────────────────────
const pad = (n: number) => String(n).padStart(2, "0");
function joinList(items: string[]): string {
if (items.length <= 1) return items[0] ?? "";
if (items.length === 2) return `${items[0]} and ${items[1]}`;
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
}
/** The step of a bare `*/n` field, or `null` for anything else. */
function simpleStep(field: string): number | null {
const match = /^\*\/([0-9]+)$/.exec(field);
return match ? Number(match[1]) : null;
}
/**
* Every value a (already valid) field selects, or `null` for "all of them".
* Bounded by the field's own range, so this cannot run away.
*/
function expandField(spec: CronFieldSpec, field: string): number[] | null {
if (field === "*") return null;
const values = new Set<number>();
for (const element of field.split(",")) {
const slash = element.indexOf("/");
const base = slash === -1 ? element : element.slice(0, slash);
const step = slash === -1 ? 1 : Number(element.slice(slash + 1));
let from: number;
let to: number;
if (base === "*") {
from = spec.min;
to = spec.max;
} else {
const dash = base.indexOf("-");
if (dash === -1) {
from = to = cronValue(spec, base) as number;
} else {
from = cronValue(spec, base.slice(0, dash)) as number;
to = cronValue(spec, base.slice(dash + 1)) as number;
}
}
for (let v = from; v <= to; v += step) values.add(v);
}
const sorted = [...values].sort((a, b) => a - b);
// A field that names every value reads better as "every".
return sorted.length >= spec.max - spec.min + 1 ? null : sorted;
}
const isContiguous = (values: number[]) =>
values.every((v, i) => i === 0 || v === values[i - 1] + 1);
function timePhrase(
minutes: number[] | null,
hours: number[] | null,
minuteField: string,
hourField: string,
): string {
if (minutes === null && hours === null) return "Every minute";
if (hours === null) {
const step = simpleStep(minuteField);
if (step !== null) return step === 1 ? "Every minute" : `Every ${step} minutes`;
return `At ${joinList((minutes as number[]).map((m) => `:${pad(m)}`))} past every hour`;
}
if (minutes === null) {
return `Every minute of ${joinList(hours.map((h) => `${pad(h)}:00`))}`;
}
const hourStep = simpleStep(hourField);
if (hourStep !== null && minutes.length === 1) {
return `At :${pad(minutes[0])} past every ${hourStep === 1 ? "hour" : `${hourStep} hours`}`;
}
if (minutes.length === 1 && hours.length >= 3 && isContiguous(hours)) {
return `At :${pad(minutes[0])} past every hour from ${pad(hours[0])}:00 to ${pad(
hours[hours.length - 1],
)}:00`;
}
const times: string[] = [];
for (const h of hours) for (const m of minutes) times.push(`${pad(h)}:${pad(m)}`);
if (times.length <= 6) return `At ${joinList(times)}`;
return `At minute ${joinList(minutes.map(String))} of hour ${joinList(hours.map(String))}`;
}
function weekdayPhrase(dows: number[]): string {
const labels = dows.map((d) => DOW_LABELS[d]);
if (dows.length >= 3 && isContiguous(dows))
return `${labels[0]} to ${labels[labels.length - 1]}`;
return joinList(labels);
}
function dayPhrase(doms: number[] | null, dows: number[] | null): string {
if (doms === null && dows === null) return "every day";
if (dows !== null && doms === null) return `on ${weekdayPhrase(dows)}`;
if (doms !== null && dows === null)
return `on day ${joinList(doms.map(String))} of the month`;
// Cron ORs the two day fields when both are restricted.
return `on day ${joinList((doms as number[]).map(String))} of the month or on ${weekdayPhrase(
dows as number[],
)}`;
}
/**
* Read a cron expression back to the user in English, or `null` if it is not
* valid. Deliberately a *reading*, not a scheduler: it never claims to know the
* next run time.
*/
export function describeCron(expression: string): string | null {
if (validateCronExpression(expression)) return null;
const [minuteField, hourField, domField, monthField, dowField] = expression
.trim()
.split(/\s+/);
const minutes = expandField(CRON_FIELDS[0], minuteField);
const hours = expandField(CRON_FIELDS[1], hourField);
const doms = expandField(CRON_FIELDS[2], domField);
const months = expandField(CRON_FIELDS[3], monthField);
let dows = expandField(CRON_FIELDS[4], dowField);
if (dows) {
// 0 and 7 are both Sunday.
dows = [...new Set(dows.map((d) => (d === 7 ? 0 : d)))].sort((a, b) => a - b);
if (dows.length === 7) dows = null;
}
const monthPart =
months === null ? "" : ` in ${joinList(months.map((m) => MONTH_LABELS[m - 1]))}`;
return `${timePhrase(minutes, hours, minuteField, hourField)}, ${dayPhrase(
doms,
dows,
)}${monthPart}.`;
}
+4 -4
View File
@@ -65,7 +65,7 @@ export default function AwsSettings() {
value={globalAws.aws_config_path ?? ""} value={globalAws.aws_config_path ?? ""}
onChange={(e) => handleChange("aws_config_path", e.target.value)} onChange={(e) => handleChange("aws_config_path", e.target.value)}
placeholder="~/.aws" placeholder="~/.aws"
className="flex-1 px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="flex-1 px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
<button <button
onClick={handleDetect} onClick={handleDetect}
@@ -86,7 +86,7 @@ export default function AwsSettings() {
<select <select
value={globalAws.aws_profile ?? ""} value={globalAws.aws_profile ?? ""}
onChange={(e) => handleChange("aws_profile", e.target.value)} onChange={(e) => handleChange("aws_profile", e.target.value)}
className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] text-[var(--text-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
> >
<option value="">None (use default)</option> <option value="">None (use default)</option>
{profiles.map((p) => ( {profiles.map((p) => (
@@ -103,7 +103,7 @@ export default function AwsSettings() {
value={globalAws.aws_region ?? ""} value={globalAws.aws_region ?? ""}
onChange={(e) => handleChange("aws_region", e.target.value)} onChange={(e) => handleChange("aws_region", e.target.value)}
placeholder="e.g., us-east-1" placeholder="e.g., us-east-1"
className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
@@ -115,7 +115,7 @@ export default function AwsSettings() {
value={globalAws.default_model_id ?? ""} value={globalAws.default_model_id ?? ""}
onChange={(e) => handleChange("default_model_id", e.target.value)} onChange={(e) => handleChange("default_model_id", e.target.value)}
placeholder="anthropic.claude-sonnet-4-20250514-v1:0" placeholder="anthropic.claude-sonnet-4-20250514-v1:0"
className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
</div> </div>
@@ -0,0 +1,205 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, act } from "@testing-library/react";
import ClaudeAuthModal from "./ClaudeAuthModal";
const acquireClaudeToken = vi.fn();
const submitClaudeTokenCode = vi.fn();
vi.mock("../../lib/tauri-commands", () => ({
acquireClaudeToken: (...args: unknown[]) => acquireClaudeToken(...args),
submitClaudeTokenCode: (...args: unknown[]) => submitClaudeTokenCode(...args),
hasClaudeToken: vi.fn(),
clearClaudeToken: vi.fn(),
cancelClaudeToken: (...args: unknown[]) => cancelClaudeToken(...args),
}));
const cancelClaudeToken = vi.fn(() => Promise.resolve());
const openUrl = vi.fn();
vi.mock("@tauri-apps/plugin-opener", () => ({
openUrl: (...args: unknown[]) => openUrl(...args),
}));
/** Captured event handlers, keyed by event name, so tests can emit. */
const handlers = new Map<string, (event: { payload: unknown }) => void>();
const unlisten = vi.fn();
vi.mock("@tauri-apps/api/event", () => ({
listen: vi.fn(async (name: string, handler: (e: { payload: unknown }) => void) => {
handlers.set(name, handler);
return unlisten;
}),
}));
function emitOutput(chunk: string, projectId = "p1") {
act(() => {
handlers.get("claude-token-output")?.({
payload: { project_id: projectId, chunk },
});
});
}
function renderModal(
overrides: { onClose?: () => void; onAuthenticated?: () => void } = {},
) {
return render(
<ClaudeAuthModal
projectId="p1"
projectName="api-server"
onClose={overrides.onClose ?? vi.fn()}
onAuthenticated={overrides.onAuthenticated ?? vi.fn()}
/>,
);
}
/** Both listeners register before `acquire_claude_token` is invoked. */
async function flowStarted() {
await waitFor(() => expect(acquireClaudeToken).toHaveBeenCalledWith("p1"));
}
describe("ClaudeAuthModal", () => {
beforeEach(() => {
vi.clearAllMocks();
handlers.clear();
// A flow that never resolves on its own — the CLI is sitting on its prompt.
acquireClaudeToken.mockImplementation(() => new Promise(() => {}));
submitClaudeTokenCode.mockResolvedValue(undefined);
});
it("starts the flow for the given project", async () => {
renderModal();
await flowStarted();
});
it("submits the pasted code to the backend", async () => {
renderModal();
await flowStarted();
fireEvent.change(screen.getByLabelText("Authentication code"), {
target: { value: " code-123 " },
});
fireEvent.click(screen.getByRole("button", { name: "Submit code" }));
// Trimmed on the way out — the backend rejects surrounding whitespace noise.
await waitFor(() =>
expect(submitClaudeTokenCode).toHaveBeenCalledWith("code-123"),
);
await waitFor(() =>
expect(screen.getByLabelText("Authentication code")).toHaveValue(""),
);
});
it("submits on Enter as well as on the button", async () => {
renderModal();
await flowStarted();
const input = screen.getByLabelText("Authentication code");
fireEvent.change(input, { target: { value: "code-456" } });
fireEvent.submit(input.closest("form")!);
await waitFor(() =>
expect(submitClaudeTokenCode).toHaveBeenCalledWith("code-456"),
);
});
it("refuses an empty code without calling the backend", async () => {
renderModal();
await flowStarted();
fireEvent.click(screen.getByRole("button", { name: "Submit code" }));
await screen.findByText("Enter the code shown after signing in.");
expect(submitClaudeTokenCode).not.toHaveBeenCalled();
});
it("reports a backend rejection instead of dumping the raw value", async () => {
submitClaudeTokenCode.mockRejectedValue(
"That code contains invalid characters. Copy it again and retry.",
);
renderModal();
await flowStarted();
fireEvent.change(screen.getByLabelText("Authentication code"), {
target: { value: "bad" },
});
fireEvent.click(screen.getByRole("button", { name: "Submit code" }));
await screen.findByText(
"That code contains invalid characters. Copy it again and retry.",
);
});
it("linkifies the sign-in URL from the streamed output and opens it in the host browser", async () => {
renderModal();
await flowStarted();
const url = "https://claude.ai/oauth/authorize?code=true&client_id=abc";
emitOutput(`Use this url to sign in:\n${url}\n`);
const link = await screen.findByRole("link", { name: url });
fireEvent.click(link);
await waitFor(() => expect(openUrl).toHaveBeenCalledWith(url));
});
it("ignores output belonging to a different project", async () => {
renderModal();
await flowStarted();
emitOutput("https://claude.ai/oauth/authorize?code=other", "p2");
expect(screen.getByTestId("claude-auth-output")).not.toHaveTextContent(
"code=other",
);
});
it("surfaces an actionable failure when the flow ends badly", async () => {
acquireClaudeToken.mockRejectedValue(
"`claude setup-token` finished but printed no recognisable token. Nothing was stored.",
);
renderModal();
const banner = await screen.findByTestId("claude-auth-error");
expect(banner).toHaveTextContent(/printed no recognisable token/);
});
it("announces success and notifies the caller", async () => {
acquireClaudeToken.mockResolvedValue(undefined);
const onAuthenticated = vi.fn();
renderModal({ onAuthenticated });
await screen.findByTestId("claude-auth-success");
expect(onAuthenticated).toHaveBeenCalledTimes(1);
});
it("confirms before cancelling, then aborts the container-side CLI", async () => {
const onClose = vi.fn();
renderModal({ onClose });
await flowStarted();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(screen.getByText(/no token is stored/i)).toBeInTheDocument();
// Confirming is required — the first click must not cancel anything.
expect(cancelClaudeToken).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Cancel sign-in" }));
await waitFor(() => expect(cancelClaudeToken).toHaveBeenCalledTimes(1));
await waitFor(() => expect(onClose).toHaveBeenCalled());
});
it("still closes when the cancel command rejects", async () => {
cancelClaudeToken.mockRejectedValueOnce(new Error("nope"));
const onClose = vi.fn();
renderModal({ onClose });
await flowStarted();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
fireEvent.click(screen.getByRole("button", { name: "Cancel sign-in" }));
await waitFor(() => expect(onClose).toHaveBeenCalled());
});
it("removes its event listeners on unmount", async () => {
const { unmount } = renderModal();
await flowStarted();
unmount();
await waitFor(() => expect(unlisten).toHaveBeenCalledTimes(2));
});
});
@@ -0,0 +1,306 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { openUrl } from "@tauri-apps/plugin-opener";
import { cancelClaudeToken } from "../../lib/tauri-commands";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
import StatusIndicator, { type StatusTone } from "../ui/StatusIndicator";
import { inputClass } from "../ui/Field";
import {
authErrorMessage,
useClaudeTokenAcquisition,
} from "../../hooks/useClaudeAuth";
interface Props {
/** Project whose running container is borrowed to run the CLI. */
projectId: string;
projectName: string;
onClose: () => void;
/** Fired once the token has been stored, so callers can re-check status. */
onAuthenticated: () => void;
}
const PHASE_STATUS: Record<string, { tone: StatusTone; label: string }> = {
waiting: { tone: "busy", label: "Waiting for sign-in" },
finishing: { tone: "busy", label: "Finishing sign-in" },
succeeded: { tone: "ok", label: "Token stored" },
failed: { tone: "error", label: "Authentication failed" },
};
/**
* Drives one `claude setup-token` run.
*
* The CLI prints a sign-in URL, the user signs in on an Anthropic-hosted page,
* copies a code from it, and the CLI then blocks on stdin waiting for that
* code. The input below is the only way to answer that prompt, so it is the
* centre of this dialog rather than a footnote.
*
* Everything shown here is redacted backend-side; the token is never sent to
* the frontend and is never held in component state.
*/
export default function ClaudeAuthModal({
projectId,
projectName,
onClose,
onAuthenticated,
}: Props) {
const flow = useClaudeTokenAcquisition(projectId, onAuthenticated);
const [code, setCode] = useState("");
const [copied, setCopied] = useState(false);
const [linkError, setLinkError] = useState<string | null>(null);
const [confirmCancel, setConfirmCancel] = useState(false);
const codeRef = useRef<HTMLInputElement>(null);
const outputRef = useRef<HTMLPreElement>(null);
const running = flow.phase === "running";
// Cancelling actually aborts the container-side `setup-token` and releases
// the single-flight guard, so the user can retry immediately. Closing without
// it would leave the CLI waiting until its 15-minute timeout, blocking any
// second attempt. Best-effort: if the flow just finished on its own the
// command is a no-op, and either way the dialog closes.
const handleCancel = useCallback(() => {
cancelClaudeToken()
.catch((e) => console.error("Failed to cancel Claude authentication:", e))
.finally(onClose);
}, [onClose]);
// Follow the tail of the transcript as it streams in.
useEffect(() => {
const el = outputRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [flow.output]);
useEffect(() => {
if (!copied) return;
const timer = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(timer);
}, [copied]);
const status =
flow.phase === "succeeded"
? PHASE_STATUS.succeeded
: flow.phase === "failed"
? PHASE_STATUS.failed
: flow.codeSubmitted
? PHASE_STATUS.finishing
: PHASE_STATUS.waiting;
const handleOpen = async () => {
if (!flow.signInUrl) return;
setLinkError(null);
try {
await openUrl(flow.signInUrl);
} catch (e) {
setLinkError(
authErrorMessage(
e,
"Could not hand the link to your browser. Copy it and paste it in manually.",
),
);
}
};
const handleCopy = async () => {
if (!flow.signInUrl) return;
setLinkError(null);
try {
await navigator.clipboard.writeText(flow.signInUrl);
setCopied(true);
} catch (e) {
setLinkError(
authErrorMessage(
e,
"Could not copy to the clipboard. Select the link text and copy it manually.",
),
);
}
};
const handleSubmitCode = async (e: React.FormEvent) => {
e.preventDefault();
const ok = await flow.submitCode(code);
if (ok) setCode("");
};
const latestProgress = flow.progress[flow.progress.length - 1] ?? null;
return (
<Modal
title="Shared Claude authentication"
description={
<>
Running <code className="font-mono">claude setup-token</code> in{" "}
<strong className="text-[var(--text-primary)]">{projectName}</strong>&rsquo;s
container. The token it produces is shared by every project.
</>
}
widthClassName="w-[40rem]"
dismissible={!running}
onClose={onClose}
initialFocusRef={codeRef}
footer={
confirmCancel ? (
<>
<Button size="md" onClick={() => setConfirmCancel(false)}>
Keep waiting
</Button>
<Button size="md" variant="danger" onClick={handleCancel}>
Cancel sign-in
</Button>
</>
) : running ? (
<Button size="md" variant="ghost" onClick={() => setConfirmCancel(true)}>
Cancel
</Button>
) : (
<Button
size="md"
variant={flow.phase === "succeeded" ? "primary" : "secondary"}
onClick={onClose}
>
{flow.phase === "succeeded" ? "Done" : "Close"}
</Button>
)
}
>
<div className="space-y-4">
<div className="flex items-center justify-between gap-3">
<StatusIndicator tone={status.tone} label={status.label} className="text-xs" />
{latestProgress && (
<p
data-testid="claude-auth-progress"
className="min-w-0 flex-1 text-right text-xs text-[var(--text-secondary)] truncate"
title={latestProgress}
>
{latestProgress}
</p>
)}
</div>
{/* Step 1 — sign in. */}
<section>
<h3 className="text-[13px] font-medium text-[var(--text-primary)]">
1. Sign in with Anthropic
</h3>
{flow.signInUrl ? (
<div className="mt-1 space-y-1.5">
<div className="flex items-center gap-1.5">
<a
href={flow.signInUrl}
onClick={(e) => {
e.preventDefault();
void handleOpen();
}}
className="min-w-0 flex-1 truncate px-2.5 py-1.5 font-mono text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] transition-colors"
title={flow.signInUrl}
>
{flow.signInUrl}
</a>
<Button size="md" onClick={() => void handleOpen()}>
Open
</Button>
<Button size="md" onClick={() => void handleCopy()}>
{copied ? "Copied ✓" : "Copy"}
</Button>
</div>
<p className="text-xs text-[var(--text-secondary)] leading-snug">
Opens in your normal browser. After signing in, Anthropic shows you a
code &mdash; copy it and paste it below.
</p>
</div>
) : (
<p className="mt-1 text-xs text-[var(--text-secondary)] leading-snug">
Waiting for <code className="font-mono">claude setup-token</code> to print
the sign-in link&hellip; It appears in the output below as soon as the CLI
starts.
</p>
)}
{linkError && (
<p className="mt-1 text-xs text-[var(--error)]">{linkError}</p>
)}
</section>
{/* Step 2 — the code. Without this the CLI sits on its stdin prompt forever. */}
<section>
<h3 className="text-[13px] font-medium text-[var(--text-primary)]">
2. Paste the code
</h3>
<form onSubmit={handleSubmitCode} className="mt-1 flex items-start gap-1.5">
<div className="min-w-0 flex-1">
<input
ref={codeRef}
type="text"
value={code}
onChange={(e) => setCode(e.target.value)}
disabled={!running || flow.submitting}
aria-label="Authentication code"
placeholder="Paste the code from the Anthropic page"
autoComplete="off"
spellCheck={false}
className={`${inputClass} font-mono`}
/>
{flow.submitError && (
<p className="mt-1 text-xs text-[var(--error)]">{flow.submitError}</p>
)}
{!flow.submitError && flow.codeSubmitted && running && (
<p className="mt-1 text-xs text-[var(--text-secondary)]">
Code sent. Waiting for <code className="font-mono">setup-token</code>{" "}
to finish&hellip;
</p>
)}
</div>
<Button
size="md"
variant="primary"
type="submit"
disabled={!running || flow.submitting}
>
{flow.submitting ? "Sending…" : "Submit code"}
</Button>
</form>
</section>
{/* Step 3 — outcome. */}
{flow.phase === "succeeded" && (
<p
data-testid="claude-auth-success"
className="px-2.5 py-2 text-xs text-[var(--success)] bg-[var(--success-muted)] border border-[var(--success)]/40 rounded-[var(--radius-control)]"
>
Token stored in the OS keychain. Restart your Anthropic-backend containers
to start using it.
</p>
)}
{flow.phase === "failed" && flow.error && (
<p
data-testid="claude-auth-error"
className="px-2.5 py-2 text-xs text-[var(--error)] bg-[var(--error-muted)] border border-[var(--error)]/40 rounded-[var(--radius-control)]"
>
{flow.error}
</p>
)}
{confirmCancel && (
<p className="px-2.5 py-2 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/40 rounded-[var(--radius-control)] leading-snug">
This stops <code className="font-mono">claude setup-token</code> inside the
container and discards the sign-in. No token is stored. You can start again
straight away.
</p>
)}
{/* Redacted backend-side before it is emitted; still never parsed here. */}
<section>
<h3 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)]">
Command output
</h3>
<pre
ref={outputRef}
data-testid="claude-auth-output"
aria-label="Command output"
className="mt-1 h-40 overflow-auto whitespace-pre-wrap break-words px-2.5 py-2 font-mono text-[11px] leading-relaxed text-[var(--text-secondary)] bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)]"
>
{flow.output || "Starting `claude setup-token`…\n"}
</pre>
</section>
</div>
</Modal>
);
}
@@ -96,7 +96,7 @@ export default function DockerSettings() {
onClick={() => handleSourceChange(opt.value)} onClick={() => handleSourceChange(opt.value)}
className={`flex-1 px-2 py-1.5 text-xs rounded border transition-colors ${ className={`flex-1 px-2 py-1.5 text-xs rounded border transition-colors ${
imageSource === opt.value imageSource === opt.value
? "bg-[var(--accent)] text-white border-[var(--accent)]" ? "bg-[var(--accent-emphasis)] text-white border-[var(--accent)]"
: "bg-[var(--bg-tertiary)] border-[var(--border-color)] hover:bg-[var(--border-color)]" : "bg-[var(--bg-tertiary)] border-[var(--border-color)] hover:bg-[var(--border-color)]"
}`} }`}
title={opt.description} title={opt.description}
@@ -116,7 +116,7 @@ export default function DockerSettings() {
value={customInput} value={customInput}
onChange={(e) => handleCustomChange(e.target.value)} onChange={(e) => handleCustomChange(e.target.value)}
placeholder="e.g., myregistry.com/image:tag" placeholder="e.g., myregistry.com/image:tag"
className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
)} )}
@@ -149,7 +149,7 @@ export default function DockerSettings() {
<button <button
onClick={handleBuild} onClick={handleBuild}
disabled={working || !dockerAvailable} disabled={working || !dockerAvailable}
className="px-3 py-1.5 text-xs bg-[var(--accent)] text-white rounded hover:bg-[var(--accent-hover)] disabled:opacity-50 transition-colors" className="px-3 py-1.5 text-xs bg-[var(--accent-emphasis)] text-white rounded hover:bg-[var(--accent-emphasis-hover)] disabled:text-[var(--text-disabled)] transition-colors"
> >
{working ? "Building..." : imageExists ? "Rebuild Image" : "Build Image"} {working ? "Building..." : imageExists ? "Rebuild Image" : "Build Image"}
</button> </button>
@@ -157,7 +157,7 @@ export default function DockerSettings() {
<button <button
onClick={handlePull} onClick={handlePull}
disabled={working || !dockerAvailable} disabled={working || !dockerAvailable}
className="px-3 py-1.5 text-xs bg-[var(--accent)] text-white rounded hover:bg-[var(--accent-hover)] disabled:opacity-50 transition-colors" className="px-3 py-1.5 text-xs bg-[var(--accent-emphasis)] text-white rounded hover:bg-[var(--accent-emphasis-hover)] disabled:text-[var(--text-disabled)] transition-colors"
> >
{working ? "Pulling..." : imageExists ? "Re-pull Image" : "Pull Image"} {working ? "Pulling..." : imageExists ? "Re-pull Image" : "Pull Image"}
</button> </button>
@@ -1,5 +1,6 @@
import { useEffect, useRef, useCallback } from "react";
import type { ImageUpdateInfo } from "../../lib/types"; import type { ImageUpdateInfo } from "../../lib/types";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
interface Props { interface Props {
imageUpdateInfo: ImageUpdateInfo; imageUpdateInfo: ImageUpdateInfo;
@@ -12,23 +13,6 @@ export default function ImageUpdateDialog({
onDismiss, onDismiss,
onClose, onClose,
}: Props) { }: Props) {
const overlayRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
const shortDigest = (digest: string) => { const shortDigest = (digest: string) => {
// Show first 16 chars of the hash part (after "sha256:") // Show first 16 chars of the hash part (after "sha256:")
const hash = digest.startsWith("sha256:") ? digest.slice(7) : digest; const hash = digest.startsWith("sha256:") ? digest.slice(7) : digest;
@@ -36,56 +20,45 @@ export default function ImageUpdateDialog({
}; };
return ( return (
<div <Modal
ref={overlayRef} title="Container Image Update"
onClick={handleOverlayClick} onClose={onClose}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" widthClassName="w-[30rem]"
footer={
<>
<Button variant="ghost" onClick={onDismiss}>
Dismiss
</Button>
<Button onClick={onClose}>Close</Button>
</>
}
> >
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[28rem] max-h-[80vh] overflow-y-auto shadow-xl"> <p className="text-[13px] text-[var(--text-secondary)] mb-4">
<h2 className="text-lg font-semibold mb-3">Container Image Update</h2> A newer version of the container image is available in the registry. Re-pull the
image in Docker settings to get the latest tools and fixes.
</p>
<p className="text-sm text-[var(--text-secondary)] mb-4"> <div className="space-y-2 mb-4 text-xs bg-[var(--bg-primary)] rounded-[var(--radius-control)] p-3 border border-[var(--border-color)]">
A newer version of the container image is available in the registry. {imageUpdateInfo.local_digest && (
Re-pull the image in Docker settings to get the latest tools and fixes.
</p>
<div className="space-y-2 mb-4 text-xs bg-[var(--bg-primary)] rounded p-3 border border-[var(--border-color)]">
{imageUpdateInfo.local_digest && (
<div className="flex justify-between">
<span className="text-[var(--text-secondary)]">Local digest</span>
<span className="font-mono text-[var(--text-primary)]">
{shortDigest(imageUpdateInfo.local_digest)}...
</span>
</div>
)}
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-[var(--text-secondary)]">Remote digest</span> <span className="text-[var(--text-secondary)]">Local digest</span>
<span className="font-mono text-[var(--accent)]"> <span className="font-mono text-[var(--text-primary)]">
{shortDigest(imageUpdateInfo.remote_digest)}... {shortDigest(imageUpdateInfo.local_digest)}
</span> </span>
</div> </div>
</div> )}
<div className="flex justify-between">
<p className="text-xs text-[var(--text-secondary)] mb-4"> <span className="text-[var(--text-secondary)]">Remote digest</span>
Go to Settings &gt; Docker and click &quot;Re-pull Image&quot; to update. <span className="font-mono text-[var(--accent)]">
Running containers will not be affected until restarted. {shortDigest(imageUpdateInfo.remote_digest)}
</p> </span>
<div className="flex items-center justify-end gap-2">
<button
onClick={onDismiss}
className="px-3 py-1.5 text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors"
>
Dismiss
</button>
<button
onClick={onClose}
className="px-3 py-1.5 text-xs bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] transition-colors"
>
Close
</button>
</div> </div>
</div> </div>
</div>
<p className="text-xs text-[var(--text-secondary)]">
Go to Settings &gt; Container and click &quot;Re-pull Image&quot; to update.
Running containers will not be affected until restarted.
</p>
</Modal>
); );
} }
@@ -77,7 +77,7 @@ export default function MicrophoneSettings() {
value={selected} value={selected}
onChange={(e) => handleChange(e.target.value)} onChange={(e) => handleChange(e.target.value)}
disabled={loading} disabled={loading}
className="flex-1 px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="flex-1 px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
> >
<option value="">System Default</option> <option value="">System Default</option>
{devices.map((d) => ( {devices.map((d) => (
@@ -90,7 +90,7 @@ export default function MicrophoneSettings() {
onClick={enumerateDevices} onClick={enumerateDevices}
disabled={loading} disabled={loading}
title="Refresh microphone list" title="Refresh microphone list"
className="text-xs px-2 py-1 text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-primary)] rounded transition-colors disabled:opacity-50" className="text-xs px-2 py-1 text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-primary)] rounded transition-colors disabled:text-[var(--text-disabled)]"
> >
{loading ? "..." : "Refresh"} {loading ? "..." : "Refresh"}
</button> </button>
@@ -33,7 +33,7 @@ export default function OllamaSettings() {
value={globalOllama.base_url ?? ""} value={globalOllama.base_url ?? ""}
onChange={(e) => handleChange("base_url", e.target.value)} onChange={(e) => handleChange("base_url", e.target.value)}
placeholder="http://host.docker.internal:11434" placeholder="http://host.docker.internal:11434"
className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
@@ -44,7 +44,7 @@ export default function OllamaSettings() {
value={globalOllama.default_model_id ?? ""} value={globalOllama.default_model_id ?? ""}
onChange={(e) => handleChange("default_model_id", e.target.value)} onChange={(e) => handleChange("default_model_id", e.target.value)}
placeholder="qwen3.5:27b" placeholder="qwen3.5:27b"
className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
</div> </div>
@@ -33,7 +33,7 @@ export default function OpenAiCompatibleSettings() {
value={globalOai.base_url ?? ""} value={globalOai.base_url ?? ""}
onChange={(e) => handleChange("base_url", e.target.value)} onChange={(e) => handleChange("base_url", e.target.value)}
placeholder="http://host.docker.internal:4000" placeholder="http://host.docker.internal:4000"
className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
@@ -44,7 +44,7 @@ export default function OpenAiCompatibleSettings() {
value={globalOai.default_model_id ?? ""} value={globalOai.default_model_id ?? ""}
onChange={(e) => handleChange("default_model_id", e.target.value)} onChange={(e) => handleChange("default_model_id", e.target.value)}
placeholder="gpt-4o / gemini-pro / etc." placeholder="gpt-4o / gemini-pro / etc."
className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
</div> </div>
+18 -17
View File
@@ -12,8 +12,10 @@ import { detectHostTimezone } from "../../lib/tauri-commands";
import type { EnvVar } from "../../lib/types"; import type { EnvVar } from "../../lib/types";
import Tooltip from "../ui/Tooltip"; import Tooltip from "../ui/Tooltip";
import AccordionSection from "../ui/AccordionSection"; import AccordionSection from "../ui/AccordionSection";
import Toggle from "../ui/Toggle";
import WebTerminalSettings from "./WebTerminalSettings"; import WebTerminalSettings from "./WebTerminalSettings";
import SttSettings from "./SttSettings"; import SttSettings from "./SttSettings";
import SharedAuthSettings from "./SharedAuthSettings";
export default function SettingsPanel() { export default function SettingsPanel() {
const { appSettings, saveSettings } = useSettings(); const { appSettings, saveSettings } = useSettings();
@@ -86,7 +88,7 @@ export default function SettingsPanel() {
} }
}} }}
placeholder="UTC" placeholder="UTC"
className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
@@ -148,6 +150,10 @@ export default function SettingsPanel() {
</div> </div>
</AccordionSection> </AccordionSection>
<AccordionSection id="claude-auth" title="Claude Authentication" defaultOpen={false}>
<SharedAuthSettings />
</AccordionSection>
<AccordionSection id="backends" title="Backends" defaultOpen={false}> <AccordionSection id="backends" title="Backends" defaultOpen={false}>
<AwsSettings /> <AwsSettings />
<div className="pt-3 border-t border-[var(--border-color)]" /> <div className="pt-3 border-t border-[var(--border-color)]" />
@@ -177,7 +183,7 @@ export default function SettingsPanel() {
} }
}} }}
placeholder="~/.ssh" placeholder="~/.ssh"
className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
@@ -194,7 +200,7 @@ export default function SettingsPanel() {
} }
}} }}
placeholder="Your Name" placeholder="Your Name"
className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
@@ -211,7 +217,7 @@ export default function SettingsPanel() {
} }
}} }}
placeholder="you@example.com" placeholder="you@example.com"
className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
</AccordionSection> </AccordionSection>
@@ -230,27 +236,22 @@ export default function SettingsPanel() {
)} )}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<label className="text-xs text-[var(--text-secondary)]">Auto-check for updates</label> <label className="text-xs text-[var(--text-secondary)]">Auto-check for updates</label>
<button <Toggle
onClick={handleAutoCheckToggle} label="Auto-check for updates"
className={`px-2 py-0.5 text-xs rounded transition-colors ${ checked={appSettings?.auto_check_updates !== false}
appSettings?.auto_check_updates !== false onChange={handleAutoCheckToggle}
? "bg-[var(--success)] text-white" />
: "bg-[var(--bg-primary)] border border-[var(--border-color)] text-[var(--text-secondary)]"
}`}
>
{appSettings?.auto_check_updates !== false ? "ON" : "OFF"}
</button>
</div> </div>
<button <button
onClick={handleCheckNow} onClick={handleCheckNow}
disabled={checkingUpdates} disabled={checkingUpdates}
className="px-3 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] disabled:opacity-50 transition-colors" className="px-3 py-1.5 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] disabled:text-[var(--text-disabled)] transition-colors"
> >
{checkingUpdates ? "Checking..." : "Check now"} {checkingUpdates ? "Checking..." : "Check now"}
</button> </button>
{imageUpdateInfo && ( {imageUpdateInfo && (
<div className="flex items-center gap-2 px-3 py-2 text-xs bg-[var(--bg-primary)] border border-[var(--warning,#f59e0b)] rounded"> <div className="flex items-center gap-2 px-3 py-2 text-xs bg-[var(--bg-primary)] border border-[var(--warning)] rounded">
<span className="inline-block w-2 h-2 rounded-full bg-[var(--warning,#f59e0b)]" /> <span className="inline-block w-2 h-2 rounded-full bg-[var(--warning)]" />
<span>A newer container image is available. Re-pull the image in Container settings above to update.</span> <span>A newer container image is available. Re-pull the image in Container settings above to update.</span>
</div> </div>
)} )}
@@ -0,0 +1,126 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import SharedAuthSettings from "./SharedAuthSettings";
import type { Project } from "../../lib/types";
const hasClaudeToken = vi.fn();
const clearClaudeToken = vi.fn();
vi.mock("../../lib/tauri-commands", () => ({
hasClaudeToken: () => hasClaudeToken(),
clearClaudeToken: () => clearClaudeToken(),
acquireClaudeToken: vi.fn(),
submitClaudeTokenCode: vi.fn(),
}));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => vi.fn()) }));
vi.mock("@tauri-apps/plugin-opener", () => ({ openUrl: vi.fn() }));
let projects: Project[] = [];
vi.mock("../../hooks/useProjects", () => ({
useProjects: () => ({ projects }),
}));
const baseProject: Project = {
id: "p1",
name: "api-server",
paths: [{ host_path: "/src/api", mount_name: "api" }],
container_id: null,
status: "stopped",
backend: "anthropic",
bedrock_config: null,
ollama_config: null,
openai_compatible_config: null,
allow_docker_access: false,
sandbox_mode_enabled: true,
mission_control_enabled: false,
auth_bridge_enabled: false,
use_shared_auth_token: true,
full_permissions: false,
permission_mode: null,
ssh_key_path: null,
git_token: null,
git_user_name: null,
git_user_email: null,
custom_env_vars: [],
port_mappings: [],
claude_instructions: null,
claude_code_settings: null,
renamed_session_names: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
const running = (over: Partial<Project> = {}): Project => ({
...baseProject,
status: "running",
container_id: "container-1",
...over,
});
describe("SharedAuthSettings", () => {
beforeEach(() => {
vi.clearAllMocks();
projects = [];
hasClaudeToken.mockResolvedValue(false);
});
it("disables Authenticate and says why when nothing is running", async () => {
projects = [baseProject];
render(<SharedAuthSettings />);
expect(screen.getByRole("button", { name: "Authenticate" })).toBeDisabled();
expect(screen.getByTestId("shared-auth-no-container")).toHaveTextContent(
/start a project first/i,
);
await waitFor(() => expect(hasClaudeToken).toHaveBeenCalled());
});
it("treats a running project with no container id as unusable", async () => {
projects = [running({ container_id: null })];
render(<SharedAuthSettings />);
expect(screen.getByRole("button", { name: "Authenticate" })).toBeDisabled();
await waitFor(() => expect(hasClaudeToken).toHaveBeenCalled());
});
it("enables Authenticate once a container is running", async () => {
projects = [running()];
render(<SharedAuthSettings />);
expect(screen.getByRole("button", { name: "Authenticate" })).toBeEnabled();
expect(screen.queryByTestId("shared-auth-no-container")).not.toBeInTheDocument();
await waitFor(() => expect(hasClaudeToken).toHaveBeenCalled());
});
it("offers a host picker only when more than one project is running", async () => {
projects = [running()];
const { rerender } = render(<SharedAuthSettings />);
expect(screen.queryByLabelText("Run the sign-in in")).not.toBeInTheDocument();
projects = [running(), running({ id: "p2", name: "web" })];
rerender(<SharedAuthSettings />);
expect(screen.getByLabelText("Run the sign-in in")).toBeInTheDocument();
await waitFor(() => expect(hasClaudeToken).toHaveBeenCalled());
});
it("shows Revoke only when a token is stored", async () => {
projects = [running()];
hasClaudeToken.mockResolvedValue(true);
render(<SharedAuthSettings />);
await screen.findByRole("button", { name: "Revoke" });
expect(screen.getByRole("button", { name: "Re-authenticate" })).toBeEnabled();
expect(screen.getByTestId("shared-auth-detail")).toHaveTextContent(
/A shared token is stored/,
);
});
it("reports a keychain read failure instead of claiming there is no token", async () => {
projects = [running()];
hasClaudeToken.mockRejectedValue("keyring backend unavailable");
render(<SharedAuthSettings />);
await screen.findByText("keyring backend unavailable");
expect(screen.queryByRole("button", { name: "Revoke" })).not.toBeInTheDocument();
});
});
@@ -0,0 +1,227 @@
import { useState } from "react";
import Button from "../ui/Button";
import Modal from "../ui/Modal";
import StatusIndicator, { type StatusTone } from "../ui/StatusIndicator";
import { selectClass } from "../ui/Field";
import ClaudeAuthModal from "./ClaudeAuthModal";
import { clearClaudeToken } from "../../lib/tauri-commands";
import { useProjects } from "../../hooks/useProjects";
import { useAppState } from "../../store/appState";
import { authErrorMessage, useClaudeTokenStatus } from "../../hooks/useClaudeAuth";
const STATUS_DISPLAY: Record<
string,
{ tone: StatusTone; label: string; detail: string }
> = {
checking: {
tone: "unknown",
label: "Checking",
detail: "Looking for a stored token in the OS keychain.",
},
stored: {
tone: "ok",
label: "Authenticated",
detail:
"A shared token is stored. Anthropic-backend projects use it from their next container start.",
},
absent: {
tone: "off",
label: "Not authenticated",
detail:
"No shared token yet, so each Anthropic-backend project still needs its own `claude login`.",
},
unavailable: {
tone: "error",
label: "Unknown",
detail: "The OS keychain could not be read.",
},
};
/**
* Host-level control for the one long-lived Claude Code token shared by every
* project. Acquisition needs a running container to run the CLI in, so the
* user picks which project lends one.
*/
export default function SharedAuthSettings() {
const { projects } = useProjects();
const pushToast = useAppState((s) => s.pushToast);
const { status, error, refresh } = useClaudeTokenStatus();
const [pickedId, setPickedId] = useState<string | null>(null);
const [authOpen, setAuthOpen] = useState(false);
const [confirmRevoke, setConfirmRevoke] = useState(false);
const [revoking, setRevoking] = useState(false);
// `claude setup-token` runs inside a container, so only running projects can
// host the flow.
const runnable = projects.filter(
(p) => p.status === "running" && p.container_id !== null,
);
const host = runnable.find((p) => p.id === pickedId) ?? runnable[0] ?? null;
const display = STATUS_DISPLAY[status];
const handleRevoke = async () => {
setRevoking(true);
try {
await clearClaudeToken();
setConfirmRevoke(false);
await refresh();
pushToast({
kind: "success",
message: "Shared Claude token removed from the keychain.",
});
} catch (e) {
pushToast({
kind: "error",
message: "Could not remove the shared Claude token.",
detail: authErrorMessage(
e,
"The OS keychain rejected the delete. The token may still be stored.",
),
});
} finally {
setRevoking(false);
}
};
return (
<div className="space-y-3">
<div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-[var(--text-primary)]">
Shared Claude authentication
</span>
<StatusIndicator
tone={display.tone}
label={display.label}
className="text-xs"
/>
</div>
<p className="mt-1 text-xs text-[var(--text-secondary)] leading-snug">
Authenticate once and every project on the Anthropic backend signs in with
that token, instead of each container running its own{" "}
<code className="font-mono">claude login</code>. The token is held in your OS
keychain and injected into containers as an environment variable.
</p>
<p
data-testid="shared-auth-detail"
className="mt-1 text-xs text-[var(--text-secondary)] leading-snug"
>
{display.detail}
</p>
{error && <p className="mt-1 text-xs text-[var(--error)]">{error}</p>}
</div>
{runnable.length > 1 && (
<div>
<label
htmlFor="shared-auth-host"
className="block text-xs text-[var(--text-secondary)] mb-1"
>
Run the sign-in in
</label>
<select
id="shared-auth-host"
value={host?.id ?? ""}
onChange={(e) => setPickedId(e.target.value)}
className={selectClass}
>
{runnable.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
)}
<div className="flex items-center gap-2">
<Button
size="md"
variant="primary"
disabled={!host}
onClick={() => setAuthOpen(true)}
>
{status === "stored" ? "Re-authenticate" : "Authenticate"}
</Button>
{status === "stored" && (
<Button
size="md"
variant="danger"
disabled={revoking}
onClick={() => setConfirmRevoke(true)}
>
Revoke
</Button>
)}
</div>
{!host && (
<p
data-testid="shared-auth-no-container"
className="text-xs text-[var(--warning)] leading-snug"
>
No project is running. Signing in runs{" "}
<code className="font-mono">claude setup-token</code> inside a container, so
start a project first &mdash; any one will do, it only lends its container.
</p>
)}
{host && (
<p className="text-xs text-[var(--text-secondary)] leading-snug">
The sign-in runs in{" "}
<strong className="text-[var(--text-primary)]">{host.name}</strong>&rsquo;s
container, but the resulting token is shared by all projects.
</p>
)}
{authOpen && host && (
<ClaudeAuthModal
projectId={host.id}
projectName={host.name}
onClose={() => setAuthOpen(false)}
onAuthenticated={() => {
void refresh();
}}
/>
)}
{confirmRevoke && (
<Modal
title="Revoke shared Claude token"
widthClassName="w-[26rem]"
onClose={() => setConfirmRevoke(false)}
footer={
<>
<Button
size="md"
variant="ghost"
onClick={() => setConfirmRevoke(false)}
disabled={revoking}
>
Cancel
</Button>
<Button
size="md"
variant="danger"
disabled={revoking}
onClick={() => void handleRevoke()}
>
{revoking ? "Revoking…" : "Revoke token"}
</Button>
</>
}
>
<p className="text-[13px] text-[var(--text-secondary)] leading-snug">
This deletes the shared token from your OS keychain. Anthropic-backend
projects fall back to their own{" "}
<code className="font-mono">claude login</code> the next time their
container starts. Existing running containers keep working until they are
restarted.
</p>
</Modal>
)}
</div>
);
}
+11 -15
View File
@@ -4,6 +4,7 @@ import { getSttStatus, startStt, stopStt, pullSttImage, buildSttImage } from "..
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import type { SttStatus } from "../../lib/types"; import type { SttStatus } from "../../lib/types";
import Tooltip from "../ui/Tooltip"; import Tooltip from "../ui/Tooltip";
import Toggle from "../ui/Toggle";
export default function SttSettings() { export default function SttSettings() {
const { appSettings, saveSettings } = useSettings(); const { appSettings, saveSettings } = useSettings();
@@ -130,16 +131,11 @@ export default function SttSettings() {
<div className="space-y-2"> <div className="space-y-2">
{/* Enable toggle */} {/* Enable toggle */}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <Toggle
onClick={handleToggleEnabled} label="Speech to text"
className={`px-2 py-0.5 text-xs rounded transition-colors ${ checked={!!appSettings?.stt?.enabled}
appSettings?.stt?.enabled onChange={handleToggleEnabled}
? "bg-[var(--success)] text-white" />
: "bg-[var(--bg-primary)] border border-[var(--border-color)] text-[var(--text-secondary)]"
}`}
>
{appSettings?.stt?.enabled ? "ON" : "OFF"}
</button>
<span className="text-xs text-[var(--text-secondary)]"> <span className="text-xs text-[var(--text-secondary)]">
{appSettings?.stt?.enabled ? "Enabled" : "Disabled"} {appSettings?.stt?.enabled ? "Enabled" : "Disabled"}
</span> </span>
@@ -154,7 +150,7 @@ export default function SttSettings() {
value={model} value={model}
onChange={(e) => setModel(e.target.value)} onChange={(e) => setModel(e.target.value)}
onBlur={handleSaveModel} onBlur={handleSaveModel}
className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
> >
<option value="tiny">Tiny (fastest, ~75MB)</option> <option value="tiny">Tiny (fastest, ~75MB)</option>
<option value="small">Small (balanced, ~500MB)</option> <option value="small">Small (balanced, ~500MB)</option>
@@ -172,7 +168,7 @@ export default function SttSettings() {
onBlur={handleSavePort} onBlur={handleSavePort}
min={1} min={1}
max={65535} max={65535}
className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
@@ -185,7 +181,7 @@ export default function SttSettings() {
onChange={(e) => setLanguage(e.target.value)} onChange={(e) => setLanguage(e.target.value)}
onBlur={handleSaveLanguage} onBlur={handleSaveLanguage}
placeholder="Auto-detect" placeholder="Auto-detect"
className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:outline-none focus:border-[var(--accent)]" className="w-full px-2 py-1 text-sm bg-[var(--bg-primary)] border border-[var(--border-color)] rounded focus:border-[var(--accent)]"
/> />
</div> </div>
@@ -222,14 +218,14 @@ export default function SttSettings() {
<button <button
onClick={handlePull} onClick={handlePull}
disabled={pulling || building} disabled={pulling || building}
className="px-3 py-1 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] disabled:opacity-50 transition-colors" className="px-3 py-1 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] disabled:text-[var(--text-disabled)] transition-colors"
> >
{pulling ? "Pulling..." : "Pull Image"} {pulling ? "Pulling..." : "Pull Image"}
</button> </button>
<button <button
onClick={handleBuild} onClick={handleBuild}
disabled={pulling || building} disabled={pulling || building}
className="px-3 py-1 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] disabled:opacity-50 transition-colors" className="px-3 py-1 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] disabled:text-[var(--text-disabled)] transition-colors"
> >
{building ? "Building..." : "Build Locally"} {building ? "Building..." : "Build Locally"}
</button> </button>
+57 -84
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useCallback } from "react";
import { openUrl } from "@tauri-apps/plugin-opener"; import { openUrl } from "@tauri-apps/plugin-opener";
import type { UpdateInfo } from "../../lib/types"; import type { UpdateInfo } from "../../lib/types";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
interface Props { interface Props {
updateInfo: UpdateInfo; updateInfo: UpdateInfo;
@@ -15,23 +16,6 @@ export default function UpdateDialog({
onDismiss, onDismiss,
onClose, onClose,
}: Props) { }: Props) {
const overlayRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (e.target === overlayRef.current) onClose();
},
[onClose],
);
const handleDownload = async (url: string) => { const handleDownload = async (url: string) => {
try { try {
await openUrl(url); await openUrl(url);
@@ -46,76 +30,65 @@ export default function UpdateDialog({
}; };
return ( return (
<div <Modal
ref={overlayRef} title="Update Available"
onClick={handleOverlayClick} onClose={onClose}
className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" widthClassName="w-[30rem]"
> footer={
<div className="bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded-lg p-6 w-[28rem] max-h-[80vh] overflow-y-auto shadow-xl"> <>
<h2 className="text-lg font-semibold mb-3">Update Available</h2> <Button
variant="ghost"
<div className="flex items-center gap-2 mb-4 text-sm"> className="mr-auto text-[var(--accent)] hover:text-[var(--accent-hover)]"
<span className="text-[var(--text-secondary)]">{currentVersion}</span>
<span className="text-[var(--text-secondary)]">&rarr;</span>
<span className="text-[var(--accent)] font-semibold">
{updateInfo.version}
</span>
</div>
{updateInfo.body && (
<div className="mb-4">
<h3 className="text-xs font-semibold uppercase text-[var(--text-secondary)] mb-1">
Release Notes
</h3>
<div className="text-xs text-[var(--text-primary)] whitespace-pre-wrap bg-[var(--bg-primary)] rounded p-3 max-h-48 overflow-y-auto border border-[var(--border-color)]">
{updateInfo.body}
</div>
</div>
)}
{updateInfo.assets.length > 0 && (
<div className="mb-4 space-y-1">
<h3 className="text-xs font-semibold uppercase text-[var(--text-secondary)] mb-1">
Downloads
</h3>
{updateInfo.assets.map((asset) => (
<button
key={asset.name}
onClick={() => handleDownload(asset.browser_download_url)}
className="w-full flex items-center justify-between px-3 py-2 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded hover:border-[var(--accent)] transition-colors"
>
<span className="truncate">{asset.name}</span>
<span className="text-[var(--text-secondary)] ml-2 flex-shrink-0">
{formatSize(asset.size)}
</span>
</button>
))}
</div>
)}
<div className="flex items-center justify-between">
<button
onClick={() => handleDownload(updateInfo.release_url)} onClick={() => handleDownload(updateInfo.release_url)}
className="text-xs text-[var(--accent)] hover:text-[var(--accent-hover)] transition-colors"
> >
View on Gitea View on Gitea
</button> </Button>
<div className="flex gap-2"> <Button variant="ghost" onClick={onDismiss}>
<button Dismiss
onClick={onDismiss} </Button>
className="px-3 py-1.5 text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors" <Button onClick={onClose}>Close</Button>
> </>
Dismiss }
</button> >
<button <div className="flex items-center gap-2 mb-4 text-[13px]">
onClick={onClose} <span className="text-[var(--text-secondary)] font-mono">{currentVersion}</span>
className="px-3 py-1.5 text-xs bg-[var(--bg-tertiary)] border border-[var(--border-color)] rounded hover:bg-[var(--border-color)] transition-colors" <span className="text-[var(--text-secondary)]">&rarr;</span>
> <span className="text-[var(--accent)] font-semibold font-mono">
Close {updateInfo.version}
</button> </span>
</div>
{updateInfo.body && (
<div className="mb-4">
<h3 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)] mb-1">
Release notes
</h3>
<div className="text-xs text-[var(--text-primary)] whitespace-pre-wrap bg-[var(--bg-primary)] rounded-[var(--radius-control)] p-3 max-h-48 overflow-y-auto border border-[var(--border-color)]">
{updateInfo.body}
</div> </div>
</div> </div>
</div> )}
</div>
{updateInfo.assets.length > 0 && (
<div className="space-y-1">
<h3 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)] mb-1">
Downloads
</h3>
{updateInfo.assets.map((asset) => (
<button
key={asset.name}
type="button"
onClick={() => handleDownload(asset.browser_download_url)}
className="w-full flex items-center justify-between px-3 py-2 text-xs bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] hover:border-[var(--accent)] transition-colors"
>
<span className="truncate font-mono">{asset.name}</span>
<span className="text-[var(--text-secondary)] ml-2 flex-shrink-0">
{formatSize(asset.size)}
</span>
</button>
))}
</div>
)}
</Modal>
); );
} }
@@ -2,6 +2,7 @@ import { useState, useEffect } from "react";
import { startWebTerminal, stopWebTerminal, getWebTerminalStatus, regenerateWebTerminalToken } from "../../lib/tauri-commands"; import { startWebTerminal, stopWebTerminal, getWebTerminalStatus, regenerateWebTerminalToken } from "../../lib/tauri-commands";
import type { WebTerminalInfo } from "../../lib/types"; import type { WebTerminalInfo } from "../../lib/types";
import Tooltip from "../ui/Tooltip"; import Tooltip from "../ui/Tooltip";
import Toggle from "../ui/Toggle";
export default function WebTerminalSettings() { export default function WebTerminalSettings() {
const [info, setInfo] = useState<WebTerminalInfo | null>(null); const [info, setInfo] = useState<WebTerminalInfo | null>(null);
@@ -68,17 +69,12 @@ export default function WebTerminalSettings() {
<div className="space-y-2"> <div className="space-y-2">
{/* Toggle */} {/* Toggle */}
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <Toggle
onClick={handleToggle} label="Web terminal"
checked={!!info?.running}
disabled={loading} disabled={loading}
className={`px-2 py-0.5 text-xs rounded transition-colors ${ onChange={handleToggle}
info?.running />
? "bg-[var(--success)] text-white"
: "bg-[var(--bg-primary)] border border-[var(--border-color)] text-[var(--text-secondary)]"
}`}
>
{loading ? "..." : info?.running ? "ON" : "OFF"}
</button>
<span className="text-xs text-[var(--text-secondary)]"> <span className="text-xs text-[var(--text-secondary)]">
{info?.running {info?.running
? `Running on port ${info.port}` ? `Running on port ${info.port}`
@@ -116,7 +112,7 @@ export default function WebTerminalSettings() {
</button> </button>
<button <button
onClick={handleRegenerate} onClick={handleRegenerate}
className="text-xs px-2 py-0.5 text-[var(--warning,#f59e0b)] hover:bg-[var(--bg-primary)] rounded transition-colors" className="text-xs px-2 py-0.5 text-[var(--warning)] hover:bg-[var(--bg-primary)] rounded transition-colors"
> >
Regenerate Regenerate
</button> </button>
@@ -1,201 +0,0 @@
import { useEffect, useRef, useState } from "react";
import { useTerminal } from "../../hooks/useTerminal";
import { useProjects } from "../../hooks/useProjects";
interface ContextMenuState {
sessionId: string;
x: number;
y: number;
}
export default function TerminalTabs() {
const { sessions, activeSessionId, setActiveSession, close } = useTerminal();
const { projects, update } = useProjects();
const [menu, setMenu] = useState<ContextMenuState | null>(null);
const [renamingId, setRenamingId] = useState<string | null>(null);
const [renameDraft, setRenameDraft] = useState("");
const renameInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!menu) return;
const dismiss = () => setMenu(null);
window.addEventListener("click", dismiss);
window.addEventListener("scroll", dismiss, true);
return () => {
window.removeEventListener("click", dismiss);
window.removeEventListener("scroll", dismiss, true);
};
}, [menu]);
useEffect(() => {
if (renamingId) {
renameInputRef.current?.focus();
renameInputRef.current?.select();
}
}, [renamingId]);
if (sessions.length === 0) {
return (
<div className="px-3 text-xs text-[var(--text-secondary)] leading-10">
No active terminals
</div>
);
}
const getCustomName = (projectId: string, sessionId: string): string | null => {
const project = projects.find((p) => p.id === projectId);
return project?.renamed_session_names?.[sessionId] ?? null;
};
const startRename = (sessionId: string) => {
const session = sessions.find((s) => s.id === sessionId);
if (!session) return;
const current = getCustomName(session.projectId, sessionId) ?? session.sessionName ?? session.projectName;
setRenameDraft(current);
setRenamingId(sessionId);
setMenu(null);
};
const commitRename = async (sessionId: string) => {
const session = sessions.find((s) => s.id === sessionId);
if (!session) {
setRenamingId(null);
return;
}
const project = projects.find((p) => p.id === session.projectId);
if (!project) {
setRenamingId(null);
return;
}
const trimmed = renameDraft.trim();
const map = { ...(project.renamed_session_names ?? {}) };
if (trimmed) {
map[sessionId] = trimmed;
} else {
delete map[sessionId];
}
try {
await update({ ...project, renamed_session_names: map });
} catch (err) {
console.error("Failed to rename terminal tab:", err);
} finally {
setRenamingId(null);
}
};
const clearCustomName = async (sessionId: string) => {
const session = sessions.find((s) => s.id === sessionId);
if (!session) return;
const project = projects.find((p) => p.id === session.projectId);
if (!project) return;
const map = { ...(project.renamed_session_names ?? {}) };
if (!(sessionId in map)) {
setMenu(null);
return;
}
delete map[sessionId];
try {
await update({ ...project, renamed_session_names: map });
} catch (err) {
console.error("Failed to reset terminal tab name:", err);
} finally {
setMenu(null);
}
};
return (
<div className="flex items-center h-full">
{sessions.map((session) => {
const customName = getCustomName(session.projectId, session.id);
const baseLabel =
(session.sessionName ?? session.projectName) +
(session.sessionType === "bash" ? " (bash)" : "");
const displayLabel = customName
? `${session.projectName}: ${customName}`
: baseLabel;
const isRenaming = renamingId === session.id;
return (
<div
key={session.id}
onClick={() => setActiveSession(session.id)}
onContextMenu={(e) => {
e.preventDefault();
setMenu({ sessionId: session.id, x: e.clientX, y: e.clientY });
}}
onDoubleClick={() => startRename(session.id)}
className={`flex items-center gap-2 px-3 h-full text-xs cursor-pointer border-r border-[var(--border-color)] transition-colors ${
activeSessionId === session.id
? "bg-[var(--bg-primary)] text-[var(--text-primary)]"
: "text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
}`}
>
{isRenaming ? (
<input
ref={renameInputRef}
value={renameDraft}
onChange={(e) => setRenameDraft(e.target.value)}
onClick={(e) => e.stopPropagation()}
onBlur={() => commitRename(session.id)}
onKeyDown={(e) => {
if (e.key === "Enter") (e.target as HTMLInputElement).blur();
if (e.key === "Escape") setRenamingId(null);
}}
className="max-w-[180px] px-1 py-0 bg-[var(--bg-primary)] border border-[var(--accent)] rounded text-xs text-[var(--text-primary)] focus:outline-none"
/>
) : (
<span className="truncate max-w-[200px]" title={displayLabel}>
{displayLabel}
</span>
)}
<button
onClick={(e) => {
e.stopPropagation();
close(session.id);
}}
className="text-[var(--text-secondary)] hover:text-[var(--error)] transition-colors"
title="Close terminal"
>
×
</button>
</div>
);
})}
{menu && (() => {
const session = sessions.find((s) => s.id === menu.sessionId);
const hasCustom = session ? !!getCustomName(session.projectId, menu.sessionId) : false;
return (
<div
className="fixed z-50 min-w-[160px] py-1 bg-[var(--bg-secondary)] border border-[var(--border-color)] rounded shadow-lg text-xs"
style={{ top: menu.y, left: menu.x }}
onClick={(e) => e.stopPropagation()}
>
<button
className="w-full text-left px-3 py-1.5 text-[var(--text-primary)] hover:bg-[var(--bg-primary)] transition-colors"
onClick={() => startRename(menu.sessionId)}
>
Rename tab
</button>
{hasCustom && (
<button
className="w-full text-left px-3 py-1.5 text-[var(--text-secondary)] hover:bg-[var(--bg-primary)] transition-colors"
onClick={() => clearCustomName(menu.sessionId)}
>
Reset name
</button>
)}
<div className="border-t border-[var(--border-color)] my-1" />
<button
className="w-full text-left px-3 py-1.5 text-[var(--error)] hover:bg-[var(--bg-primary)] transition-colors"
onClick={() => {
close(menu.sessionId);
setMenu(null);
}}
>
Close tab
</button>
</div>
);
})()}
</div>
);
}
+50
View File
@@ -0,0 +1,50 @@
import type { ButtonHTMLAttributes, ReactNode } from "react";
export type ButtonVariant = "primary" | "secondary" | "danger" | "ghost";
export type ButtonSize = "sm" | "md";
interface Props extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
size?: ButtonSize;
children: ReactNode;
}
/**
* Real buttons with visible bounds and a 24px hit target.
* Filled variants use the *-emphasis tokens so white text clears WCAG AA;
* `--accent` stays reserved for foreground/link use.
*/
const VARIANTS: Record<ButtonVariant, string> = {
primary:
"bg-[var(--accent-emphasis)] text-white border border-transparent hover:bg-[var(--accent-emphasis-hover)] disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-disabled)] disabled:border-[var(--border-color)]",
secondary:
"bg-[var(--bg-tertiary)] text-[var(--text-primary)] border border-[var(--border-color)] hover:bg-[var(--border-color)] disabled:text-[var(--text-disabled)] disabled:hover:bg-[var(--bg-tertiary)]",
danger:
"bg-transparent text-[var(--error)] border border-[var(--error)]/40 hover:bg-[var(--error-muted)] disabled:text-[var(--text-disabled)] disabled:border-[var(--border-color)] disabled:hover:bg-transparent",
ghost:
"bg-transparent text-[var(--text-secondary)] border border-transparent hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] disabled:text-[var(--text-disabled)] disabled:hover:bg-transparent",
};
const SIZES: Record<ButtonSize, string> = {
sm: "h-6 px-2 text-xs gap-1",
md: "h-8 px-3 text-[13px] gap-1.5",
};
export default function Button({
variant = "secondary",
size = "sm",
className = "",
type = "button",
children,
...rest
}: Props) {
return (
<button
type={type}
{...rest}
className={`inline-flex items-center justify-center whitespace-nowrap rounded-[var(--radius-control)] font-medium transition-colors disabled:cursor-not-allowed ${SIZES[size]} ${VARIANTS[variant]} ${className}`}
>
{children}
</button>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { useId, type ReactNode } from "react";
/**
* Shared control styling. Full-width forms mean the helper text that used to
* hide inside 27 hover-only tooltips can just be visible.
*/
export const inputClass =
"w-full px-2.5 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] text-[13px] text-[var(--text-primary)] focus:border-[var(--accent)] disabled:text-[var(--text-disabled)] disabled:bg-[var(--bg-secondary)] transition-colors";
export const monoInputClass = `${inputClass} font-mono`;
export const selectClass =
"px-2.5 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-[var(--radius-control)] text-[13px] text-[var(--text-primary)] focus:border-[var(--accent)] disabled:text-[var(--text-disabled)] disabled:bg-[var(--bg-secondary)] transition-colors";
interface FieldProps {
label: string;
/** Visible helper text — the replacement for hover-only tooltips. */
hint?: ReactNode;
children: (id: string) => ReactNode;
className?: string;
}
export default function Field({ label, hint, children, className = "" }: FieldProps) {
const id = useId();
return (
<div className={className}>
<label
htmlFor={id}
className="block text-[13px] font-medium text-[var(--text-primary)]"
>
{label}
</label>
{hint && (
<p className="mt-0.5 mb-1 text-xs text-[var(--text-secondary)] leading-snug">
{hint}
</p>
)}
<div className={hint ? "" : "mt-1"}>{children(id)}</div>
</div>
);
}
/** Label + helper text on the left, a control (usually a Toggle) on the right. */
export function SwitchRow({
label,
hint,
control,
}: {
label: string;
hint?: ReactNode;
control: ReactNode;
}) {
return (
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<div className="text-[13px] font-medium text-[var(--text-primary)]">{label}</div>
{hint && (
<p className="mt-0.5 text-xs text-[var(--text-secondary)] leading-snug">{hint}</p>
)}
</div>
<div className="flex-shrink-0 pt-0.5">{control}</div>
</div>
);
}
/** Grouping card used by the Config tab (Workspace / Model / Access / Runtime). */
export function ConfigGroup({
title,
description,
children,
}: {
title: string;
description?: string;
children: ReactNode;
}) {
return (
<section className="border border-[var(--border-color)] rounded-[var(--radius-panel)] bg-[var(--bg-secondary)]">
<header className="px-4 py-2.5 border-b border-[var(--border-color)]">
<h3 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)]">
{title}
</h3>
{description && (
<p className="mt-0.5 text-xs text-[var(--text-secondary)]">{description}</p>
)}
</header>
<div className="px-4 py-4 space-y-4">{children}</div>
</section>
);
}
+118
View File
@@ -0,0 +1,118 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, fireEvent, act } from "@testing-library/react";
import Modal from "./Modal";
/**
* Modal focuses asynchronously via rAF so the panel is laid out first; jsdom
* needs that flushed manually.
*/
async function flushFocus() {
await act(async () => {
vi.advanceTimersByTime(20);
});
}
describe("Modal", () => {
beforeEach(() => {
vi.useFakeTimers({ toFake: ["requestAnimationFrame", "setTimeout"] });
});
afterEach(() => {
vi.useRealTimers();
});
it("exposes dialog semantics and an accessible name", async () => {
render(
<Modal title="Remove Project" onClose={vi.fn()}>
<p>body</p>
</Modal>,
);
const dialog = screen.getByRole("dialog", { name: "Remove Project" });
expect(dialog).toHaveAttribute("aria-modal", "true");
});
it("moves focus into the dialog on open", async () => {
render(
<Modal title="Dialog" onClose={vi.fn()}>
<button>First</button>
<button>Second</button>
</Modal>,
);
await flushFocus();
const dialog = screen.getByRole("dialog");
expect(dialog.contains(document.activeElement)).toBe(true);
});
it("traps Tab inside the dialog, wrapping at both ends", async () => {
render(
<Modal title="Dialog" onClose={vi.fn()} hideCloseButton>
<button>First</button>
<button>Last</button>
</Modal>,
);
await flushFocus();
const first = screen.getByRole("button", { name: "First" });
const last = screen.getByRole("button", { name: "Last" });
last.focus();
fireEvent.keyDown(document, { key: "Tab" });
expect(document.activeElement).toBe(first);
first.focus();
fireEvent.keyDown(document, { key: "Tab", shiftKey: true });
expect(document.activeElement).toBe(last);
});
it("restores focus to the trigger on unmount", async () => {
const trigger = document.createElement("button");
document.body.appendChild(trigger);
trigger.focus();
const { unmount } = render(
<Modal title="Dialog" onClose={vi.fn()}>
<button>Inside</button>
</Modal>,
);
await flushFocus();
expect(document.activeElement).not.toBe(trigger);
unmount();
expect(document.activeElement).toBe(trigger);
trigger.remove();
});
it("closes on Escape and on an overlay click", async () => {
const onClose = vi.fn();
const { container } = render(
<Modal title="Dialog" onClose={onClose}>
<p>body</p>
</Modal>,
);
await flushFocus();
fireEvent.keyDown(document, { key: "Escape" });
expect(onClose).toHaveBeenCalledTimes(1);
// The overlay is the portal root's only child.
const overlay = document.querySelector(".fixed.inset-0");
expect(overlay).not.toBeNull();
fireEvent.click(overlay!);
expect(onClose).toHaveBeenCalledTimes(2);
expect(container).toBeTruthy();
});
it("ignores Escape and overlay clicks when not dismissible", async () => {
const onClose = vi.fn();
render(
<Modal title="Installing" onClose={onClose} dismissible={false}>
<p>body</p>
</Modal>,
);
await flushFocus();
fireEvent.keyDown(document, { key: "Escape" });
fireEvent.click(document.querySelector(".fixed.inset-0")!);
expect(onClose).not.toHaveBeenCalled();
});
});
+183
View File
@@ -0,0 +1,183 @@
import { useCallback, useEffect, useId, useRef, type ReactNode } from "react";
import { createPortal } from "react-dom";
const FOCUSABLE_SELECTOR = [
"a[href]",
"area[href]",
"input:not([disabled])",
"select:not([disabled])",
"textarea:not([disabled])",
"button:not([disabled])",
"iframe",
"object",
"embed",
'[tabindex]:not([tabindex="-1"])',
'[contenteditable="true"]',
].join(",");
function focusableWithin(root: HTMLElement): HTMLElement[] {
// Deliberately no `offsetParent` check: everything a dialog renders is
// visible, and `offsetParent` is unreliable inside fixed-position overlays.
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(
(el) => !el.closest("[hidden]") && el.getAttribute("aria-hidden") !== "true",
);
}
export interface ModalProps {
/** Accessible name for the dialog. Rendered as the header unless `hideTitle`. */
title: string;
onClose: () => void;
children: ReactNode;
/** Optional sticky footer row (buttons live here). */
footer?: ReactNode;
/** Optional sub-header description, wired to `aria-describedby`. */
description?: ReactNode;
/** Tailwind width class for the dialog panel. */
widthClassName?: string;
/** When false, Escape / overlay click / the ✕ button do not close. */
dismissible?: boolean;
/** Hide the ✕ in the header (the footer usually carries a Close button). */
hideCloseButton?: boolean;
/** Focused on mount; falls back to the first focusable child. */
initialFocusRef?: React.RefObject<HTMLElement | null>;
/** Applied to the scrollable body wrapper. */
bodyClassName?: string;
}
/**
* The one modal primitive. Every dialog in the app renders through this so
* `role="dialog"`, `aria-modal`, a focus trap, focus restore, Escape and
* click-outside are implemented once instead of twelve times.
*/
export default function Modal({
title,
onClose,
children,
footer,
description,
widthClassName = "w-[32rem]",
dismissible = true,
hideCloseButton = false,
initialFocusRef,
bodyClassName = "",
}: ModalProps) {
const overlayRef = useRef<HTMLDivElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const restoreFocusRef = useRef<HTMLElement | null>(null);
const titleId = useId();
const descId = useId();
// Remember what had focus, move focus inside, restore on unmount.
useEffect(() => {
restoreFocusRef.current = document.activeElement as HTMLElement | null;
const panel = panelRef.current;
if (panel) {
const target =
initialFocusRef?.current ?? focusableWithin(panel)[0] ?? panel;
// Defer so the panel is laid out (offsetParent) before we query it.
requestAnimationFrame(() => target.focus?.());
}
return () => {
restoreFocusRef.current?.focus?.();
};
// Mount/unmount only — re-running would steal focus mid-interaction.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Escape closes; Tab is trapped inside the panel.
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape" && dismissible) {
e.stopPropagation();
onClose();
return;
}
if (e.key !== "Tab") return;
const panel = panelRef.current;
if (!panel) return;
const items = focusableWithin(panel);
if (items.length === 0) {
e.preventDefault();
panel.focus();
return;
}
const first = items[0];
const last = items[items.length - 1];
const active = document.activeElement as HTMLElement | null;
if (!active || !panel.contains(active)) {
e.preventDefault();
first.focus();
return;
}
if (e.shiftKey && active === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
};
document.addEventListener("keydown", onKeyDown, true);
return () => document.removeEventListener("keydown", onKeyDown, true);
}, [dismissible, onClose]);
const handleOverlayClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (dismissible && e.target === overlayRef.current) onClose();
},
[dismissible, onClose],
);
return createPortal(
<div
ref={overlayRef}
onClick={handleOverlayClick}
className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4"
>
<div
ref={panelRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
aria-describedby={description ? descId : undefined}
tabIndex={-1}
className={`flex flex-col max-h-[85vh] ${widthClassName} max-w-full bg-[var(--bg-overlay)] border border-[var(--border-color)] rounded-[var(--radius-panel)]`}
style={{ boxShadow: "var(--shadow-overlay)" }}
>
<div className="flex items-start justify-between gap-4 px-5 py-3 border-b border-[var(--border-color)] flex-shrink-0">
<div className="min-w-0">
<h2 id={titleId} className="text-sm font-semibold text-[var(--text-primary)]">
{title}
</h2>
{description && (
<p id={descId} className="mt-0.5 text-xs text-[var(--text-secondary)]">
{description}
</p>
)}
</div>
{!hideCloseButton && dismissible && (
<button
type="button"
onClick={onClose}
aria-label="Close dialog"
className="flex-shrink-0 w-6 h-6 flex items-center justify-center rounded-[var(--radius-control)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-tertiary)] transition-colors"
>
<span aria-hidden="true"></span>
</button>
)}
</div>
<div className={`flex-1 min-h-0 overflow-y-auto px-5 py-4 ${bodyClassName}`}>
{children}
</div>
{footer && (
<div className="flex items-center justify-end gap-2 px-5 py-3 border-t border-[var(--border-color)] flex-shrink-0">
{footer}
</div>
)}
</div>
</div>,
document.body,
);
}
+82
View File
@@ -0,0 +1,82 @@
import { useEffect, useRef, useState } from "react";
export interface OverflowItem {
label: string;
onSelect: () => void;
danger?: boolean;
disabled?: boolean;
}
interface Props {
items: OverflowItem[];
label?: string;
align?: "left" | "right";
}
/** The `⋯` menu that keeps destructive actions out of the main button row. */
export default function OverflowMenu({
items,
label = "More actions",
align = "right",
}: Props) {
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDocClick = (e: MouseEvent) => {
if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setOpen(false);
};
document.addEventListener("mousedown", onDocClick);
document.addEventListener("keydown", onKey);
return () => {
document.removeEventListener("mousedown", onDocClick);
document.removeEventListener("keydown", onKey);
};
}, [open]);
return (
<div ref={rootRef} className="relative inline-block">
<button
type="button"
aria-haspopup="menu"
aria-expanded={open}
aria-label={label}
onClick={() => setOpen((o) => !o)}
className="inline-flex items-center justify-center h-6 w-7 rounded-[var(--radius-control)] border border-[var(--border-color)] bg-[var(--bg-tertiary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--border-color)] transition-colors"
>
<span aria-hidden="true" className="leading-none"></span>
</button>
{open && (
<div
role="menu"
className={`absolute z-40 mt-1 min-w-[11rem] py-1 bg-[var(--bg-overlay)] border border-[var(--border-color)] rounded-[var(--radius-panel)] ${
align === "right" ? "right-0" : "left-0"
}`}
style={{ boxShadow: "var(--shadow-overlay)" }}
>
{items.map((item) => (
<button
key={item.label}
type="button"
role="menuitem"
disabled={item.disabled}
onClick={() => {
setOpen(false);
item.onSelect();
}}
className={`w-full text-left px-3 py-1.5 text-xs transition-colors disabled:text-[var(--text-disabled)] disabled:hover:bg-transparent hover:bg-[var(--bg-tertiary)] ${
item.danger ? "text-[var(--error)]" : "text-[var(--text-primary)]"
}`}
>
{item.label}
</button>
))}
</div>
)}
</div>
);
}

Some files were not shown because too many files have changed in this diff Show More