Compare commits

..
42 Commits
Author SHA1 Message Date
shadowdaoandClaude Opus 5.5 d73a19a9e7 docs: note the stop guard order, background polls, clone skip and trap order
Secret Scan / scan (push) Successful in 18s
Build App (Preview) / compute-version (pull_request) Successful in 5s
Build App (Preview) / test (pull_request) Successful in 6m21s
Secret Scan / scan (pull_request) Successful in 8s
Build App (Preview) / create-release (pull_request) Successful in 1s
Build App (Preview) / build-macos (pull_request) Successful in 5m55s
Build App (Preview) / build-linux (pull_request) Successful in 8m29s
Build App (Preview) / build-windows (pull_request) Successful in 10m36s
Build App (Preview) / prune-previews (pull_request) Successful in 2s
Build Container / build-container (pull_request) Successful in 22m23s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:08:05 -08:00
shadowdaoandClaude Opus 5.5 c467308513 fix(aws): keep the access point id when a removal keeps the saved files
remove_aws_resources cleared access_point_id even without discard_data, though the
access point stays; the project could then move hosts and orphan it. The id is
now kept, so a later start reuses it, a later removal with "Also remove the
access point" deletes it, and moving the project is refused until then (the
message and the Host section say so).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:08:05 -08:00
shadowdaoandClaude Opus 5.5 be2825d344 fix(aws): the file viewer's change poll no longer counts as workspace activity
Its 2 s sha256sum poll now carries X-Triple-C-Background, so an open viewer does
not keep an idle AWS workspace up. Opening and saving a file stay foreground;
Docker is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:08:05 -08:00
shadowdaoandClaude Opus 5.5 33eb63d907 fix(aws): forget a stale stopped mark on a project's unattached target id
The death watch's stopped marks are keyed by target id, and an unattached AWS
project's id (http://unattached.invalid/<id>/) is reused by every later unattached
spell, but only an endpoint URL's mark was ever removed. A stale mark could make
the watch report a live, billed task as stopped. Registering a tunnel now clears
the project's placeholder mark, and reconcile forgets it before asking ECS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:08:05 -08:00
shadowdaoandClaude Opus 5.5 884a665e7d fix(aws): close terminals before the stop guard's push and bound it in the container
The guard pushed and recorded `pushed` while terminals (and Claude in them) were
still open; the TERM hook then skipped its push, so later edits were lost. Stop now
closes the project's exec sessions and auth bridge first, then pushes, records the
marker and stops the task. A failed push still aborts the stop with the status
restored; the auth bridge is re-armed and the error says the terminals were closed.

The script also runs under `/usr/bin/timeout -k 5` ending 10 s before the client's
timeout: the agent does not kill an exec its client gave up on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:07:54 -08:00
shadowdaoandClaude Opus 5.5 170ba1e94d fix(container): skip repos still cloning, re-check idleness after the idle push, trap TERM before background work
- clone_repos records `<folder>\tcloning` as each clone begins; triple-c-wip-push
  skips a folder whose last state is `cloning` while the clone is not done (dry run
  reports "cloning": true; RepoState/TS carry it, the stop guard lists it as
  "still cloning — nothing to push" and never asks because of it).
- The idle watcher re-checks quiet() after a successful push and goes back to
  watching if someone came back during it.
- The entrypoint installs its stop trap before the idle watcher and the background
  clone start, so a TERM in between still runs aws_before_stop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:07:53 -08:00
shadowdaoandClaude Opus 5.5 276f5378a4 fix(aws): give the permission check room for throttled retries and say it can be slow
Secret Scan / scan (push) Successful in 5s
Build App (Preview) / compute-version (pull_request) Successful in 4s
Build App (Preview) / create-release (pull_request) Successful in 2s
Secret Scan / scan (pull_request) Successful in 6s
Build App (Preview) / build-macos (pull_request) Successful in 5m56s
Build App (Preview) / build-linux (pull_request) Successful in 8m42s
Build App (Preview) / build-windows (pull_request) Successful in 10m38s
Build App (Preview) / prune-previews (pull_request) Successful in 3s
Build App (Preview) / test (pull_request) Successful in 22m44s
Build Container / build-container (pull_request) Successful in 25m25s
The connection-wide 30 s operation limit counts retry backoff, so a
throttled SimulatePrincipalPolicy got about six of its ten adaptive
attempts. The IAM client used by the check now has a 120 s operation
limit, and Settings tells the user a check can take a few minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:54:34 -08:00
shadowdaoandClaude Opus 5.5 3c1c276769 docs(aws): note the idle-stop changes are not yet re-verified live
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:37:58 -08:00
shadowdaoandClaude Opus 5.5 8a3c552958 test(aws): the live idle stop holds a terminal open and polls in the background
The idle wait now keeps an attach open (silent) and runs the auth
bridge's background exec every 2 s; the task must still stop itself and
ECS must report it as an idle stop (exit 75 -> StopKind::Idle).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:36:23 -08:00
shadowdaoandClaude Opus 5.5 ce020f79a1 fix(aws): the e2e script uses only the named profile and always cleans up
It unsets every caller AWS_* variable (keeping only where the profile's
files are, now documented), sets AWS_PROFILE explicitly, attempts the ECR
delete in the EXIT trap unconditionally (RepositoryNotFound tolerated,
bounded at 120 s), and exits 130/143 on INT/TERM (M21).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:35:50 -08:00
shadowdaoandClaude Opus 5.5 24a82bd4c8 fix(aws): warn that Bedrock profile auth can't work in an AWS workspace
The task has no ~/.aws from this machine and SSO can't refresh there;
the note points at static keys or a bearer token (m10). The auth bridge
stays enabled on AWS (its poll is now a background request).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:34:34 -08:00
shadowdaoandClaude Opus 5.5 7f113f58ac fix(aws): refuse credentials in repo URLs and HEAD as a branch
- validate_repo_url rejects https URLs with userinfo (user:pass@ or
  token@), pointing at the project's Git HTTPS token setting (m4).
- validate_branch rejects HEAD (m5).
- The FIXED_ENVIRONMENT doc comment sits on FIXED_ENVIRONMENT again (m6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:34:03 -08:00
shadowdaoandClaude Opus 5.5 2772647690 fix(aws): reconcile AWS projects at startup without waiting for Docker
- New reconcile_aws_projects command (handler, capability, TS wrapper)
  that App runs on mount regardless of Docker; reconcile_project_statuses
  now skips AWS projects. Projects reconcile concurrently, 4 at a time,
  each still bounded at 15 s.
- reconcile_task falls back to find_project_task when the stored task is
  gone or stopped, before calling the project Gone (m3).
- An AWS project with no registered tunnel gets a placeholder target id
  (http://unattached.invalid/<id>/) instead of the last run's loopback
  URL, so a reused port can't match the wrong project; the death watch
  still reports it by that id until a re-attach registers (m9).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:33:22 -08:00
shadowdaoandClaude Opus 5.5 5e8e67a0a4 fix(aws): say why a task stopped, and bound every AWS call
- classify_stop is wired into the death watch: stopped_among returns
  each task's StopKind, the tunnel registry keeps it, and ContainerExited
  carries a StopNote. Spot -> 'Spot interruption'; TaskFailedToStart ->
  Error with the reason; the entrypoint's idle exit (75, read from the
  workspace container's exit code) -> 'stopped after being idle'; a user
  stop is applied silently (P8). is_quota_error, dead, moved to tests.
- The SDK config has a TimeoutConfig (30 s operation / 10 s attempt); the
  watch's per-group poll and StopTask also have tokio bounds.
- Watcher tests cover silent sessions, unsaved work with the WIP push on
  and off, a failing push and the idle exit status; docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:31:28 -08:00
shadowdaoandClaude Opus 5.5 151b7690df fix(aws): the auth bridge's poll no longer keeps a workspace up
The auth bridge reads /proc/net every 2 s; on the agent that now goes
through ContainerTarget::exec_oneshot_background, which sends
X-Triple-C-Background: 1 so the agent does not count it as activity.
Docker behaviour is unchanged. The idle-stop hint says what idle means
now (R11) and what happens to unsaved work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:31:28 -08:00
shadowdaoandClaude Opus 5.5 95b68ed068 fix(container): idle stop ignores silent sessions and never loses work
- The agent marks requests with X-Triple-C-Background: 1 (and the
  attach/tunnel sessions they open) as not activity (R11).
- triple-c-idle-watch no longer requires zero open execs/tunnels: idle is
  last_activity older than N minutes, no claude, no scheduler job, no
  running clone, and no unsaved git work. With the WIP push on, it pushes
  as claude before signalling and stays up (backing off) when the push
  fails; with it off, dirty repos keep the workspace up.
- An idle stop exits 75 so ECS reports it distinctly from a crash; the
  TERM trap no longer pushes again after the watcher's push.
- start_clone_repos writes done from an EXIT trap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:31:19 -08:00
shadowdaoandClaude Opus 5.5 3f986368aa fix(aws): removal deletes the secret at once and words the access point honestly
Removing a project's AWS resources now deletes its secret with
ForceDeleteWithoutRecovery (R10) so the next start can create it again,
and the EFS option is renamed: it removes the access point, while the
files stay on the user's own file system until offboarding (R9).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 12:10:52 -08:00
shadowdaoandClaude Sonnet 5.5 55ec7e33fe docs(aws): fix policy sizes and a constant name
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 11:59:31 -08:00
shadowdaoandClaude Sonnet 5.5 595897a5fd docs(aws): phase 5 Fargate workspaces
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 11:58:42 -08:00
shadowdaoandClaude Opus 5.5 084fa6efe4 test(aws): guard the live workspace test against hangs and leaks
Review round 1 of Task 9:
- the phase-5 body runs under a 45-minute timeout and each exec under
  180 s, so a hang becomes a panic the guard catches; the body future is
  boxed (moved into the timeout it overflowed the test thread's stack,
  which aborts without any guard);
- scripts/aws-e2e-workspace.sh builds and pushes the image to a throwaway
  ECR repository, runs the test and deletes the repository in an exit
  trap; the test's guard deletes it too (TRIPLEC_E2E_ECR_REPO);
- the guard survives a poisoned lock, closes the tunnel and restores
  AWS_CONFIG_FILE;
- new live probe: a bare elasticfilesystem:TagResource on the user's own
  file system is denied; README records it and the final run (R8 removal
  end state), and the admin command uses xargs -r.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:56:40 -08:00
shadowdaoandClaude Opus 5.5 1700cc7985 fix(aws): leave task definitions to admins on removal
Ruling R8. ECS authorizes ecs:DeregisterTaskDefinition against * only,
with no tag condition (verified live), so the workspace tier's
RetireOwnTaskDefinitions could never match, and allowing it on * would
let any user deregister any revision in the account. DeleteTaskDefinitions
is resource-level but deletes only INACTIVE revisions, so it goes too.

Removing an AWS project now stops the task, schedules the secret and
(with discard) deletes the access point, and leaves the task definition
revisions registered, saying so in the log: they hold no secret values,
cost nothing, and RunOwnTasks still needs the owner tag. aws/README.md
tells admins how to deregister them. The policy statement, its checks and
owner-scoped rows, the RuntimeApi methods, the fakes, the removal UI copy
and the live test's final assertion follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:34:52 -08:00
shadowdaoandClaude Opus 5.5 e901a08ab6 test(aws): live Fargate workspace lifecycle
aws::live_tests::environment::a_fargate_workspace_round_trips (ignored):
a public environment deployed by the environment admin, a role holding
only the workspace-user files onboarded to it and driving ProjectHost::Aws
through a profile connection: start (Hybrid, 1 vCPU / 2 GB, one public
repo), exec, background clone, ~/.claude persistence across stop/start,
attach without a second RunTask, the stop guard's dry run, the SIGTERM
WIP path, idle stop at 5 minutes, bubblewrap, denials on another owner's
revision and secret, and project removal. TRIPLEC_E2E_IMAGE names the
image; a private ECR image gets a test-only pull policy on the exec role.
A guard stops tasks, retires revisions, deletes access points and the
secret before the fixture destroys the modules.

aws/README.md gains the phase 5 results; the spec's To verify items are
answered. Open: DeregisterTaskDefinition is authorized against * only,
so the workspace tier cannot retire revisions (the test's last assertion
fails until that is decided).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 11:30:33 -08:00
shadowdaoandClaude Opus 5.5 1eed994da7 fix(aws): tag access points at create against their file system
EFS authorizes the elasticfilesystem:TagResource that a tagged
CreateAccessPoint needs against the parent file system's ARN, not the new
access point's: a workspace user's first Hybrid start was denied
("not authorized to perform: elasticfilesystem:TagResource on the
specified resource"). Verified live with a probe role: access-point/*
is denied; file-system/* is allowed, as is * with each of
elasticfilesystem:CreateAction, aws:RequestTag and aws:TagKeys.

TagOwnAccessPointsAtCreate now names file-system/* with the same
conditions (CreateAction = CreateAccessPoint, owner request tag, the
three tag keys); its check and owner-scoped test follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:46:59 -08:00
shadowdaoandClaude Opus 5.5 074cb28848 docs(aws): correct the 0.25 vCPU Fargate memory sizes in the phase 5 plan
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:31:06 -08:00
shadowdaoandClaude Opus 5.5 08b6d341f2 fix(aws): stop guard review round 2
A failed StopTask removes the stop marker it recorded, so a later stop
pushes as configured. The unchecked guard's Stop anyway sends no choice
and records nothing, so the workspace's own shutdown push still runs as
the dialog says. The idle watcher keeps a pushed/discard marker instead
of overwriting it; the remove-resources dialog sends discard only when
there may be saved files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:30:56 -08:00
shadowdaoandClaude Opus 5.5 8441a096c8 fix(aws): stop guard review round 1
The stop guard's choice now reaches the workspace: after a successful
push (or for Stop without pushing) the app records pushed/discard in
/run/triple-c/stop-reason as root, and the entrypoint's shutdown hook
then skips its own push; a marker that can't be written is reported
and the stop goes on. The push runs before the auth bridge is stopped;
a guarded stop of a workspace that already stopped succeeds. The
Fargate table allows only 512/1024/2048 MiB with 256 CPU, pinned on
both sides by a shared fixture. Removal's missing-connection refusal
carries a stable prefix. OpenAI Compatible is allowed on AWS, with a
warning for local addresses and the app's own gateway. HostSection
locks resource actions unless Stopped, the add dialog drops the
environment on a region change, and the repository editor keeps rows
in progress across a refresh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:26:53 -08:00
shadowdaoandClaude Opus 5.5 eb7c6c7b21 feat(aws): AWS project settings and the stop guard
Add Project picks Local or an AWS connection, a region and a ready,
joined environment, with repositories instead of folders. The Config
tab's Host section edits CPU/memory (valid pairs only), architecture,
storage, ephemeral size, Spot, idle stop, WIP push and repositories, and
can remove the AWS resources or move the project back to this machine.
Docker access, VPN, port mappings and the gateway backend are disabled on
AWS with the reason; the sandbox shows Off on AWS for now. Stop on an AWS
workspace with unsaved work asks first (Push to WIP branch preselected);
a failed start shows the task's last log lines; removing an AWS project
can delete its saved files, and asks again when its connection is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:15:14 -08:00
shadowdaoandClaude Opus 5.5 51042f5d9e feat(aws): stop guard, task log and AWS resource removal commands
check_unsaved_work runs triple-c-wip-push --dry-run through the agent as
claude (checked:false with the reason when the workspace can't be asked);
stop_project_container takes wip: push runs the push first and a failure
aborts the stop with its output. aws_task_log reads the current or last
task's stream in the environment record's log group. remove_aws_resources
removes a stopped project's AWS resources and clears its runtime handles,
so it can move off AWS. add_project takes the host fields; an AWS project
takes repositories, no folders, and no runtime handles from the caller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 10:15:14 -08:00
shadowdaoandClaude Opus 5.5 b1ac78613c fix(container): aws mode review round 1
Clone repos in the background after the agent starts (progress in
/run/triple-c-clone; an unfinished clone keeps the workspace from idling),
give the task definition stopTimeout 120 for the SIGTERM WIP push, reserve
the TRIPLEC_ env prefix on both hosts, and stop root writing through
claude-controlled links (~/.claude.json written as claude only via the exact
Hybrid link; ~/.ssh merged only through the exact Hybrid link, Docker paths
unchanged). Keep the user's ssh command and add BatchMode, cover dot-folders,
refuse undecodable or over-long file names by name, and upload LFS objects
before the --no-verify push.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:59:00 -08:00
shadowdaoandClaude Opus 5.5 51f71212d2 feat(container): aws mode — secret files, repo clone, Hybrid home, WIP push, idle stop
With TRIPLEC_HOST=aws the entrypoint decodes TRIPLEC_FILES into
/tmp/.host-ssh and /tmp/.host-ca and unsets it (and TRIPLEC_REPOS) before
the agent's environment snapshot; links ~/.claude, ~/.claude.json and ~/.ssh
into /mnt/triple-c-home for Hybrid storage; clones TRIPLEC_REPOS as claude
after git credentials and ~/.ssh are set up; runs triple-c-wip-push from the
TERM trap; and starts triple-c-idle-watch, which signals the entrypoint
itself (PID 1 is docker-init under initProcessEnabled). Docker mode is
unchanged: every new step is gated on TRIPLEC_HOST=aws.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:46:03 -08:00
shadowdaoandClaude Opus 5.5 8d45a93d63 fix(aws): a start cancels a pending re-attach; keep an unstoppable task recorded
ensure_started cancels a background re-attach instead of waiting for it,
and every register bumps the project's generation, so a late re-attach can
never replace a newer tunnel. A task StopTask refused after a failed start
keeps its ARN. A re-attach that gives up clears the pending flag only if
still current; close_if_task checks and takes under one lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:30:17 -08:00
shadowdaoandClaude Opus 5.5 37e94b1ee6 fix(aws): record a task as soon as it exists; repair a raced token; guard re-attach
A start stores the task ARN when RunTask returns (or the task is found),
reconcile finds an unrecorded live task, and a failed attach leaves the
project in Error rather than hiding a running task. The winner of a start
race puts its agent token back in the secret. A background re-attach
registers only if the project still runs that task and was not stopped
meanwhile. Removing a project whose connection is gone needs explicit
confirmation. Names come from tofu_modules; files are read with a hard cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:25:53 -08:00
shadowdaoandClaude Opus 5.5 e05f7e3cd8 feat(aws): start, attach and stop a project on its AWS environment
ProjectHost::Aws and the tunnel registry: start looks for the project's
live task before preparing (a running task is attached to with the token
read back from its secret, never rotated), waits for a new access point,
runs, waits, tunnels and checks the agent; a task the start ran is stopped
on any later failure. Stop, remove (resources; data only on request),
reconcile (background re-attach) and the AWS death watch, with exits
confirmed through the registry. Docker-only Reset, migration, staleness
and container info refuse or skip AWS projects; an AWS project with
resources can't be moved off its host. Shutdown closes every tunnel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:15:37 -08:00
shadowdaoandClaude Opus 5.5 7fd6fa6aaa feat(aws): environment record, agent token, access point wait and resource removal
RuntimeApi (GetParameter, GetRole, GetSecretValue, DescribeAccessPoints,
task definition retirement, DeleteSecret with a 7-day window,
DeleteAccessPoint) with the decisions in tested functions over it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:15:37 -08:00
shadowdaoandClaude Opus 5.5 e43ed26e20 feat(aws): run, find, stop and watch workspace tasks
aws/tasks.rs: TaskApi (+ SdkTaskApi) with RunTask, DescribeTasks (tags),
ListTasks by family, StopTask and a GetLogEvents tail. find_or_run reuses
the project's live task only when its tags name the caller and the
project, and otherwise runs the exact family:revision with the three
ownership tags (FARGATE, or the FARGATE_SPOT capacity provider for Spot),
with a client token so SDK retries cannot start a second task.
wait_ready polls with injectable timing and fails with the stop reason
and the last 50 log lines. Quota refusals become AwsError::QuotaExceeded
and are never retried. classify_stop maps stop codes per the spec.

host/watch.rs: ExitSource::Aws polls an injected project-to-task lookup
every 15 s, per connection+region+cluster, 100 tasks per call; a group
that can't be asked is skipped. has_exited's Agent arm is unchanged (R3).
container_watch::run/spawn take their ExitSource.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:56:11 -08:00
shadowdaoandClaude Opus 5.5 30d6b26a42 fix(aws): fingerprint the built task definition; harden workspace lookups
- The fingerprint hashes a canonical rendering of the built request
  (Debug-redacted environment and HashMap log options rendered
  separately, labels excluded) instead of the plan plus a template
  constant, so a builder change can't silently keep old revisions.
- Page ListTaskDefinitions so a longer family can't crowd out the
  caller's revisions.
- Project ids that aren't [A-Za-z0-9-] get a hash suffix in names, so
  ids that sanitise alike can't share a secret.
- Name a secret scheduled for deletion; only mount an available file
  system; drop the unused FileSystemRef.arn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:46:32 -08:00
shadowdaoandClaude Opus 5.5 64ff3baab2 feat(aws): per-project secret, access point and task definition
aws::workspace prepares an AWS project before its task runs: one
Secrets Manager secret holding every project-shaped value (P1; files
as one TRIPLEC_FILES key per R1), the Hybrid EFS access point, and a
task definition whose environment is only TRIPLEC_HOST and COLORTERM
(R2), with every payload key as a valueFrom secret reference.

A revision is reused only when it carries the caller's owner tag, this
project's tag and the expected fingerprint label (other users can
register into any triple-c-* family), always by its exact
family:revision ARN. Payload keys and secrets entries are sorted so
unchanged settings never register a new revision. Names (family,
secret, access point root, log stream prefix, file system token) live
in tofu_modules and use owner_key.

Adds aws-sdk-efs and aws-sdk-cloudwatchlogs (released with the pinned
aws-sdk-ecs; lock gains only their own entries).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:39:58 -08:00
shadowdaoandClaude Opus 5.5 7320aaa5d4 fix(aws): document register-into-family residual risk, correct sizes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:27:48 -08:00
shadowdaoandClaude Opus 5.5 d1883310dd feat(aws): workspace users register their own task definitions
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:26:08 -08:00
shadowdaoandClaude Sonnet 5.5 01e7b2752a refactor(docker): build container env in one host-neutral function
workspace_env() builds every project-shaped KEY=VALUE pair (backends, CA vars,
MANAGED_AUTH_KEYS blanking, custom env, instructions, Claude Code settings);
create_container keeps COLORTERM, HOST_UID/GID and the host lookups (CA
resolution, keychain token) and formats the pairs. Golden vectors recorded from
the pre-refactor block pin the order and values.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 08:22:13 -08:00
shadowdaoandClaude Opus 5.5 0fc99738bb feat(aws): project model for the AWS host
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:16:56 -08:00
shadowdaoandClaude Opus 5.5 a674f6f196 docs(aws): phase 5 plan — Fargate workspaces
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 07:47:15 -08:00
115 changed files with 17214 additions and 714 deletions

No files matched your search

+52 -1
View File
@@ -292,6 +292,14 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
when it drops, so an `AgentEndpoint` stays valid. The `StartSession` token goes to the plugin
through its environment, never argv, and the plugin's environment is stripped of every
inherited `AWS_*` variable before the session's own credentials are added.
`aws_host.rs` is `ProjectHost::Aws` (an ECS Fargate task per project; a running task is
attached to with the token read back from its secret, never rotated; a task a failed start ran
is stopped again) and `tunnels.rs` the registry of open tunnels by project — an AWS project's
`ContainerTarget::for_project` is its tunnel's endpoint, its stored `container_id` is that
endpoint's URL, and the AWS death watch confirms exits through the registry. Shutdown closes
every tunnel (`for_project` is `None` while none is open; `for_project_waiting` covers the
background re-attach after an app restart). AWS SDK calls stay in `aws/` (`runtime.rs`,
`tasks.rs`, `workspace.rs`).
`agent.rs` reuses `docker/exec.rs`'s `OneshotOutput`, host-file reader and uid probe so the two
variants cannot drift; an `Agent` target's token never appears in `Debug` or error text.
**Container-interior code must go through `ContainerTarget`, never `docker::exec`, bollard or
@@ -312,7 +320,7 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
`identity.rs` is `GetCallerIdentity` and the principal to simulate (an assumed role's ARN is
recovered with `iam:GetRole`, because SSO roles have an `/aws-reserved/…` path the session ARN
lacks); `error.rs` classifies SDK errors (SSO expired, access denied naming the action, …);
`policies.rs` embeds `aws/policies/*.json` (the tier policies — the admin tier spans several
`policies.rs` embeds `aws/policies/*.json` (the tier policies — both tiers span several
files, `policy_files` lists them — and the permissions boundary) and the table of checks the
simulator is asked; `permissions.rs` runs it
(`SimulatePrincipalPolicy`, adaptive retries — it throttles — or read-only probes when the
@@ -330,6 +338,26 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
`aws/README.md` ("Live verification"). Its `environment` tests apply the real modules as a role
holding only the admin files (`cargo build` first: the runner they start is the built app
binary), in a throwaway state bucket.
**A Fargate workspace's resources** (`workspace.rs`, `tasks.rs`, `runtime.rs`). **No project
data in a task definition (P1):** every workspace user has `ecs:Describe*` on `*`, so
`environment`, tags, labels and `overrides` are public to the account. The task definition carries
`TRIPLEC_HOST=aws`, `COLORTERM`, the three ownership tags, a fingerprint docker label (a hash,
`FINGERPRINT_LABEL`) and `valueFrom` references into the project's **one secret**
(`triple-c/<env>/<owner_key>/<project-id>`, JSON, 64 KB cap: files, repos, instructions, settings,
custom env, the agent token). The token rotates each start; a running task is attached to by reading
it back (the task role has no Secrets Manager access). **Anyone may register a revision into any
`triple-c-*` family** (IAM can't scope it), so a revision or task is reused only when it carries the
caller's own owner tag + this project's tag (+ the fingerprint), and `RunTask` always names the exact
`family:revision` ARN, never "latest". Names come only from `tofu_modules.rs`, built from `owner_key`
(`aws:userid` contains `:`). Workspace users can't deregister or delete task definitions
(`DeregisterTaskDefinition` is `*`-only in IAM): removal leaves revisions ACTIVE for an admin
(`aws/README.md`). Stop: the stop guard (`commands/stop_guard.rs`) dry-runs `triple-c-wip-push`
through the agent, closes the project's terminals and auth bridge (so nothing is written after the
push's snapshot), may push first (under an in-container `timeout`, since the agent does not kill an
exec the client gave up on), then writes `pushed` or `discard` to `/run/triple-c/stop-reason`
(root-owned; the entrypoint's TERM hook reads it, and the idle watcher writes `idle`) so the hook
doesn't push twice; the marker is cleared if StopTask fails. Claude Code's sandbox is forced off in
the generated settings (bubblewrap can't create namespaces on Fargate, verified live).
**Environments are OpenTofu modules** (`aws/terraform/{environment,user-onboard,permissions-boundary}`;
spec D2–D10). `tofu_modules.rs` embeds them and is the **only** place the shared names are built
(environment, `/triple-c/environments/<env>` record, owner key — `sha256("<region>:<aws:userid>")`,
@@ -361,6 +389,29 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
- **`Dockerfile`** — Ubuntu 24.04 base with Claude Code, Node.js 22, Python 3.12, Rust, Docker CLI, git, gh, AWS CLI v2, ripgrep, pnpm, uv, ruff pre-installed, plus the shared
libraries a browser links against (see below) and the VPN tooling the `vpn_support_enabled`
toggle grants capability for (`iproute2`, `wireguard-tools`, `iptables`)
- **`TRIPLEC_HOST=aws` mode** (`entrypoint.sh`, the `aws_*` blocks; inert without it). There are no
bind mounts: `TRIPLEC_FILES` (JSON of base64 files) is decoded into `/tmp/.host-ssh` / `/tmp/.host-ca`
so the SSH merge and CA install run unchanged, and `TRIPLEC_REPOS` is kept in an unexported shell
variable; **both are unset before the agent-token block snapshots the environment** (that snapshot is
every terminal's env and the files hold private keys). Repos clone in the background after the agent
starts (terminals are usable before they arrive). Hybrid storage mounts EFS at `/mnt/triple-c-home`
and symlinks `~/.claude`, `~/.claude.json`, `~/.ssh` into it (mounting over `/home/claude` would hide
the image's tooling); root never follows those links outside the mount (`aws_hybrid_ssh_dir`). On
TERM the hook pushes unsaved work to a `triple-c/wip/<stamp>` branch via a temporary index (the
user's index is untouched; needs the task definition's `stopTimeout` raised, 120 s) unless the stop
marker says the app handled it. The idle watcher runs as root under a supervisor and signals the
entrypoint's own PID (not PID 1, which is docker-init), so idle and ECS stops share one trap.
Idle = the agent's `last_activity_unix` older than N minutes (open-but-silent attaches/tunnels
don't count; requests with `X-Triple-C-Background: 1` — the auth bridge's and the file viewer's polls — never do),
no `claude`, no scheduler job, no running clone, and no unsaved git work: with the WIP push on the
watcher pushes *before* signalling and stays up if that fails; with it off, dirty repos keep the
workspace up; activity during the watcher's push sends it back to watching. A repo the background
clone is still writing (`/run/triple-c-clone/repos` last says `cloning`, no `done`) is skipped by
`triple-c-wip-push` (dry run: `"cloning": true`). The stop trap is set before any background work
starts. An idle stop exits 75 (`aws::tasks::IDLE_EXIT_CODE`) so the death watch can tell it
from a crash (`classify_stop` → the `ContainerExited` toast).
**The `TRIPLEC_` env prefix is reserved** on both hosts (`RESERVED_ENV_PREFIXES`; `workspace.rs`
drops custom variables in it): the entrypoint's settings live there.
- **Browser runtime libraries are baked in; browser *binaries* are not.** A layer runs
`npx --yes playwright@latest install-deps chromium` as root, so Playwright names its own
dependencies and the list cannot rot against Ubuntu 24.04's `t64` renames or a new Chromium
+51
View File
@@ -367,6 +367,30 @@ dependencies = [
"uuid",
]
[[package]]
name = "aws-sdk-cloudwatchlogs"
version = "1.165.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "581cf82c1682f1251b910a32af5b19f9f5faed98c9117825391c1fcdfde21855"
dependencies = [
"arc-swap",
"aws-credential-types",
"aws-runtime",
"aws-smithy-async",
"aws-smithy-eventstream",
"aws-smithy-http",
"aws-smithy-json",
"aws-smithy-observability",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
"aws-smithy-schema",
"aws-smithy-types",
"aws-types",
"fastrand",
"regex-lite",
"tracing",
]
[[package]]
name = "aws-sdk-ecs"
version = "1.159.0"
@@ -390,6 +414,31 @@ dependencies = [
"tracing",
]
[[package]]
name = "aws-sdk-efs"
version = "1.125.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa82ea1472278e955c2f59c534a23681f630e6f215e29263eb10e25b0b8b281a"
dependencies = [
"arc-swap",
"aws-credential-types",
"aws-runtime",
"aws-smithy-async",
"aws-smithy-http",
"aws-smithy-json",
"aws-smithy-observability",
"aws-smithy-runtime",
"aws-smithy-runtime-api",
"aws-smithy-schema",
"aws-smithy-types",
"aws-types",
"bytes",
"fastrand",
"http",
"regex-lite",
"tracing",
]
[[package]]
name = "aws-sdk-iam"
version = "1.136.0"
@@ -7392,7 +7441,9 @@ dependencies = [
"aws-config",
"aws-credential-types",
"aws-runtime",
"aws-sdk-cloudwatchlogs",
"aws-sdk-ecs",
"aws-sdk-efs",
"aws-sdk-iam",
"aws-sdk-kms",
"aws-sdk-s3",
+2
View File
@@ -68,6 +68,8 @@ aws-sdk-ecs = { version = "1.159.0", default-features = false, features = ["defa
aws-sdk-sts = { version = "1.126.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] }
aws-sdk-iam = { version = "1.136.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] }
aws-sdk-secretsmanager = { version = "1.128.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] }
aws-sdk-efs = { version = "1.125.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] }
aws-sdk-cloudwatchlogs = { version = "1.165.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] }
# Named by src/aws/connection.rs: the credentials-provider trait (its profile
# wrapper) and the profile-file set (aws-config's alias for it is deprecated).
# Both are the versions aws-config already resolves.
+4
View File
@@ -18,8 +18,12 @@
"allow-update-project",
"allow-start-project-container",
"allow-stop-project-container",
"allow-check-unsaved-work",
"allow-aws-task-log",
"allow-remove-aws-resources",
"allow-rebuild-project-container",
"allow-reconcile-project-statuses",
"allow-reconcile-aws-projects",
"allow-list-notes",
"allow-save-note",
"allow-delete-note",
+1 -1
View File
@@ -1 +1 @@
{"__app-acl__":{"default_permission":null,"permissions":{"allow-acquire-claude-token":{"identifier":"allow-acquire-claude-token","description":"Enables the acquire_claude_token command without any pre-configured scope.","commands":{"allow":["acquire_claude_token"],"deny":[]}},"allow-add-aws-keys-connection":{"identifier":"allow-add-aws-keys-connection","description":"Enables the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":["add_aws_keys_connection"],"deny":[]}},"allow-add-aws-profile-connection":{"identifier":"allow-add-aws-profile-connection","description":"Enables the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":["add_aws_profile_connection"],"deny":[]}},"allow-add-marketplace":{"identifier":"allow-add-marketplace","description":"Enables the add_marketplace command without any pre-configured scope.","commands":{"allow":["add_marketplace"],"deny":[]}},"allow-add-marketplace-gh-host-account":{"identifier":"allow-add-marketplace-gh-host-account","description":"Enables the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_gh_host_account"],"deny":[]}},"allow-add-marketplace-token-account":{"identifier":"allow-add-marketplace-token-account","description":"Enables the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_token_account"],"deny":[]}},"allow-add-project":{"identifier":"allow-add-project","description":"Enables the add_project command without any pre-configured scope.","commands":{"allow":["add_project"],"deny":[]}},"allow-add-scheduled-task":{"identifier":"allow-add-scheduled-task","description":"Enables the add_scheduled_task command without any pre-configured scope.","commands":{"allow":["add_scheduled_task"],"deny":[]}},"allow-apply-marketplace-now":{"identifier":"allow-apply-marketplace-now","description":"Enables the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":["apply_marketplace_now"],"deny":[]}},"allow-apply-settings-import":{"identifier":"allow-apply-settings-import","description":"Enables the apply_settings_import command without any pre-configured scope.","commands":{"allow":["apply_settings_import"],"deny":[]}},"allow-aws-connection-identity":{"identifier":"allow-aws-connection-identity","description":"Enables the aws_connection_identity command without any pre-configured scope.","commands":{"allow":["aws_connection_identity"],"deny":[]}},"allow-aws-connection-sso-login":{"identifier":"allow-aws-connection-sso-login","description":"Enables the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":["aws_connection_sso_login"],"deny":[]}},"allow-aws-policy-document":{"identifier":"allow-aws-policy-document","description":"Enables the aws_policy_document command without any pre-configured scope.","commands":{"allow":["aws_policy_document"],"deny":[]}},"allow-aws-sso-refresh":{"identifier":"allow-aws-sso-refresh","description":"Enables the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":["aws_sso_refresh"],"deny":[]}},"allow-build-gateway-image":{"identifier":"allow-build-gateway-image","description":"Enables the build_gateway_image command without any pre-configured scope.","commands":{"allow":["build_gateway_image"],"deny":[]}},"allow-build-image":{"identifier":"allow-build-image","description":"Enables the build_image command without any pre-configured scope.","commands":{"allow":["build_image"],"deny":[]}},"allow-build-stt-image":{"identifier":"allow-build-stt-image","description":"Enables the build_stt_image command without any pre-configured scope.","commands":{"allow":["build_stt_image"],"deny":[]}},"allow-cancel-aws-deployment":{"identifier":"allow-cancel-aws-deployment","description":"Enables the cancel_aws_deployment command without any pre-configured scope.","commands":{"allow":["cancel_aws_deployment"],"deny":[]}},"allow-cancel-claude-token":{"identifier":"allow-cancel-claude-token","description":"Enables the cancel_claude_token command without any pre-configured scope.","commands":{"allow":["cancel_claude_token"],"deny":[]}},"allow-cancel-marketplace-gh-login":{"identifier":"allow-cancel-marketplace-gh-login","description":"Enables the cancel_marketplace_gh_login command without any pre-configured scope.","commands":{"allow":["cancel_marketplace_gh_login"],"deny":[]}},"allow-check-aws-permissions":{"identifier":"allow-check-aws-permissions","description":"Enables the check_aws_permissions command without any pre-configured scope.","commands":{"allow":["check_aws_permissions"],"deny":[]}},"allow-check-browser-view-support":{"identifier":"allow-check-browser-view-support","description":"Enables the check_browser_view_support command without any pre-configured scope.","commands":{"allow":["check_browser_view_support"],"deny":[]}},"allow-check-docker":{"identifier":"allow-Line truncated
{"__app-acl__":{"default_permission":null,"permissions":{"allow-acquire-claude-token":{"identifier":"allow-acquire-claude-token","description":"Enables the acquire_claude_token command without any pre-configured scope.","commands":{"allow":["acquire_claude_token"],"deny":[]}},"allow-add-aws-keys-connection":{"identifier":"allow-add-aws-keys-connection","description":"Enables the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":["add_aws_keys_connection"],"deny":[]}},"allow-add-aws-profile-connection":{"identifier":"allow-add-aws-profile-connection","description":"Enables the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":["add_aws_profile_connection"],"deny":[]}},"allow-add-marketplace":{"identifier":"allow-add-marketplace","description":"Enables the add_marketplace command without any pre-configured scope.","commands":{"allow":["add_marketplace"],"deny":[]}},"allow-add-marketplace-gh-host-account":{"identifier":"allow-add-marketplace-gh-host-account","description":"Enables the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_gh_host_account"],"deny":[]}},"allow-add-marketplace-token-account":{"identifier":"allow-add-marketplace-token-account","description":"Enables the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_token_account"],"deny":[]}},"allow-add-project":{"identifier":"allow-add-project","description":"Enables the add_project command without any pre-configured scope.","commands":{"allow":["add_project"],"deny":[]}},"allow-add-scheduled-task":{"identifier":"allow-add-scheduled-task","description":"Enables the add_scheduled_task command without any pre-configured scope.","commands":{"allow":["add_scheduled_task"],"deny":[]}},"allow-apply-marketplace-now":{"identifier":"allow-apply-marketplace-now","description":"Enables the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":["apply_marketplace_now"],"deny":[]}},"allow-apply-settings-import":{"identifier":"allow-apply-settings-import","description":"Enables the apply_settings_import command without any pre-configured scope.","commands":{"allow":["apply_settings_import"],"deny":[]}},"allow-aws-connection-identity":{"identifier":"allow-aws-connection-identity","description":"Enables the aws_connection_identity command without any pre-configured scope.","commands":{"allow":["aws_connection_identity"],"deny":[]}},"allow-aws-connection-sso-login":{"identifier":"allow-aws-connection-sso-login","description":"Enables the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":["aws_connection_sso_login"],"deny":[]}},"allow-aws-policy-document":{"identifier":"allow-aws-policy-document","description":"Enables the aws_policy_document command without any pre-configured scope.","commands":{"allow":["aws_policy_document"],"deny":[]}},"allow-aws-sso-refresh":{"identifier":"allow-aws-sso-refresh","description":"Enables the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":["aws_sso_refresh"],"deny":[]}},"allow-aws-task-log":{"identifier":"allow-aws-task-log","description":"Enables the aws_task_log command without any pre-configured scope.","commands":{"allow":["aws_task_log"],"deny":[]}},"allow-build-gateway-image":{"identifier":"allow-build-gateway-image","description":"Enables the build_gateway_image command without any pre-configured scope.","commands":{"allow":["build_gateway_image"],"deny":[]}},"allow-build-image":{"identifier":"allow-build-image","description":"Enables the build_image command without any pre-configured scope.","commands":{"allow":["build_image"],"deny":[]}},"allow-build-stt-image":{"identifier":"allow-build-stt-image","description":"Enables the build_stt_image command without any pre-configured scope.","commands":{"allow":["build_stt_image"],"deny":[]}},"allow-cancel-aws-deployment":{"identifier":"allow-cancel-aws-deployment","description":"Enables the cancel_aws_deployment command without any pre-configured scope.","commands":{"allow":["cancel_aws_deployment"],"deny":[]}},"allow-cancel-claude-token":{"identifier":"allow-cancel-claude-token","description":"Enables the cancel_claude_token command without any pre-configured scope.","commands":{"allow":["cancel_claude_token"],"deny":[]}},"allow-cancel-marketplace-gh-login":{"identifier":"allow-cancel-marketplace-gh-login","description":"Enables the cancel_marketplace_gh_login command without any pre-configured scope.","commands":{"allow":["cancel_marketplace_gh_login"],"deny":[]}},"allow-check-aws-permissions":{"identifier":"allow-check-aws-permissions","description":"Enables the check_aws_permissions command without any pre-configured scope.","commands":{"allow":["check_aws_permissions"],"deny":[]}},"allow-check-browser-view-support":{"identifier":"allow-check-browser-view-support","description":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"default":{"identifier":"default","description":"Default capabilities for Triple-C. Every entry here is an IPC command a compromised webview can call directly, so the set is an enumeration of what `app/src` actually invokes — plugin and core grants verified against tauri 2.11.0's `PLUGINS` table in tauri's own `build.rs` rather than assumed from a plugin's `default` set, app-command grants (the bare `allow-*` entries) cross-checked by this crate's `build.rs` against `generate_handler!`. `core:default` in particular is NOT used: it is an alias for `core:{path,event,window,webview,app,image,resources,menu,tray}:default`, and `core:image:default` carries `allow-from-path`, whose handler (`tauri-2.11.0/src/image/plugin.rs:41` → `src/image/mod.rs:96`) is a bare `std::fs::read(path)` with no scope mechanism of any kind. Nothing imports `@tauri-apps/api/image`, so the whole plugin is dropped rather than scoped — there is nothing to scope it with. `core:menu` and `core:tray` are dropped for the same reason (no menu, no tray icon); `core:window` and `core:path` because nothing imports them; `core:resources:allow-close` because no frontend value is a `Resource`; and `core:event`'s `allow-emit`/`allow-emit-to` because the frontend only ever *listens* — every emit in this app originates in Rust. Three notes on what is deliberately kept or accepted: (1) `core:webview:allow-internal-toggle-devtools` is not called by `app/src` at all — it is called by Tauri's own injected `toggle-devtools.js`, which binds Ctrl/Cmd+Shift+I. Both that script and the command behind it are `#[cfg(any(debug_assertions, feature = \"devtools\"))]`, so this grant is a `tauri dev` convenience that does not exist in a release bundle. (2) `opener:allow-open-url` is **gone**. It could not be narrowed by host — `TerminalView`'s `WebLinksAddon` opens links Claude printed inside the container, which are arbitrary by construction, so a host allowlist would have deleted the feature rather than bounded it — and it was carried here as an accepted residual risk: a compromised webview could make the OS open an attacker-chosen http(s) URL, an outbound channel. That risk is now closed rather than recorded. Every host-browser open in the app goes through the `open_url_external` command in `url_open.rs`, which exists because the AppImage environment leaks into a cold-launched browser on Linux (triple-c#34) and which re-validates the URL in Rust — scheme allowlist, no embedded credentials, no control characters, length cap, ASCII asserted before `execvp`. On macOS and Windows that command reaches the same plugin as before, via `OpenerExt::open_url`, whose desktop implementation calls `crate::open::open` directly and is therefore not gated by this file at all (`tauri-plugin-opener-2.5.3/src/lib.rs:60`). The plugin stays a dependency for exactly that reason; what is removed is the webview's ability to reach it without passing the Rust validation. (3) `drag:allow-start-drag` is **gone**, together with the OS drag-out it existed for. It could not be scoped — `tauri-plugin-drag` takes the item paths from the caller and has no scope mechanism, so a compromised webview could call `startDrag({ item: ['~/.ssh/id_rsa'] })` against any host path the user can read — and it was carried as an accepted residual risk for one gesture. Drag-out was held back for separate hardening (see branch `hold/disk-and-dragout`) and the plugin is no longer a dependency. Getting a file *out* of a container is either \"Back up container\" on the project's Overview tab, which archives a tree through the Docker API, or the Files tab's per-row \"Save to host…\", which copies one file; getting one *in* is a drop on the Terminal or the Files tab's \"Upload…\". None of the four touches this permission. The Files tab's two are worth separating out here, because they are the only host-path commands in the app whose dialog is opened by **Rust** rather than by the webview — `pick_save_path` and `pick_files_to_upload` in `commands/file_commands.rs` drive `tauri-plugin-dialog` from the backend, so a compromised webview can ask for a picker and nothing more: it cannot name a host path as an *input* to either command. Be precise about the limit of that claim — host paths do still travel outward in error text (`Failed to create /home/j/Documents/x.txt.triple-c-part-1a2b3c4d: Permission denied`), including canonicalized ones, which disclose symlink targets. That is accepted; the app already hands the webview the project paths. What is closed is the direction that mattered — the webview naming where bytes go. That is the shape an earlier revision of this file named as the honest one if the Files tab ever regained host I/O, and it is the shape it regained it in. The `dialog:allow-open` / `dialog:allow-save` grants below are therefore *not* what those two use; they remain for the frontend pickers in Add Project, the Config tab's workspace and access sections, the CA-certificate fielLine truncated
{"default":{"identifier":"default","description":"Default capabilities for Triple-C. Every entry here is an IPC command a compromised webview can call directly, so the set is an enumeration of what `app/src` actually invokes — plugin and core grants verified against tauri 2.11.0's `PLUGINS` table in tauri's own `build.rs` rather than assumed from a plugin's `default` set, app-command grants (the bare `allow-*` entries) cross-checked by this crate's `build.rs` against `generate_handler!`. `core:default` in particular is NOT used: it is an alias for `core:{path,event,window,webview,app,image,resources,menu,tray}:default`, and `core:image:default` carries `allow-from-path`, whose handler (`tauri-2.11.0/src/image/plugin.rs:41` → `src/image/mod.rs:96`) is a bare `std::fs::read(path)` with no scope mechanism of any kind. Nothing imports `@tauri-apps/api/image`, so the whole plugin is dropped rather than scoped — there is nothing to scope it with. `core:menu` and `core:tray` are dropped for the same reason (no menu, no tray icon); `core:window` and `core:path` because nothing imports them; `core:resources:allow-close` because no frontend value is a `Resource`; and `core:event`'s `allow-emit`/`allow-emit-to` because the frontend only ever *listens* — every emit in this app originates in Rust. Three notes on what is deliberately kept or accepted: (1) `core:webview:allow-internal-toggle-devtools` is not called by `app/src` at all — it is called by Tauri's own injected `toggle-devtools.js`, which binds Ctrl/Cmd+Shift+I. Both that script and the command behind it are `#[cfg(any(debug_assertions, feature = \"devtools\"))]`, so this grant is a `tauri dev` convenience that does not exist in a release bundle. (2) `opener:allow-open-url` is **gone**. It could not be narrowed by host — `TerminalView`'s `WebLinksAddon` opens links Claude printed inside the container, which are arbitrary by construction, so a host allowlist would have deleted the feature rather than bounded it — and it was carried here as an accepted residual risk: a compromised webview could make the OS open an attacker-chosen http(s) URL, an outbound channel. That risk is now closed rather than recorded. Every host-browser open in the app goes through the `open_url_external` command in `url_open.rs`, which exists because the AppImage environment leaks into a cold-launched browser on Linux (triple-c#34) and which re-validates the URL in Rust — scheme allowlist, no embedded credentials, no control characters, length cap, ASCII asserted before `execvp`. On macOS and Windows that command reaches the same plugin as before, via `OpenerExt::open_url`, whose desktop implementation calls `crate::open::open` directly and is therefore not gated by this file at all (`tauri-plugin-opener-2.5.3/src/lib.rs:60`). The plugin stays a dependency for exactly that reason; what is removed is the webview's ability to reach it without passing the Rust validation. (3) `drag:allow-start-drag` is **gone**, together with the OS drag-out it existed for. It could not be scoped — `tauri-plugin-drag` takes the item paths from the caller and has no scope mechanism, so a compromised webview could call `startDrag({ item: ['~/.ssh/id_rsa'] })` against any host path the user can read — and it was carried as an accepted residual risk for one gesture. Drag-out was held back for separate hardening (see branch `hold/disk-and-dragout`) and the plugin is no longer a dependency. Getting a file *out* of a container is either \"Back up container\" on the project's Overview tab, which archives a tree through the Docker API, or the Files tab's per-row \"Save to host…\", which copies one file; getting one *in* is a drop on the Terminal or the Files tab's \"Upload…\". None of the four touches this permission. The Files tab's two are worth separating out here, because they are the only host-path commands in the app whose dialog is opened by **Rust** rather than by the webview — `pick_save_path` and `pick_files_to_upload` in `commands/file_commands.rs` drive `tauri-plugin-dialog` from the backend, so a compromised webview can ask for a picker and nothing more: it cannot name a host path as an *input* to either command. Be precise about the limit of that claim — host paths do still travel outward in error text (`Failed to create /home/j/Documents/x.txt.triple-c-part-1a2b3c4d: Permission denied`), including canonicalized ones, which disclose symlink targets. That is accepted; the app already hands the webview the project paths. What is closed is the direction that mattered — the webview naming where bytes go. That is the shape an earlier revision of this file named as the honest one if the Files tab ever regained host I/O, and it is the shape it regained it in. The `dialog:allow-open` / `dialog:allow-save` grants below are therefore *not* what those two use; they remain for the frontend pickers in Add Project, the Config tab's workspace and access sections, the CA-certificate fielLine truncated
@@ -428,6 +428,12 @@
"const": "allow-aws-sso-refresh",
"markdownDescription": "Enables the aws_sso_refresh command without any pre-configured scope."
},
{
"description": "Enables the aws_task_log command without any pre-configured scope.",
"type": "string",
"const": "allow-aws-task-log",
"markdownDescription": "Enables the aws_task_log command without any pre-configured scope."
},
{
"description": "Enables the build_gateway_image command without any pre-configured scope.",
"type": "string",
@@ -506,6 +512,12 @@
"const": "allow-check-image-update",
"markdownDescription": "Enables the check_image_update command without any pre-configured scope."
},
{
"description": "Enables the check_unsaved_work command without any pre-configured scope.",
"type": "string",
"const": "allow-check-unsaved-work",
"markdownDescription": "Enables the check_unsaved_work command without any pre-configured scope."
},
{
"description": "Enables the clear_claude_token command without any pre-configured scope.",
"type": "string",
@@ -926,6 +938,12 @@
"const": "allow-rebuild-project-container",
"markdownDescription": "Enables the rebuild_project_container command without any pre-configured scope."
},
{
"description": "Enables the reconcile_aws_projects command without any pre-configured scope.",
"type": "string",
"const": "allow-reconcile-aws-projects",
"markdownDescription": "Enables the reconcile_aws_projects command without any pre-configured scope."
},
{
"description": "Enables the reconcile_project_statuses command without any pre-configured scope.",
"type": "string",
@@ -950,6 +968,12 @@
"const": "allow-regenerate-web-terminal-token",
"markdownDescription": "Enables the regenerate_web_terminal_token command without any pre-configured scope."
},
{
"description": "Enables the remove_aws_resources command without any pre-configured scope.",
"type": "string",
"const": "allow-remove-aws-resources",
"markdownDescription": "Enables the remove_aws_resources command without any pre-configured scope."
},
{
"description": "Enables the remove_host_connection command without any pre-configured scope.",
"type": "string",
@@ -1358,6 +1382,12 @@
"const": "deny-aws-sso-refresh",
"markdownDescription": "Denies the aws_sso_refresh command without any pre-configured scope."
},
{
"description": "Denies the aws_task_log command without any pre-configured scope.",
"type": "string",
"const": "deny-aws-task-log",
"markdownDescription": "Denies the aws_task_log command without any pre-configured scope."
},
{
"description": "Denies the build_gateway_image command without any pre-configured scope.",
"type": "string",
@@ -1436,6 +1466,12 @@
"const": "deny-check-image-update",
"markdownDescription": "Denies the check_image_update command without any pre-configured scope."
},
{
"description": "Denies the check_unsaved_work command without any pre-configured scope.",
"type": "string",
"const": "deny-check-unsaved-work",
"markdownDescription": "Denies the check_unsaved_work command without any pre-configured scope."
},
{
"description": "Denies the clear_claude_token command without any pre-configured scope.",
"type": "string",
@@ -1856,6 +1892,12 @@
"const": "deny-rebuild-project-container",
"markdownDescription": "Denies the rebuild_project_container command without any pre-configured scope."
},
{
"description": "Denies the reconcile_aws_projects command without any pre-configured scope.",
"type": "string",
"const": "deny-reconcile-aws-projects",
"markdownDescription": "Denies the reconcile_aws_projects command without any pre-configured scope."
},
{
"description": "Denies the reconcile_project_statuses command without any pre-configured scope.",
"type": "string",
@@ -1880,6 +1922,12 @@
"const": "deny-regenerate-web-terminal-token",
"markdownDescription": "Denies the regenerate_web_terminal_token command without any pre-configured scope."
},
{
"description": "Denies the remove_aws_resources command without any pre-configured scope.",
"type": "string",
"const": "deny-remove-aws-resources",
"markdownDescription": "Denies the remove_aws_resources command without any pre-configured scope."
},
{
"description": "Denies the remove_host_connection command without any pre-configured scope.",
"type": "string",
@@ -428,6 +428,12 @@
"const": "allow-aws-sso-refresh",
"markdownDescription": "Enables the aws_sso_refresh command without any pre-configured scope."
},
{
"description": "Enables the aws_task_log command without any pre-configured scope.",
"type": "string",
"const": "allow-aws-task-log",
"markdownDescription": "Enables the aws_task_log command without any pre-configured scope."
},
{
"description": "Enables the build_gateway_image command without any pre-configured scope.",
"type": "string",
@@ -506,6 +512,12 @@
"const": "allow-check-image-update",
"markdownDescription": "Enables the check_image_update command without any pre-configured scope."
},
{
"description": "Enables the check_unsaved_work command without any pre-configured scope.",
"type": "string",
"const": "allow-check-unsaved-work",
"markdownDescription": "Enables the check_unsaved_work command without any pre-configured scope."
},
{
"description": "Enables the clear_claude_token command without any pre-configured scope.",
"type": "string",
@@ -926,6 +938,12 @@
"const": "allow-rebuild-project-container",
"markdownDescription": "Enables the rebuild_project_container command without any pre-configured scope."
},
{
"description": "Enables the reconcile_aws_projects command without any pre-configured scope.",
"type": "string",
"const": "allow-reconcile-aws-projects",
"markdownDescription": "Enables the reconcile_aws_projects command without any pre-configured scope."
},
{
"description": "Enables the reconcile_project_statuses command without any pre-configured scope.",
"type": "string",
@@ -950,6 +968,12 @@
"const": "allow-regenerate-web-terminal-token",
"markdownDescription": "Enables the regenerate_web_terminal_token command without any pre-configured scope."
},
{
"description": "Enables the remove_aws_resources command without any pre-configured scope.",
"type": "string",
"const": "allow-remove-aws-resources",
"markdownDescription": "Enables the remove_aws_resources command without any pre-configured scope."
},
{
"description": "Enables the remove_host_connection command without any pre-configured scope.",
"type": "string",
@@ -1358,6 +1382,12 @@
"const": "deny-aws-sso-refresh",
"markdownDescription": "Denies the aws_sso_refresh command without any pre-configured scope."
},
{
"description": "Denies the aws_task_log command without any pre-configured scope.",
"type": "string",
"const": "deny-aws-task-log",
"markdownDescription": "Denies the aws_task_log command without any pre-configured scope."
},
{
"description": "Denies the build_gateway_image command without any pre-configured scope.",
"type": "string",
@@ -1436,6 +1466,12 @@
"const": "deny-check-image-update",
"markdownDescription": "Denies the check_image_update command without any pre-configured scope."
},
{
"description": "Denies the check_unsaved_work command without any pre-configured scope.",
"type": "string",
"const": "deny-check-unsaved-work",
"markdownDescription": "Denies the check_unsaved_work command without any pre-configured scope."
},
{
"description": "Denies the clear_claude_token command without any pre-configured scope.",
"type": "string",
@@ -1856,6 +1892,12 @@
"const": "deny-rebuild-project-container",
"markdownDescription": "Denies the rebuild_project_container command without any pre-configured scope."
},
{
"description": "Denies the reconcile_aws_projects command without any pre-configured scope.",
"type": "string",
"const": "deny-reconcile-aws-projects",
"markdownDescription": "Denies the reconcile_aws_projects command without any pre-configured scope."
},
{
"description": "Denies the reconcile_project_statuses command without any pre-configured scope.",
"type": "string",
@@ -1880,6 +1922,12 @@
"const": "deny-regenerate-web-terminal-token",
"markdownDescription": "Denies the regenerate_web_terminal_token command without any pre-configured scope."
},
{
"description": "Denies the remove_aws_resources command without any pre-configured scope.",
"type": "string",
"const": "deny-remove-aws-resources",
"markdownDescription": "Denies the remove_aws_resources command without any pre-configured scope."
},
{
"description": "Denies the remove_host_connection command without any pre-configured scope.",
"type": "string",
+2 -1
View File
@@ -326,7 +326,8 @@ async fn poll_loop(
// bridge or stopping the container doesn't wait out an in-flight poll.
let discovery = tokio::select! {
_ = cancel.changed() => break,
res = container.exec_oneshot_limited("claude", cmd, PROC_NET_OUTPUT_LIMIT) => {
// Background: on AWS this poll must not keep an idle workspace up.
res = container.exec_oneshot_background("claude", cmd, PROC_NET_OUTPUT_LIMIT) => {
res.map(|(out, _)| out)
}
};
+35 -3
View File
@@ -5,6 +5,7 @@ use aws_config::identity::IdentityCache;
use aws_config::profile::ProfileFileCredentialsProvider;
use aws_config::provider_config::ProviderConfig;
use aws_config::retry::RetryConfig;
use aws_config::timeout::TimeoutConfig;
use aws_config::{BehaviorVersion, Region, SdkConfig};
use aws_credential_types::provider::error::CredentialsError;
use aws_credential_types::provider::{future, ProvideCredentials, SharedCredentialsProvider};
@@ -81,9 +82,9 @@ fn keys_credentials(keys: &secure::AwsKeys) -> SharedCredentialsProvider {
/// stray endpoint there would send every connection's signed requests (and
/// the permission check) somewhere other than AWS. Connections talk to the
/// real regional endpoints; a profile's own `endpoint_url` is ignored too.
/// The HTTP client, timeouts and stalled-stream protection are each service
/// client's defaults (the `default-https-client` stack every AWS crate here
/// is built with).
/// The HTTP client and stalled-stream protection are each service client's
/// defaults (the `default-https-client` stack every AWS crate here is built
/// with). Timeouts are ours: [`OPERATION_TIMEOUT`] / [`ATTEMPT_TIMEOUT`].
fn build_sdk_config(region: Region, credentials: SharedCredentialsProvider) -> SdkConfig {
let mut builder = SdkConfig::builder()
.behavior_version(BehaviorVersion::latest())
@@ -91,6 +92,7 @@ fn build_sdk_config(region: Region, credentials: SharedCredentialsProvider) -> S
.credentials_provider(credentials)
.identity_cache(IdentityCache::lazy().build())
.retry_config(RetryConfig::standard())
.timeout_config(timeouts())
.time_source(SharedTimeSource::default());
if let Some(sleep) = default_async_sleep() {
builder = builder.sleep_impl(sleep);
@@ -98,6 +100,22 @@ fn build_sdk_config(region: Region, credentials: SharedCredentialsProvider) -> S
builder.build()
}
/// Every call the app makes through the SDK is a control-plane call with a
/// small answer (ECS, Secrets Manager, EFS, IAM, SSM, CloudWatch Logs, STS,
/// and S3 reads of state objects capped at 2 KiB); OpenTofu talks to AWS
/// itself, not through these clients. Without a bound a half-open
/// connection would hang a start, a stop or the death watch for minutes.
/// The operation bound covers every retry; the attempt bound is one try.
pub const OPERATION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
pub const ATTEMPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
fn timeouts() -> TimeoutConfig {
TimeoutConfig::builder()
.operation_timeout(OPERATION_TIMEOUT)
.operation_attempt_timeout(ATTEMPT_TIMEOUT)
.build()
}
/// Puts the profile's name into the source chain of every credentials error,
/// so a failure deep inside the SDK can be reported against the profile.
#[derive(Debug)]
@@ -297,4 +315,18 @@ sts =
assert_isolated(&cfg);
assert!(cfg.credentials_provider().is_some());
}
#[test]
fn every_sdk_call_is_bounded() {
let keys = crate::storage::secure::AwsKeys {
access_key_id: "AKIDTEST".into(),
secret_access_key: "s".into(),
session_token: None,
};
let cfg = build_sdk_config(Region::new("us-west-2"), keys_credentials(&keys));
let t = cfg.timeout_config().expect("a timeout config");
assert_eq!(t.operation_timeout(), Some(OPERATION_TIMEOUT));
assert_eq!(t.operation_attempt_timeout(), Some(ATTEMPT_TIMEOUT));
assert!(ATTEMPT_TIMEOUT < OPERATION_TIMEOUT);
}
}
+8 -3
View File
@@ -130,7 +130,12 @@ pub fn parse_environment_record(
.ok_or_else(|| "template_version is not a version number".to_string())?;
let cluster_arn = str_field(obj, "cluster_arn")?;
if cluster_arn != format!("arn:aws:ecs:{region}:{account}:cluster/triple-c-{name}") {
if cluster_arn
!= format!(
"arn:aws:ecs:{region}:{account}:cluster/{}",
super::tofu_modules::environment_cluster_name(&name)
)
{
return Err(
"cluster_arn is not this environment's cluster in this account and region".into(),
);
@@ -171,7 +176,7 @@ pub fn parse_environment_record(
return Err("kms_key_arn is not a KMS key in this account and region".into());
}
let log_group = str_field(obj, "log_group")?;
if log_group != format!("/triple-c/{name}") {
if log_group != super::tofu_modules::environment_log_group(&name) {
return Err("log_group is not this environment's log group".into());
}
let network_mode = str_field(obj, "network_mode")?;
@@ -754,7 +759,7 @@ fn error_parts<E: ProvideErrorMetadata>(
}
/// Yes / No (missing) / Unknown (denied) from a lookup's result.
fn knowable<T, E>(
pub(crate) fn knowable<T, E>(
action: &str,
res: Result<T, SdkError<E, HttpResponse>>,
) -> Result<Knowable, AwsError>
+8 -1
View File
@@ -29,6 +29,11 @@ pub enum AwsError {
StateBucketTaken {
bucket: String,
},
/// An account limit (Fargate vCPUs, tasks, ...) refused the request.
/// Never retried; `message` says what to do.
QuotaExceeded {
message: String,
},
Other {
message: String,
},
@@ -63,7 +68,9 @@ impl std::fmt::Display for AwsError {
"The state bucket name \"{bucket}\" is already taken by another AWS account, so \
Triple-C can't keep OpenTofu state there"
),
AwsError::Other { message } => f.write_str(message),
AwsError::QuotaExceeded { message } | AwsError::Other { message } => {
f.write_str(message)
}
}
}
}
+744 -1
View File
@@ -561,6 +561,7 @@ async fn a_role_with_no_policy_checks_as_insufficient_and_lists_every_action() {
#[ignore]
async fn a_role_without_simulate_permission_falls_back_to_probes() {
e2e(|e| async move {
// `InspectOwnPrincipal` lives in the first file.
let mut doc: serde_json::Value =
serde_json::from_str(policy_files(Tier::WorkspaceUser)[0].1).unwrap();
doc["Statement"]
@@ -570,6 +571,11 @@ async fn a_role_without_simulate_permission_falls_back_to_probes() {
let role = e.role("nosim", None, &[]).await;
let arn = e.managed_policy("nosim", &doc.to_string()).await;
e.attach(&role, &arn).await;
// The tasks file is attached whole.
let tasks = e
.managed_policy("nosim-tasks", policy_files(Tier::WorkspaceUser)[1].1)
.await;
e.attach(&role, &tasks).await;
let cfg = e.assume(&role).await;
let me = caller_identity(&cfg).await.expect("identity");
assert_eq!(me.user_id, role.session_user_id());
@@ -790,6 +796,20 @@ async fn secrets_use_the_environment_key_and_only_their_owner_can_change_them()
as_user.put_secret_value().secret_id(&own).secret_string("v2").send().await,
);
// `workspace-user-tasks.json`: the owner reads their own secret, never
// the environment's or someone else's.
let read = ok(
"get own",
as_user.get_secret_value().secret_id(&own).send().await,
);
assert_eq!(read.secret_string(), Some("v2"));
for (what, arn) in [("environment", &environment), ("someone else's", &someone_elses)] {
denied(
&format!("get {what}"),
as_user.get_secret_value().secret_id(arn).send().await,
);
}
// Any other key is refused.
for (i, (what, k)) in [("no KmsKeyId", None), ("aws/secretsmanager", Some(aws_managed.as_str()))]
.into_iter()
@@ -997,7 +1017,8 @@ mod environment {
use aws_config::SdkConfig;
use super::{e2e, ok, E2e, Role};
use super::{classify_sdk_error, e2e, ok, E2e, Role};
use futures_util::FutureExt;
use crate::aws::environments::{
ensure_named_state_bucket, is_empty_state, scan_in_bucket, EnvironmentAction, EnvironmentState, Knowable,
OnboardingState, SdkDetectApi,
@@ -1695,4 +1716,726 @@ mod environment {
})
.await;
}
// ─────────────────────────────────────────────── phase 5: a workspace
/// What the phase-5 test made outside the modules, for its own guard
/// (which runs before the environment fixture's destroy).
#[derive(Default)]
struct Phase5 {
/// The onboarded execution role holding the test-only ECR policy.
exec_role: Option<String>,
cluster: Option<String>,
/// Task definition family prefixes to retire (`triple-c-<env>-`).
families: Vec<String>,
/// The user's file system's creation token.
fs_token: Option<String>,
secrets: Vec<String>,
/// The project whose tunnel to close.
project_id: Option<String>,
/// `AWS_CONFIG_FILE` before the test pointed it at its own file
/// (outer `None`: not changed).
config_file_before: Option<Option<std::ffi::OsString>>,
/// `TRIPLEC_E2E_ECR_REPO`: the throwaway repository to force-delete.
ecr_repo: Option<String>,
}
/// The whole phase-5 body: a hang anywhere becomes a panic the guard
/// catches, so nothing billed outlives it.
const PHASE5_TIMEOUT: Duration = Duration::from_secs(45 * 60);
/// One exec through the agent.
const SH_TIMEOUT: Duration = Duration::from_secs(180);
/// The phase-5 guard's state, even after a panic poisoned the lock.
fn p5_lock(m: &std::sync::Mutex<Phase5>) -> std::sync::MutexGuard<'_, Phase5> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
const ECR_POLICY: &str = "triple-c-e2e-ecr-pull";
/// As the account admin: stop every task in the cluster and wait for
/// them, retire the test's task definitions, delete the user's access
/// points and the project secret (no recovery window), and take the
/// test-only ECR policy off the execution role, so the modules'
/// `tofu destroy` can remove the rest. Logs, never fails.
async fn phase5_cleanup(e: &E2e, p: &Phase5) {
if let Some(id) = &p.project_id {
crate::host::tunnels::close(id).await;
}
match &p.config_file_before {
Some(Some(v)) => std::env::set_var("AWS_CONFIG_FILE", v),
Some(None) => std::env::remove_var("AWS_CONFIG_FILE"),
None => {}
}
let ecs = aws_sdk_ecs::Client::new(&e.cfg);
if let Some(cluster) = &p.cluster {
let mut arns = Vec::new();
for status in [aws_sdk_ecs::types::DesiredStatus::Running, aws_sdk_ecs::types::DesiredStatus::Pending] {
if let Ok(out) = ecs.list_tasks().cluster(cluster).desired_status(status).send().await {
arns.extend(out.task_arns().iter().cloned());
}
}
for arn in &arns {
eprintln!("cleanup: stopping task {arn}");
if let Err(err) = ecs.stop_task().cluster(cluster).task(arn).reason("triple-c-e2e cleanup").send().await {
eprintln!("cleanup: stop {arn}: {err:?}");
}
}
// Until none is left running (a stop takes up to stopTimeout).
for _ in 0..40 {
let mut live = 0;
if !arns.is_empty() {
if let Ok(out) = ecs.describe_tasks().cluster(cluster).set_tasks(Some(arns.clone())).send().await {
live = out.tasks().iter().filter(|t| t.last_status() != Some("STOPPED")).count();
}
}
if live == 0 {
break;
}
tokio::time::sleep(Duration::from_secs(10)).await;
}
}
for prefix in &p.families {
let mut defs = Vec::new();
for status in [aws_sdk_ecs::types::TaskDefinitionStatus::Active, aws_sdk_ecs::types::TaskDefinitionStatus::Inactive] {
let mut next = None;
loop {
let Ok(out) = ecs
.list_task_definitions()
.family_prefix(prefix)
.status(status.clone())
.set_next_token(next.take())
.send()
.await
else {
break;
};
defs.extend(out.task_definition_arns().iter().cloned());
next = out.next_token().map(str::to_string);
if next.is_none() {
break;
}
}
}
for arn in &defs {
let _ = ecs.deregister_task_definition().task_definition(arn).send().await;
}
for chunk in defs.chunks(10) {
if let Err(err) = ecs.delete_task_definitions().set_task_definitions(Some(chunk.to_vec())).send().await {
eprintln!("cleanup: delete task definitions: {err:?}");
}
}
if !defs.is_empty() {
eprintln!("cleanup: retired {} task definition revision(s) of {prefix}*", defs.len());
}
}
if let Some(token) = &p.fs_token {
let efs = aws_sdk_efs::Client::new(&e.cfg);
if let Ok(out) = efs.describe_file_systems().creation_token(token).send().await {
for fs in out.file_systems() {
if let Ok(aps) = efs.describe_access_points().file_system_id(fs.file_system_id()).send().await {
for ap in aps.access_points() {
let id = ap.access_point_id().unwrap_or_default();
eprintln!("cleanup: deleting access point {id}");
if let Err(err) = efs.delete_access_point().access_point_id(id).send().await {
eprintln!("cleanup: delete access point {id}: {err:?}");
}
}
}
}
}
}
for name in &p.secrets {
match e.secrets.delete_secret().secret_id(name).force_delete_without_recovery(true).send().await {
Ok(_) => eprintln!("cleanup: deleted secret {name} (no recovery window)"),
Err(err) => {
let err = classify_sdk_error("secretsmanager:DeleteSecret", &err);
if !err.to_string().contains("ResourceNotFound") {
eprintln!("cleanup: delete secret {name}: {err}");
}
}
}
}
if let Some(role) = &p.exec_role {
match e.iam.delete_role_policy().role_name(role).policy_name(ECR_POLICY).send().await {
Ok(_) => eprintln!("cleanup: removed {ECR_POLICY} from {role}"),
Err(err) => {
if !format!("{err:?}").contains("NoSuchEntity") {
eprintln!("cleanup: remove {ECR_POLICY} from {role}: {err:?}");
}
}
}
}
if let Some(repo) = &p.ecr_repo {
// No ECR crate in the app: the AWS CLI, as the e2e profile.
let out = tokio::process::Command::new("aws")
.args(["--profile", &super::var("TRIPLEC_AWS_E2E_PROFILE"), "--region", &e.region])
.args(["ecr", "delete-repository", "--repository-name", repo, "--force"])
.output()
.await;
match out {
Ok(o) if o.status.success() => eprintln!("cleanup: deleted ECR repository {repo}"),
Ok(o) if String::from_utf8_lossy(&o.stderr).contains("RepositoryNotFound") => {}
other => eprintln!("cleanup: delete ECR repository {repo}: {other:?}"),
}
}
}
/// Poll `f` every `every` until it returns `Some`, or `None` after `within`.
async fn poll<T, F, Fut>(within: Duration, every: Duration, mut f: F) -> Option<T>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Option<T>>,
{
let deadline = std::time::Instant::now() + within;
loop {
if let Some(v) = f().await {
return Some(v);
}
if std::time::Instant::now() + every > deadline {
return None;
}
tokio::time::sleep(every).await;
}
}
/// `sh -c script` as `user`: (output, exit code).
async fn sh(t: &crate::host::ContainerTarget, user: &str, script: &str) -> (String, i64) {
tokio::time::timeout(
SH_TIMEOUT,
t.exec_oneshot_as(user, vec!["sh".into(), "-c".into(), script.into()], Vec::new()),
)
.await
.unwrap_or_else(|_| panic!("exec `{script}` did not finish in {SH_TIMEOUT:?}"))
.unwrap_or_else(|err| panic!("exec `{script}`: {err}"))
}
/// Phase 5: a Fargate workspace's whole life through `ProjectHost::Aws`,
/// as a role holding **only** the workspace-user files, in an
/// environment the environment admin deployed and onboarded it to.
///
/// ```sh
/// cd app/src-tauri
/// cargo build
/// TRIPLEC_AWS_E2E_PROFILE=… TRIPLEC_AWS_E2E_REGION=us-west-2 \
/// TRIPLEC_E2E_IMAGE=<account>.dkr.ecr.<region>.amazonaws.com/triple-c-e2e-sandbox:<tag> \
/// cargo test aws::live_tests::environment::a_fargate_workspace_round_trips \
/// -- --ignored --test-threads=1 --nocapture
/// ```
///
/// `TRIPLEC_E2E_IMAGE` is the image the project names as its Custom
/// image: one built from this branch (`docker build --platform
/// linux/amd64 ./container`) and pushed to a registry Fargate can pull.
/// For a private ECR repository in the test account, the test gives the
/// onboarded execution role a **test-only** inline pull policy
/// (`triple-c-e2e-ecr-pull`; the boundary allows ECR pulls, the
/// onboarding module grants none) and removes it before the onboarding
/// is destroyed. `scripts/aws-e2e-workspace.sh` does it all: builds the
/// image, creates the throwaway repository `triple-c-e2e-sandbox`,
/// pushes, runs this test with `TRIPLEC_E2E_ECR_REPO` set (this test's
/// guard then force-deletes that repository too) and deletes it in a
/// trap on exit.
///
/// The body runs under a 45-minute timeout and every exec under its own,
/// so a hang becomes a panic and the guard still runs.
///
/// The workspace user signs in the way a saved profile connection does:
/// a profile (`role_arn` + `source_profile` = the e2e profile, session
/// name `triple-c-e2e`) in a config file this test writes and points
/// `AWS_CONFIG_FILE` at. About 30 Fargate task-minutes at 1 vCPU / 2 GB.
#[tokio::test]
#[ignore]
async fn a_fargate_workspace_round_trips() {
use crate::aws::runtime::SdkRuntimeApi;
use crate::aws::tasks::{run_task_request, task_log_stream, SdkTaskApi, TaskApi};
use crate::aws::tofu_modules::{
environment_cluster_name, log_stream_prefix, project_secret_name, task_family,
user_file_system_token,
};
use crate::aws::workspace::workspace_tags;
use crate::host::{lifecycle::ProjectHost, tunnels};
use crate::models::app_settings::ImageSource;
use crate::models::project::{AwsPlacement, AwsWorkspaceConfig, RepoSource, StorageMode};
use crate::models::{AppSettings, Project};
use crate::storage::projects_store::ProjectsStore;
let image = super::var("TRIPLEC_E2E_IMAGE");
let ecr_repo = std::env::var("TRIPLEC_E2E_ECR_REPO").ok().filter(|r| !r.is_empty());
env_e2e(|t| async move {
let p5 = std::sync::Mutex::new(Phase5 { ecr_repo, ..Default::default() });
// Boxed: the body's state machine is far larger than a test
// thread's 2 MiB stack once it is moved into the timeout.
let inner = Box::pin(async {
let region = t.e.region.clone();
let admin = t.admin().await;
let (keys, cfg, who) = t.session(&admin).await;
t.ensure_bucket(&cfg, &who).await;
t.ensure_boundary().await;
// ── the environment, deployed by the environment admin ──
let name = format!("e2e{}", &uuid::Uuid::new_v4().simple().to_string()[..6]);
let (cluster, families) = (environment_cluster_name(&name), format!("triple-c-{name}-"));
{
let mut g = p5_lock(&p5);
g.cluster = Some(cluster);
g.families.push(families);
}
let vars = environment_vars(&name, &region, &NetworkChoice::Public).unwrap();
let (_, outcome, denied) = t
.run(ModuleKind::Environment, Deployment::Environment(&name), &vars, TofuOp::Apply, t.keys_env(&keys))
.await;
assert_ok("deploy", &outcome, &denied);
// ── the workspace user: only the workspace files ──
let user = t.e.tier_role("wsuser", &[Tier::WorkspaceUser]).await;
let owner = validate_owner_id(&user.session_user_id()).expect("owner id");
let okey = owner_key(&region, &owner);
let fs_token = user_file_system_token(&name, &okey);
p5_lock(&p5).fs_token = Some(fs_token.clone());
// Onboarded by the admin (an onboarding from an admin bundle).
let (keys, _, _) = t.session(&admin).await;
let (_, outcome, denied) = t
.run(
ModuleKind::UserOnboard,
Deployment::User { env: &name, owner_key: &okey },
&onboarding_vars(&name, &region, &owner),
TofuOp::Apply,
t.keys_env(&keys),
)
.await;
assert_ok("onboard the workspace user", &outcome, &denied);
let (_, exec_role) = user_role_names(&name, &okey);
// Test-only: pull from the throwaway private ECR repository.
if let Some((registry, rest)) = image.split_once('/') {
if registry.contains(".dkr.ecr.") {
let repo = rest.split([':', '@']).next().unwrap();
let doc = format!(
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Action":"ecr:GetAuthorizationToken","Resource":"*"}},{{"Effect":"Allow","Action":["ecr:BatchGetImage","ecr:GetDownloadUrlForLayer","ecr:BatchCheckLayerAvailability"],"Resource":"arn:aws:ecr:{region}:{}:repository/{repo}"}}]}}"#,
t.e.account
);
p5_lock(&p5).exec_role = Some(exec_role.clone());
ok(
"put the test-only ECR policy",
t.e.iam.put_role_policy().role_name(&exec_role).policy_name(ECR_POLICY).policy_document(doc).send().await,
);
eprintln!("test-only: {ECR_POLICY} on {exec_role} for {repo}");
}
}
// The workspace user's profile connection.
let profile = format!("{}-wsuser", t.e.prefix);
let cfg_file = t.root.join(format!("{}-config", t.e.prefix));
std::fs::write(
&cfg_file,
format!(
"[profile {profile}]\nrole_arn = {}\nsource_profile = {}\nrole_session_name = {}\n",
user.arn,
super::var("TRIPLEC_AWS_E2E_PROFILE"),
super::SESSION
),
)
.unwrap();
let before = std::env::var_os("AWS_CONFIG_FILE");
p5_lock(&p5).config_file_before = Some(before);
std::env::set_var("AWS_CONFIG_FILE", &cfg_file);
let conn = HostConnection {
id: "e2e-wsuser".into(),
name: "e2e-wsuser".into(),
kind: HostKind::Aws {
auth: AwsAuth::Profile { name: profile.clone() },
default_region: region.clone(),
},
};
let ws_cfg = crate::aws::sdk_config(&conn, &region).await.expect("workspace user config");
let ws = caller_identity(&ws_cfg).await.expect("workspace user identity");
assert_eq!(ws.user_id, owner, "the profile session is the onboarded owner");
eprintln!("workspace user: {}", ws.arn);
let mut settings = AppSettings::default();
settings.hosts = vec![conn];
settings.image_source = ImageSource::Custom;
settings.custom_image_name = Some(image.clone());
let mut project = Project::new("e2e-fargate".into(), Vec::new());
project.host_id = Some("e2e-wsuser".into());
project.aws_placement = Some(AwsPlacement { region: region.clone(), environment: name.clone() });
project.aws = Some(AwsWorkspaceConfig {
cpu: 1024,
memory_mib: 2048,
storage: StorageMode::Hybrid,
repos: vec![RepoSource {
url: "https://github.com/octocat/Hello-World.git".into(),
branch: None,
folder: "Hello-World".into(),
}],
wip_push_on_stop: true,
// On from the first start: turning it on later adds a
// secret key, so the next start registers a new revision.
// The test's own execs keep task 1 busy until its stop.
idle_stop_minutes: Some(5),
..Default::default()
});
let id = project.id.clone();
let secret_name = project_secret_name(&name, &okey, &id);
{
let mut g = p5_lock(&p5);
g.project_id = Some(id.clone());
g.secrets.push(secret_name);
}
let store_dir = tempfile::tempdir().unwrap();
let store = ProjectsStore::over_file_for_test(store_dir.path().join("projects.json"), vec![project.clone()]);
let host = ProjectHost::for_project(&project);
assert_eq!(host, ProjectHost::Aws);
let progress = |m: &str| eprintln!(" progress: {m}");
let api = SdkTaskApi::new(&ws_cfg);
let env = crate::aws::runtime::read_environment(&SdkRuntimeApi::new(&ws_cfg), &name, &ws.account, &region)
.await
.expect("the environment record, as the workspace user");
let family = task_family(&name, &okey, &id);
let stream_prefix = log_stream_prefix(&okey, &id);
let current = |store: &ProjectsStore| store.get(&id).unwrap();
// ── start 1 ──
let t0 = std::time::Instant::now();
let target = host.ensure_started(&current(&store), &settings, &store, &progress).await.expect("start 1");
let first_start = t0.elapsed();
let p = current(&store);
let aws = p.aws.clone().unwrap();
let task1 = aws.task_arn.clone().expect("the task ARN is stored");
let revision1 = aws.task_definition_arn.clone().expect("the task definition is stored");
eprintln!("RESULT start 1 (cold: register, access point, RunTask, pull, agent, tunnel): {first_start:?}; task {task1}; {revision1}");
assert!(revision1.contains(&format!(":task-definition/{family}:")), "{revision1}");
assert!(aws.access_point_id.is_some(), "Hybrid has an access point");
// ECS's own health check (startPeriod 120 s, interval 30 s).
let health = poll(Duration::from_secs(300), Duration::from_secs(10), || async {
let d = api.describe(&env.cluster_arn, std::slice::from_ref(&task1)).await.ok()?;
let h = d.first()?.health.clone();
(h.as_deref() == Some("HEALTHY")).then_some(())
})
.await;
eprintln!("RESULT ECS health HEALTHY after {:?} from RunTask's start ({health:?})", t0.elapsed());
assert!(health.is_some(), "the task never became HEALTHY");
// Resource-level checks, as the account admin: the revision and
// the task carry exactly the three tags.
let ecs_admin = aws_sdk_ecs::Client::new(&t.e.cfg);
let td = ok(
"describe the revision",
ecs_admin.describe_task_definition().task_definition(&revision1).include(aws_sdk_ecs::types::TaskDefinitionField::Tags).send().await,
);
let mut tags: Vec<(String, String)> = td
.tags()
.iter()
.map(|t| (t.key().unwrap_or_default().to_string(), t.value().unwrap_or_default().to_string()))
.collect();
tags.sort();
let mut want = workspace_tags(&owner, &id, &name);
want.sort();
assert_eq!(tags, want, "RegisterTaskDefinition tagged at registration");
eprintln!("RESULT RegisterTaskDefinition as the workspace user on task-definition/triple-c-*: allowed, tagged {tags:?}");
eprintln!("RESULT RunTask (owner-tagged revision, iam:PassRole by tag on the user's own roles): allowed");
// ── through the agent ──
let (out, code) = sh(&target, "claude", "echo hello-from-fargate").await;
assert_eq!((out.trim(), code), ("hello-from-fargate", 0));
let (id_out, _) = sh(&target, "claude", "id").await;
eprintln!("RESULT id: {}", id_out.trim());
assert!(id_out.contains("uid=1000(claude)"), "{id_out}");
let cloned = poll(Duration::from_secs(300), Duration::from_secs(5), || async {
let (out, code) = sh(&target, "root", "test -f /run/triple-c-clone/done && cat /run/triple-c-clone/repos").await;
(code == 0).then_some(out)
})
.await
.expect("the background clone never finished");
eprintln!("RESULT clone status: {}", cloned.trim());
let (head, code) = sh(&target, "claude", "git -C /workspace/Hello-World log -1 --format=%H").await;
assert_eq!(code, 0, "{head}");
eprintln!("RESULT cloned Hello-World at {}", head.trim());
let (links, _) = sh(
&target,
"claude",
"for f in ~/.claude ~/.claude.json ~/.ssh; do printf '%s -> %s\n' \"$f\" \"$(readlink \"$f\")\"; done; \
grep ' /mnt/triple-c-home ' /proc/mounts; stat -c '%U:%G %a' /mnt/triple-c-home",
)
.await;
eprintln!("RESULT Hybrid home:\n{}", links.trim());
assert!(links.contains(".claude -> /mnt/triple-c-home/"), "{links}");
let marker = uuid::Uuid::new_v4().to_string();
let (_, code) = sh(&target, "claude", &format!("printf %s {marker} > ~/.claude/marker")).await;
assert_eq!(code, 0);
// Claude Code's own writes to ~/.claude.json (no login: it
// still starts, and fails at the API call).
let (claude, _) = sh(
&target,
"claude",
"cd /workspace && timeout 90 claude -p 'say ok' </dev/null 2>&1 | tail -3; \
test -L ~/.claude.json && echo STILL-A-LINK || echo REPLACED; ls -la ~/.claude.json",
)
.await;
eprintln!("RESULT claude run:\n{}", claude.trim());
// P9: bubblewrap's unprivileged user namespace on Fargate.
let (bwrap, code) = sh(
&target,
"claude",
"bwrap --ro-bind / / --unshare-user true 2>&1; echo \"unshare-user rc=$?\"; \
bwrap --ro-bind / / --dev /dev --proc /proc --unshare-all --die-with-parent true 2>&1; echo \"unshare-all rc=$?\"; \
cat /proc/sys/user/max_user_namespaces 2>&1; cat /proc/sys/kernel/unprivileged_userns_clone 2>&1; uname -r",
)
.await;
eprintln!("RESULT P9 bwrap (exit {code}):\n{}", bwrap.trim());
// The stop guard's dry run through the agent, on a dirty repo.
let (_, code) = sh(&target, "claude", "echo e2e >> /workspace/Hello-World/README && touch /workspace/Hello-World/e2e-new").await;
assert_eq!(code, 0);
let (raw, code) = sh(&target, "claude", "/usr/local/bin/triple-c-wip-push --dry-run").await;
eprintln!("RESULT triple-c-wip-push --dry-run (exit {code}): {}", raw.trim());
let unsaved = crate::commands::stop_guard::unsaved_work(Some(&target), crate::commands::stop_guard::DRY_RUN_TIMEOUT).await;
eprintln!("RESULT stop guard check: {unsaved:?}");
assert!(unsaved.checked, "{unsaved:?}");
assert!(unsaved.repos.iter().any(|r| r.folder == "Hello-World" && r.dirty), "{unsaved:?}");
// GetSecretValue: another owner's triple-c/* secret is denied.
let foreign_secret = format!("triple-c/{}/someone-else", t.e.prefix);
let created = ok(
"admin creates another owner's secret",
t.e.secrets
.create_secret()
.name(&foreign_secret)
.secret_string("e2e")
.tags(super::sm_tag("triple-c:owner", "AROAEXAMPLEOTHER:bob"))
.send()
.await,
);
t.e.record_secret(created.arn().unwrap());
let ws_secrets = aws_sdk_secretsmanager::Client::new(&ws_cfg);
super::denied(
"GetSecretValue on another owner's secret",
ws_secrets.get_secret_value().secret_id(created.arn().unwrap()).send().await,
);
eprintln!("RESULT GetSecretValue on another owner's secret: denied");
// A bare TagResource on the user's own file system (no
// CreateAction) is refused: tagging is only at creation.
let efs_admin = aws_sdk_efs::Client::new(&t.e.cfg);
let fs = ok(
"find the user's file system",
efs_admin.describe_file_systems().creation_token(&fs_token).send().await,
);
let fs_id = fs.file_systems().first().expect("the user's file system").file_system_id().to_string();
let ws_efs = aws_sdk_efs::Client::new(&ws_cfg);
super::denied(
"bare TagResource on own file system",
ws_efs
.tag_resource()
.resource_id(&fs_id)
.tags(aws_sdk_efs::types::Tag::builder().key("triple-c:owner").value(&owner).build().unwrap())
.send()
.await,
);
eprintln!("RESULT bare elasticfilesystem:TagResource on the user's own file system {fs_id}: denied");
// RunTask on a revision the user does not own is denied.
let foreign_family = format!("triple-c-{name}-e2e-foreign");
let reg = ok(
"admin registers a foreign revision",
ecs_admin
.register_task_definition()
.family(&foreign_family)
.requires_compatibilities(aws_sdk_ecs::types::Compatibility::Fargate)
.network_mode(aws_sdk_ecs::types::NetworkMode::Awsvpc)
.cpu("256")
.memory("512")
.container_definitions(
aws_sdk_ecs::types::ContainerDefinition::builder()
.name("x")
.image("public.ecr.aws/docker/library/alpine:3")
.essential(true)
.build(),
)
.tags(aws_sdk_ecs::types::Tag::builder().key("triple-c:owner").value("AROAEXAMPLEOTHER:bob").build())
.send()
.await,
);
let foreign_arn = reg.task_definition().unwrap().task_definition_arn().unwrap().to_string();
let r = api.run_task(run_task_request(&env, &foreign_arn, false, &workspace_tags(&owner, &id, &name))).await;
match r {
Err(crate::aws::error::AwsError::AccessDenied { .. }) => {
eprintln!("RESULT RunTask on another owner's revision: denied")
}
other => panic!("RunTask on another owner's revision: expected AccessDenied, got {other:?}"),
}
// A second start while running: an attach, no second RunTask.
// With the tunnel up it is reused outright; with it closed the
// start finds the live task and reads the token back (own
// GetSecretValue).
let again = host.ensure_started(&current(&store), &settings, &store, &progress).await.expect("start while running (tunnel up)");
assert_eq!(again.id(), target.id());
tunnels::close(&id).await;
let t1 = std::time::Instant::now();
let attached = host.ensure_started(&current(&store), &settings, &store, &progress).await.expect("attach");
eprintln!("RESULT attach to the running task (find, GetSecretValue own secret, tunnel): {:?}", t1.elapsed());
assert_eq!(current(&store).aws.unwrap().task_arn.as_deref(), Some(task1.as_str()));
let live = api.list_project_tasks(&env.cluster_arn, &family).await.unwrap();
assert_eq!(live, vec![task1.clone()], "exactly one task: no second RunTask");
let (out, _) = sh(&attached, "claude", "cat ~/.claude/marker").await;
assert_eq!(out.trim(), marker);
// ── stop 1: StopTask → SIGTERM → the entrypoint's WIP push ──
let t2 = std::time::Instant::now();
host.stop_project(&current(&store), &settings).await.expect("stop 1");
let stopped = poll(Duration::from_secs(240), Duration::from_secs(5), || async {
let d = api.describe(&env.cluster_arn, std::slice::from_ref(&task1)).await.ok()?;
let t = d.into_iter().next()?;
(t.last_status == "STOPPED").then_some(t)
})
.await
.expect("task 1 never stopped");
eprintln!("RESULT stop 1: STOPPED after {:?}; code {:?}, reason {:?}", t2.elapsed(), stopped.stop_code, stopped.stopped_reason);
tokio::time::sleep(Duration::from_secs(15)).await;
let log1 = api.log_tail(&env.log_group, &task_log_stream(&stream_prefix, &task1), 60).await.unwrap();
let tail1: Vec<&String> = log1.iter().filter(|l| l.contains("entrypoint: stopping") || l.contains("wip") || l.contains("WIP")).collect();
eprintln!("RESULT task 1 stop log lines: {tail1:#?}");
assert!(log1.iter().any(|l| l.contains("entrypoint: stopping (sigterm) — pushing work in progress")), "{log1:#?}");
store.set_aws_runtime(&id, None, current(&store).aws.unwrap().access_point_id, Some(revision1.clone())).unwrap();
// ── start 2, unchanged; idle stop is at its minimum ──
let t3 = std::time::Instant::now();
let target2 = host.ensure_started(&current(&store), &settings, &store, &progress).await.expect("start 2");
let aws2 = current(&store).aws.unwrap();
let task2 = aws2.task_arn.clone().unwrap();
eprintln!("RESULT start 2 (same revision): {:?}; task {task2}", t3.elapsed());
assert_ne!(task2, task1, "a new task");
assert_eq!(aws2.task_definition_arn.as_deref(), Some(revision1.as_str()), "same family revision");
let (out, _) = sh(&target2, "claude", "cat ~/.claude/marker; test -L ~/.claude.json && echo STILL-A-LINK").await;
eprintln!("RESULT after restart: {}", out.trim());
assert!(out.contains(&marker), "the ~/.claude marker persisted: {out}");
poll(Duration::from_secs(300), Duration::from_secs(5), || async {
let (_, code) = sh(&target2, "root", "test -f /run/triple-c-clone/done").await;
(code == 0).then_some(())
})
.await
.expect("clone 2 never finished");
let (check, _) = sh(&target2, "root", "TRIPLEC_IDLE_STOP_MINUTES=5 /usr/local/bin/triple-c-idle-watch --check; echo idle-check=$?").await;
eprintln!("RESULT idle --check right after use: {}", check.trim());
// Leave it alone, the way a user does (R11): a terminal tab stays
// open but silent (an attach held through the tunnel), and the
// auth bridge's background poll keeps running every 2 s. Neither
// may keep the workspace up.
let held = target2
.attach(crate::host::ExecSpec::new(vec!["cat".into()]).tty(true))
.await
.expect("hold a terminal open");
let poller = {
let t = target2.clone();
tokio::spawn(async move {
loop {
let _ = t
.exec_oneshot_background(
"claude",
vec!["/usr/bin/cat".into(), "/proc/net/tcp".into()],
crate::host::PROC_NET_OUTPUT_LIMIT,
)
.await;
tokio::time::sleep(Duration::from_secs(2)).await;
}
})
};
let idle_from = std::time::Instant::now();
let stopped2 = poll(Duration::from_secs(15 * 60), Duration::from_secs(20), || async {
let d = api.describe(&env.cluster_arn, std::slice::from_ref(&task2)).await.ok()?;
let t = d.into_iter().next()?;
(t.desired_status == "STOPPED" || t.last_status == "STOPPED").then_some(t)
})
.await
.expect("the idle task did not stop by itself within 15 minutes (open tab + background poll)");
poller.abort();
drop(held);
tunnels::close(&id).await;
eprintln!(
"RESULT idle stop: desired STOPPED {:?} after the last use; code {:?}, reason {:?}",
idle_from.elapsed(),
stopped2.stop_code,
stopped2.stopped_reason
);
let final2 = poll(Duration::from_secs(240), Duration::from_secs(10), || async {
let d = api.describe(&env.cluster_arn, std::slice::from_ref(&task2)).await.ok()?;
let t = d.into_iter().next()?;
(t.last_status == "STOPPED").then_some(t)
})
.await
.expect("task 2 never reached STOPPED");
eprintln!(
"RESULT idle stop as ECS reports it: code {:?}, exit {:?}, kind {:?}",
final2.stop_code,
final2.exit_code,
crate::aws::tasks::classify_stop(&final2)
);
assert_eq!(crate::aws::tasks::classify_stop(&final2), crate::aws::tasks::StopKind::Idle);
tokio::time::sleep(Duration::from_secs(15)).await;
let log2 = api.log_tail(&env.log_group, &task_log_stream(&stream_prefix, &task2), 60).await.unwrap();
let tail2: Vec<&String> = log2.iter().filter(|l| l.contains("stopping") || l.contains("idle")).collect();
eprintln!("RESULT task 2 stop log lines: {tail2:#?}");
assert!(log2.iter().any(|l| l.contains("entrypoint: stopping (idle)")), "{log2:#?}");
// ── remove: the task, the secret and (data discarded) the access
// point; the task definition is left (R8) ──
store.set_aws_runtime(&id, None, aws2.access_point_id.clone(), aws2.task_definition_arn.clone()).unwrap();
// Every step runs even when one fails (the failures are
// reported together), so check them all before the result.
let removed = host.remove_aws_resources(&current(&store), &settings, true).await;
eprintln!("RESULT remove_aws_resources: {:?}", removed.as_ref().map_err(|e| e.chars().take(400).collect::<String>()));
// R10: deleted at once, so the next start can create it again.
// The forced delete completes asynchronously; give it a moment.
let secret_gone = poll(Duration::from_secs(60), Duration::from_secs(5), || async {
match t.e.secrets.describe_secret().secret_id(project_secret_name(&name, &okey, &id)).send().await {
Err(e) if e.as_service_error().is_some_and(|s| s.is_resource_not_found_exception()) => Some(()),
_ => None,
}
})
.await;
eprintln!("RESULT project secret after remove: gone {secret_gone:?}");
assert!(secret_gone.is_some(), "the secret is deleted without a recovery window");
let defs = ok(
"list the family",
ecs_admin.list_task_definitions().family_prefix(&family).send().await,
);
eprintln!("RESULT active revisions after remove: {:?}", defs.task_definition_arns());
let td = ecs_admin.describe_task_definition().task_definition(&revision1).send().await;
eprintln!(
"RESULT revision after remove: {:?}",
td.map(|o| o.task_definition().and_then(|d| d.status().cloned())).map_err(|e| format!("{e:?}").chars().take(200).collect::<String>())
);
let efs = aws_sdk_efs::Client::new(&t.e.cfg);
let gone = efs.describe_access_points().access_point_id(aws2.access_point_id.clone().unwrap()).send().await;
eprintln!("RESULT access point after remove: {:?}", gone.as_ref().map(|o| o.access_points().len()).map_err(|e| format!("{e:?}").chars().take(120).collect::<String>()));
assert!(gone.is_err() || gone.unwrap().access_points().iter().all(|a| a.life_cycle_state() != Some(&aws_sdk_efs::types::LifeCycleState::Available)));
removed.expect("remove the project's resources");
// R8: the revisions stay registered for an admin to clear
// (the guard does, as the account admin).
assert_eq!(defs.task_definition_arns(), [revision1.clone()], "the project's revision is left ACTIVE");
});
let body = async {
if tokio::time::timeout(PHASE5_TIMEOUT, inner).await.is_err() {
panic!("the phase-5 body did not finish in {PHASE5_TIMEOUT:?}");
}
};
let result = std::panic::AssertUnwindSafe(body).catch_unwind().await;
let guard = std::mem::take(&mut *p5_lock(&p5));
phase5_cleanup(&t.e, &guard).await;
if let Err(panic) = result {
std::panic::resume_unwind(panic);
}
})
.await;
}
}
+3
View File
@@ -13,8 +13,11 @@ pub mod permissions;
pub mod policies;
#[cfg(test)]
mod policy_eval;
pub mod runtime;
pub mod tasks;
pub mod tofu;
pub mod tofu_modules;
pub mod workspace;
pub use connection::{sdk_config, sdk_config_for_keys};
pub use error::{classify_sdk_error, AwsError};
+16
View File
@@ -135,8 +135,13 @@ impl SdkPermissionApi {
// hundred simulations) failed a third of its rows with "Rate
// exceeded" under standard retries (verified live). Adaptive retry
// backs off client-side once throttled, with room to retry.
//
// The connection's 30 s operation limit counts the retries' backoff
// too, which would cut those ten attempts to about six; the check
// gets its own, longer limit, and the UI says it can take a while.
let iam = aws_sdk_iam::config::Builder::from(cfg)
.retry_config(aws_config::retry::RetryConfig::adaptive().with_max_attempts(10))
.timeout_config(iam_check_timeouts())
.build();
SdkPermissionApi {
iam: aws_sdk_iam::Client::from_conf(iam),
@@ -147,6 +152,17 @@ impl SdkPermissionApi {
}
}
/// The whole of one simulation, retries and backoff included. Ten adaptive
/// attempts with backoff capped at 20 s fit in two minutes.
pub const IAM_CHECK_OPERATION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
fn iam_check_timeouts() -> aws_config::timeout::TimeoutConfig {
aws_config::timeout::TimeoutConfig::builder()
.operation_timeout(IAM_CHECK_OPERATION_TIMEOUT)
.operation_attempt_timeout(super::connection::ATTEMPT_TIMEOUT)
.build()
}
impl PermissionApi for SdkPermissionApi {
async fn resolve_principal(&self, principal: PrincipalArn) -> Result<String, AwsError> {
identity::resolve_principal(&self.iam, principal).await
@@ -628,3 +628,13 @@ fn no_probe_is_cloudformation() {
}
assert_eq!(Probe::for_action("cloudformation:DescribeStacks"), None);
}
#[test]
fn the_iam_check_gets_room_for_its_throttled_retries() {
let t = iam_check_timeouts();
assert_eq!(t.operation_timeout(), Some(IAM_CHECK_OPERATION_TIMEOUT));
assert!(IAM_CHECK_OPERATION_TIMEOUT > crate::aws::connection::OPERATION_TIMEOUT);
// Ten adaptive attempts, backoff capped at 20 s, fit inside it.
assert!(IAM_CHECK_OPERATION_TIMEOUT >= std::time::Duration::from_secs(9 * 20 / 2 + 20));
assert_eq!(t.operation_attempt_timeout(), Some(crate::aws::connection::ATTEMPT_TIMEOUT));
}
+221 -7
View File
@@ -35,10 +35,16 @@ pub fn policy_files(tier: Tier) -> &'static [(&'static str, &'static str)] {
include_str!("../../../../aws/policies/environment-admin-network.json"),
),
],
Tier::WorkspaceUser => &[(
"workspace-user.json",
include_str!("../../../../aws/policies/workspace-user.json"),
)],
Tier::WorkspaceUser => &[
(
"workspace-user.json",
include_str!("../../../../aws/policies/workspace-user.json"),
),
(
"workspace-user-tasks.json",
include_str!("../../../../aws/policies/workspace-user-tasks.json"),
),
],
}
}
@@ -240,6 +246,34 @@ const WORKSPACE_USER_CHECKS: &[Check] = &[
("ecs:CreateAction", Literal("RunTask")),
],
),
// `workspace-user-tasks.json`: a user registers and tags their own task
// definitions, and reads their own secrets. Retiring them is the admin's
// (R8): ECS authorizes `DeregisterTaskDefinition` against `*` only, with
// no tag condition, so it can't be confined to a user's own revisions.
// Residual risk the policy cannot close: the family carries the owner
// key, which IAM can't condition on, so any user may register a revision
// into another owner's family. The app's mitigation: it runs only the
// exact `family:revision` ARN its own register call returned, and when it
// looks up an existing revision it accepts only one tagged with the
// caller's own owner ID (never "latest of the family").
write(
"ecs:RegisterTaskDefinition",
PROBE_TASK_DEFINITION,
&[(OWNER_REQUEST_TAG, OwnerId)],
),
write(
"ecs:TagResource",
PROBE_TASK_DEFINITION,
&[
(OWNER_REQUEST_TAG, OwnerId),
("ecs:CreateAction", Literal("RegisterTaskDefinition")),
],
),
read(
"secretsmanager:GetSecretValue",
PROBE_SECRET,
&[(OWNER_RESOURCE_TAG, OwnerId)],
),
write(
"iam:PassRole",
PROBE_ROLE,
@@ -320,9 +354,11 @@ const WORKSPACE_USER_CHECKS: &[Check] = &[
(COMPONENT_RESOURCE_TAG, Literal("user-onboarding")),
],
),
// Authorized against the parent file system, not the new access point
// (verified live, phase 5).
write(
"elasticfilesystem:TagResource",
PROBE_ACCESS_POINT,
PROBE_FILE_SYSTEM,
&[
(OWNER_REQUEST_TAG, OwnerId),
(
@@ -904,6 +940,17 @@ mod tests {
("ecs:RunTask", "task-definition/", OWNER_REQUEST_TAG),
("ecs:RunTask", "task-definition/", OWNER_RESOURCE_TAG),
("ecs:TagResource", "task/", OWNER_REQUEST_TAG),
(
"ecs:RegisterTaskDefinition",
"task-definition/",
OWNER_REQUEST_TAG,
),
("ecs:TagResource", "task-definition/", OWNER_REQUEST_TAG),
(
"secretsmanager:GetSecretValue",
"secret:",
OWNER_RESOURCE_TAG,
),
("ecs:StopTask", "task/", OWNER_RESOURCE_TAG),
("ecs:ExecuteCommand", "task/", OWNER_RESOURCE_TAG),
("ssm:StartSession", "task/", OWNER_RESOURCE_TAG),
@@ -930,7 +977,7 @@ mod tests {
),
(
"elasticfilesystem:TagResource",
"access-point/",
"file-system/",
OWNER_REQUEST_TAG,
),
(
@@ -1066,6 +1113,170 @@ mod tests {
assert!(!allowed(Tier::WorkspaceUser, &other_cluster, ME, ME));
}
/// The three tag keys a workspace user may put on anything they create.
const OWN_TAG_KEYS: Context = &[
("aws:TagKeys", Literal("triple-c:owner")),
("aws:TagKeys", Literal("triple-c:project")),
("aws:TagKeys", Literal("triple-c:environment")),
];
fn ws_check(action: &str, resource_part: &str) -> &'static Check {
checks(Tier::WorkspaceUser)
.iter()
.find(|c| c.action == action && c.resource.contains(resource_part))
.unwrap_or_else(|| panic!("no workspace-user check for {action} on {resource_part}"))
}
#[test]
fn registering_a_task_definition_needs_the_owner_tag_and_only_the_three_keys() {
let reg = ws_check("ecs:RegisterTaskDefinition", "task-definition/");
const THREE_KEYS: Context = &[
(OWNER_REQUEST_TAG, OwnerId),
("aws:TagKeys", Literal("triple-c:owner")),
("aws:TagKeys", Literal("triple-c:project")),
("aws:TagKeys", Literal("triple-c:environment")),
];
const FOUR_KEYS: Context = &[
(OWNER_REQUEST_TAG, OwnerId),
("aws:TagKeys", Literal("triple-c:owner")),
("aws:TagKeys", Literal("triple-c:project")),
("aws:TagKeys", Literal("triple-c:environment")),
("aws:TagKeys", Literal("extra")),
];
let with_keys = |context: Context| Check { context, ..*reg };
assert!(allowed(Tier::WorkspaceUser, &with_keys(THREE_KEYS), ME, ME));
assert!(
!allowed(Tier::WorkspaceUser, &with_keys(FOUR_KEYS), ME, ME),
"an extra tag key must be refused"
);
let no_owner = Check {
context: OWN_TAG_KEYS,
..*reg
};
assert!(
!allowed(Tier::WorkspaceUser, &no_owner, ME, ME),
"no owner request tag"
);
let someone_elses = Check {
context: &[(OWNER_REQUEST_TAG, Literal(SOMEONE_ELSE))],
..*reg
};
assert!(!allowed(Tier::WorkspaceUser, &someone_elses, ME, ME));
// Only Triple-C's families.
let other_family = Check {
resource: "arn:aws:ecs:{region}:{account}:task-definition/production:1",
..*reg
};
assert!(!allowed(Tier::WorkspaceUser, &other_family, ME, ME));
}
#[test]
fn task_definitions_are_tagged_only_at_register_and_only_with_the_three_keys() {
let tag = ws_check("ecs:TagResource", "task-definition/");
assert!(allowed(Tier::WorkspaceUser, tag, ME, ME));
let retag = Check {
context: &[(OWNER_REQUEST_TAG, OwnerId)],
..*tag
};
assert!(!allowed(Tier::WorkspaceUser, &retag, ME, ME));
let other_create = Check {
context: &[
(OWNER_REQUEST_TAG, OwnerId),
("ecs:CreateAction", Literal("RunTask")),
],
..*tag
};
assert!(!allowed(Tier::WorkspaceUser, &other_create, ME, ME));
let extra_key = Check {
context: &[
(OWNER_REQUEST_TAG, OwnerId),
("ecs:CreateAction", Literal("RegisterTaskDefinition")),
("aws:TagKeys", Literal("triple-c:owner")),
("aws:TagKeys", Literal("triple-c:component")),
],
..*tag
};
assert!(
!allowed(Tier::WorkspaceUser, &extra_key, ME, ME),
"a task definition must not be tagged triple-c:component"
);
}
/// R8: the workspace tier retires no task definition, not even its own
/// (`DeregisterTaskDefinition` is authorized against `*` only).
#[test]
fn the_workspace_tier_never_retires_a_task_definition() {
let register = ws_check("ecs:RegisterTaskDefinition", "task-definition/");
for action in ["ecs:DeregisterTaskDefinition", "ecs:DeleteTaskDefinitions"] {
assert!(
!checks(Tier::WorkspaceUser).iter().any(|c| c.action == action),
"{action} is checked for the workspace tier"
);
for resource in ["*", register.resource] {
let own = Check {
action,
resource,
context: &[(OWNER_RESOURCE_TAG, OwnerId)],
..*register
};
assert!(!allowed(Tier::WorkspaceUser, &own, ME, ME), "{action} on {resource}");
}
}
}
/// RegisterTaskDefinition with a task or execution role also authorizes
/// `iam:PassRole` on each; `PassOwnTaskRoles` (owner-tagged, to ECS
/// tasks, `triple-c-*` roles) must cover both and nothing else.
#[test]
fn register_task_definition_can_pass_the_users_task_and_execution_roles() {
let pass = ws_check("iam:PassRole", "role/");
for role in [
"arn:aws:iam::{account}:role/triple-c-prod-0123456789ab-task",
"arn:aws:iam::{account}:role/triple-c-prod-0123456789ab-exec",
] {
let c = Check { resource: role, ..*pass };
assert!(allowed(Tier::WorkspaceUser, &c, ME, ME), "{role}");
assert!(!allowed(Tier::WorkspaceUser, &c, ME, SOMEONE_ELSE), "{role}");
}
}
#[test]
fn secrets_are_readable_only_by_their_owner_and_never_the_environments() {
let get = ws_check("secretsmanager:GetSecretValue", "secret:");
assert!(allowed(Tier::WorkspaceUser, get, ME, ME));
assert!(!allowed(Tier::WorkspaceUser, get, ME, SOMEONE_ELSE));
// Even tagged with the caller's owner ID, a component-tagged secret
// (the environment's) is off limits: the Deny holds on its own.
let environments = Check {
context: &[
(OWNER_RESOURCE_TAG, OwnerId),
(COMPONENT_RESOURCE_TAG, Literal("environment")),
],
..*get
};
assert!(!allowed(Tier::WorkspaceUser, &environments, ME, ME));
let component_only = Check {
context: &[(COMPONENT_RESOURCE_TAG, Literal("environment"))],
..*get
};
let req = Request {
check: &component_only,
caller: ME,
owner: ME,
};
let stmts = denies(Tier::WorkspaceUser);
assert!(
matching(&stmts, &req).iter().any(|s| conditions_hold(s, &req)),
"missing a Deny of GetSecretValue on component-tagged secrets"
);
// Not outside Triple-C's secrets.
let other = Check {
resource: "arn:aws:secretsmanager:{region}:{account}:secret:prod/db-AbCdEf",
..*get
};
assert!(!allowed(Tier::WorkspaceUser, &other, ME, ME));
}
#[test]
fn ecs_tag_resource_only_tags_at_run_task() {
let tag = checks(Tier::WorkspaceUser)
@@ -1617,7 +1828,10 @@ mod tests {
names(Tier::EnvironmentAdmin),
["environment-admin.json", "environment-admin-network.json"]
);
assert_eq!(names(Tier::WorkspaceUser), ["workspace-user.json"]);
assert_eq!(
names(Tier::WorkspaceUser),
["workspace-user.json", "workspace-user-tasks.json"]
);
}
/// D8: CloudFormation leaves the policies, the checks and the probes.
+463
View File
@@ -0,0 +1,463 @@
//! What the AWS host asks AWS around a task, besides running it
//! (`tasks.rs`) and preparing its resources (`workspace.rs`): the
//! environment's record, whether the caller is onboarded, the agent token of
//! a running task (P2), waiting for a new access point, and removing a
//! project's resources.
//!
//! Like the other `aws/` modules, the decisions are made by the functions
//! here over a small trait ([`RuntimeApi`]) so a fake exercises them; the SDK
//! calls are in [`SdkRuntimeApi`].
use std::future::Future;
use std::time::Duration;
use aws_config::SdkConfig;
use aws_sdk_secretsmanager::error::ProvideErrorMetadata;
use super::environments::{knowable, parse_environment_record, EnvironmentInfo, Knowable};
use super::error::{classify_sdk_error, AwsError};
use super::tasks::{find_project_task, TaskApi, STOP_REASON};
use super::tofu_modules::{
access_point_root, environment_cluster_name, environment_parameter_name, project_secret_name, task_family,
user_file_system_token, user_role_names,
};
use super::workspace::WorkspaceApi;
/// The secret key holding the agent token (Task 4's payload).
pub const AGENT_TOKEN_KEY: &str = "TRIPLEC_AGENT_TOKEN";
/// A project secret is at most 64 KiB; anything bigger is not ours.
const MAX_SECRET_READ: usize = 70_000;
fn other(message: impl Into<String>) -> AwsError {
AwsError::Other {
message: message.into(),
}
}
pub trait RuntimeApi: Send + Sync {
/// `ssm:GetParameter` of an environment's record; `None` when absent.
fn environment_record(
&self,
env: &str,
) -> impl Future<Output = Result<Option<String>, AwsError>> + Send;
/// `iam:GetRole`.
fn role_exists(&self, name: &str) -> impl Future<Output = Result<Knowable, AwsError>> + Send;
/// `secretsmanager:GetSecretValue`'s `SecretString`.
fn secret_string(&self, name: &str) -> impl Future<Output = Result<String, AwsError>> + Send;
/// The access point's `LifeCycleState`; `None` when it is gone.
fn access_point_state(
&self,
id: &str,
) -> impl Future<Output = Result<Option<String>, AwsError>> + Send;
/// Delete at once (`ForceDeleteWithoutRecovery`, ruling R10): a secret
/// left pending deletion would make the project's next start fail, and
/// the app rebuilds it from local data. A secret that does not exist is
/// success.
fn delete_secret(&self, name: &str) -> impl Future<Output = Result<(), AwsError>> + Send;
/// A missing access point is success.
fn delete_access_point(&self, id: &str) -> impl Future<Output = Result<(), AwsError>> + Send;
}
// ------------------------------------------------------------ environment
/// The environment's record, read with one `GetParameter` and validated.
pub async fn read_environment<R: RuntimeApi>(
rt: &R,
env: &str,
account: &str,
region: &str,
) -> Result<EnvironmentInfo, AwsError> {
let value = rt.environment_record(env).await?.ok_or_else(|| {
other(format!(
"The environment \"{env}\" was not found in {region}. It may have been removed; \
check Settings → Hosts."
))
})?;
parse_environment_record(env, &value, account, region).map_err(|e| {
other(format!(
"The record of environment \"{env}\" in {region} is not usable: {e}"
))
})
}
/// Whether the caller's task role exists in the environment: the onboarding
/// signal a workspace user can read. A denied lookup is not an answer, so
/// it is let through (RunTask will say what is wrong).
pub async fn check_onboarded<R: RuntimeApi>(
rt: &R,
env: &str,
owner_key: &str,
) -> Result<(), AwsError> {
let (task_role, _) = user_role_names(env, owner_key);
match rt.role_exists(&task_role).await? {
Knowable::No => Err(other(format!(
"You have not joined the environment \"{env}\" yet. Join it in Settings → Hosts \
(or ask an administrator to onboard you), then start the project again."
))),
Knowable::Yes | Knowable::Unknown => Ok(()),
}
}
/// The agent token in a project secret's JSON. The error never echoes the
/// secret.
pub fn agent_token_from_secret(json: &str) -> Result<String, String> {
if json.len() > MAX_SECRET_READ {
return Err("The project secret is larger than a project secret can be".into());
}
let v: serde_json::Value = serde_json::from_str(json)
.map_err(|_| "The project secret is not a JSON object".to_string())?;
v.get(AGENT_TOKEN_KEY)
.and_then(|t| t.as_str())
.filter(|t| !t.is_empty() && t.bytes().all(|b| b.is_ascii_graphic()))
.map(str::to_string)
.ok_or_else(|| "The project secret holds no agent token".to_string())
}
/// The token a running task of this project started with (P2: the caller
/// may read their own secret; `prepare_workspace` wrote it before RunTask).
pub async fn read_agent_token<R: RuntimeApi>(
rt: &R,
env: &str,
owner_key: &str,
project_id: &str,
) -> Result<String, AwsError> {
let name = project_secret_name(env, owner_key, project_id);
let json = rt.secret_string(&name).await?;
agent_token_from_secret(&json).map_err(other)
}
/// After a start this call ran is up and its agent answered with `ours`:
/// make sure the secret still holds `ours`. A start that lost the RunTask
/// race (another machine, the same moment) rotated the token in the secret
/// before it found this task, and every later attach would read a token the
/// task never saw. Returns whether the secret had to be put back.
pub async fn ensure_agent_token<W: WorkspaceApi, R: RuntimeApi>(
work: &W,
rt: &R,
env: &EnvironmentInfo,
owner_user_id: &str,
owner_key: &str,
project_id: &str,
ours: &str,
) -> Result<bool, AwsError> {
let name = project_secret_name(&env.name, owner_key, project_id);
let json = rt.secret_string(&name).await?;
if agent_token_from_secret(&json).ok().as_deref() == Some(ours) {
return Ok(false);
}
let mut v: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&json)
.map_err(|_| other("The project secret is not a JSON object"))?;
v.insert(AGENT_TOKEN_KEY.to_string(), serde_json::Value::String(ours.to_string()));
let repaired = serde_json::to_string(&v).map_err(|e| other(e.to_string()))?;
let tags = super::workspace::workspace_tags(owner_user_id, project_id, &env.name);
work.put_project_secret(&name, &env.kms_key_arn, &repaired, &tags).await?;
Ok(true)
}
/// How long a fresh access point may take to become `available`.
#[derive(Debug, Clone, Copy)]
pub struct PollTiming {
pub interval: Duration,
pub timeout: Duration,
}
impl Default for PollTiming {
fn default() -> Self {
PollTiming {
interval: Duration::from_secs(2),
timeout: Duration::from_secs(90),
}
}
}
/// Wait until the access point is `available` (a task mounting one that is
/// still `creating` fails to start).
pub async fn wait_access_point<R: RuntimeApi>(
rt: &R,
id: &str,
timing: PollTiming,
) -> Result<(), AwsError> {
let deadline = tokio::time::Instant::now() + timing.timeout;
loop {
match rt.access_point_state(id).await?.as_deref() {
Some("available") => return Ok(()),
Some("creating") | Some("updating") => {}
Some(s) => {
return Err(other(format!(
"The project's EFS access point {id} is {s}; start the project again"
)))
}
None => {
return Err(other(format!(
"The project's EFS access point {id} disappeared; start the project again"
)))
}
}
if tokio::time::Instant::now() + timing.interval > deadline {
return Err(other(format!(
"The project's EFS access point {id} did not become available in time; \
start the project again in a minute"
)));
}
tokio::time::sleep(timing.interval).await;
}
}
// ------------------------------------------------------------------ ARNs
/// The cluster *name* of `arn:...:task/<cluster>/<id>` (ECS accepts a name
/// wherever it takes a cluster).
pub fn cluster_of_task(task_arn: &str) -> Option<&str> {
let (_, rest) = task_arn.split_once(":task/")?;
let (cluster, id) = rest.split_once('/')?;
(task_arn.starts_with("arn:") && !cluster.is_empty() && !id.is_empty() && !id.contains('/'))
.then_some(cluster)
}
/// The cluster ARN of a task ARN (same partition, region and account).
pub fn cluster_arn_of_task(task_arn: &str) -> Option<String> {
let cluster = cluster_of_task(task_arn)?;
let (prefix, _) = task_arn.split_once(":task/")?;
Some(format!("{prefix}:cluster/{cluster}"))
}
// ---------------------------------------------------------------- removal
/// What removing a project's AWS resources needs to know.
pub struct RemoveRequest<'a> {
pub env: &'a str,
pub region: &'a str,
pub owner_user_id: &'a str,
pub owner_key: &'a str,
pub project_id: &'a str,
/// The task ARN the store has, if any (stopped too, in case the listing
/// missed it).
pub stored_task_arn: Option<&'a str>,
pub stored_access_point_id: Option<&'a str>,
/// Delete the EFS access point (ruling R9). The files stay on the
/// user's own file system (only their task role can read it) until
/// offboarding destroys it; a later start of the same project gets a new
/// access point onto the same directory.
pub discard_data: bool,
}
/// Stop the project's task, delete its secret (no recovery window, R10) and,
/// with `discard_data`, delete its access point (not the files, R9). Task definition revisions
/// are left registered (R8). A task that can't be stopped stops the removal (nothing
/// billed may be left running); the rest is attempted in full and every
/// failure reported.
pub async fn remove_workspace_resources<T: TaskApi, W: WorkspaceApi, R: RuntimeApi>(
tasks: &T,
work: &W,
rt: &R,
req: &RemoveRequest<'_>,
) -> Result<(), AwsError> {
let cluster = environment_cluster_name(req.env);
let family = task_family(req.env, req.owner_key, req.project_id);
// 1. The task.
let live =
find_project_task(tasks, &cluster, &family, req.owner_user_id, req.project_id).await?;
let mut to_stop: Vec<String> = live.into_iter().map(|t| t.arn).collect();
if let Some(arn) = req.stored_task_arn {
if cluster_of_task(arn) == Some(cluster.as_str()) && !to_stop.iter().any(|a| a == arn) {
to_stop.push(arn.to_string());
}
}
for arn in &to_stop {
tasks.stop_task(&cluster, arn, STOP_REASON).await?;
}
let mut failures: Vec<String> = Vec::new();
// 2. Task definition revisions are left ACTIVE (ruling R8): ECS
// authorizes `DeregisterTaskDefinition` against `*` only, with no tag
// condition, so the workspace tier can't retire just its own. They are
// inert (no secret values, only the secret's ARN) and free, and
// `RunOwnTasks` still requires the owner tag, so nobody else can run
// them. An admin can deregister them (`aws/README.md`).
log::info!(
"Project {}: its task definition revisions ({family}:*) are left registered; an \
administrator can deregister them",
req.project_id
);
// 3. The secret.
let secret = project_secret_name(req.env, req.owner_key, req.project_id);
if let Err(e) = rt.delete_secret(&secret).await {
failures.push(format!("secret {secret}: {e}"));
}
// 4. The access point, only when asked.
if req.discard_data {
let mut ids: Vec<String> = req.stored_access_point_id.map(String::from).into_iter().collect();
let token = user_file_system_token(req.env, req.owner_key);
match work.find_file_system(&token).await {
Ok(Some(fs)) if fs.owner.as_deref() == Some(req.owner_user_id) => {
let root = access_point_root(req.owner_key, req.project_id);
match work.access_points(&fs.id).await {
Ok(points) => ids.extend(
points
.into_iter()
.filter(|a| {
a.file_system_id == fs.id
&& a.root_path.as_deref() == Some(root.as_str())
&& a.owner.as_deref() == Some(req.owner_user_id)
&& a.project.as_deref() == Some(req.project_id)
})
.map(|a| a.id),
),
Err(e) => failures.push(format!("access points: {e}")),
}
}
Ok(_) => {}
Err(e) => failures.push(format!("file system: {e}")),
}
ids.sort();
ids.dedup();
for id in ids {
if let Err(e) = rt.delete_access_point(&id).await {
failures.push(format!("access point {id}: {e}"));
}
}
}
if failures.is_empty() {
Ok(())
} else {
Err(other(format!(
"Some of the project's AWS resources in {} could not be removed: {}",
req.region,
failures.join("; ")
)))
}
}
// ---------------------------------------------------------------- real API
pub struct SdkRuntimeApi {
ssm: aws_sdk_ssm::Client,
iam: aws_sdk_iam::Client,
secrets: aws_sdk_secretsmanager::Client,
efs: aws_sdk_efs::Client,
}
impl SdkRuntimeApi {
pub fn new(cfg: &SdkConfig) -> Self {
SdkRuntimeApi {
ssm: aws_sdk_ssm::Client::new(cfg),
iam: aws_sdk_iam::Client::new(cfg),
secrets: aws_sdk_secretsmanager::Client::new(cfg),
efs: aws_sdk_efs::Client::new(cfg),
}
}
}
impl RuntimeApi for SdkRuntimeApi {
async fn environment_record(&self, env: &str) -> Result<Option<String>, AwsError> {
const ACTION: &str = "ssm:GetParameter";
match self
.ssm
.get_parameter()
.name(environment_parameter_name(env))
.with_decryption(false)
.send()
.await
{
Ok(out) => Ok(out.parameter().and_then(|p| p.value()).map(str::to_string)),
Err(e)
if e.as_service_error()
.is_some_and(|s| s.is_parameter_not_found()) =>
{
Ok(None)
}
Err(e) => Err(classify_sdk_error(ACTION, &e)),
}
}
async fn role_exists(&self, name: &str) -> Result<Knowable, AwsError> {
let res = self.iam.get_role().role_name(name).send().await;
knowable("iam:GetRole", res)
}
async fn secret_string(&self, name: &str) -> Result<String, AwsError> {
const ACTION: &str = "secretsmanager:GetSecretValue";
let out = self
.secrets
.get_secret_value()
.secret_id(name)
.send()
.await
.map_err(|e| classify_sdk_error(ACTION, &e))?;
out.secret_string()
.map(str::to_string)
.ok_or_else(|| other(format!("{ACTION} returned no SecretString")))
}
async fn access_point_state(&self, id: &str) -> Result<Option<String>, AwsError> {
const ACTION: &str = "elasticfilesystem:DescribeAccessPoints";
match self.efs.describe_access_points().access_point_id(id).send().await {
Ok(out) => Ok(out
.access_points()
.iter()
.find(|a| a.access_point_id() == Some(id))
.and_then(|a| a.life_cycle_state())
.map(|s| s.as_str().to_string())),
Err(e)
if e.as_service_error()
.is_some_and(|s| s.is_access_point_not_found()) =>
{
Ok(None)
}
Err(e) => Err(classify_sdk_error(ACTION, &e)),
}
}
async fn delete_secret(&self, name: &str) -> Result<(), AwsError> {
const ACTION: &str = "secretsmanager:DeleteSecret";
match self
.secrets
.delete_secret()
.secret_id(name)
.force_delete_without_recovery(true)
.send()
.await
{
Ok(_) => Ok(()),
Err(e)
if e.as_service_error()
.is_some_and(|s| s.is_resource_not_found_exception()) =>
{
Ok(())
}
// Scheduled by an older version of the app and AWS refused the
// forced delete: nothing more this tier may do (no RestoreSecret).
Err(e)
if e.as_service_error().is_some_and(|s| {
s.is_invalid_request_exception()
&& s.message().is_some_and(|m| m.contains("scheduled for deletion"))
}) =>
{
Ok(())
}
Err(e) => Err(classify_sdk_error(ACTION, &e)),
}
}
async fn delete_access_point(&self, id: &str) -> Result<(), AwsError> {
const ACTION: &str = "elasticfilesystem:DeleteAccessPoint";
match self.efs.delete_access_point().access_point_id(id).send().await {
Ok(_) => Ok(()),
Err(e)
if e.as_service_error()
.is_some_and(|s| s.is_access_point_not_found()) =>
{
Ok(())
}
Err(e) => Err(classify_sdk_error(ACTION, &e)),
}
}
}
#[cfg(test)]
mod tests;
+331
View File
@@ -0,0 +1,331 @@
use std::sync::Mutex;
use aws_sdk_ecs::operation::register_task_definition::RegisterTaskDefinitionInput;
use aws_sdk_ecs::operation::run_task::RunTaskInput;
use super::*;
use crate::aws::tasks::TaskInfo;
use crate::aws::tofu_modules::owner_key;
use crate::aws::workspace::{AccessPointRef, FileSystemRef, TaskDefinitionRef};
const REGION: &str = "eu-west-1";
const ACCOUNT: &str = "111122223333";
const USER: &str = "AROAEXAMPLEID:alice@example.com";
const PROJECT: &str = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0";
fn ok() -> String {
owner_key(REGION, USER)
}
fn family() -> String {
task_family("dev", &ok(), PROJECT)
}
fn task_arn(id: &str) -> String {
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task/triple-c-dev/{id}")
}
#[derive(Default)]
struct Fake {
calls: Mutex<Vec<String>>,
record: Option<String>,
role: Option<Knowable>,
secret: Option<String>,
ap_states: Mutex<Vec<Option<String>>>,
live_tasks: Vec<TaskInfo>,
revisions: Vec<TaskDefinitionRef>,
access_points: Vec<AccessPointRef>,
fail_secret_delete: bool,
}
impl Fake {
fn log(&self, s: String) {
self.calls.lock().unwrap().push(s);
}
fn calls(&self) -> Vec<String> {
self.calls.lock().unwrap().clone()
}
}
impl RuntimeApi for Fake {
async fn environment_record(&self, env: &str) -> Result<Option<String>, AwsError> {
self.log(format!("record {env}"));
Ok(self.record.clone())
}
async fn role_exists(&self, name: &str) -> Result<Knowable, AwsError> {
self.log(format!("role {name}"));
Ok(self.role.clone().unwrap_or(Knowable::Yes))
}
async fn secret_string(&self, name: &str) -> Result<String, AwsError> {
self.log(format!("secret {name}"));
self.secret.clone().ok_or_else(|| other("no secret"))
}
async fn access_point_state(&self, id: &str) -> Result<Option<String>, AwsError> {
self.log(format!("ap {id}"));
let mut s = self.ap_states.lock().unwrap();
Ok(if s.len() > 1 { s.remove(0) } else { s.first().cloned().flatten() })
}
async fn delete_secret(&self, name: &str) -> Result<(), AwsError> {
self.log(format!("delete-secret {name}"));
if self.fail_secret_delete {
return Err(other("denied"));
}
Ok(())
}
async fn delete_access_point(&self, id: &str) -> Result<(), AwsError> {
self.log(format!("delete-ap {id}"));
Ok(())
}
}
impl TaskApi for Fake {
async fn run_task(&self, _req: RunTaskInput) -> Result<TaskInfo, AwsError> {
unreachable!("removal never runs a task")
}
async fn describe(&self, _c: &str, arns: &[String]) -> Result<Vec<TaskInfo>, AwsError> {
Ok(self.live_tasks.iter().filter(|t| arns.contains(&t.arn)).cloned().collect())
}
async fn list_project_tasks(&self, _c: &str, _f: &str) -> Result<Vec<String>, AwsError> {
Ok(self.live_tasks.iter().map(|t| t.arn.clone()).collect())
}
async fn stop_task(&self, cluster: &str, arn: &str, reason: &str) -> Result<(), AwsError> {
self.log(format!("stop {cluster} {arn} {reason}"));
Ok(())
}
async fn log_tail(&self, _g: &str, _s: &str, _l: i32) -> Result<Vec<String>, AwsError> {
Ok(Vec::new())
}
}
impl WorkspaceApi for Fake {
async fn find_file_system(&self, _token: &str) -> Result<Option<FileSystemRef>, AwsError> {
Ok(Some(FileSystemRef { id: "fs-1".into(), owner: Some(USER.into()) }))
}
async fn access_points(&self, _fs: &str) -> Result<Vec<AccessPointRef>, AwsError> {
Ok(self.access_points.clone())
}
async fn create_access_point(
&self,
_fs: &str,
_root: &str,
_tags: &[(String, String)],
) -> Result<String, AwsError> {
unreachable!()
}
async fn put_project_secret(
&self,
_n: &str,
_k: &str,
_j: &str,
_t: &[(String, String)],
) -> Result<String, AwsError> {
unreachable!()
}
async fn task_definition_revisions(&self, _f: &str) -> Result<Vec<String>, AwsError> {
Ok(self.revisions.iter().map(|r| r.arn.clone()).collect())
}
async fn describe_task_definition(
&self,
arn: &str,
) -> Result<Option<TaskDefinitionRef>, AwsError> {
Ok(self.revisions.iter().find(|r| r.arn == arn).cloned())
}
async fn register_task_definition(
&self,
_req: RegisterTaskDefinitionInput,
) -> Result<String, AwsError> {
unreachable!()
}
}
fn record() -> String {
serde_json::json!({
"schema": 1, "name": "dev", "template_version": 1,
"cluster_arn": format!("arn:aws:ecs:{REGION}:{ACCOUNT}:cluster/triple-c-dev"),
"security_group_id": "sg-0123456789abcdef0",
"subnet_ids": ["subnet-0a", "subnet-0b"],
"assign_public_ip": true,
"kms_key_arn": format!("arn:aws:kms:{REGION}:{ACCOUNT}:key/1234-abcd"),
"log_group": "/triple-c/dev", "network_mode": "public", "tenancy": "strict"
})
.to_string()
}
#[tokio::test]
async fn the_environment_is_read_with_one_lookup_and_validated() {
let fake = Fake { record: Some(record()), ..Default::default() };
let env = read_environment(&fake, "dev", ACCOUNT, REGION).await.unwrap();
assert_eq!(env.log_group, "/triple-c/dev");
assert_eq!(fake.calls(), vec!["record dev"]);
let missing = Fake::default();
let e = read_environment(&missing, "dev", ACCOUNT, REGION).await.unwrap_err();
assert!(e.to_string().contains("was not found"), "{e}");
// A record from another account is refused, by field name only.
let foreign = Fake { record: Some(record()), ..Default::default() };
let e = read_environment(&foreign, "dev", "999999999999", REGION).await.unwrap_err();
assert!(e.to_string().contains("cluster_arn"), "{e}");
}
#[tokio::test]
async fn a_missing_task_role_means_not_joined_and_a_denied_lookup_lets_the_start_try() {
let no = Fake { role: Some(Knowable::No), ..Default::default() };
let e = check_onboarded(&no, "dev", &ok()).await.unwrap_err();
assert!(e.to_string().contains("not joined"), "{e}");
assert_eq!(no.calls(), vec![format!("role triple-c-dev-{}-task", ok())]);
let unknown = Fake { role: Some(Knowable::Unknown), ..Default::default() };
assert!(check_onboarded(&unknown, "dev", &ok()).await.is_ok());
}
#[test]
fn the_agent_token_is_read_from_the_secret_without_echoing_it() {
let json = r#"{"TRIPLEC_AGENT_TOKEN":"abc-DEF_123","OTHER":"SENTINEL-VALUE-7f3a"}"#;
assert_eq!(agent_token_from_secret(json).unwrap(), "abc-DEF_123");
for bad in [
r#"{"OTHER":"SENTINEL-VALUE-7f3a"}"#,
r#"{"TRIPLEC_AGENT_TOKEN":""}"#,
r#"{"TRIPLEC_AGENT_TOKEN":"has space"}"#,
"SENTINEL-VALUE-7f3a",
] {
let e = agent_token_from_secret(bad).unwrap_err();
assert!(!e.contains("SENTINEL") && !e.contains("space"), "{e}");
}
}
#[tokio::test]
async fn the_token_comes_from_the_projects_own_secret() {
let fake = Fake {
secret: Some(r#"{"TRIPLEC_AGENT_TOKEN":"tok"}"#.into()),
..Default::default()
};
assert_eq!(read_agent_token(&fake, "dev", &ok(), PROJECT).await.unwrap(), "tok");
assert_eq!(fake.calls(), vec![format!("secret triple-c/dev/{}/{PROJECT}", ok())]);
}
#[tokio::test(start_paused = true)]
async fn a_new_access_point_is_waited_for_until_available() {
let fake = Fake {
ap_states: Mutex::new(vec![Some("creating".into()), Some("creating".into()), Some("available".into())]),
..Default::default()
};
wait_access_point(&fake, "fsap-1", PollTiming::default()).await.unwrap();
assert_eq!(fake.calls().len(), 3);
let stuck = Fake { ap_states: Mutex::new(vec![Some("creating".into())]), ..Default::default() };
let e = wait_access_point(&stuck, "fsap-1", PollTiming::default()).await.unwrap_err();
assert!(e.to_string().contains("did not become available"), "{e}");
let gone = Fake { ap_states: Mutex::new(vec![Some("deleting".into())]), ..Default::default() };
assert!(wait_access_point(&gone, "fsap-1", PollTiming::default()).await.is_err());
}
#[test]
fn task_arns_name_their_cluster() {
let arn = task_arn("abc123");
assert_eq!(cluster_of_task(&arn), Some("triple-c-dev"));
assert_eq!(
cluster_arn_of_task(&arn).as_deref(),
Some(format!("arn:aws:ecs:{REGION}:{ACCOUNT}:cluster/triple-c-dev").as_str())
);
assert_eq!(cluster_of_task("arn:aws:ecs:r:a:task/abc"), None, "old format, no cluster");
assert_eq!(cluster_of_task("task/triple-c-dev/abc"), None);
assert_eq!(cluster_of_task("arn:aws:ecs:r:a:task/c/a/b"), None);
}
fn live(id: &str) -> TaskInfo {
TaskInfo {
arn: task_arn(id),
last_status: "RUNNING".into(),
desired_status: "RUNNING".into(),
health: None,
stop_code: None,
stopped_reason: None,
task_definition_arn: format!(
"arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{}:2",
family()
),
runtime_id: None,
exec_agent_running: false,
exit_code: None,
owner: Some(USER.into()),
project: Some(PROJECT.into()),
}
}
fn rev(n: u32, owner: &str) -> TaskDefinitionRef {
TaskDefinitionRef {
arn: format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{}:{n}", family()),
family: family(),
owner: Some(owner.into()),
project: Some(PROJECT.into()),
fingerprint: None,
}
}
#[tokio::test]
async fn removal_stops_the_task_leaves_the_revisions_and_schedules_the_secret() {
let fake = Fake {
live_tasks: vec![live("t1")],
revisions: vec![rev(2, USER), rev(3, "AROAOTHER:mallory"), rev(1, USER)],
access_points: vec![AccessPointRef {
id: "fsap-found".into(),
file_system_id: "fs-1".into(),
root_path: Some(access_point_root(&ok(), PROJECT)),
owner: Some(USER.into()),
project: Some(PROJECT.into()),
state: Some("available".into()),
}],
..Default::default()
};
let key = ok();
let t0 = task_arn("t0");
let mut r = RemoveRequest {
env: "dev",
region: REGION,
owner_user_id: USER,
owner_key: &key,
project_id: PROJECT,
stored_task_arn: Some(&t0),
stored_access_point_id: Some("fsap-stored"),
discard_data: false,
};
remove_workspace_resources(&fake, &fake, &fake, &r).await.unwrap();
let calls = fake.calls();
let secret = project_secret_name("dev", &ok(), PROJECT);
assert_eq!(
calls,
vec![
format!("stop triple-c-dev {} {STOP_REASON}", task_arn("t1")),
format!("stop triple-c-dev {} {STOP_REASON}", task_arn("t0")),
format!("delete-secret {secret}"),
],
"no task definition is touched (R8) and the access point is kept"
);
let keep = Fake { access_points: fake.access_points.clone(), ..Default::default() };
r.discard_data = true;
remove_workspace_resources(&keep, &keep, &keep, &r).await.unwrap();
let calls = keep.calls();
assert!(calls.contains(&"delete-ap fsap-found".to_string()), "{calls:?}");
assert!(calls.contains(&"delete-ap fsap-stored".to_string()), "{calls:?}");
}
#[tokio::test]
async fn a_failed_step_is_reported_but_the_rest_still_runs() {
let fake = Fake { fail_secret_delete: true, ..Default::default() };
let key = ok();
let r = RemoveRequest {
env: "dev",
region: REGION,
owner_user_id: USER,
owner_key: &key,
project_id: PROJECT,
stored_task_arn: None,
stored_access_point_id: Some("fsap-1"),
discard_data: true,
};
let e = remove_workspace_resources(&fake, &fake, &fake, &r).await.unwrap_err();
assert!(e.to_string().contains("secret"), "{e}");
assert!(fake.calls().contains(&"delete-ap fsap-1".to_string()));
}
+695
View File
@@ -0,0 +1,695 @@
//! A project's ECS task: find the one already running, or run one; wait
//! until it is ready; stop it; and read why it stopped.
//!
//! **A task is trusted by its tags, not its family.** Family names are built
//! from a 12-character id prefix and any workspace user may register into any
//! `triple-c-*` family, so a task listed under the project's family is reused
//! only when DescribeTasks shows the caller's own `triple-c:owner` (which only
//! the caller can set, at RunTask) and this project's `triple-c:project`.
//!
//! **RunTask names an exact revision.** Never a bare family: "the latest
//! revision" of a family is whatever anyone registered last.
//!
//! **A quota refusal is final.** Fargate's vCPU limit (and its kin) surface as
//! [`AwsError::QuotaExceeded`] with a message saying what to do; nothing here
//! retries a RunTask, and the SDK's own retries are made idempotent by a
//! client token.
use std::future::Future;
use std::time::Duration;
use aws_config::SdkConfig;
use aws_sdk_ecs::operation::run_task::RunTaskInput;
use aws_sdk_ecs::types::{
AssignPublicIp, AwsVpcConfiguration, CapacityProviderStrategyItem, DesiredStatus, LaunchType,
ManagedAgentName, NetworkConfiguration, Tag, Task, TaskField,
};
use super::environments::EnvironmentInfo;
use super::error::{classify_sdk_error, AwsError};
pub use super::tofu_modules::task_log_stream;
use super::workspace::{workspace_tags, CONTAINER_NAME, TAG_OWNER, TAG_PROJECT};
/// The `reason` StopTask records when the app stops a task.
pub const STOP_REASON: &str = "Stopped from Triple-C";
/// Log lines shown when a task stops before it is ready.
pub const LOG_TAIL_LINES: i32 = 50;
const SPOT_PROVIDER: &str = "FARGATE_SPOT";
/// DescribeTasks takes at most 100 tasks per call.
const DESCRIBE_BATCH: usize = 100;
/// ListTasks pages read per status; a project has one task, so this is slack.
const MAX_LIST_PAGES: usize = 5;
fn other(message: impl Into<String>) -> AwsError {
AwsError::Other {
message: message.into(),
}
}
/// What the app needs to know about a task.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskInfo {
pub arn: String,
/// `PROVISIONING`, `PENDING`, `ACTIVATING`, `RUNNING`, `DEACTIVATING`,
/// `STOPPING`, `DEPROVISIONING`, `STOPPED`.
pub last_status: String,
pub desired_status: String,
/// `HEALTHY`, `UNHEALTHY`, `UNKNOWN`.
pub health: Option<String>,
/// ECS `stopCode` (`EssentialContainerExited`, `SpotInterruption`, ...).
pub stop_code: Option<String>,
pub stopped_reason: Option<String>,
pub task_definition_arn: String,
/// The `workspace` container's runtime id (needed for an SSM target).
pub runtime_id: Option<String>,
/// The `workspace` container's ExecuteCommandAgent is RUNNING.
pub exec_agent_running: bool,
/// The `workspace` container's exit code, once it has one.
pub exit_code: Option<i32>,
/// Its `triple-c:owner` / `triple-c:project` tags (DescribeTasks with
/// TAGS; RunTask's answer carries the tags it was given).
pub owner: Option<String>,
pub project: Option<String>,
}
impl TaskInfo {
fn is_stopping(&self) -> bool {
self.last_status == "STOPPED" || self.desired_status == "STOPPED"
}
/// On its way up or up, and meant to stay that way.
fn is_live(&self) -> bool {
self.desired_status == "RUNNING"
&& matches!(
self.last_status.as_str(),
"PROVISIONING" | "PENDING" | "ACTIVATING" | "RUNNING"
)
}
fn is_ready(&self) -> bool {
self.last_status == "RUNNING" && self.exec_agent_running && self.runtime_id.is_some()
}
}
fn tag_value(tags: &[Tag], key: &str) -> Option<String> {
tags.iter()
.find(|t| t.key() == Some(key))
.and_then(|t| t.value())
.map(str::to_string)
}
/// An SDK task as a [`TaskInfo`]. The container facts come from the
/// `workspace` container only.
pub(crate) fn task_info(t: &Task) -> TaskInfo {
let workspace = t
.containers()
.iter()
.find(|c| c.name() == Some(CONTAINER_NAME));
TaskInfo {
arn: t.task_arn().unwrap_or_default().to_string(),
last_status: t.last_status().unwrap_or_default().to_string(),
desired_status: t.desired_status().unwrap_or_default().to_string(),
health: t.health_status().map(|h| h.as_str().to_string()),
stop_code: t.stop_code().map(|c| c.as_str().to_string()),
stopped_reason: t.stopped_reason().map(str::to_string),
task_definition_arn: t.task_definition_arn().unwrap_or_default().to_string(),
runtime_id: workspace.and_then(|c| c.runtime_id()).map(str::to_string),
exec_agent_running: workspace.is_some_and(|c| {
c.managed_agents().iter().any(|a| {
a.name() == Some(&ManagedAgentName::ExecuteCommandAgent)
&& a.last_status() == Some("RUNNING")
})
}),
exit_code: workspace.and_then(|c| c.exit_code()),
owner: tag_value(t.tags(), TAG_OWNER),
project: tag_value(t.tags(), TAG_PROJECT),
}
}
/// What running and watching tasks asks AWS. Like `WorkspaceApi`, each
/// method returns a `Send` future and an impl may write them as `async fn`;
/// the decisions are made by the functions below, so a fake exercises them.
pub trait TaskApi: Send + Sync {
/// RunTask. A quota refusal is [`AwsError::QuotaExceeded`].
fn run_task(
&self,
req: RunTaskInput,
) -> impl Future<Output = Result<TaskInfo, AwsError>> + Send;
/// DescribeTasks (with tags). Tasks ECS no longer knows are left out.
fn describe(
&self,
cluster: &str,
arns: &[String],
) -> impl Future<Output = Result<Vec<TaskInfo>, AwsError>> + Send;
/// ListTasks of exactly `family`, desired status RUNNING and PENDING.
fn list_project_tasks(
&self,
cluster: &str,
family: &str,
) -> impl Future<Output = Result<Vec<String>, AwsError>> + Send;
fn stop_task(
&self,
cluster: &str,
arn: &str,
reason: &str,
) -> impl Future<Output = Result<(), AwsError>> + Send;
/// The last `limit` lines of a log stream, oldest first. A stream (or
/// group) that does not exist is no lines, not an error.
fn log_tail(
&self,
group: &str,
stream: &str,
limit: i32,
) -> impl Future<Output = Result<Vec<String>, AwsError>> + Send;
}
// ------------------------------------------------------------- run request
/// The RunTask request: the exact revision, on the environment's cluster and
/// network, with ECS Exec on and exactly the `tags` given (no propagation,
/// no ECS-managed tags, no overrides — P1). Spot runs on the `FARGATE_SPOT`
/// capacity provider with no launch type (the two are exclusive).
pub fn run_task_request(
env: &EnvironmentInfo,
task_def_arn: &str,
spot: bool,
tags: &[(String, String)],
) -> RunTaskInput {
const BUILT: &str = "every required field is set";
let mut req = RunTaskInput::builder()
.cluster(&env.cluster_arn)
.task_definition(task_def_arn)
.count(1)
.enable_execute_command(true)
.network_configuration(
NetworkConfiguration::builder()
.awsvpc_configuration(
AwsVpcConfiguration::builder()
.set_subnets(Some(env.subnet_ids.clone()))
.security_groups(&env.security_group_id)
.assign_public_ip(if env.assign_public_ip {
AssignPublicIp::Enabled
} else {
AssignPublicIp::Disabled
})
.build()
.expect(BUILT),
)
.build(),
)
.set_tags(Some(
tags.iter()
.map(|(k, v)| Tag::builder().key(k).value(v).build())
.collect(),
))
// SDK retries of this call must not start a second task.
.client_token(uuid::Uuid::new_v4().to_string());
req = if spot {
req.capacity_provider_strategy(
CapacityProviderStrategyItem::builder()
.capacity_provider(SPOT_PROVIDER)
.weight(1)
.build()
.expect(BUILT),
)
} else {
req.launch_type(LaunchType::Fargate)
};
req.build().expect(BUILT)
}
/// The family of `arn:...:task-definition/<family>:<revision>`, when the
/// revision is a number. `None` for a bare family or anything else.
pub fn revision_family(arn: &str) -> Option<&str> {
if !arn.starts_with("arn:") {
return None;
}
let (_, rest) = arn.rsplit_once(":task-definition/")?;
let (family, rev) = rest.rsplit_once(':')?;
(!family.is_empty()
&& !family.contains('/')
&& !rev.is_empty()
&& rev.bytes().all(|c| c.is_ascii_digit()))
.then_some(family)
}
// ------------------------------------------------------------- find or run
/// The project's live task (provisioning through running, not being
/// stopped), owned by the caller and tagged with this project. A RUNNING
/// one is preferred.
pub async fn find_project_task<A: TaskApi>(
api: &A,
cluster: &str,
family: &str,
owner_user_id: &str,
project_id: &str,
) -> Result<Option<TaskInfo>, AwsError> {
let arns = api.list_project_tasks(cluster, family).await?;
if arns.is_empty() {
return Ok(None);
}
let mut mine: Vec<TaskInfo> = Vec::new();
for chunk in arns.chunks(DESCRIBE_BATCH) {
mine.extend(api.describe(cluster, chunk).await?.into_iter().filter(|t| {
t.owner.as_deref() == Some(owner_user_id)
&& t.project.as_deref() == Some(project_id)
&& revision_family(&t.task_definition_arn) == Some(family)
&& t.is_live()
}));
}
mine.sort_by_key(|t| t.last_status != "RUNNING");
Ok(mine.into_iter().next())
}
/// What [`find_or_run`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskStart {
pub task: TaskInfo,
/// An existing task was found (nothing was run). Its agent token is the
/// one it started with — see [`find_project_task`] in the report for
/// why a caller should look before rotating the token.
pub reused: bool,
}
/// The project's live task if there is one (Review Focus 2: never a second
/// task for a project), else RunTask with the exact `task_def_arn`.
pub async fn find_or_run<A: TaskApi>(
api: &A,
env: &EnvironmentInfo,
owner_user_id: &str,
project_id: &str,
task_def_arn: &str,
spot: bool,
) -> Result<TaskStart, AwsError> {
let family = revision_family(task_def_arn).ok_or_else(|| {
other(format!(
"\"{task_def_arn}\" is not an exact task definition revision"
))
})?;
if !family.starts_with("triple-c-") {
return Err(other(format!(
"\"{task_def_arn}\" is not a Triple-C task definition"
)));
}
if let Some(task) =
find_project_task(api, &env.cluster_arn, family, owner_user_id, project_id).await?
{
return Ok(TaskStart { task, reused: true });
}
let tags = workspace_tags(owner_user_id, project_id, &env.name);
let task = api
.run_task(run_task_request(env, task_def_arn, spot, &tags))
.await?;
Ok(TaskStart {
task,
reused: false,
})
}
// ------------------------------------------------------------------ quotas
/// Whether an AWS message says an account limit or quota was hit.
pub fn looks_like_quota(text: &str) -> bool {
let t = text.to_lowercase();
[
"you've reached the limit",
"you\u{2019}ve reached the limit",
"limitexceeded",
"limit exceeded",
"quota",
]
.iter()
.any(|s| t.contains(s))
}
/// The error for a RunTask refused on a quota.
pub fn quota_error(detail: &str) -> AwsError {
AwsError::QuotaExceeded {
message: format!(
"AWS would not start the task because an account limit was reached: {detail}. \
Stop another workspace, or ask an administrator to raise the Fargate quota \
(Service Quotas, AWS Fargate) for this region. Triple-C does not retry."
),
}
}
/// `e` as a quota error when its message is one; otherwise unchanged.
pub fn quota_or(e: AwsError) -> AwsError {
match e {
AwsError::Other { ref message } if looks_like_quota(message) => quota_error(message),
e => e,
}
}
/// RunTask's answer: its one task, or an error from its `failures`
/// (`(reason, detail)`), a quota one when they say so.
pub fn run_task_outcome(
tasks: Vec<TaskInfo>,
failures: Vec<(Option<String>, Option<String>)>,
) -> Result<TaskInfo, AwsError> {
if let Some(task) = tasks.into_iter().find(|t| !t.arn.is_empty()) {
return Ok(task);
}
let text = failures
.iter()
.map(|(r, d)| match (r, d) {
(Some(r), Some(d)) => format!("{r} ({d})"),
(Some(r), None) => r.clone(),
(None, Some(d)) => d.clone(),
(None, None) => "unknown failure".into(),
})
.collect::<Vec<_>>()
.join("; ");
if text.is_empty() {
return Err(other("ecs:RunTask returned no task and no failure"));
}
if looks_like_quota(&text) {
return Err(quota_error(&text));
}
Err(other(format!("ECS could not start the task: {text}")))
}
// -------------------------------------------------------------------- wait
/// How [`wait_ready`] polls. Injectable so tests don't wait.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WaitTiming {
pub interval: Duration,
pub timeout: Duration,
}
impl Default for WaitTiming {
fn default() -> Self {
WaitTiming {
interval: Duration::from_secs(5),
timeout: Duration::from_secs(6 * 60),
}
}
}
/// Where a project's task logs go: the environment's log group and the
/// project's `awslogs-stream-prefix` (Task 4's `log_stream_prefix`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskLogs {
pub group: String,
pub stream_prefix: String,
}
fn describe_timeout(t: Duration) -> String {
let secs = t.as_secs();
if secs >= 60 && secs % 60 == 0 {
let m = secs / 60;
format!("{m} minute{}", if m == 1 { "" } else { "s" })
} else {
format!("{secs} seconds")
}
}
/// Poll until the task is RUNNING with its exec agent up and a runtime id
/// (what an SSM session needs), calling `progress` with each look. A task
/// that stops (or is being stopped) fails with its reason and the last
/// [`LOG_TAIL_LINES`] lines of its log; one that never gets there fails
/// after `timing.timeout` with its last status. The task is left as it is
/// either way: stopping it is the caller's call.
pub async fn wait_ready<A: TaskApi>(
api: &A,
cluster: &str,
arn: &str,
logs: &TaskLogs,
timing: WaitTiming,
progress: impl Fn(&TaskInfo),
) -> Result<TaskInfo, AwsError> {
let deadline = tokio::time::Instant::now() + timing.timeout;
let wanted = [arn.to_string()];
loop {
let Some(t) = api
.describe(cluster, &wanted)
.await?
.into_iter()
.find(|t| t.arn == arn)
else {
return Err(other(format!(
"The task {arn} is no longer known to ECS; start the project again"
)));
};
progress(&t);
if t.is_stopping() {
return Err(stopped_error(api, logs, &t).await);
}
if t.is_ready() {
return Ok(t);
}
if tokio::time::Instant::now() + timing.interval > deadline {
return Err(other(format!(
"The task did not become ready within {} (last status {}{}). It may still \
be starting; check the ECS console, or stop the project and start it again.",
describe_timeout(timing.timeout),
t.last_status,
if t.last_status == "RUNNING" && !t.exec_agent_running {
", ECS Exec agent not running yet"
} else {
""
}
)));
}
tokio::time::sleep(timing.interval).await;
}
}
async fn stopped_error<A: TaskApi>(api: &A, logs: &TaskLogs, t: &TaskInfo) -> AwsError {
let reason = t
.stopped_reason
.clone()
.unwrap_or_else(|| "no reason given".into());
let code = t
.stop_code
.as_deref()
.map(|c| format!(" ({c})"))
.unwrap_or_default();
let stream = task_log_stream(&logs.stream_prefix, &t.arn);
let tail = match api.log_tail(&logs.group, &stream, LOG_TAIL_LINES).await {
Ok(lines) if lines.is_empty() => "\n(The task wrote no log lines.)".to_string(),
Ok(lines) => format!("\nLast log lines:\n{}", lines.join("\n")),
Err(e) => format!("\n(Its log could not be read: {e})"),
};
other(format!(
"The task stopped before it was ready: {reason}{code}.{tail}"
))
}
// ----------------------------------------------------------- stop / watch
/// The entrypoint's exit status after an idle stop (`container/entrypoint.sh`,
/// `stop_keepalive`). A stop from ECS (SIGTERM) exits 0; this one is distinct
/// so an idle stop (`EssentialContainerExited`) is not mistaken for a crash.
pub const IDLE_EXIT_CODE: i32 = 75;
/// Why a task stopped, as the app reports it (spec, "Lifecycle and status").
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StopKind {
/// Exited on its own (the essential container ended, or AWS retired it),
/// with ECS's stopped reason when it gave one.
Exited(Option<String>),
/// The workspace's own idle stop ([`IDLE_EXIT_CODE`]).
Idle,
/// A Fargate Spot interruption (P8).
Spot,
/// Never got going: the project goes to Error with this reason.
FailedToStart(String),
/// Stopped by someone (the app, the console, the CLI).
UserInitiated,
}
pub fn classify_stop(info: &TaskInfo) -> StopKind {
match info.stop_code.as_deref() {
Some("SpotInterruption") => StopKind::Spot,
Some("TaskFailedToStart") => StopKind::FailedToStart(
info.stopped_reason
.clone()
.filter(|r| !r.trim().is_empty())
.unwrap_or_else(|| "The task failed to start".into()),
),
Some("UserInitiated") => StopKind::UserInitiated,
Some("EssentialContainerExited") if info.exit_code == Some(IDLE_EXIT_CODE) => StopKind::Idle,
_ => StopKind::Exited(info.stopped_reason.clone().filter(|r| !r.trim().is_empty())),
}
}
/// Of `arns`, the ones that are STOPPED or that ECS no longer knows (it
/// forgets stopped tasks after about an hour), each with why it stopped (a
/// forgotten task: [`StopKind::Exited`] without a reason). A task merely
/// being stopped is not yet reported. For the AWS death watch.
pub async fn stopped_among<A: TaskApi>(
api: &A,
cluster: &str,
arns: &[String],
) -> Result<Vec<(String, StopKind)>, AwsError> {
let mut stopped = Vec::new();
for chunk in arns.chunks(DESCRIBE_BATCH) {
let known = api.describe(cluster, chunk).await?;
for arn in chunk {
match known.iter().find(|t| &t.arn == arn) {
Some(t) if t.last_status != "STOPPED" => {}
Some(t) => stopped.push((arn.clone(), classify_stop(t))),
None => stopped.push((arn.clone(), StopKind::Exited(None))),
}
}
}
Ok(stopped)
}
// ---------------------------------------------------------------- real API
/// The real thing, from a connection's `SdkConfig`.
pub struct SdkTaskApi {
ecs: aws_sdk_ecs::Client,
logs: aws_sdk_cloudwatchlogs::Client,
}
impl SdkTaskApi {
pub fn new(cfg: &SdkConfig) -> Self {
SdkTaskApi {
ecs: aws_sdk_ecs::Client::new(cfg),
logs: aws_sdk_cloudwatchlogs::Client::new(cfg),
}
}
}
impl TaskApi for SdkTaskApi {
async fn run_task(&self, req: RunTaskInput) -> Result<TaskInfo, AwsError> {
const ACTION: &str = "ecs:RunTask";
// The fluent builder takes no whole input; copy every field.
let out = self
.ecs
.run_task()
.set_capacity_provider_strategy(req.capacity_provider_strategy)
.set_cluster(req.cluster)
.set_count(req.count)
.set_enable_ecs_managed_tags(req.enable_ecs_managed_tags)
.set_enable_execute_command(req.enable_execute_command)
.set_group(req.group)
.set_launch_type(req.launch_type)
.set_network_configuration(req.network_configuration)
.set_overrides(req.overrides)
.set_placement_constraints(req.placement_constraints)
.set_placement_strategy(req.placement_strategy)
.set_platform_version(req.platform_version)
.set_propagate_tags(req.propagate_tags)
.set_reference_id(req.reference_id)
.set_started_by(req.started_by)
.set_tags(req.tags)
.set_task_definition(req.task_definition)
.set_client_token(req.client_token)
.set_volume_configurations(req.volume_configurations)
.send()
.await
.map_err(|e| quota_or(classify_sdk_error(ACTION, &e)))?;
run_task_outcome(
out.tasks().iter().map(task_info).collect(),
out.failures()
.iter()
.map(|f| (f.reason().map(String::from), f.detail().map(String::from)))
.collect(),
)
}
async fn describe(&self, cluster: &str, arns: &[String]) -> Result<Vec<TaskInfo>, AwsError> {
const ACTION: &str = "ecs:DescribeTasks";
let mut out = Vec::new();
for chunk in arns.chunks(DESCRIBE_BATCH) {
let page = self
.ecs
.describe_tasks()
.cluster(cluster)
.set_tasks(Some(chunk.to_vec()))
.include(TaskField::Tags)
.send()
.await
.map_err(|e| classify_sdk_error(ACTION, &e))?;
out.extend(page.tasks().iter().map(task_info));
}
Ok(out)
}
async fn list_project_tasks(
&self,
cluster: &str,
family: &str,
) -> Result<Vec<String>, AwsError> {
const ACTION: &str = "ecs:ListTasks";
let mut found: Vec<String> = Vec::new();
for status in [DesiredStatus::Running, DesiredStatus::Pending] {
let mut token: Option<String> = None;
for _ in 0..MAX_LIST_PAGES {
let page = self
.ecs
.list_tasks()
.cluster(cluster)
.family(family)
.desired_status(status.clone())
.set_next_token(token.take())
.send()
.await
.map_err(|e| classify_sdk_error(ACTION, &e))?;
for a in page.task_arns() {
if !found.contains(a) {
found.push(a.clone());
}
}
match page.next_token() {
Some(t) => token = Some(t.to_string()),
None => break,
}
}
}
Ok(found)
}
async fn stop_task(&self, cluster: &str, arn: &str, reason: &str) -> Result<(), AwsError> {
const ACTION: &str = "ecs:StopTask";
self.ecs
.stop_task()
.cluster(cluster)
.task(arn)
.reason(reason)
.send()
.await
.map_err(|e| classify_sdk_error(ACTION, &e))?;
Ok(())
}
async fn log_tail(
&self,
group: &str,
stream: &str,
limit: i32,
) -> Result<Vec<String>, AwsError> {
const ACTION: &str = "logs:GetLogEvents";
let out = self
.logs
.get_log_events()
.log_group_name(group)
.log_stream_name(stream)
.start_from_head(false)
.limit(limit)
.send()
.await;
match out {
Ok(page) => Ok(page
.events()
.iter()
.filter_map(|e| e.message())
.map(str::to_string)
.collect()),
Err(e)
if e.as_service_error()
.is_some_and(|s| s.is_resource_not_found_exception()) =>
{
Ok(Vec::new())
}
Err(e) => Err(classify_sdk_error(ACTION, &e)),
}
}
}
#[cfg(test)]
mod tests;
+744
View File
@@ -0,0 +1,744 @@
use std::sync::Mutex;
use std::time::Duration;
use aws_sdk_ecs::types::{
AssignPublicIp, Container, LaunchType, ManagedAgent, ManagedAgentName, Tag, Task, TaskStopCode,
};
use super::*;
use crate::aws::environments::EnvironmentInfo;
use crate::aws::tofu_modules::{log_stream_prefix, owner_key};
const ACCOUNT: &str = "111122223333";
const REGION: &str = "eu-west-1";
const USER: &str = "AROAEXAMPLEID:alice@example.com";
const OTHER: &str = "AROAOTHERID:mallory";
const PROJECT_ID: &str = "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0";
const FAMILY: &str = "triple-c-dev-abcdef012345-0f1e2d3c-4b5";
fn cluster() -> String {
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:cluster/triple-c-dev")
}
fn td_arn(rev: u32) -> String {
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{FAMILY}:{rev}")
}
fn task_arn(id: &str) -> String {
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task/triple-c-dev/{id}")
}
fn env_info() -> EnvironmentInfo {
EnvironmentInfo {
schema: 1,
name: "dev".into(),
template_version: 1,
cluster_arn: cluster(),
security_group_id: "sg-0123456789abcdef0".into(),
subnet_ids: vec!["subnet-0a".into(), "subnet-0b".into()],
assign_public_ip: true,
kms_key_arn: format!("arn:aws:kms:{REGION}:{ACCOUNT}:key/1234"),
log_group: "/triple-c/dev".into(),
network_mode: "public".into(),
tenancy: "strict".into(),
}
}
fn is_quota_error(e: &AwsError) -> bool {
matches!(e, AwsError::QuotaExceeded { .. })
}
fn info(id: &str, last: &str) -> TaskInfo {
TaskInfo {
arn: task_arn(id),
last_status: last.into(),
desired_status: if last == "STOPPED" {
"STOPPED"
} else {
"RUNNING"
}
.into(),
health: None,
stop_code: None,
stopped_reason: None,
task_definition_arn: td_arn(3),
runtime_id: None,
exec_agent_running: false,
exit_code: None,
owner: Some(USER.into()),
project: Some(PROJECT_ID.into()),
}
}
fn ready(id: &str) -> TaskInfo {
TaskInfo {
runtime_id: Some(format!("{id}-123")),
exec_agent_running: true,
..info(id, "RUNNING")
}
}
/// A scripted `TaskApi`: `listed` answers ListTasks, `described` answers
/// every DescribeTasks in turn (the last one repeats), `run` answers RunTask.
#[derive(Default)]
struct Fake {
listed: Vec<String>,
described: Mutex<Vec<Vec<TaskInfo>>>,
run: Mutex<Option<Result<TaskInfo, AwsError>>>,
logs: Vec<String>,
calls: Mutex<Vec<String>>,
run_requests: Mutex<Vec<RunTaskInput>>,
log_requests: Mutex<Vec<(String, String, i32)>>,
}
impl Fake {
fn calls(&self) -> Vec<String> {
self.calls.lock().unwrap().clone()
}
fn describing(self, answers: Vec<Vec<TaskInfo>>) -> Self {
*self.described.lock().unwrap() = answers;
self
}
fn running(self, r: Result<TaskInfo, AwsError>) -> Self {
*self.run.lock().unwrap() = Some(r);
self
}
}
impl TaskApi for Fake {
async fn run_task(&self, req: RunTaskInput) -> Result<TaskInfo, AwsError> {
self.calls.lock().unwrap().push("run".into());
self.run_requests.lock().unwrap().push(req);
self.run
.lock()
.unwrap()
.clone()
.unwrap_or_else(|| Ok(info("new", "PROVISIONING")))
}
async fn describe(&self, cluster: &str, arns: &[String]) -> Result<Vec<TaskInfo>, AwsError> {
self.calls
.lock()
.unwrap()
.push(format!("describe {cluster} {}", arns.join(",")));
let mut d = self.described.lock().unwrap();
let answer = if d.len() > 1 {
d.remove(0)
} else {
d.first().cloned().unwrap_or_default()
};
Ok(answer
.into_iter()
.filter(|t| arns.contains(&t.arn))
.collect())
}
async fn list_project_tasks(
&self,
cluster: &str,
family: &str,
) -> Result<Vec<String>, AwsError> {
self.calls
.lock()
.unwrap()
.push(format!("list {cluster} {family}"));
Ok(self.listed.clone())
}
async fn stop_task(&self, _cluster: &str, arn: &str, reason: &str) -> Result<(), AwsError> {
self.calls
.lock()
.unwrap()
.push(format!("stop {arn} {reason}"));
Ok(())
}
async fn log_tail(
&self,
group: &str,
stream: &str,
limit: i32,
) -> Result<Vec<String>, AwsError> {
self.log_requests
.lock()
.unwrap()
.push((group.into(), stream.into(), limit));
Ok(self.logs.clone())
}
}
fn tags() -> Vec<(String, String)> {
crate::aws::workspace::workspace_tags(USER, PROJECT_ID, "dev")
}
// ------------------------------------------------------------ run request
#[test]
fn on_demand_runs_fargate_on_the_environment_network_with_exec_and_the_three_tags() {
let req = run_task_request(&env_info(), &td_arn(3), false, &tags());
assert_eq!(req.cluster(), Some(cluster().as_str()));
assert_eq!(req.task_definition(), Some(td_arn(3).as_str()));
assert_eq!(req.launch_type(), Some(&LaunchType::Fargate));
assert!(req.capacity_provider_strategy().is_empty());
assert_eq!(req.enable_execute_command(), Some(true));
assert_eq!(req.count(), Some(1));
let vpc = req
.network_configuration()
.and_then(|n| n.awsvpc_configuration())
.expect("awsvpc");
assert_eq!(vpc.subnets(), ["subnet-0a", "subnet-0b"]);
assert_eq!(vpc.security_groups(), ["sg-0123456789abcdef0"]);
assert_eq!(vpc.assign_public_ip(), Some(&AssignPublicIp::Enabled));
let got: Vec<(String, String)> = req
.tags()
.iter()
.map(|t| (t.key().unwrap().to_string(), t.value().unwrap().to_string()))
.collect();
assert_eq!(got, tags());
// Nothing project-shaped rides along (P1), and tags are given, not propagated.
assert!(req.overrides().is_none());
assert!(req.propagate_tags().is_none());
assert!(req.enable_ecs_managed_tags().is_none());
}
#[test]
fn spot_uses_the_fargate_spot_capacity_provider_and_no_launch_type() {
let req = run_task_request(&env_info(), &td_arn(3), true, &tags());
assert_eq!(req.launch_type(), None);
let strategy = req.capacity_provider_strategy();
assert_eq!(strategy.len(), 1);
assert_eq!(strategy[0].capacity_provider(), "FARGATE_SPOT");
assert_eq!(strategy[0].weight(), 1);
}
#[test]
fn a_private_environment_gets_no_public_ip() {
let mut env = env_info();
env.assign_public_ip = false;
let req = run_task_request(&env, &td_arn(3), false, &tags());
let vpc = req
.network_configuration()
.unwrap()
.awsvpc_configuration()
.unwrap();
assert_eq!(vpc.assign_public_ip(), Some(&AssignPublicIp::Disabled));
}
// ------------------------------------------------------------ find or run
#[tokio::test]
async fn an_existing_running_task_is_reused_and_nothing_is_run() {
let api = Fake {
listed: vec![task_arn("t1")],
..Default::default()
}
.describing(vec![vec![ready("t1")]]);
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(4), false)
.await
.unwrap();
assert!(got.reused);
assert_eq!(got.task.arn, task_arn("t1"));
assert!(!api.calls().contains(&"run".to_string()));
assert_eq!(api.calls()[0], format!("list {} {FAMILY}", cluster()));
}
#[tokio::test]
async fn a_pending_task_is_reused_too() {
let api = Fake {
listed: vec![task_arn("t1")],
..Default::default()
}
.describing(vec![vec![info("t1", "PENDING")]]);
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(3), false)
.await
.unwrap();
assert!(got.reused);
assert_eq!(got.task.last_status, "PENDING");
assert!(!api.calls().contains(&"run".to_string()));
}
#[tokio::test]
async fn a_task_of_another_owner_or_project_in_the_family_is_never_reused() {
let mut foreign = info("theirs", "RUNNING");
foreign.owner = Some(OTHER.into());
let mut other_project = info("other-project", "RUNNING");
other_project.project = Some("ffffffff-0000-0000-0000-000000000000".into());
let mut untagged = info("untagged", "RUNNING");
untagged.owner = None;
untagged.project = None;
let api = Fake {
listed: vec![
task_arn("theirs"),
task_arn("other-project"),
task_arn("untagged"),
],
..Default::default()
}
.describing(vec![vec![foreign, other_project, untagged]]);
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(3), false)
.await
.unwrap();
assert!(!got.reused);
assert_eq!(got.task.arn, task_arn("new"));
assert_eq!(api.calls().last().unwrap(), "run");
}
#[tokio::test]
async fn a_task_already_stopping_is_not_reused() {
let mut stopping = info("t1", "RUNNING");
stopping.desired_status = "STOPPED".into();
let api = Fake {
listed: vec![task_arn("t1"), task_arn("t2")],
..Default::default()
}
.describing(vec![vec![stopping, info("t2", "DEPROVISIONING")]]);
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(3), false)
.await
.unwrap();
assert!(!got.reused);
}
#[tokio::test]
async fn a_running_task_is_preferred_over_a_pending_one() {
let api = Fake {
listed: vec![task_arn("p"), task_arn("r")],
..Default::default()
}
.describing(vec![vec![info("p", "PENDING"), ready("r")]]);
let got = find_project_task(&api, &cluster(), FAMILY, USER, PROJECT_ID)
.await
.unwrap()
.unwrap();
assert_eq!(got.arn, task_arn("r"));
}
#[tokio::test]
async fn nothing_listed_means_no_describe_and_a_run_with_the_exact_revision_and_tags() {
let api = Fake::default();
let got = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(7), true)
.await
.unwrap();
assert!(!got.reused);
assert_eq!(api.calls().len(), 2, "{:?}", api.calls());
let reqs = api.run_requests.lock().unwrap();
assert_eq!(reqs[0].task_definition(), Some(td_arn(7).as_str()));
assert_eq!(reqs[0].launch_type(), None);
let keys: Vec<&str> = reqs[0].tags().iter().filter_map(|t| t.key()).collect();
assert_eq!(
keys,
["triple-c:environment", "triple-c:owner", "triple-c:project"]
);
assert_eq!(
reqs[0]
.tags()
.iter()
.find(|t| t.key() == Some("triple-c:owner"))
.unwrap()
.value(),
Some(USER)
);
}
#[tokio::test]
async fn a_bare_family_or_foreign_arn_is_refused_before_any_call() {
let api = Fake::default();
for bad in [
FAMILY.to_string(),
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{FAMILY}"),
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{FAMILY}:latest"),
"arn:aws:ecs:eu-west-1:1:task-definition/someone-else:1".to_string(),
] {
let err = find_or_run(&api, &env_info(), USER, PROJECT_ID, &bad, false)
.await
.unwrap_err();
assert!(matches!(err, AwsError::Other { .. }), "{bad}: {err:?}");
}
assert!(api.calls().is_empty());
}
#[tokio::test]
async fn a_quota_refusal_is_reported_once_without_retrying() {
let api = Fake::default().running(Err(quota_error(
"You've reached the limit on the number of vCPUs you can run concurrently",
)));
let err = find_or_run(&api, &env_info(), USER, PROJECT_ID, &td_arn(3), false)
.await
.unwrap_err();
assert!(is_quota_error(&err));
let text = err.to_string();
assert!(text.contains("limit"), "{text}");
assert!(text.contains("quota"), "{text}");
assert!(text.contains("vCPUs"), "{text}");
assert_eq!(
api.calls().iter().filter(|c| *c == "run").count(),
1,
"no retry"
);
}
// ------------------------------------------------------------ quota mapping
#[test]
fn quota_texts_are_recognised_and_others_are_not() {
for q in [
"You've reached the limit on the number of vCPUs you can run concurrently",
"You\u{2019}ve reached the limit on the number of tasks you can run concurrently",
"LimitExceededException: too many",
"Service quota exceeded for Fargate On-Demand vCPU",
"limit exceeded",
] {
assert!(looks_like_quota(q), "{q}");
}
for not in [
"Capacity is unavailable at this time. Please try again later",
"AccessDeniedException: not authorized",
"CannotPullContainerError",
] {
assert!(!looks_like_quota(not), "{not}");
}
}
#[test]
fn quota_mapping_turns_other_errors_into_quota_errors_and_leaves_the_rest() {
let q = quota_or(AwsError::Other {
message: "ClientException: You've reached the limit on the number of vCPUs".into(),
});
assert!(is_quota_error(&q));
// The frontend's `quota_exceeded` kind (lib/types.ts).
let v = serde_json::to_value(&q).unwrap();
assert_eq!(v["kind"], "quota_exceeded");
assert!(v["message"].as_str().unwrap().contains("vCPUs"));
let denied = AwsError::AccessDenied {
action: "ecs:RunTask".into(),
message: "limit".into(),
};
assert_eq!(quota_or(denied.clone()), denied);
assert!(!is_quota_error(&AwsError::Other {
message: "x".into()
}));
}
#[test]
fn run_task_failures_become_errors_and_quota_failures_quota_errors() {
let ok = run_task_outcome(vec![info("a", "PROVISIONING")], vec![]).unwrap();
assert_eq!(ok.arn, task_arn("a"));
let err = run_task_outcome(
vec![],
vec![(Some("RESOURCE:ENI".into()), Some("no ENIs left".into()))],
)
.unwrap_err();
assert!(!is_quota_error(&err));
assert!(err.to_string().contains("RESOURCE:ENI"), "{err}");
assert!(err.to_string().contains("no ENIs left"), "{err}");
let err = run_task_outcome(
vec![],
vec![(
Some("You've reached the limit on the number of tasks you can run concurrently".into()),
None,
)],
)
.unwrap_err();
assert!(is_quota_error(&err));
let err = run_task_outcome(vec![], vec![]).unwrap_err();
assert!(err.to_string().contains("no task"), "{err}");
}
// ------------------------------------------------------------ wait
fn timing() -> WaitTiming {
WaitTiming {
interval: Duration::from_secs(5),
timeout: Duration::from_secs(360),
}
}
fn logs() -> TaskLogs {
TaskLogs {
group: "/triple-c/dev".into(),
stream_prefix: log_stream_prefix(&owner_key(REGION, USER), PROJECT_ID),
}
}
#[tokio::test(start_paused = true)]
async fn wait_polls_until_running_with_the_exec_agent_and_a_runtime_id() {
let mut half = info("t1", "RUNNING");
half.runtime_id = Some("rt".into());
let api = Fake::default().describing(vec![
vec![info("t1", "PROVISIONING")],
vec![info("t1", "PENDING")],
vec![half],
vec![ready("t1")],
]);
let seen = Mutex::new(Vec::new());
let t0 = tokio::time::Instant::now();
let got = wait_ready(
&api,
&cluster(),
&task_arn("t1"),
&logs(),
timing(),
|t: &TaskInfo| seen.lock().unwrap().push(t.last_status.clone()),
)
.await
.unwrap();
assert_eq!(got, ready("t1"));
assert_eq!(
*seen.lock().unwrap(),
["PROVISIONING", "PENDING", "RUNNING", "RUNNING"]
);
assert_eq!(t0.elapsed(), Duration::from_secs(15));
}
#[tokio::test(start_paused = true)]
async fn a_task_that_stops_while_waiting_reports_its_reason_and_last_log_lines() {
let mut stopped = info("t1", "STOPPED");
stopped.stop_code = Some("EssentialContainerExited".into());
stopped.stopped_reason = Some("Essential container in task exited".into());
let api = Fake {
logs: vec!["Triple-C: starting".into(), "fatal: boom".into()],
..Default::default()
}
.describing(vec![vec![info("t1", "PENDING")], vec![stopped]]);
let err = wait_ready(
&api,
&cluster(),
&task_arn("t1"),
&logs(),
timing(),
|_: &TaskInfo| {},
)
.await
.unwrap_err();
let text = err.to_string();
assert!(
text.contains("Essential container in task exited"),
"{text}"
);
assert!(text.contains("Triple-C: starting\nfatal: boom"), "{text}");
let reqs = api.log_requests.lock().unwrap();
assert_eq!(
*reqs,
[(
"/triple-c/dev".to_string(),
format!("{}/workspace/t1", logs().stream_prefix),
50
)]
);
}
#[tokio::test(start_paused = true)]
async fn a_task_being_stopped_fails_the_wait_at_once() {
let mut stopping = info("t1", "RUNNING");
stopping.desired_status = "STOPPED".into();
stopping.stop_code = Some("SpotInterruption".into());
stopping.stopped_reason = Some("Your Spot Task was interrupted.".into());
let api = Fake::default().describing(vec![vec![stopping]]);
let err = wait_ready(
&api,
&cluster(),
&task_arn("t1"),
&logs(),
timing(),
|_: &TaskInfo| {},
)
.await
.unwrap_err();
assert!(
err.to_string().contains("Your Spot Task was interrupted."),
"{err}"
);
}
#[tokio::test(start_paused = true)]
async fn a_task_that_never_gets_ready_times_out_with_its_last_status() {
let api = Fake::default().describing(vec![vec![info("t1", "PENDING")]]);
let t0 = tokio::time::Instant::now();
let err = wait_ready(
&api,
&cluster(),
&task_arn("t1"),
&logs(),
timing(),
|_: &TaskInfo| {},
)
.await
.unwrap_err();
assert!(t0.elapsed() >= Duration::from_secs(360));
assert!(t0.elapsed() < Duration::from_secs(366));
let text = err.to_string();
assert!(text.contains("6 minutes"), "{text}");
assert!(text.contains("PENDING"), "{text}");
}
#[tokio::test(start_paused = true)]
async fn a_task_that_vanishes_is_an_error_not_a_hang() {
let api = Fake::default().describing(vec![vec![]]);
let err = wait_ready(
&api,
&cluster(),
&task_arn("t1"),
&logs(),
timing(),
|_: &TaskInfo| {},
)
.await
.unwrap_err();
assert!(err.to_string().contains("no longer"), "{err}");
}
#[test]
fn the_default_wait_is_five_seconds_for_six_minutes() {
let t = WaitTiming::default();
assert_eq!(t.interval, Duration::from_secs(5));
assert_eq!(t.timeout, Duration::from_secs(360));
}
// ------------------------------------------------------------ stop / logs
#[tokio::test]
async fn stop_passes_the_reason() {
let api = Fake::default();
api.stop_task(&cluster(), &task_arn("t1"), STOP_REASON)
.await
.unwrap();
assert_eq!(
api.calls(),
[format!("stop {} Stopped from Triple-C", task_arn("t1"))]
);
}
#[test]
fn the_log_stream_is_prefix_container_task_id() {
assert_eq!(
task_log_stream("abc/p", &task_arn("0123abcd")),
"abc/p/workspace/0123abcd"
);
}
#[tokio::test]
async fn stopped_among_reports_stopped_and_vanished_tasks_only() {
let api = Fake::default().describing(vec![vec![
ready("up"),
info("down", "STOPPED"),
info("pending", "PENDING"),
]]);
let arns = vec![
task_arn("up"),
task_arn("down"),
task_arn("pending"),
task_arn("gone"),
];
let mut got = stopped_among(&api, &cluster(), &arns).await.unwrap();
got.sort_by(|a, b| a.0.cmp(&b.0));
assert_eq!(
got,
[
(task_arn("down"), StopKind::Exited(None)),
(task_arn("gone"), StopKind::Exited(None)),
]
);
}
// ------------------------------------------------------------ classify
#[test]
fn classify_stop_follows_the_spec_table() {
let with = |code: Option<&str>, reason: Option<&str>| TaskInfo {
stop_code: code.map(String::from),
stopped_reason: reason.map(String::from),
..info("t", "STOPPED")
};
assert_eq!(
classify_stop(&with(Some("EssentialContainerExited"), Some("Essential container in task exited"))),
StopKind::Exited(Some("Essential container in task exited".into()))
);
// The entrypoint's idle stop exits with its own status.
let idle = TaskInfo { exit_code: Some(IDLE_EXIT_CODE), ..with(Some("EssentialContainerExited"), None) };
assert_eq!(classify_stop(&idle), StopKind::Idle);
let crashed = TaskInfo { exit_code: Some(137), ..with(Some("EssentialContainerExited"), None) };
assert_eq!(classify_stop(&crashed), StopKind::Exited(None));
// Only with that stop code: a user stop of a task that exits 75 is a user stop.
let user = TaskInfo { exit_code: Some(IDLE_EXIT_CODE), ..with(Some("UserInitiated"), None) };
assert_eq!(classify_stop(&user), StopKind::UserInitiated);
assert_eq!(
classify_stop(&with(Some("SpotInterruption"), None)),
StopKind::Spot
);
assert_eq!(
classify_stop(&with(
Some("TaskFailedToStart"),
Some("CannotPullContainerError: nope")
)),
StopKind::FailedToStart("CannotPullContainerError: nope".into())
);
assert!(matches!(
classify_stop(&with(Some("TaskFailedToStart"), None)),
StopKind::FailedToStart(r) if !r.is_empty()
));
assert_eq!(
classify_stop(&with(Some("UserInitiated"), Some("Stopped from Triple-C"))),
StopKind::UserInitiated
);
assert_eq!(
classify_stop(&with(Some("TerminationNotice"), None)),
StopKind::Exited(None)
);
assert_eq!(
classify_stop(&with(Some("ServiceSchedulerInitiated"), None)),
StopKind::Exited(None)
);
assert_eq!(classify_stop(&with(None, Some(" "))), StopKind::Exited(None));
}
// ------------------------------------------------------------ SDK mapping
#[test]
fn task_info_reads_the_workspace_container_and_its_exec_agent() {
let task = Task::builder()
.task_arn(task_arn("t1"))
.last_status("RUNNING")
.desired_status("RUNNING")
.health_status(aws_sdk_ecs::types::HealthStatus::Healthy)
.stop_code(TaskStopCode::SpotInterruption)
.stopped_reason("r")
.task_definition_arn(td_arn(3))
.containers(
Container::builder()
.name("sidecar")
.runtime_id("wrong")
.exit_code(1)
.build(),
)
.containers(
Container::builder()
.name("workspace")
.runtime_id("rt-1")
.exit_code(75)
.managed_agents(
ManagedAgent::builder()
.name(ManagedAgentName::ExecuteCommandAgent)
.last_status("RUNNING")
.build(),
)
.build(),
)
.tags(Tag::builder().key("triple-c:owner").value(USER).build())
.tags(
Tag::builder()
.key("triple-c:project")
.value(PROJECT_ID)
.build(),
)
.build();
let i = task_info(&task);
assert_eq!(i.arn, task_arn("t1"));
assert_eq!(i.health.as_deref(), Some("HEALTHY"));
assert_eq!(i.stop_code.as_deref(), Some("SpotInterruption"));
assert_eq!(i.runtime_id.as_deref(), Some("rt-1"));
assert!(i.exec_agent_running);
assert_eq!(i.exit_code, Some(75), "the workspace container's, not the sidecar's");
assert_eq!(i.owner.as_deref(), Some(USER));
assert_eq!(i.project.as_deref(), Some(PROJECT_ID));
let bare = task_info(&Task::builder().task_arn("x").last_status("PENDING").build());
assert!(!bare.exec_agent_running);
assert_eq!(bare.runtime_id, None);
assert_eq!(bare.exit_code, None);
assert_eq!(bare.owner, None);
}
+100
View File
@@ -96,6 +96,16 @@ pub fn validate_environment_name(name: &str) -> Result<String, String> {
}
}
/// An environment's ECS cluster name (the environment module's).
pub fn environment_cluster_name(env: &str) -> String {
format!("triple-c-{env}")
}
/// An environment's CloudWatch log group (the environment module's).
pub fn environment_log_group(env: &str) -> String {
format!("/triple-c/{env}")
}
/// The SSM parameter holding an environment's record.
pub fn environment_parameter_name(env: &str) -> String {
format!("/triple-c/environments/{env}")
@@ -122,6 +132,96 @@ pub fn user_role_names(env: &str, owner_key: &str) -> (String, String) {
)
}
/// Whether a project id is used in names as it is: 1 to 64 characters of
/// `[A-Za-z0-9-]`. Every UUID (how the app makes ids) is.
fn is_clean_project_id(id: &str) -> bool {
(1..=64).contains(&id.len()) && id.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-')
}
/// 16 hex characters of `sha256(id)`.
fn project_id_hash(id: &str) -> String {
Sha256::digest(id.as_bytes())
.iter()
.take(8)
.map(|b| format!("{b:02x}"))
.collect()
}
/// A project id as a name component, safe in a secret name, an EFS path and
/// a log stream. A clean id (see [`is_clean_project_id`]) is used as is.
/// Anything else — only a hand-edited `projects.json` has one — becomes its
/// first 40 characters with everything outside `[A-Za-z0-9-]` replaced by
/// `-`, then `_` and a hash of the whole id. Clean ids never contain `_`, so
/// the two forms can't collide, and ids that sanitise alike (`a/b`, `a:b`)
/// still differ by the hash.
fn project_component(project_id: &str) -> String {
if is_clean_project_id(project_id) {
return project_id.to_string();
}
let prefix: String = project_id
.chars()
.take(40)
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' {
c
} else {
'-'
}
})
.collect();
format!("{prefix}_{}", project_id_hash(project_id))
}
/// A project's ECS task definition family:
/// `triple-c-<env>-<owner_key>-<first 12 of the project id>` (an id that
/// isn't clean contributes `_` and 11 hex of its hash instead). At most 55
/// characters of `[A-Za-z0-9_-]`. Other users can register revisions into
/// any `triple-c-*` family, so a family is never trusted by name alone (see
/// `aws::workspace`), and two of a user's projects could share 12 leading
/// characters, so a family's tasks and revisions are told apart by their
/// `triple-c:project` tag.
pub fn task_family(env: &str, owner_key: &str, project_id: &str) -> String {
let id: String = if is_clean_project_id(project_id) {
project_id.chars().take(12).collect()
} else {
format!("_{}", &project_id_hash(project_id)[..11])
};
format!("triple-c-{env}-{owner_key}-{id}")
}
/// The project's Secrets Manager secret (P1): `triple-c/<env>/<owner_key>/<project id>`.
pub fn project_secret_name(env: &str, owner_key: &str, project_id: &str) -> String {
format!(
"triple-c/{env}/{owner_key}/{}",
project_component(project_id)
)
}
/// The root of the project's EFS access point (P4), at most 90 characters.
pub fn access_point_root(owner_key: &str, project_id: &str) -> String {
format!("/triple-c/{owner_key}/{}", project_component(project_id))
}
/// The container's `awslogs-stream-prefix`; ECS names the stream
/// `<prefix>/workspace/<task id>`.
pub fn log_stream_prefix(owner_key: &str, project_id: &str) -> String {
format!("{owner_key}/{}", project_component(project_id))
}
/// The awslogs stream of a task's `workspace` container:
/// `<prefix>/<container>/<task-id>`, the task id being the last segment of
/// its ARN.
pub fn task_log_stream(stream_prefix: &str, task_arn: &str) -> String {
let task_id = task_arn.rsplit('/').next().unwrap_or(task_arn);
format!("{stream_prefix}/workspace/{task_id}")
}
/// The `creation_token` of the user's file system (the onboarding module's
/// `local.name`).
pub fn user_file_system_token(env: &str, owner_key: &str) -> String {
format!("triple-c-{env}-{owner_key}")
}
/// The per-account, per-region state bucket.
pub fn state_bucket_name(account: &str, region: &str) -> String {
format!("triple-c-tfstate-{account}-{region}")
@@ -163,6 +163,12 @@ fn environment_names_are_validated() {
);
}
#[test]
fn the_environment_cluster_and_log_group_names_match_the_module() {
assert_eq!(environment_cluster_name("dev"), "triple-c-dev");
assert_eq!(environment_log_group("dev"), "/triple-c/dev");
}
#[test]
fn same_user_and_environment_in_two_regions_do_not_collide() {
// IAM role names are account-global but environments are regional: the
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -34,6 +34,11 @@ pub async fn get_container_info(
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
// An AWS project has no Docker container (its own name could match a
// stale one from before it moved to AWS).
if project.is_aws() {
return Ok(None);
}
docker::get_container_info(&project).await
}
+5 -2
View File
@@ -547,8 +547,11 @@ mod tests {
serde_json::from_str::<serde_json::Value>(&f.json).expect("policy JSON");
}
let ws = aws_policy_document(Tier::WorkspaceUser);
assert_eq!(ws.len(), 1);
assert_eq!(ws[0].name, "workspace-user.json");
let names: Vec<&str> = ws.iter().map(|f| f.name.as_str()).collect();
assert_eq!(names, ["workspace-user.json", "workspace-user-tasks.json"]);
for f in &ws {
serde_json::from_str::<serde_json::Value>(&f.json).expect("policy JSON");
}
assert_eq!(
serde_json::to_value(&ws[0]).unwrap()["name"],
"workspace-user.json"
@@ -432,6 +432,11 @@ pub async fn get_container_staleness(
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
// An AWS task has no local container or snapshot to compare: no claim
// either way ("unknown"), and nothing is probed.
if project.is_aws() {
return Ok(ContainerStaleness::default());
}
let settings = state.settings_store.get();
let base_image = crate::models::container_config::resolve_image_name(
&settings.image_source,
@@ -708,6 +713,9 @@ pub async fn migrate_project_to_base(
app_handle: tauri::AppHandle,
state: State<'_, AppState>,
) -> Result<MigrationReport, String> {
if let Some(p) = state.projects_store.get(&project_id) {
crate::commands::project_commands::refuse_aws(&p, "Updating to the current base image")?;
}
let _guard = match ActiveGuard::acquire(&project_id) {
Ok(guard) => guard,
Err(busy) => return Ok(MigrationReport::failed_preflight(&busy)),
+1
View File
@@ -15,6 +15,7 @@ pub mod migration_commands;
pub mod notes_commands;
pub mod project_commands;
pub mod settings_commands;
pub mod stop_guard;
pub mod settings_export_commands;
pub mod stt_commands;
pub mod terminal_commands;
+733 -14
View File
@@ -4,7 +4,10 @@ use crate::commands::aws_commands;
use crate::docker;
use crate::host::lifecycle::{DiscardLeftovers, ProjectHost};
use crate::host::ContainerTarget;
use crate::models::{Backend, BedrockAuthMethod, Project, ProjectPath, ProjectRemovalReport, ProjectResetOutcome, ProjectStatus};
use crate::models::{
AwsPlacement, AwsWorkspaceConfig, Backend, BedrockAuthMethod, Project, ProjectPath,
ProjectRemovalReport, ProjectResetOutcome, ProjectStatus, UnsavedWork, WipChoice,
};
use crate::storage::secure;
use crate::AppState;
@@ -633,9 +636,47 @@ pub async fn list_projects(state: State<'_, AppState>) -> Result<Vec<Project>, S
pub async fn add_project(
name: String,
paths: Vec<ProjectPath>,
host_id: Option<String>,
aws_placement: Option<AwsPlacement>,
aws: Option<AwsWorkspaceConfig>,
state: State<'_, AppState>,
) -> Result<Project, String> {
// Validate paths
let project = new_project(name, paths, host_id, aws_placement, aws, &state.settings_store.get().hosts)?;
// Nothing can have been blanked on a project that did not exist a line ago.
store_secrets_for_project(&project, &[])?;
state.projects_store.add(project)
}
/// The project `add_project` creates. A local project needs a folder; an
/// AWS project (all three host fields) clones repositories instead and
/// takes no folders. The host fields are checked as a save would check them.
fn new_project(
name: String,
paths: Vec<ProjectPath>,
host_id: Option<String>,
aws_placement: Option<AwsPlacement>,
aws: Option<AwsWorkspaceConfig>,
hosts: &[crate::models::HostConnection],
) -> Result<Project, String> {
let on_host = host_id.is_some() || aws_placement.is_some() || aws.is_some();
if on_host {
if paths.iter().any(|p| !p.host_path.is_empty() || !p.mount_name.is_empty()) {
return Err("A project on AWS clones repositories; it can't mount folders from this machine.".into());
}
let blank = Project::new(name.clone(), Vec::new());
let mut project = Project::new(name, Vec::new());
project.host_id = host_id;
project.aws_placement = aws_placement;
// Runtime handles belong to the start path, never to the caller.
project.aws = aws.map(|a| AwsWorkspaceConfig {
task_arn: None,
access_point_id: None,
task_definition_arn: None,
..a
});
validate_aws_update(&blank, &project, hosts)?;
return Ok(project);
}
// A new project needs a folder; the blank row `validate_project_paths`
// tolerates is the Config tab's placeholder on an *existing* one.
if paths.is_empty()
@@ -646,15 +687,14 @@ pub async fn add_project(
return Err("At least one folder path is required.".to_string());
}
validate_project_paths(&paths)?;
let project = Project::new(name, paths);
// Nothing can have been blanked on a project that did not exist a line ago.
store_secrets_for_project(&project, &[])?;
state.projects_store.add(project)
Ok(Project::new(name, paths))
}
#[tauri::command]
pub async fn remove_project(
project_id: String,
discard_data: Option<bool>,
forget_aws_resources: Option<bool>,
state: State<'_, AppState>,
) -> Result<ProjectRemovalReport, String> {
// **H-2: the only writer of these three categories that held nothing.**
@@ -673,6 +713,34 @@ pub async fn remove_project(
let _guard =
crate::project_lock::try_acquire(&project_id, crate::project_lock::ProjectOp::Destroy)?;
// An AWS project's task and resources go first, and a failure keeps the
// project: its record is the only handle on a billed task and its
// secret. Its EFS access point goes only when asked (the files stay on the
// user's own file system until offboarding).
if let Some(project) = state.projects_store.get(&project_id).filter(|p| p.is_aws()) {
let settings = state.settings_store.get();
if let Some(target) = ContainerTarget::for_project(&project) {
state.exec_manager.close_sessions_for_container(target.id()).await;
}
let connection_exists = project
.host_id
.as_deref()
.is_some_and(|id| settings.hosts.iter().any(|h| h.id == id));
if connection_exists {
ProjectHost::for_project(&project)
.remove_aws_resources(&project, &settings, discard_data.unwrap_or(false))
.await?;
} else {
missing_connection_removal(forget_aws_resources.unwrap_or(false))?;
log::warn!(
"Project {}: removed without its AWS connection; its task, secret and data (if \
any) are left in AWS, as the user confirmed",
project_id
);
crate::host::tunnels::close(&project_id).await;
}
}
// 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;
@@ -1054,6 +1122,8 @@ pub async fn update_project(
// [`crate::models::validate_env_vars_update`].
crate::models::validate_env_vars_update(&stored.custom_env_vars, &project.custom_env_vars)?;
validate_aws_update(&stored, &project, &state.settings_store.get().hosts)?;
restore_store_owned_fields(&mut project, &stored);
project.updated_at = chrono::Utc::now().to_rfc3339();
@@ -1115,6 +1185,59 @@ fn restore_store_owned_fields(project: &mut Project, stored: &Project) {
// Owned by the marketplace commands; a Config-tab save carries a stale copy.
project.marketplace_installs = stored.marketplace_installs.clone();
project.marketplace_disabled = stored.marketplace_disabled.clone();
// Runtime handles of an AWS task belong to the start/stop path.
if let Some(aws) = project.aws.as_mut() {
let s = stored.aws.as_ref();
aws.task_arn = s.and_then(|a| a.task_arn.clone());
aws.access_point_id = s.and_then(|a| a.access_point_id.clone());
aws.task_definition_arn = s.and_then(|a| a.task_definition_arn.clone());
}
}
/// Checks an incoming save's host placement against what is stored and the
/// configured connections.
fn validate_aws_update(
stored: &Project,
project: &Project,
hosts: &[crate::models::HostConnection],
) -> Result<(), String> {
match (&project.host_id, &project.aws_placement, &project.aws) {
(None, None, None) => {}
(Some(id), Some(place), Some(cfg)) => {
if !hosts.iter().any(|h| &h.id == id) {
return Err(format!("Host connection \"{}\" does not exist", id.escape_debug()));
}
crate::models::validate_region(&place.region)?;
crate::aws::tofu_modules::validate_environment_name(&place.environment)?;
crate::models::validate_aws_workspace(cfg)?;
}
_ => {
return Err(
"A host project needs a host, a placement and a workspace configuration together"
.into(),
)
}
}
let moved = stored.host_id != project.host_id || stored.aws_placement != project.aws_placement;
if moved && stored.status != ProjectStatus::Stopped {
return Err("Stop the project before changing its host or placement".into());
}
// The task, access point and task definition live in the stored
// connection's account and region; moving the project would orphan them.
if moved
&& stored.aws.as_ref().is_some_and(|a| {
a.task_arn.is_some() || a.access_point_id.is_some() || a.task_definition_arn.is_some()
})
{
return Err(
"This project still has AWS resources (a task, its saved files' access point or task \
definitions) where it runs now; remove the workspace's AWS resources first — \
including the access point (\"Also remove the workspace's file-system access \
point\"), which stays when the saved files are kept"
.into(),
);
}
Ok(())
}
#[tauri::command]
@@ -1282,7 +1405,7 @@ async fn start_project_container_locked(
let host = ProjectHost::for_project(&project);
let result: Result<ContainerTarget, String> = async {
let target = host
.ensure_started(&project, &settings, &|msg: &str| {
.ensure_started(&project, &settings, &state.projects_store, &|msg: &str| {
emit_progress(&app_handle, &project_id, msg)
})
.await?;
@@ -1307,10 +1430,24 @@ async fn start_project_container_locked(
Ok(target)
}.await;
// On failure, reset status to Stopped so the project doesn't get stuck.
// On failure, reset status to Stopped so the project doesn't get stuck —
// unless an AWS task is still running (an attach that failed, or a start
// that lost the race): Stopped would hide a billed task, so the project
// is left in Error with its task ARN, which Stop and Start both use.
if let Err(ref e) = result {
log::error!("Failed to start container for project {}: {}", project_id, e);
let _ = state.projects_store.update_status(&project_id, ProjectStatus::Stopped);
let task_left = state
.projects_store
.get(&project_id)
.is_some_and(|p| aws_task_left_after_failed_start(&p));
let status = if task_left { ProjectStatus::Error } else { ProjectStatus::Stopped };
let _ = state.projects_store.update_status(&project_id, status);
if task_left {
return Err(format!(
"{e}\n\nThe workspace's task is still running on AWS. Start again to connect to \
it, or Stop to stop it."
));
}
}
let target = result?;
@@ -1318,6 +1455,21 @@ async fn start_project_container_locked(
// Update project with container info using granular methods (Issue 14: TOCTOU)
state.projects_store.set_container_id(&project_id, Some(container_id.clone()))?;
// AWS: the task's handles, store-owned like the container id. The target
// id stored above is the tunnel's endpoint URL, which is what the death
// watch reports a stopped task as.
if project.is_aws() {
if let Some((task_arn, access_point_id, task_definition_arn)) =
crate::host::tunnels::runtime(&project_id)
{
state.projects_store.set_aws_runtime(
&project_id,
Some(task_arn),
access_point_id,
Some(task_definition_arn),
)?;
}
}
state.projects_store.update_status(&project_id, ProjectStatus::Running)?;
// Arm the auth bridge if this project opted in. Purely host-side, so it
@@ -1342,9 +1494,10 @@ async fn start_project_container_locked(
#[tauri::command]
pub async fn stop_project_container(
project_id: String,
wip: Option<WipChoice>,
app_handle: tauri::AppHandle,
state: State<'_, AppState>,
) -> Result<(), String> {
) -> Result<Option<String>, String> {
// Stop had **no** exclusion at all, which is the one gap CLAUDE.md's "every
// command that stops, removes or recreates the container consults
// `is_migrating`" rule already named and this function did not honour. A
@@ -1358,12 +1511,84 @@ pub async fn stop_project_container(
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
// The stop guard asked, and meanwhile the workspace stopped by itself
// (idle stop, another window): what the user wanted has happened.
if project.is_aws() && wip.is_some() && project.status == ProjectStatus::Stopped {
return Ok(None);
}
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;
// AWS: the terminals and the auth bridge close *before* the stop guard's
// push, so nothing written after its snapshot is silently dropped (the
// entrypoint's hook skips its own push once `pushed` is recorded). A push
// that fails aborts the stop with the status as it was; the auth bridge
// is re-armed, and the error says the terminals were closed.
let mut note = None;
let guard_target = if project.is_aws() { ContainerTarget::for_project(&project) } else { None };
if project.is_aws() {
let close_first = async {
state.auth_bridge.stop(&project_id).await;
if let Some(container) = guard_target.as_ref() {
state.exec_manager.close_sessions_for_container(container.id()).await;
}
if wip == Some(WipChoice::Push) {
emit_progress(&app_handle, &project_id, "Pushing unsaved work...");
}
};
let guarded = aws_guard_before_stop(
&state.projects_store,
&project_id,
project.status.clone(),
guard_target.as_ref(),
wip,
super::stop_guard::PUSH_TIMEOUT,
close_first,
)
.await;
match guarded {
Ok(n) => note = n,
Err(e) => {
if project.auth_bridge_enabled {
if let Some(target) = guard_target.clone() {
state
.auth_bridge
.start(project_id.clone(), target, app_handle.clone(), state.projects_store.clone())
.await;
}
}
return Err(e);
}
}
} else {
// Drop host listeners first: they only make sense while the container runs.
state.auth_bridge.stop(&project_id).await;
}
if let Some(container) = ContainerTarget::for_project(&project) {
if project.is_aws() {
// A failed StopTask leaves a billed task running, so unlike Docker it
// is not papered over: the project keeps its status and the user
// sees why (expired SSO, typically), and can retry. Its terminals
// and auth bridge were closed before the stop guard's step above.
emit_progress(&app_handle, &project_id, "Stopping task...");
let settings = state.settings_store.get();
if let Err(e) = ProjectHost::for_project(&project).stop_project(&project, &settings).await {
log::warn!("Stop failed for project {}: {}", project_id, e);
// Still running: a later stop must push as configured again.
super::stop_guard::forget_choice(guard_target.as_ref(), wip).await;
let _ = state.projects_store.update_status(&project_id, project.status.clone());
return Err(format!("Could not stop the task: {e}"));
}
if let Some(a) = project.aws.as_ref() {
state.projects_store.set_aws_runtime(
&project_id,
None,
a.access_point_id.clone(),
a.task_definition_arn.clone(),
)?;
}
state.projects_store.set_container_id(&project_id, None)?;
} else if let Some(container) = ContainerTarget::for_project(&project) {
// Close exec sessions for this project
emit_progress(&app_handle, &project_id, "Stopping container...");
state.exec_manager.close_sessions_for_container(container.id()).await;
@@ -1374,6 +1599,127 @@ pub async fn stop_project_container(
}
state.projects_store.update_status(&project_id, ProjectStatus::Stopped)?;
Ok(note)
}
/// Appended to a failed stop-guard push: its terminals were closed first.
const TERMINALS_CLOSED_FOR_PUSH: &str =
"Its terminals were closed before the push, so nothing written after it could be lost; \
open them again to keep working.";
/// The AWS stop guard's step before StopTask ([`super::stop_guard::prepare_stop`]),
/// after `close_first` (the project's terminals and auth bridge): whatever
/// they write after the push's snapshot would otherwise be lost, since the
/// entrypoint's hook does not push again after `pushed`. A failed push puts
/// `previous` back, so the project's status is as it was.
async fn aws_guard_before_stop<R, F>(
store: &crate::storage::projects_store::ProjectsStore,
project_id: &str,
previous: ProjectStatus,
runner: Option<&R>,
wip: Option<WipChoice>,
push_timeout: std::time::Duration,
close_first: F,
) -> Result<Option<String>, String>
where
R: super::stop_guard::WipRunner,
F: std::future::Future<Output = ()>,
{
close_first.await;
match super::stop_guard::prepare_stop(runner, wip, push_timeout).await {
Ok(note) => Ok(note),
Err(e) => {
log::warn!("Project {}: WIP push before stop failed: {}", project_id, e);
let _ = store.update_status(project_id, previous);
Err(format!("{e}\n\n{TERMINALS_CLOSED_FOR_PUSH}"))
}
}
}
/// The stop guard's question: what would stopping this AWS workspace lose?
/// A local project (or a stopped one) has nothing to check.
#[tauri::command]
pub async fn check_unsaved_work(
project_id: String,
state: State<'_, AppState>,
) -> Result<UnsavedWork, String> {
let project = state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
if !project.is_aws() || project.status != ProjectStatus::Running {
return Ok(UnsavedWork { checked: true, ..Default::default() });
}
let target = ContainerTarget::for_project(&project);
Ok(super::stop_guard::unsaved_work(target.as_ref(), super::stop_guard::DRY_RUN_TIMEOUT).await)
}
/// The last `limit` (1–200) lines of the AWS project's current or last task's
/// log. Empty when there is no task to read (or the project is local).
#[tauri::command]
pub async fn aws_task_log(
project_id: String,
limit: u32,
state: State<'_, AppState>,
) -> Result<Vec<String>, String> {
let project = state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
if !project.is_aws() {
return Ok(Vec::new());
}
let settings = state.settings_store.get();
crate::host::aws_host::task_log(&project, &settings, limit.clamp(1, 200) as i32).await
}
/// Remove an AWS project's task definitions, secret and (with
/// `discard_data`) saved files, keeping the project, so it can move to
/// another host. Stopped projects only.
#[tauri::command]
pub async fn remove_aws_resources(
project_id: String,
discard_data: bool,
state: State<'_, AppState>,
) -> Result<Project, String> {
let _guard =
crate::project_lock::try_acquire(&project_id, crate::project_lock::ProjectOp::Destroy)?;
let project = state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
check_aws_resources_removable(&project)?;
let settings = state.settings_store.get();
ProjectHost::for_project(&project)
.remove_aws_resources(&project, &settings, discard_data)
.await?;
state
.projects_store
.set_aws_runtime(&project_id, None, access_point_after_removal(&project, discard_data), None)?;
state
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))
}
/// The access point a removal leaves stored: kept when the saved files were
/// kept (it is still there, a later start reuses it and a later removal
/// with `discard_data` deletes it; and while it is stored the project can't
/// move away from it — [`validate_aws_update`]), gone when they were not.
fn access_point_after_removal(project: &Project, discard_data: bool) -> Option<String> {
if discard_data {
return None;
}
project.aws.as_ref().and_then(|a| a.access_point_id.clone())
}
fn check_aws_resources_removable(project: &Project) -> Result<(), String> {
if !project.is_aws() {
return Err("This project does not run on AWS".into());
}
if project.status != ProjectStatus::Stopped {
return Err("Stop the project before removing its AWS resources".into());
}
Ok(())
}
@@ -1397,6 +1743,7 @@ pub async fn rebuild_project_container(
.projects_store
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
refuse_aws(&project, "Reset")?;
// Reset supersedes any migration decision that was still pending: the
// snapshot image and both volumes are about to go, so a surviving record
@@ -1472,6 +1819,44 @@ pub async fn rebuild_project_container(
/// [`crate::commands::migration_commands::reconcile_migration`]. The migration
/// pass runs over *every* project, not just the Running ones, because a project
/// whose container was removed mid-migration reports Stopped.
/// Removing an AWS project whose connection was deleted can't reach AWS:
/// refused unless the user confirmed leaving its resources behind.
/// Stable prefix of that refusal, so the UI can offer the second confirm
/// without matching prose. Mirrored by `AWS_CONNECTION_MISSING` in `lib/types.ts`.
pub const AWS_CONNECTION_MISSING: &str = "AWS_CONNECTION_MISSING: ";
fn missing_connection_removal(forget_aws_resources: bool) -> Result<(), String> {
if forget_aws_resources {
return Ok(());
}
Err(AWS_CONNECTION_MISSING.to_string()
+ "This project's AWS connection no longer exists, so its task (which may still be \
running and billed), secret and data can't be removed from here. Add the connection \
again in Settings → Hosts and remove the project, or confirm removing it while leaving \
those resources in AWS.")
}
/// After a failed start: an AWS project whose task ARN is still stored has
/// a task that may still be running (a start stops, and forgets, only a task
/// it ran itself).
fn aws_task_left_after_failed_start(project: &Project) -> bool {
project.is_aws() && project.aws.as_ref().is_some_and(|a| a.task_arn.is_some())
}
/// How long reconcile waits on AWS for one project.
const AWS_RECONCILE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
/// Refuse a Docker-only operation on an AWS project.
pub(crate) fn refuse_aws(project: &Project, what: &str) -> Result<(), String> {
if project.is_aws() {
return Err(format!(
"{what} is not available for a project that runs on AWS; it applies to local \
Docker containers only"
));
}
Ok(())
}
#[tauri::command]
pub async fn reconcile_project_statuses(
app_handle: tauri::AppHandle,
@@ -1479,7 +1864,7 @@ pub async fn reconcile_project_statuses(
) -> Result<Vec<Project>, String> {
let projects = state.projects_store.list();
for project in &projects {
for project in projects.iter().filter(|p| !p.is_aws()) {
crate::commands::migration_commands::reconcile_migration(project, &app_handle).await;
}
@@ -1513,6 +1898,12 @@ pub async fn reconcile_project_statuses(
continue;
}
// AWS projects are reconciled by `reconcile_aws_projects`, which the
// UI runs at startup whether or not Docker answers.
if project.is_aws() {
continue;
}
let is_running = if let Some(container) = ContainerTarget::for_project(project) {
container.is_running().await.unwrap_or(false)
} else {
@@ -1555,6 +1946,62 @@ pub async fn reconcile_project_statuses(
}
/// How many AWS projects reconcile at once.
const AWS_RECONCILE_CONCURRENCY: usize = 4;
/// Reconcile every AWS project against ECS (the authority), independently of
/// Docker: an app started without Docker still learns which tasks run and
/// re-opens their tunnels. One bounded DescribeTasks per project, a few at a
/// time; a live task's tunnel is re-opened in the background.
#[tauri::command]
pub async fn reconcile_aws_projects(state: State<'_, AppState>) -> Result<Vec<Project>, String> {
use futures_util::StreamExt;
let projects: Vec<Project> = state.projects_store.list().into_iter().filter(|p| p.is_aws()).collect();
// A target id left from the last run is a loopback URL whose port a new
// tunnel (any project's) may now own; until a re-attach registers, the
// project gets an id no tunnel can have (m9).
// A stopped mark a past unattached spell left on that id is forgotten
// first: reconcile asks ECS now, and a stale mark would make the death
// watch report a live, billed task as stopped.
for p in &projects {
if let Some(id) = crate::host::aws_host::prepare_unattached(p) {
let _ = state.projects_store.set_container_id(&p.id, Some(id));
}
}
let settings = state.settings_store.get();
let store = state.projects_store.clone();
futures_util::stream::iter(projects.into_iter().filter(|p| {
matches!(
p.status,
ProjectStatus::Running | ProjectStatus::Error | ProjectStatus::Starting | ProjectStatus::Stopping
) && crate::project_lock::held(&p.id).is_none()
}))
.for_each_concurrent(AWS_RECONCILE_CONCURRENCY, |project| {
let settings = settings.clone();
let store = store.clone();
async move {
// The store's current copy: the id above may have changed.
let project = store.get(&project.id).unwrap_or(project);
if tokio::time::timeout(
AWS_RECONCILE_TIMEOUT,
crate::host::aws_host::reconcile(&project, &settings, store),
)
.await
.is_err()
{
log::warn!(
"Project {}: AWS did not answer within {}s; status left as is",
project.id,
AWS_RECONCILE_TIMEOUT.as_secs()
);
}
}
})
.await;
Ok(state.projects_store.list())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2161,4 +2608,276 @@ mod tests {
assert_eq!(payload.marketplace_installs, stored.marketplace_installs);
assert_eq!(payload.marketplace_disabled, stored.marketplace_disabled);
}
#[test]
fn a_save_cannot_change_the_aws_runtime_handles() {
let (mut stored, mut payload) = stored_and_stale_payload();
let mut sc = crate::models::AwsWorkspaceConfig::default();
sc.task_arn = Some("arn:task".into());
sc.access_point_id = Some("fsap-1".into());
sc.task_definition_arn = Some("arn:td".into());
stored.aws = Some(sc.clone());
let mut pc = crate::models::AwsWorkspaceConfig::default();
pc.cpu = 2048;
pc.memory_mib = 8192;
pc.task_arn = Some("evil".into());
pc.access_point_id = None;
payload.aws = Some(pc);
restore_store_owned_fields(&mut payload, &stored);
let a = payload.aws.unwrap();
assert_eq!(a.task_arn, sc.task_arn);
assert_eq!(a.access_point_id, sc.access_point_id);
assert_eq!(a.task_definition_arn, sc.task_definition_arn);
assert_eq!(a.cpu, 2048, "the edit itself goes through");
}
fn host(id: &str) -> crate::models::HostConnection {
crate::models::HostConnection {
id: id.into(),
name: "n".into(),
kind: crate::models::HostKind::Aws {
auth: crate::models::AwsAuth::Profile { name: "p".into() },
default_region: "us-west-2".into(),
},
}
}
fn aws_project() -> Project {
let (mut p, _) = stored_and_stale_payload();
p.status = ProjectStatus::Stopped;
p.host_id = Some("h1".into());
p.aws_placement = Some(crate::models::AwsPlacement { region: "us-west-2".into(), environment: "dev".into() });
p.aws = Some(Default::default());
p
}
#[test]
fn host_update_rules() {
let hosts = vec![host("h1")];
let local = { let mut p = aws_project(); p.host_id = None; p.aws_placement = None; p.aws = None; p };
assert!(validate_aws_update(&local, &local, &hosts).is_ok());
let aws = aws_project();
assert!(validate_aws_update(&aws, &aws, &hosts).is_ok());
// moving a stopped project onto a host is fine
assert!(validate_aws_update(&local, &aws, &hosts).is_ok());
// unknown connection
assert!(validate_aws_update(&local, &aws, &[]).unwrap_err().contains("does not exist"));
// partial triple
let mut half = aws_project(); half.aws = None;
assert!(validate_aws_update(&aws, &half, &hosts).is_err());
let mut half = local.clone(); half.aws = Some(Default::default());
assert!(validate_aws_update(&local, &half, &hosts).is_err());
// bad region / environment / workspace
let mut bad = aws_project(); bad.aws_placement.as_mut().unwrap().region = "nope".into();
assert!(validate_aws_update(&aws, &bad, &hosts).is_err());
let mut bad = aws_project(); bad.aws_placement.as_mut().unwrap().environment = "Bad_Env".into();
assert!(validate_aws_update(&aws, &bad, &hosts).is_err());
let mut bad = aws_project(); bad.aws.as_mut().unwrap().cpu = 300;
assert!(validate_aws_update(&aws, &bad, &hosts).is_err());
// host/placement frozen while not stopped; other edits still fine
let mut running = aws_project(); running.status = ProjectStatus::Running;
let mut moved = running.clone(); moved.aws_placement.as_mut().unwrap().environment = "prod".into();
assert!(validate_aws_update(&running, &moved, &hosts).unwrap_err().contains("Stop the project"));
let mut moved = running.clone(); moved.host_id = None; moved.aws_placement = None; moved.aws = None;
assert!(validate_aws_update(&running, &moved, &hosts).is_err());
let mut edited = running.clone(); edited.aws.as_mut().unwrap().spot = true;
assert!(validate_aws_update(&running, &edited, &hosts).is_ok());
}
#[test]
fn a_removal_that_keeps_the_saved_files_keeps_their_access_point_and_the_project_in_place() {
let hosts = vec![host("h1")];
let mut stored = aws_project();
stored.aws.as_mut().unwrap().access_point_id = Some("fsap-1".into());
assert_eq!(access_point_after_removal(&stored, false), Some("fsap-1".into()));
assert_eq!(access_point_after_removal(&stored, true), None);
// What the store holds after a keep-the-files removal still blocks a move.
let mut after = stored.clone();
let a = after.aws.as_mut().unwrap();
a.task_arn = None;
a.task_definition_arn = None;
a.access_point_id = access_point_after_removal(&stored, false);
let mut local = after.clone();
local.host_id = None;
local.aws_placement = None;
local.aws = None;
let e = validate_aws_update(&after, &local, &hosts).unwrap_err();
assert!(e.contains("access point"), "{e}");
// After a discarding removal it can move.
after.aws.as_mut().unwrap().access_point_id = access_point_after_removal(&stored, true);
assert!(validate_aws_update(&after, &local, &hosts).is_ok());
}
#[test]
fn a_project_with_aws_resources_cannot_be_moved_off_its_host() {
let hosts = vec![host("h1"), host("h2")];
let mut stored = aws_project();
stored.aws.as_mut().unwrap().access_point_id = Some("fsap-1".into());
let mut local = stored.clone();
local.host_id = None;
local.aws_placement = None;
local.aws = None;
let e = validate_aws_update(&stored, &local, &hosts).unwrap_err();
assert!(e.contains("remove the workspace's AWS resources first"), "{e}");
let mut other = stored.clone();
other.host_id = Some("h2".into());
assert!(validate_aws_update(&stored, &other, &hosts).is_err());
let mut moved = stored.clone();
moved.aws_placement.as_mut().unwrap().environment = "prod".into();
assert!(validate_aws_update(&stored, &moved, &hosts).is_err());
for set in [
|a: &mut crate::models::AwsWorkspaceConfig| a.task_arn = Some("t".into()),
|a: &mut crate::models::AwsWorkspaceConfig| a.task_definition_arn = Some("td".into()),
] {
let mut st = aws_project();
set(st.aws.as_mut().unwrap());
assert!(validate_aws_update(&st, &local, &hosts).is_err());
}
// No handles: free to move. Other edits are fine with handles.
assert!(validate_aws_update(&aws_project(), &local, &hosts).is_ok());
let mut edited = stored.clone();
edited.aws.as_mut().unwrap().cpu = 2048;
edited.aws.as_mut().unwrap().memory_mib = 8192;
assert!(validate_aws_update(&stored, &edited, &hosts).is_ok());
}
#[test]
fn docker_only_operations_refuse_aws_projects() {
assert!(refuse_aws(&aws_project(), "Reset").unwrap_err().contains("Reset is not available"));
let mut local = aws_project();
local.host_id = None;
assert!(refuse_aws(&local, "Reset").is_ok());
}
#[test]
fn a_failed_start_with_a_task_left_running_is_not_stopped() {
let mut p = aws_project();
assert!(!aws_task_left_after_failed_start(&p));
p.aws.as_mut().unwrap().task_arn = Some("arn:aws:ecs:r:a:task/c/t".into());
assert!(aws_task_left_after_failed_start(&p));
let mut local = p.clone();
local.host_id = None;
assert!(!aws_task_left_after_failed_start(&local));
}
#[test]
fn removing_without_the_connection_needs_explicit_confirmation() {
let e = missing_connection_removal(false).unwrap_err();
assert!(e.contains("still be running") && e.contains("Settings → Hosts"), "{e}");
assert!(e.starts_with(AWS_CONNECTION_MISSING));
assert!(missing_connection_removal(true).is_ok());
// The frontend keys its second confirm on the same prefix.
let ts = include_str!("../../../src/lib/types.ts");
assert!(
ts.contains(&format!("export const AWS_CONNECTION_MISSING = {:?};", AWS_CONNECTION_MISSING)),
"lib/types.ts must mirror AWS_CONNECTION_MISSING"
);
}
fn stop_store(status: ProjectStatus) -> (tempfile::TempDir, crate::storage::projects_store::ProjectsStore, String) {
let mut p = aws_project();
p.status = status;
let dir = tempfile::tempdir().unwrap();
let store = crate::storage::projects_store::ProjectsStore::over_file_for_test(
dir.path().join("projects.json"),
vec![p.clone()],
);
(dir, store, p.id)
}
#[tokio::test]
async fn a_failed_push_before_stop_puts_the_status_back_and_records_nothing() {
use crate::commands::stop_guard::tests::Fake;
let (_d, store, id) = stop_store(ProjectStatus::Running);
store.update_status(&id, ProjectStatus::Stopping).unwrap();
let fake = Fake::new(Ok(("push to origin failed: denied".into(), 1)));
let e = aws_guard_before_stop(&store, &id, ProjectStatus::Running, Some(&fake), Some(WipChoice::Push), std::time::Duration::from_secs(5), async {})
.await
.unwrap_err();
assert!(e.contains("denied"), "{e}");
assert!(e.contains("terminals were closed"), "{e}");
assert_eq!(store.get(&id).unwrap().status, ProjectStatus::Running);
assert!(fake.markers.lock().unwrap().is_empty());
}
#[tokio::test]
async fn a_successful_push_before_stop_records_it_and_leaves_the_stop_going() {
use crate::commands::stop_guard::tests::Fake;
let (_d, store, id) = stop_store(ProjectStatus::Running);
store.update_status(&id, ProjectStatus::Stopping).unwrap();
let fake = Fake::new(Ok(("pushed".into(), 0)));
let note = aws_guard_before_stop(&store, &id, ProjectStatus::Running, Some(&fake), Some(WipChoice::Push), std::time::Duration::from_secs(5), async {})
.await
.unwrap();
assert_eq!(note, None);
assert_eq!(store.get(&id).unwrap().status, ProjectStatus::Stopping, "untouched: the stop goes on");
assert_eq!(*fake.markers.lock().unwrap(), vec!["pushed".to_string()]);
assert_eq!(fake.calls.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn the_terminals_close_before_the_stop_guard_pushes_or_records_anything() {
use crate::commands::stop_guard::tests::Fake;
for wip in [Some(WipChoice::Push), Some(WipChoice::Discard), None] {
let (_d, store, id) = stop_store(ProjectStatus::Running);
let fake = Fake::new(Ok(("pushed".into(), 0)));
let seen_at_close = std::sync::Mutex::new(None);
aws_guard_before_stop(&store, &id, ProjectStatus::Running, Some(&fake), wip, std::time::Duration::from_secs(5), async {
*seen_at_close.lock().unwrap() =
Some((fake.calls.lock().unwrap().len(), fake.markers.lock().unwrap().len()));
})
.await
.unwrap();
assert_eq!(*seen_at_close.lock().unwrap(), Some((0, 0)), "{wip:?}: closed first");
}
// Stop's own code closes them through that step, not after it.
let src = include_str!("project_commands.rs");
let stop = &src[src.find("pub async fn stop_project_container").unwrap()..];
let stop = &stop[..stop.find("\n}\n").unwrap()];
let close = stop.find("close_sessions_for_container").unwrap();
assert!(close < stop.find("aws_guard_before_stop(").unwrap());
assert!(stop.find("auth_bridge.stop").unwrap() < stop.find("aws_guard_before_stop(").unwrap());
}
#[test]
fn a_new_aws_project_takes_repos_not_folders_and_no_runtime_handles() {
let hosts = vec![host("h1")];
let place = || Some(AwsPlacement { region: "us-west-2".into(), environment: "dev".into() });
let cfg = AwsWorkspaceConfig {
task_arn: Some("arn:forged".into()),
access_point_id: Some("fsap-forged".into()),
repos: vec![crate::models::RepoSource { url: "https://h/r.git".into(), branch: None, folder: "r".into() }],
..Default::default()
};
let p = new_project("a".into(), vec![], Some("h1".into()), place(), Some(cfg.clone()), &hosts).unwrap();
assert!(p.is_aws() && p.paths.is_empty());
let a = p.aws.unwrap();
assert_eq!((a.task_arn, a.access_point_id, a.task_definition_arn), (None, None, None));
assert_eq!(a.repos.len(), 1);
// folders are refused, so are half placements, unknown hosts and invalid configs
let folder = vec![ProjectPath { host_path: "/x".into(), mount_name: "x".into() }];
assert!(new_project("a".into(), folder, Some("h1".into()), place(), Some(cfg.clone()), &hosts).is_err());
assert!(new_project("a".into(), vec![], Some("h1".into()), None, Some(cfg.clone()), &hosts).is_err());
assert!(new_project("a".into(), vec![], Some("nope".into()), place(), Some(cfg.clone()), &hosts).is_err());
let bad = AwsWorkspaceConfig { cpu: 256, memory_mib: 8192, ..Default::default() };
let e = new_project("a".into(), vec![], Some("h1".into()), place(), Some(bad), &hosts).unwrap_err();
assert!(e.contains("not valid"), "{e}");
// a local project still needs a folder
assert!(new_project("a".into(), vec![], None, None, None, &hosts).is_err());
}
#[test]
fn aws_resources_are_removable_only_from_a_stopped_aws_project() {
let mut p = aws_project();
assert!(check_aws_resources_removable(&p).is_ok());
p.status = ProjectStatus::Running;
assert!(check_aws_resources_removable(&p).unwrap_err().contains("Stop"));
p.status = ProjectStatus::Error;
assert!(check_aws_resources_removable(&p).is_err());
let mut local = aws_project();
local.host_id = None;
assert!(check_aws_resources_removable(&local).is_err());
}
}
+458
View File
@@ -0,0 +1,458 @@
//! The AWS stop guard: what `triple-c-wip-push` says about a workspace's
//! unsaved git work, and the push a Stop may run first.
//!
//! The decisions are made over [`WipRunner`] so a fake target exercises them;
//! [`ContainerTarget`] runs the script through the agent as `claude` (the
//! script needs the user's credential helper and `~/.ssh`).
use std::future::Future;
use std::time::Duration;
use crate::host::ContainerTarget;
use crate::models::{RepoState, UnsavedWork, WipChoice};
/// The script, baked into the image (`container/triple-c-wip-push`).
pub const WIP_PUSH: &str = "/usr/local/bin/triple-c-wip-push";
/// A dry run only reads `git status`; it should be quick.
pub const DRY_RUN_TIMEOUT: Duration = Duration::from_secs(30);
/// A push goes over the network, once per dirty repo.
pub const PUSH_TIMEOUT: Duration = Duration::from_secs(300);
/// Cap on the push output carried into an error.
const MAX_OUTPUT: usize = 4000;
/// How much sooner than the client's timeout the in-container `timeout`
/// ends the script (its TERM, then 5 s to the KILL): an exec the client gives
/// up on is not killed by the agent, so the container bounds it itself.
const IN_CONTAINER_MARGIN: Duration = Duration::from_secs(10);
/// Where the entrypoint's stop hook looks for the app's decision (Task 7's
/// file, which the idle watcher also writes `idle` to).
pub const STOP_REASON_FILE: &str = "/run/triple-c/stop-reason";
/// Recorded after the guard's push succeeded: the hook does not push again.
pub const MARKER_PUSHED: &str = "pushed";
/// Recorded for "Stop without pushing": the hook does not push.
pub const MARKER_DISCARD: &str = "discard";
/// The workspace, as the stop guard uses it.
pub trait WipRunner: Sync {
/// Run the WIP script as `claude`: `(combined output, exit code)`. The
/// caller waits at most `limit`; the run must not outlive it.
fn run(
&self,
args: Vec<String>,
limit: Duration,
) -> impl Future<Output = Result<(String, i64), String>> + Send;
/// Record `marker` in [`STOP_REASON_FILE`] (as root: the directory is root's).
fn write_stop_reason(&self, marker: &str) -> impl Future<Output = Result<(), String>> + Send;
/// Remove [`STOP_REASON_FILE`] (as root), so the hook pushes as configured again.
fn clear_stop_reason(&self) -> impl Future<Output = Result<(), String>> + Send;
}
impl WipRunner for ContainerTarget {
async fn run(&self, args: Vec<String>, limit: Duration) -> Result<(String, i64), String> {
self.exec_oneshot_as("claude", wip_command(args, limit), Vec::new()).await
}
async fn write_stop_reason(&self, marker: &str) -> Result<(), String> {
let (out, code) = self
.exec_oneshot_as("root", stop_reason_command(marker), Vec::new())
.await?;
if code == 0 {
Ok(())
} else {
Err(format!("exit {code}: {}", cap(&out)))
}
}
async fn clear_stop_reason(&self) -> Result<(), String> {
let (out, code) = self
.exec_oneshot_as("root", clear_stop_reason_command(), Vec::new())
.await?;
if code == 0 {
Ok(())
} else {
Err(format!("exit {code}: {}", cap(&out)))
}
}
}
/// The script's argv under coreutils `timeout`, ending it
/// [`IN_CONTAINER_MARGIN`] before the client's `limit` (KILL 5 s after the
/// TERM), so a push the app gave up on is not left running in the workspace.
pub fn wip_command(args: Vec<String>, limit: Duration) -> Vec<String> {
let secs = limit.saturating_sub(IN_CONTAINER_MARGIN).as_secs().max(1);
let mut cmd = vec![
"/usr/bin/timeout".to_string(),
"-k".to_string(),
"5".to_string(),
secs.to_string(),
WIP_PUSH.to_string(),
];
cmd.extend(args);
cmd
}
/// The root command that forgets a recorded marker (a fixed argv).
pub fn clear_stop_reason_command() -> Vec<String> {
vec!["rm".into(), "-f".into(), STOP_REASON_FILE.into()]
}
/// After StopTask failed: the workspace keeps running, so a marker this stop
/// recorded must not suppress the push of a later stop (Spot, ECS, idle) the
/// user never chose for. Best effort; logged.
pub async fn forget_choice<R: WipRunner>(runner: Option<&R>, choice: Option<WipChoice>) {
if choice.is_none() {
return;
}
let Some(r) = runner else {
log::warn!("Stop failed and the workspace is unreachable; its stop marker may remain");
return;
};
match tokio::time::timeout(DRY_RUN_TIMEOUT, r.clear_stop_reason()).await {
Ok(Ok(())) => {}
Ok(Err(e)) => log::warn!("Could not remove the stop marker after a failed stop: {e}"),
Err(_) => log::warn!("Removing the stop marker after a failed stop timed out"),
}
}
/// The root command that records `marker`; the value travels as `$1`, never
/// inside the script.
pub fn stop_reason_command(marker: &str) -> Vec<String> {
vec![
"sh".into(),
"-c".into(),
format!(
"umask 077 && mkdir -p /run/triple-c && chmod 700 /run/triple-c && printf '%s\\n' \"$1\" > {STOP_REASON_FILE}"
),
"sh".into(),
marker.into(),
]
}
/// The repository lines of a dry run. Lines that are not JSON objects (a
/// warning on stderr) are skipped; a JSON line of the wrong shape is an error.
pub fn parse_dry_run(output: &str) -> Result<Vec<RepoState>, String> {
output
.lines()
.map(str::trim)
.filter(|l| l.starts_with('{'))
.map(|l| {
serde_json::from_str::<RepoState>(l)
.map_err(|e| format!("Unexpected output from the WIP check: {e}"))
})
.collect()
}
fn unchecked(reason: String) -> UnsavedWork {
UnsavedWork { checked: false, repos: Vec::new(), error: Some(reason) }
}
/// Ask the workspace what a stop would lose. `runner` is `None` when the
/// workspace's agent is not reachable (no tunnel).
pub async fn unsaved_work<R: WipRunner>(runner: Option<&R>, timeout: Duration) -> UnsavedWork {
let Some(runner) = runner else {
return unchecked(
"Triple-C is not connected to the workspace, so it can't check for unsaved work."
.into(),
);
};
let res = tokio::time::timeout(timeout, runner.run(vec!["--dry-run".into()], timeout)).await;
match res {
Err(_) => unchecked("The workspace did not answer the check for unsaved work in time.".into()),
Ok(Err(e)) => unchecked(format!("The workspace could not be asked about unsaved work: {e}")),
Ok(Ok((out, code))) if code != 0 => unchecked(format!(
"The check for unsaved work failed (exit {code}): {}",
cap(&out)
)),
Ok(Ok((out, _))) => match parse_dry_run(&out) {
Ok(repos) => UnsavedWork { checked: true, repos, error: None },
Err(e) => unchecked(e),
},
}
}
fn cap(s: &str) -> String {
let t = s.trim();
if t.len() <= MAX_OUTPUT {
return t.to_string();
}
let mut end = t.len() - MAX_OUTPUT;
while !t.is_char_boundary(end) {
end += 1;
}
format!("…{}", &t[end..])
}
/// What Stop does before stopping, given the user's choice. `Push` runs the
/// push and fails (aborting the stop) with its output when it does not
/// succeed; `Discard` and no choice do nothing.
pub async fn before_stop<R: WipRunner>(
runner: Option<&R>,
choice: Option<WipChoice>,
timeout: Duration,
) -> Result<(), String> {
if choice != Some(WipChoice::Push) {
return Ok(());
}
let runner = runner.ok_or_else(|| {
"Triple-C is not connected to the workspace, so it can't push unsaved work. The \
workspace was not stopped."
.to_string()
})?;
let res =
tokio::time::timeout(timeout, runner.run(vec!["--reason".into(), "stop".into()], timeout)).await;
match res {
Err(_) => Err("Pushing unsaved work did not finish in time. The workspace was not stopped.".into()),
Ok(Err(e)) => Err(format!("Could not push unsaved work: {e}. The workspace was not stopped.")),
Ok(Ok((out, 0))) => {
log::info!("WIP push before stop: {}", cap(&out));
Ok(())
}
Ok(Ok((out, code))) => Err(format!(
"Pushing unsaved work failed (exit {code}), so the workspace was not stopped:\n{}",
cap(&out)
)),
}
}
/// The note a stop returns when the hook's own push may still run.
pub const MARKER_NOT_RECORDED: &str = "Triple-C could not tell the workspace what you chose, so its own \
push of work in progress on shutdown may still run (if it is turned on).";
/// Everything the guard does before StopTask: `Push` pushes (a failure is an
/// `Err` and the stop must not happen), then records `pushed`; `Discard`
/// records `discard`; no choice does nothing. A marker that can't be
/// written does not stop the stop: `Ok(Some(note))` says the hook may push.
pub async fn prepare_stop<R: WipRunner>(
runner: Option<&R>,
choice: Option<WipChoice>,
push_timeout: Duration,
) -> Result<Option<String>, String> {
let marker = match choice {
None => return Ok(None),
Some(WipChoice::Push) => {
before_stop(runner, choice, push_timeout).await?;
MARKER_PUSHED
}
Some(WipChoice::Discard) => MARKER_DISCARD,
};
let written = match runner {
Some(r) => tokio::time::timeout(DRY_RUN_TIMEOUT, r.write_stop_reason(marker))
.await
.unwrap_or_else(|_| Err("timed out".into())),
None => Err("not connected to the workspace".into()),
};
match written {
Ok(()) => Ok(None),
Err(e) => {
log::warn!("Could not record the stop guard's choice ({marker}): {e}");
Ok(Some(MARKER_NOT_RECORDED.to_string()))
}
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use std::sync::Mutex;
pub(crate) struct Fake {
pub reply: Result<(String, i64), String>,
pub calls: Mutex<Vec<Vec<String>>>,
pub hang: bool,
pub markers: Mutex<Vec<String>>,
pub marker_fails: bool,
}
impl Fake {
pub fn new(reply: Result<(String, i64), String>) -> Self {
Fake { reply, calls: Mutex::new(Vec::new()), hang: false, markers: Mutex::new(Vec::new()), marker_fails: false }
}
fn markers(&self) -> Vec<String> {
self.markers.lock().unwrap().clone()
}
fn calls(&self) -> Vec<Vec<String>> {
self.calls.lock().unwrap().clone()
}
}
impl WipRunner for Fake {
async fn run(&self, args: Vec<String>, _limit: Duration) -> Result<(String, i64), String> {
self.calls.lock().unwrap().push(args);
if self.hang {
std::future::pending::<()>().await;
}
self.reply.clone()
}
async fn write_stop_reason(&self, marker: &str) -> Result<(), String> {
if self.marker_fails {
return Err("agent unreachable".into());
}
self.markers.lock().unwrap().push(marker.to_string());
Ok(())
}
async fn clear_stop_reason(&self) -> Result<(), String> {
self.markers.lock().unwrap().push("<cleared>".to_string());
Ok(())
}
}
const T: Duration = Duration::from_secs(5);
#[test]
fn a_dry_run_is_parsed_skipping_non_json_lines() {
let out = "warning: something\n{\"folder\":\"api\",\"dirty\":true,\"unpushed\":0,\"branch\":\"main\"}\n\
{\"folder\":\"web\",\"dirty\":false,\"unpushed\":2,\"branch\":\"HEAD\"}\n";
let repos = parse_dry_run(out).unwrap();
assert_eq!(repos.len(), 2);
assert_eq!(repos[0], RepoState { folder: "api".into(), dirty: true, unpushed: 0, branch: "main".into(), cloning: false });
assert_eq!(repos[1].unpushed, 2);
assert!(parse_dry_run("{\"folder\":1}").is_err());
assert!(parse_dry_run("").unwrap().is_empty());
}
#[tokio::test]
async fn the_check_runs_a_dry_run_and_reports_the_repos() {
let fake = Fake::new(Ok(("{\"folder\":\"a\",\"dirty\":false,\"unpushed\":0,\"branch\":\"main\"}".into(), 0)));
let w = unsaved_work(Some(&fake), T).await;
assert!(w.checked && w.error.is_none());
assert_eq!(w.repos.len(), 1);
assert_eq!(fake.calls(), vec![vec!["--dry-run".to_string()]]);
}
#[tokio::test]
async fn an_unreachable_workspace_is_unchecked_with_a_reason() {
let w = unsaved_work::<Fake>(None, T).await;
assert!(!w.checked);
assert!(w.error.as_deref().unwrap().contains("not connected"));
let failing = Fake::new(Err("connection refused".into()));
let w = unsaved_work(Some(&failing), T).await;
assert!(!w.checked && w.error.unwrap().contains("connection refused"));
let nonzero = Fake::new(Ok(("boom".into(), 2)));
let w = unsaved_work(Some(&nonzero), T).await;
assert!(!w.checked && w.error.unwrap().contains("exit 2"));
}
#[tokio::test(start_paused = true)]
async fn a_check_that_hangs_times_out_unchecked() {
let mut fake = Fake::new(Ok((String::new(), 0)));
fake.hang = true;
let w = unsaved_work(Some(&fake), Duration::from_secs(1)).await;
assert!(!w.checked && w.error.unwrap().contains("in time"));
}
#[tokio::test]
async fn push_runs_the_script_with_reason_stop() {
let fake = Fake::new(Ok(("pushed".into(), 0)));
before_stop(Some(&fake), Some(WipChoice::Push), T).await.unwrap();
assert_eq!(fake.calls(), vec![vec!["--reason".to_string(), "stop".to_string()]]);
}
#[tokio::test]
async fn a_failed_push_aborts_with_its_output() {
let fake = Fake::new(Ok(("triple-c-wip-push: api: push to origin failed: denied".into(), 1)));
let e = before_stop(Some(&fake), Some(WipChoice::Push), T).await.unwrap_err();
assert!(e.contains("push to origin failed: denied"), "{e}");
assert!(e.contains("not stopped"));
let gone = Fake::new(Err("tunnel closed".into()));
assert!(before_stop(Some(&gone), Some(WipChoice::Push), T).await.unwrap_err().contains("tunnel closed"));
assert!(before_stop::<Fake>(None, Some(WipChoice::Push), T).await.is_err());
}
#[tokio::test]
async fn discard_or_no_choice_runs_nothing() {
let fake = Fake::new(Err("must not run".into()));
before_stop(Some(&fake), Some(WipChoice::Discard), T).await.unwrap();
before_stop(Some(&fake), None, T).await.unwrap();
before_stop::<Fake>(None, None, T).await.unwrap();
assert!(fake.calls().is_empty());
}
#[test]
fn the_script_is_bounded_inside_the_workspace_before_the_client_gives_up() {
let cmd = wip_command(vec!["--reason".into(), "stop".into()], PUSH_TIMEOUT);
assert_eq!(cmd, vec!["/usr/bin/timeout", "-k", "5", "290", WIP_PUSH, "--reason", "stop"]);
let secs: u64 = cmd[3].parse().unwrap();
assert!(secs + 5 < PUSH_TIMEOUT.as_secs(), "TERM and KILL land before the client's timeout");
let dry = wip_command(vec!["--dry-run".into()], DRY_RUN_TIMEOUT);
assert_eq!(&dry[3..], &["20", WIP_PUSH, "--dry-run"]);
assert_eq!(wip_command(Vec::new(), Duration::from_secs(3))[3], "1", "never 0 (no limit)");
// The image has coreutils' timeout where the argv says.
let df = include_str!("../../../../container/Dockerfile");
assert!(df.contains("ubuntu:24.04") || df.contains("ubuntu:noble"), "coreutils at /usr/bin");
}
#[test]
fn a_cloning_repo_parses_with_its_flag_and_older_lines_without_it() {
let out = "{\"folder\":\"half\",\"dirty\":false,\"unpushed\":0,\"branch\":\"\",\"cloning\":true}\n\
{\"folder\":\"a\",\"dirty\":true,\"unpushed\":0,\"branch\":\"main\"}";
let repos = parse_dry_run(out).unwrap();
assert!(repos[0].cloning && !repos[1].cloning);
}
#[test]
fn long_output_keeps_its_end() {
let s = format!("{}END", "x".repeat(10_000));
let c = cap(&s);
assert!(c.ends_with("END") && c.len() < 4100);
}
#[tokio::test]
async fn a_successful_push_records_pushed_and_stop_without_pushing_records_discard() {
let fake = Fake::new(Ok(("pushed".into(), 0)));
assert_eq!(prepare_stop(Some(&fake), Some(WipChoice::Push), T).await.unwrap(), None);
assert_eq!(fake.markers(), vec![MARKER_PUSHED]);
let fake = Fake::new(Err("must not run".into()));
assert_eq!(prepare_stop(Some(&fake), Some(WipChoice::Discard), T).await.unwrap(), None);
assert!(fake.calls().is_empty());
assert_eq!(fake.markers(), vec![MARKER_DISCARD]);
assert_eq!(prepare_stop(Some(&fake), None, T).await.unwrap(), None);
assert_eq!(fake.markers().len(), 1, "no choice records nothing");
}
#[tokio::test]
async fn a_failed_push_records_nothing() {
let fake = Fake::new(Ok(("denied".into(), 1)));
assert!(prepare_stop(Some(&fake), Some(WipChoice::Push), T).await.is_err());
assert!(fake.markers().is_empty());
}
#[tokio::test]
async fn an_unwritable_marker_still_stops_and_says_the_hook_may_push() {
let mut fake = Fake::new(Ok((String::new(), 0)));
fake.marker_fails = true;
let note = prepare_stop(Some(&fake), Some(WipChoice::Discard), T).await.unwrap();
assert!(note.unwrap().contains("may still run"));
let note = prepare_stop::<Fake>(None, Some(WipChoice::Discard), T).await.unwrap();
assert!(note.is_some());
}
#[test]
fn the_marker_is_written_as_an_argument_to_the_file_the_hook_reads() {
let cmd = stop_reason_command("pushed");
assert_eq!(&cmd[..2], &["sh".to_string(), "-c".to_string()]);
assert!(cmd[2].contains("> /run/triple-c/stop-reason") && cmd[2].contains("\"$1\""));
assert_eq!(cmd.last().unwrap(), "pushed");
// The entrypoint matches exactly these values.
let ep = include_str!("../../../../container/entrypoint.sh");
assert!(ep.contains("pushed|discard)") && ep.contains(STOP_REASON_FILE));
}
#[tokio::test]
async fn a_failed_stop_forgets_the_recorded_choice() {
let fake = Fake::new(Ok((String::new(), 0)));
prepare_stop(Some(&fake), Some(WipChoice::Discard), T).await.unwrap();
forget_choice(Some(&fake), Some(WipChoice::Discard)).await;
assert_eq!(fake.markers(), vec![MARKER_DISCARD, "<cleared>"]);
// An unguarded stop recorded nothing, so there is nothing to forget.
let fake = Fake::new(Ok((String::new(), 0)));
forget_choice(Some(&fake), None).await;
assert!(fake.markers().is_empty());
forget_choice::<Fake>(None, Some(WipChoice::Push)).await;
assert_eq!(clear_stop_reason_command(), vec!["rm", "-f", "/run/triple-c/stop-reason"]);
}
}
@@ -160,7 +160,9 @@ pub async fn open_terminal_session(
.get(&project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
let target = ContainerTarget::for_project(&project)
// Waits while an AWS project's tunnel is being re-opened after a restart.
let target = ContainerTarget::for_project_waiting(&project)
.await
.ok_or_else(|| "Container not running".to_string())?;
if let Some(id) = resume_session_id.as_deref() {
+140 -9
View File
@@ -32,6 +32,7 @@ use serde::Serialize;
use tauri::{AppHandle, Emitter};
use tokio::sync::watch;
use crate::aws::tasks::StopKind;
use crate::host::watch::ExitSource;
use crate::host::ContainerTarget;
use crate::models::{Project, ProjectStatus};
@@ -68,6 +69,32 @@ pub enum ExitReason {
pub struct ContainerExited<'a> {
pub project: &'a Project,
pub reason: ExitReason,
/// AWS: why ECS says the task stopped (P8). `None` on Docker, or when
/// the watch has no reason on record.
pub stop: Option<StopNote>,
}
/// Why an AWS task stopped, for the UI's toast.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StopNote {
/// `spot`, `idle`, `failed` (the project goes to Error), `user` (someone
/// stopped it: no toast) or `exited` (on its own).
pub kind: &'static str,
/// ECS's stopped reason, or a fixed text.
pub message: Option<String>,
}
impl StopNote {
pub fn of(kind: &StopKind) -> StopNote {
let (kind, message) = match kind {
StopKind::Spot => ("spot", Some("Spot interruption".to_string())),
StopKind::Idle => ("idle", None),
StopKind::FailedToStart(r) => ("failed", Some(r.clone())),
StopKind::UserInitiated => ("user", None),
StopKind::Exited(r) => ("exited", r.clone()),
};
StopNote { kind, message }
}
}
fn project_busy(project_id: &str) -> bool {
@@ -143,11 +170,11 @@ async fn unless_cancelled<T>(
/// (see [`STABLE_AFTER`]).
async fn watch_once(
store: &ProjectsStore,
source: &ExitSource,
cancel: &mut watch::Receiver<bool>,
sweep_reason: ExitReason,
on_change: &impl Fn(&Project, ExitReason),
) -> Option<bool> {
let source = ExitSource::Docker;
if !unless_cancelled(cancel, source.reachable()).await? {
return Some(false);
}
@@ -187,6 +214,7 @@ async fn watch_once(
/// test can drive it without a Tauri app.
pub(crate) async fn run(
store: Arc<ProjectsStore>,
source: ExitSource,
mut cancel: watch::Receiver<bool>,
on_change: impl Fn(&Project, ExitReason),
) {
@@ -197,7 +225,7 @@ pub(crate) async fn run(
let mut sweep_reason = ExitReason::FoundStopped;
let mut failures: u32 = 0;
loop {
let Some(healthy) = watch_once(&store, &mut cancel, sweep_reason, &on_change).await else {
let Some(healthy) = watch_once(&store, &source, &mut cancel, sweep_reason, &on_change).await else {
return;
};
sweep_reason = ExitReason::Exited;
@@ -209,21 +237,59 @@ pub(crate) async fn run(
}
}
/// Start the watcher for the life of the app.
/// Start a watcher on `source` for the life of the app. One per host kind:
/// Docker's event stream, and (Task 6) the AWS task poll.
pub fn spawn(
app: AppHandle,
store: Arc<ProjectsStore>,
source: ExitSource,
cancel: watch::Receiver<bool>,
) -> tauri::async_runtime::JoinHandle<()> {
tauri::async_runtime::spawn(async move {
run(store, cancel, |p, reason| {
let store_for_aws = store.clone();
run(store, source, cancel, move |p, reason| {
log::warn!(
"Project '{}' ({}): its container stopped without the app asking ({:?}) — marking Stopped",
p.name,
p.id,
reason
);
let _ = app.emit(CONTAINER_EXITED_EVENT, ContainerExited { project: p, reason });
// Why ECS stopped it, read before the tunnel (and with it the
// registry's record) goes.
let kind = p
.is_aws()
.then(|| p.container_id.as_deref().and_then(crate::host::tunnels::stop_kind))
.flatten();
let mut shown = p.clone();
// A task that never got going is an error, not a stop (P8).
if let Some(StopKind::FailedToStart(_)) = kind {
if store_for_aws.update_status(&p.id, ProjectStatus::Error).is_ok() {
shown.status = ProjectStatus::Error;
}
}
// An AWS task that stopped: its tunnel leads nowhere now, and its
// task ARN is history (the data's access point stays).
if p.is_aws() {
if let Some(a) = p.aws.as_ref() {
let _ = store_for_aws.set_aws_runtime(
&p.id,
None,
a.access_point_id.clone(),
a.task_definition_arn.clone(),
);
}
let id = p.id.clone();
if let Some(arn) = p.aws.as_ref().and_then(|a| a.task_arn.clone()) {
tauri::async_runtime::spawn(async move {
crate::host::tunnels::close_if_task(&id, &arn).await
});
}
}
if let Some(store_p) = store_for_aws.get(&p.id) {
shown = store_p;
}
let stop = kind.as_ref().map(StopNote::of);
let _ = app.emit(CONTAINER_EXITED_EVENT, ContainerExited { project: &shown, reason, stop });
})
.await;
})
@@ -244,15 +310,38 @@ mod tests {
#[test]
fn the_event_says_why_so_the_ui_can_tell_news_from_housekeeping() {
let p = Project::new("demo".to_string(), Vec::new());
let v = serde_json::to_value(ContainerExited { project: &p, reason: ExitReason::Exited }).unwrap();
let v = serde_json::to_value(ContainerExited { project: &p, reason: ExitReason::Exited, stop: None })
.unwrap();
assert_eq!(v["reason"], "exited");
assert_eq!(v["project"]["name"], "demo");
let v = serde_json::to_value(ContainerExited { project: &p, reason: ExitReason::FoundStopped })
.unwrap();
assert!(v["stop"].is_null());
let v = serde_json::to_value(ContainerExited {
project: &p,
reason: ExitReason::FoundStopped,
stop: Some(StopNote::of(&StopKind::Spot)),
})
.unwrap();
assert_eq!(v["reason"], "found_stopped");
assert_eq!(v["stop"], serde_json::json!({ "kind": "spot", "message": "Spot interruption" }));
assert_eq!(CONTAINER_EXITED_EVENT, "project-container-exited");
}
#[test]
fn every_stop_kind_has_a_note_for_the_ui() {
let cases = [
(StopKind::Spot, "spot", Some("Spot interruption")),
(StopKind::Idle, "idle", None),
(StopKind::FailedToStart("CannotPull".into()), "failed", Some("CannotPull")),
(StopKind::UserInitiated, "user", None),
(StopKind::Exited(Some("OOM".into())), "exited", Some("OOM")),
(StopKind::Exited(None), "exited", None),
];
for (k, kind, message) in cases {
let n = StopNote::of(&k);
assert_eq!((n.kind, n.message.as_deref()), (kind, message), "{k:?}");
}
}
/// The shutdown path: a host call that never answers (a wedged daemon)
/// must give way to cancellation at once, not hold teardown.
#[tokio::test]
@@ -270,6 +359,48 @@ mod tests {
assert_eq!(unless_cancelled(&mut rx, async { 1 }).await, None);
}
/// The AWS source drives the same loop: it is "reachable" without a
/// ping, polls its lookup every interval, and gives way to cancellation.
/// No project is Running, so nothing is confirmed (and nothing reaches
/// Docker or AWS).
#[tokio::test(start_paused = true)]
async fn an_aws_source_polls_its_lookup_until_cancelled() {
use crate::host::watch::{AwsTaskLookup, AwsWatch, TaskGroup, WatchedTask};
use futures_util::future::BoxFuture;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Lookup(AtomicUsize);
impl AwsTaskLookup for Lookup {
fn running_tasks(&self) -> Vec<WatchedTask> {
self.0.fetch_add(1, Ordering::SeqCst);
Vec::new()
}
fn stopped<'a>(
&'a self,
_: &'a TaskGroup,
_: &'a [String],
) -> BoxFuture<'a, Result<Vec<String>, String>> {
Box::pin(async { Ok(Vec::new()) })
}
}
let dir = std::env::temp_dir().join(format!("triple-c-watch-aws-{}", uuid::Uuid::new_v4().simple()));
std::fs::create_dir_all(&dir).unwrap();
let store = Arc::new(ProjectsStore::over_file_for_test(dir.join("projects.json"), Vec::new()));
let lookup = Arc::new(Lookup(AtomicUsize::new(0)));
let source = ExitSource::Aws(AwsWatch::every(lookup.clone(), Duration::from_secs(15)));
let (cancel_tx, cancel_rx) = watch::channel(false);
let watcher = tokio::spawn(run(store, source, cancel_rx, |_, _| panic!("nothing stopped")));
tokio::time::sleep(Duration::from_secs(46)).await;
assert_eq!(lookup.0.load(Ordering::SeqCst), 3);
let _ = cancel_tx.send(true);
tokio::time::timeout(Duration::from_secs(1), watcher)
.await
.expect("stops at once")
.unwrap();
std::fs::remove_dir_all(&dir).ok();
}
/// End to end against a real daemon: a Running project whose container is
/// killed from outside the app is flipped to Stopped and reported as a live
/// exit; one found already stopped on the first look is reported as such;
@@ -302,7 +433,7 @@ mod tests {
let (cancel_tx, cancel_rx) = watch::channel(false);
let (seen_tx, mut seen_rx) = tokio::sync::mpsc::unbounded_channel::<(String, ExitReason)>();
let watcher = tokio::spawn(run(store.clone(), cancel_rx, move |p, why| {
let watcher = tokio::spawn(run(store.clone(), ExitSource::Docker, cancel_rx, move |p, why| {
let _ = seen_tx.send((p.id.clone(), why));
}));
let first = tokio::time::timeout(Duration::from_secs(10), seen_rx.recv()).await;
File diff suppressed because it is too large. Load diff
+68 -329
View File
@@ -9,6 +9,7 @@ use sha2::{Sha256, Digest};
use super::ca_certs;
use super::client::get_docker;
use super::workspace_env::{workspace_env, WorkspaceEnvInputs};
use crate::models::AppSettings;
use crate::models::{Backend, BedrockAuthMethod, ClaudeCodeSettings, ContainerInfo, EnvVar, GlobalAwsSettings, GlobalLlamaCppSettings, GlobalOllamaSettings, GlobalOpenAiCompatibleSettings, PortMapping, Project, ProjectPath};
@@ -139,7 +140,7 @@ The user can click a file path in this terminal to open it in a viewer (while a
/// instructions, appending port mapping docs, and appending scheduler docs.
/// Used by both create_container() and container_needs_recreation() to ensure
/// the same value is produced in both paths.
fn build_claude_instructions(
pub(super) fn build_claude_instructions(
global_instructions: Option<&str>,
project_instructions: Option<&str>,
port_mappings: &[PortMapping],
@@ -244,7 +245,11 @@ pub(crate) const LABEL_SCRUB: &str = "triple-c.scrub";
/// cannot travel onto a snapshot. See the `LABEL` block in the Dockerfile.
pub(crate) const LABEL_BASE: &str = "triple-c.base";
const RESERVED_ENV_PREFIXES: &[&str] = &["ANTHROPIC_", "AWS_", "GIT_", "HOST_", "TRIPLE_C_"];
/// `TRIPLEC_` is the AWS workspace's own namespace (`TRIPLEC_HOST`,
/// `TRIPLEC_FILES`, `TRIPLEC_AGENT_TOKEN`, … — see `container/entrypoint.sh`):
/// a custom var there could switch a local container into AWS mode or forge
/// the inputs the entrypoint trusts.
const RESERVED_ENV_PREFIXES: &[&str] = &["ANTHROPIC_", "AWS_", "GIT_", "HOST_", "TRIPLE_C_", "TRIPLEC_"];
/// Exact env var names Triple-C manages itself. Not covered by
/// [`RESERVED_ENV_PREFIXES`] because they don't share those prefixes.
@@ -356,7 +361,7 @@ fn model_alias_fingerprint_part(
}
/// Whether `key` is an env var name Triple-C reserves for itself.
fn is_reserved_env_key(key: &str) -> bool {
pub(super) 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)
@@ -375,7 +380,7 @@ fn is_reserved_env_key(key: &str) -> bool {
///
/// Empty stays empty rather than becoming the hash of the empty string: an empty
/// label is how every other `triple-c.*` key says "nothing configured".
fn compute_env_fingerprint(custom_env_vars: &[EnvVar]) -> String {
pub(super) fn compute_env_fingerprint(custom_env_vars: &[EnvVar]) -> String {
let mut parts: Vec<String> = Vec::new();
for env_var in custom_env_vars {
let key = env_var.key.trim();
@@ -401,7 +406,7 @@ fn compute_env_fingerprint(custom_env_vars: &[EnvVar]) -> String {
///
/// 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)> {
pub(super) fn shared_claude_auth(project: &Project) -> Option<(String, String)> {
if project.backend != Backend::Anthropic || !project.use_shared_auth_token {
return None;
}
@@ -432,7 +437,7 @@ fn claude_token_label(project: &Project) -> String {
/// Merge global and per-project custom environment variables.
/// Per-project variables override global variables with the same key.
fn merge_custom_env_vars(global: &[EnvVar], project: &[EnvVar]) -> Vec<EnvVar> {
pub(super) fn merge_custom_env_vars(global: &[EnvVar], project: &[EnvVar]) -> Vec<EnvVar> {
let mut merged: std::collections::HashMap<String, EnvVar> = std::collections::HashMap::new();
for ev in global {
let key = ev.key.trim().to_string();
@@ -494,7 +499,7 @@ fn sha256_hex(input: &str) -> String {
/// Resolve a per-project string value with a global fallback. Returns `None`
/// when both are blank, otherwise the per-project value if set, else the global.
fn resolve_with_global<'a>(per_project: Option<&'a str>, global: Option<&'a str>) -> Option<&'a str> {
pub(super) fn resolve_with_global<'a>(per_project: Option<&'a str>, global: Option<&'a str>) -> Option<&'a str> {
let project_val = per_project.map(str::trim).filter(|s| !s.is_empty());
if project_val.is_some() {
return project_val;
@@ -659,7 +664,7 @@ fn compute_ports_fingerprint(port_mappings: &[PortMapping]) -> String {
/// to the global set and never turn a globally-enabled setting off. `None` at
/// project level means "inherit", which is now a state the project can
/// actually be in rather than the only state an off switch could produce.
fn merge_claude_code_settings(
pub(super) fn merge_claude_code_settings(
global: Option<&ClaudeCodeSettings>,
project: Option<&ClaudeCodeSettings>,
) -> Option<ClaudeCodeSettings> {
@@ -759,7 +764,7 @@ fn compute_claude_code_settings_fingerprint(
///
/// The other two are documented as "set to `1` to …" with no meaning attached
/// to `0`, so `0` is unambiguously neutral and is stated outright.
fn claude_code_env_vars(settings: Option<&ClaudeCodeSettings>) -> Vec<String> {
pub(super) fn claude_code_env_vars(settings: Option<&ClaudeCodeSettings>) -> Vec<String> {
let owned;
let s = match settings {
Some(s) => s,
@@ -822,7 +827,7 @@ fn claude_code_env_vars(settings: Option<&ClaudeCodeSettings>) -> Vec<String> {
///
/// Returns a `String` rather than an `Option<String>`: there is no longer any
/// input for which this produces nothing to say.
fn build_claude_code_settings_json(
pub(super) fn build_claude_code_settings_json(
settings: Option<&ClaudeCodeSettings>,
sandbox_enabled: bool,
) -> String {
@@ -1080,7 +1085,7 @@ type VpnHostConfigParts = (
/// `MISSION_CONTROL_ENABLED` twenty lines above shows the failure this avoids —
/// it is pushed only when true, so a snapshot's baked `=1` survives the toggle
/// going off.
fn vpn_env_var(enabled: bool) -> String {
pub(super) fn vpn_env_var(enabled: bool) -> String {
format!("VPN_SUPPORT_ENABLED={}", u8::from(enabled))
}
@@ -1266,212 +1271,24 @@ pub async fn create_container(
log::debug!("Skipping HOST_UID/HOST_GID on Windows — Docker Desktop's Linux VM handles user mapping");
}
if let Some(ref token) = project.git_token {
env_vars.push(format!("GIT_TOKEN={}", token));
}
// Per-project git user overrides global defaults
let effective_git_name = project.git_user_name.as_deref().or(default_git_user_name);
let effective_git_email = project.git_user_email.as_deref().or(default_git_user_email);
if let Some(name) = effective_git_name {
env_vars.push(format!("GIT_USER_NAME={}", name));
}
if let Some(email) = effective_git_email {
env_vars.push(format!("GIT_USER_EMAIL={}", email));
}
// Bedrock configuration
if project.backend == Backend::Bedrock {
if let Some(ref bedrock) = project.bedrock_config {
env_vars.push("CLAUDE_CODE_USE_BEDROCK=1".to_string());
// AWS region: per-project overrides global
let region = if !bedrock.aws_region.is_empty() {
Some(bedrock.aws_region.clone())
} else {
global_aws.aws_region.clone()
};
if let Some(ref r) = region {
env_vars.push(format!("AWS_REGION={}", r));
}
match bedrock.auth_method {
BedrockAuthMethod::StaticCredentials => {
// Static/session credentials are NOT injected as env vars.
// They are written to ~/.aws/credentials by
// sync_bedrock_credentials() on every container
// start, so rotated/updated keys are picked up without a
// full container recreation (and never get baked into the
// snapshot image). The empty values set by the
// MANAGED_AUTH_KEYS neutralization pass below are ignored by
// the AWS SDK, which falls through to the credentials file.
}
BedrockAuthMethod::Profile => {
// Per-project profile overrides global
let profile = bedrock.aws_profile.as_ref()
.or(global_aws.aws_profile.as_ref());
if let Some(p) = profile {
env_vars.push(format!("AWS_PROFILE={}", p));
}
env_vars.push("AWS_SSO_AUTH_REFRESH_CMD=triple-c-sso-refresh".to_string());
}
BedrockAuthMethod::BearerToken => {
if let Some(ref token) = bedrock.aws_bearer_token {
env_vars.push(format!("AWS_BEARER_TOKEN_BEDROCK={}", token));
}
}
}
if let Some(model) = resolve_with_global(
bedrock.model_id.as_deref(),
global_aws.default_model_id.as_deref(),
) {
env_vars.push(format!("ANTHROPIC_MODEL={}", model));
}
if bedrock.disable_prompt_caching {
env_vars.push("DISABLE_PROMPT_CACHING=1".to_string());
}
if let Some(ref tier) = bedrock.service_tier {
let trimmed = tier.trim();
if !trimmed.is_empty() {
env_vars.push(format!("ANTHROPIC_BEDROCK_SERVICE_TIER={}", trimmed));
}
}
}
}
// ── Custom-endpoint backends ─────────────────────────────────────────────
// Ollama, llama.cpp and the OpenAI-Compatible gateway all point Claude Code
// at a non-Anthropic server via ANTHROPIC_BASE_URL. Each resolves its model
// id here; the model-alias vars are emitted once below, from
// `alias_model` / `alias_haiku`, so the three backends cannot drift apart.
let mut alias_model: Option<String> = None;
let mut alias_haiku: Option<String> = None;
// Ollama configuration
if project.backend == Backend::Ollama {
if let Some(ref ollama) = project.ollama_config {
if let Some(url) = resolve_with_global(
Some(&ollama.base_url),
global_ollama.base_url.as_deref(),
) {
env_vars.push(format!("ANTHROPIC_BASE_URL={}", url));
}
env_vars.push("ANTHROPIC_AUTH_TOKEN=ollama".to_string());
if let Some(model) = resolve_with_global(
ollama.model_id.as_deref(),
global_ollama.default_model_id.as_deref(),
) {
env_vars.push(format!("ANTHROPIC_MODEL={}", model));
alias_model = Some(model.to_string());
}
alias_haiku = resolve_with_global(
ollama.haiku_model_id.as_deref(),
global_ollama.default_haiku_model_id.as_deref(),
)
.map(str::to_string);
}
}
// llama.cpp (llama-server) configuration
if project.backend == Backend::LlamaCpp {
if let Some(ref cfg) = project.llamacpp_config {
if let Some(url) = resolve_with_global(
Some(&cfg.base_url),
global_llamacpp.base_url.as_deref(),
) {
env_vars.push(format!("ANTHROPIC_BASE_URL={}", url));
}
// llama-server only enforces an Authorization header when it was
// started with `--api-key` (default: none), so the value here is
// ignored in the common case. Claude Code still refuses to run
// against a custom base URL with no credential at all, so a
// placeholder is always sent — same trick as the Ollama branch
// above, which sends the literal "ollama".
env_vars.push("ANTHROPIC_AUTH_TOKEN=llama.cpp".to_string());
if let Some(model) = resolve_with_global(
cfg.model_id.as_deref(),
global_llamacpp.default_model_id.as_deref(),
) {
env_vars.push(format!("ANTHROPIC_MODEL={}", model));
alias_model = Some(model.to_string());
}
alias_haiku = resolve_with_global(
cfg.haiku_model_id.as_deref(),
global_llamacpp.default_haiku_model_id.as_deref(),
)
.map(str::to_string);
}
}
// OpenAI Compatible configuration
if project.backend == Backend::OpenAiCompatible {
if let Some(ref config) = project.openai_compatible_config {
if let Some(url) = resolve_with_global(
Some(&config.base_url),
global_openai_compatible.base_url.as_deref(),
) {
env_vars.push(format!("ANTHROPIC_BASE_URL={}", url));
}
if let Some(ref key) = config.api_key {
env_vars.push(format!("ANTHROPIC_AUTH_TOKEN={}", key));
}
if let Some(model) = resolve_with_global(
config.model_id.as_deref(),
global_openai_compatible.default_model_id.as_deref(),
) {
env_vars.push(format!("ANTHROPIC_MODEL={}", model));
alias_model = Some(model.to_string());
}
alias_haiku = resolve_with_global(
config.haiku_model_id.as_deref(),
global_openai_compatible.default_haiku_model_id.as_deref(),
)
.map(str::to_string);
}
}
// Model aliases — the fix for background Claude Code calls against a local
// server. Only for backends that talk to a custom endpoint: Anthropic and
// Bedrock reach servers that really do host the Anthropic model ids, so
// they keep Claude Code's own defaults. Anything not emitted here is
// blanked by the MANAGED_AUTH_KEYS pass below, so switching *away* from a
// custom endpoint clears the aliases out of the snapshot image too.
if project.backend.uses_custom_endpoint() {
for (key, value) in
compute_model_aliases(alias_model.as_deref(), alias_haiku.as_deref())
{
env_vars.push(format!("{}={}", key, value));
}
}
// 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.
// project). Read here — it lives in the keychain — and handed to
// `workspace_env`, which injects it before the neutralization pass.
let shared_claude = shared_claude_auth(project);
if let Some((ref token, _)) = shared_claude {
env_vars.push(format!("{}={}", CLAUDE_OAUTH_TOKEN_ENV, token));
if shared_claude.is_some() {
log::info!(
"Injecting the shared Claude authentication token into the container for project {}",
project.id
);
}
// ── Corporate CA certificates ───────────────────────────────────────────
// Resolved here (rather than down with the mounts) so the env vars land
// *before* the neutralization pass below and are seen as already-set.
// Corporate CA certificates, resolved here (not in `workspace_env`) because
// the mount below needs the same resolution.
//
// A bad path is a hard error, not a warning: behind a TLS-terminating
// proxy a container without the CA fails every HTTPS call — npm, pip, git,
// and Claude Code's own API requests — each in its own confusing way. One
// message naming the path is far kinder.
//
// The values are set here rather than exported by the entrypoint because a
// terminal session is a `docker exec`, which sees the container's
// configured env and nothing the entrypoint exported. Same lesson as
// `$BROWSER` and the URL relay shim.
let effective_ca_path =
resolve_with_global(project.ca_cert_path.as_deref(), default_ca_cert_path);
let resolved_ca = ca_certs::resolve(effective_ca_path)?;
@@ -1483,110 +1300,40 @@ pub async fn create_container(
project.id
);
}
for (key, value) in ca_certs::ca_env_vars(resolved_ca.as_ref()) {
env_vars.push(format!("{}={}", key, value));
}
// ── Neutralize stale backend auth env vars ──────────────────────────────
// When a project switches backends (e.g. Bedrock → Anthropic) the container
// is recreated *from a snapshot image* committed off the previous container,
// and `docker commit` copies that container's full ENV into the image. So
// any auth var set under the old backend (e.g. CLAUDE_CODE_USE_BEDROCK=1,
// AWS_PROFILE, a model alias) survives in the image ENV and stays active
// unless we explicitly override it at create time.
//
// This pass is about *staleness*, not secrecy. It fixes the container it is
// building and does nothing to the image, so it is not — and never was —
// a defence against a credential baked into a snapshot. That is
// `commit_container_snapshot`'s job, via SECRET_ENV_KEYS.
// Create-time env takes precedence over image ENV, so we set every managed
// auth key the *current* backend did NOT set to an empty value, clearing the
// stale baked-in one.
const MANAGED_AUTH_KEYS: &[&str] = &[
"CLAUDE_CODE_USE_BEDROCK",
"AWS_REGION",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_PROFILE",
"AWS_BEARER_TOKEN_BEDROCK",
"AWS_SSO_AUTH_REFRESH_CMD",
"ANTHROPIC_BASE_URL",
"ANTHROPIC_AUTH_TOKEN",
"ANTHROPIC_MODEL",
"DISABLE_PROMPT_CACHING",
"ANTHROPIC_BEDROCK_SERVICE_TIER",
// Switching from a custom-endpoint backend to Anthropic or Bedrock must
// *clear* the aliases, not merely stop setting them: a stale
// ANTHROPIC_DEFAULT_HAIKU_MODEL baked into the snapshot image would
// keep pointing background calls at a model id the new backend has
// never heard of.
ANTHROPIC_DEFAULT_OPUS_MODEL,
ANTHROPIC_DEFAULT_SONNET_MODEL,
ANTHROPIC_DEFAULT_HAIKU_MODEL,
ANTHROPIC_DEFAULT_FABLE_MODEL,
// 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,
];
// Same reasoning for the CA vars — `ca_env_vars` already emits them empty
// when no CA is configured, so this list is belt-and-braces for a snapshot
// committed by a build that predates the feature.
let managed_keys: Vec<&str> = MANAGED_AUTH_KEYS
.iter()
.copied()
.chain(ca_certs::CA_ENV_KEYS.iter().copied())
.collect();
let already_set: std::collections::HashSet<String> = env_vars
.iter()
.filter_map(|e| e.split('=').next().map(|k| k.to_string()))
.collect();
for key in &managed_keys {
if !already_set.contains(*key) {
env_vars.push(format!("{}=", key));
}
}
// Everything project-shaped (backend auth, CA vars, custom env, instructions,
// Claude Code settings, ...) comes from the one host-neutral builder, so the
// AWS host can put the same pairs in its secret.
env_vars.extend(
workspace_env(
project,
&WorkspaceEnvInputs {
global_aws,
global_ollama,
global_llamacpp,
global_openai_compatible,
global_claude_instructions,
global_custom_env_vars,
timezone,
global_claude_code_settings,
default_git_user_name,
default_git_user_email,
resolved_ca: resolved_ca.as_ref(),
shared_claude_token: shared_claude.as_ref().map(|(token, _)| token.as_str()),
},
)
.into_iter()
.map(|(key, value)| format!("{}={}", key, value)),
);
// 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);
for env_var in &merged_env {
let key = env_var.key.trim();
if key.is_empty() {
continue;
}
if is_reserved_env_key(key) {
log::warn!("Skipping reserved env var: {}", key);
continue;
}
env_vars.push(format!("{}={}", key, env_var.value));
}
let custom_env_fingerprint = compute_env_fingerprint(&merged_env);
env_vars.push(format!("TRIPLE_C_CUSTOM_ENV={}", custom_env_fingerprint));
// Container timezone
if let Some(tz) = timezone {
if !tz.is_empty() {
env_vars.push(format!("TZ={}", tz));
}
}
// Mission Control env var
if project.mission_control_enabled {
env_vars.push("MISSION_CONTROL_ENABLED=1".to_string());
}
env_vars.push(vpn_env_var(project.vpn_support_enabled));
// 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()
// The labels below fingerprint the inputs that went into the env; derive
// them with the same helpers `workspace_env` used, so both always agree.
let effective_git_name = project.git_user_name.as_deref().or(default_git_user_name);
let effective_git_email = project.git_user_email.as_deref().or(default_git_user_email);
let custom_env_fingerprint = compute_env_fingerprint(&merge_custom_env_vars(
global_custom_env_vars,
&project.custom_env_vars,
));
// Claude instructions (global + per-project, plus port mapping info + scheduler docs)
let combined_instructions = build_claude_instructions(
global_claude_instructions,
project.claude_instructions.as_deref(),
@@ -1594,34 +1341,10 @@ pub async fn create_container(
project.mission_control_enabled,
project.sandbox_mode_enabled,
);
if let Some(ref instructions) = combined_instructions {
env_vars.push(format!("CLAUDE_INSTRUCTIONS={}", instructions));
}
// Claude Code settings (global + per-project merged)
let merged_cc_settings = merge_claude_code_settings(
global_claude_code_settings,
project.claude_code_settings.as_ref(),
);
// Env-var-based settings, read directly by Claude Code. Extracted and unit
// tested for the `vpn_host_config` reason: a container is created once, by
// a very long function, and a variable emitted with the wrong value here is
// invisible until someone wonders why a switch does nothing.
env_vars.extend(claude_code_env_vars(merged_cc_settings.as_ref()));
// settings.json-based settings (applied by the entrypoint). Always emitted,
// even with no `ClaudeCodeSettings` struct present: the payload asserts the
// *whole* managed key set, so "no settings" still has to be stated over a
// settings.json left behind on the config volume by a previous config.
// Split so the payload is safe under an older entrypoint that has never
// heard of the null-means-delete convention — see
// `split_claude_code_settings_payload`.
let (cc_settings_set, cc_settings_clear) = split_claude_code_settings_payload(
&build_claude_code_settings_json(merged_cc_settings.as_ref(), project.sandbox_mode_enabled),
);
env_vars.push(format!("CLAUDE_CODE_SETTINGS_JSON={}", cc_settings_set));
env_vars.push(format!("CLAUDE_CODE_SETTINGS_CLEAR={}", cc_settings_clear));
let mut mounts: Vec<Mount> = Vec::new();
@@ -4377,6 +4100,22 @@ mod tests {
assert_eq!(vpn_env_var(false), "VPN_SUPPORT_ENABLED=0");
}
#[test]
fn the_aws_workspace_namespace_is_reserved_from_custom_env() {
for key in ["TRIPLEC_HOST", "TRIPLEC_FILES", "TRIPLEC_AGENT_TOKEN", "triplec_repos", "TRIPLEC_ANYTHING"] {
assert!(is_reserved_env_key(key), "{key}");
}
assert_eq!(
compute_env_fingerprint(&[EnvVar {
key: "TRIPLEC_HOST".to_string(),
value: "aws".to_string(),
}]),
"",
"a reserved key never reaches the container"
);
assert!(!is_reserved_env_key("TRIPLECX"));
}
#[test]
fn the_vpn_skill_flag_is_reserved_from_custom_env() {
// entrypoint.sh installs and removes the pia-vpn skill from this
+4
View File
@@ -17,6 +17,8 @@ const AUDIO_SHIM: &str = include_str!("../../../../container/audio-shim");
const SSO_REFRESH: &str = include_str!("../../../../container/triple-c-sso-refresh");
const TRIPLE_C_OPEN: &str = include_str!("../../../../container/triple-c-open");
const PLAYWRIGHT_HEAL: &str = include_str!("../../../../container/triple-c-playwright-heal");
const WIP_PUSH: &str = include_str!("../../../../container/triple-c-wip-push");
const IDLE_WATCH: &str = include_str!("../../../../container/triple-c-idle-watch");
static MISSION_CONTROL_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../../container/mission-control");
static SKILLS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../../container/skills");
@@ -245,6 +247,8 @@ fn create_build_context() -> Result<Vec<u8>, std::io::Error> {
append_file_to_archive(&mut archive, "triple-c-sso-refresh", SSO_REFRESH.as_bytes(), 0o755)?;
append_file_to_archive(&mut archive, "triple-c-open", TRIPLE_C_OPEN.as_bytes(), 0o755)?;
append_file_to_archive(&mut archive, "triple-c-playwright-heal", PLAYWRIGHT_HEAL.as_bytes(), 0o755)?;
append_file_to_archive(&mut archive, "triple-c-wip-push", WIP_PUSH.as_bytes(), 0o755)?;
append_file_to_archive(&mut archive, "triple-c-idle-watch", IDLE_WATCH.as_bytes(), 0o755)?;
append_embedded_dir(&mut archive, &MISSION_CONTROL_DIR, "mission-control")?;
append_embedded_dir(&mut archive, &SKILLS_DIR, "skills")?;
+3
View File
@@ -2,12 +2,15 @@ pub mod ca_certs;
pub mod client;
pub mod events;
pub mod container;
pub mod workspace_env;
pub mod image;
pub mod exec;
pub mod gateway;
pub mod legacy_cleanup;
pub mod migration;
pub mod stt;
#[cfg(all(test, unix))]
mod aws_mode_tests;
/// The container user `claude`'s home directory, as the image creates it.
pub(crate) const CONTAINER_HOME: &str = "/home/claude";
+699
View File
@@ -0,0 +1,699 @@
//! The container environment a project gets, built once for every host.
//!
//! Docker passes these pairs as the container's `Env`; the AWS host stores the
//! very same pairs in a per-project Secrets Manager secret. Both therefore call
//! [`workspace_env`], so a backend, a CA bundle or a custom variable cannot
//! reach one host and not the other.
//!
//! What is *not* here: `COLORTERM`, `HOST_UID` and `HOST_GID` (host-specific,
//! assembled by `create_container`), and anything that needs the host — the
//! corporate CA is resolved from disk and the shared Claude token read from
//! the keychain by the caller, then handed in through [`WorkspaceEnvInputs`].
//! Order is part of the contract: it is the order `docker inspect` shows.
use super::ca_certs::{self, ResolvedCa};
use super::container::{
build_claude_code_settings_json, build_claude_instructions, claude_code_env_vars,
compute_env_fingerprint, compute_model_aliases, is_reserved_env_key, merge_claude_code_settings,
merge_custom_env_vars, resolve_with_global, split_claude_code_settings_payload, vpn_env_var,
ANTHROPIC_DEFAULT_FABLE_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL, ANTHROPIC_DEFAULT_OPUS_MODEL,
ANTHROPIC_DEFAULT_SONNET_MODEL, CLAUDE_OAUTH_TOKEN_ENV,
};
use crate::models::{
Backend, BedrockAuthMethod, ClaudeCodeSettings, EnvVar, GlobalAwsSettings,
GlobalLlamaCppSettings, GlobalOllamaSettings, GlobalOpenAiCompatibleSettings, Project,
};
/// Everything besides the project that shapes its environment.
pub(crate) struct WorkspaceEnvInputs<'a> {
pub global_aws: &'a GlobalAwsSettings,
pub global_ollama: &'a GlobalOllamaSettings,
pub global_llamacpp: &'a GlobalLlamaCppSettings,
pub global_openai_compatible: &'a GlobalOpenAiCompatibleSettings,
pub global_claude_instructions: Option<&'a str>,
pub global_custom_env_vars: &'a [EnvVar],
pub timezone: Option<&'a str>,
pub global_claude_code_settings: Option<&'a ClaudeCodeSettings>,
pub default_git_user_name: Option<&'a str>,
pub default_git_user_email: Option<&'a str>,
/// The corporate CA, already resolved from disk (`ca_certs::resolve`).
pub resolved_ca: Option<&'a ResolvedCa>,
/// The shared Claude OAuth token, already read from the keychain and
/// already filtered by `shared_claude_auth` (backend, opt-out, non-blank).
pub shared_claude_token: Option<&'a str>,
}
/// `"KEY=VALUE"` to a pair, splitting at the first `=` (values may contain `=`).
fn split_pair(entry: &str) -> (String, String) {
match entry.split_once('=') {
Some((k, v)) => (k.to_string(), v.to_string()),
None => (entry.to_string(), String::new()),
}
}
/// The `KEY=VALUE` pairs a project's container gets, in order, excluding the
/// host-specific ones. See the module docs.
pub(crate) fn workspace_env(
project: &Project,
inputs: &WorkspaceEnvInputs,
) -> Vec<(String, String)> {
let WorkspaceEnvInputs {
global_aws,
global_ollama,
global_llamacpp,
global_openai_compatible,
global_claude_instructions,
global_custom_env_vars,
timezone,
global_claude_code_settings,
default_git_user_name,
default_git_user_email,
resolved_ca,
shared_claude_token,
} = *inputs;
let mut env: Vec<(String, String)> = Vec::new();
if let Some(ref token) = project.git_token {
env.push(("GIT_TOKEN".to_string(), token.to_string()));
}
// Per-project git user overrides global defaults
let effective_git_name = project.git_user_name.as_deref().or(default_git_user_name);
let effective_git_email = project.git_user_email.as_deref().or(default_git_user_email);
if let Some(name) = effective_git_name {
env.push(("GIT_USER_NAME".to_string(), name.to_string()));
}
if let Some(email) = effective_git_email {
env.push(("GIT_USER_EMAIL".to_string(), email.to_string()));
}
// Bedrock configuration
if project.backend == Backend::Bedrock {
if let Some(ref bedrock) = project.bedrock_config {
env.push(("CLAUDE_CODE_USE_BEDROCK".to_string(), "1".to_string()));
// AWS region: per-project overrides global
let region = if !bedrock.aws_region.is_empty() {
Some(bedrock.aws_region.clone())
} else {
global_aws.aws_region.clone()
};
if let Some(ref r) = region {
env.push(("AWS_REGION".to_string(), r.to_string()));
}
match bedrock.auth_method {
BedrockAuthMethod::StaticCredentials => {
// Static/session credentials are NOT injected as env vars.
// They are written to ~/.aws/credentials by
// sync_bedrock_credentials() on every container
// start, so rotated/updated keys are picked up without a
// full container recreation (and never get baked into the
// snapshot image). The empty values set by the
// MANAGED_AUTH_KEYS neutralization pass below are ignored by
// the AWS SDK, which falls through to the credentials file.
}
BedrockAuthMethod::Profile => {
// Per-project profile overrides global
let profile = bedrock.aws_profile.as_ref()
.or(global_aws.aws_profile.as_ref());
if let Some(p) = profile {
env.push(("AWS_PROFILE".to_string(), p.to_string()));
}
env.push(("AWS_SSO_AUTH_REFRESH_CMD".to_string(), "triple-c-sso-refresh".to_string()));
}
BedrockAuthMethod::BearerToken => {
if let Some(ref token) = bedrock.aws_bearer_token {
env.push(("AWS_BEARER_TOKEN_BEDROCK".to_string(), token.to_string()));
}
}
}
if let Some(model) = resolve_with_global(
bedrock.model_id.as_deref(),
global_aws.default_model_id.as_deref(),
) {
env.push(("ANTHROPIC_MODEL".to_string(), model.to_string()));
}
if bedrock.disable_prompt_caching {
env.push(("DISABLE_PROMPT_CACHING".to_string(), "1".to_string()));
}
if let Some(ref tier) = bedrock.service_tier {
let trimmed = tier.trim();
if !trimmed.is_empty() {
env.push(("ANTHROPIC_BEDROCK_SERVICE_TIER".to_string(), trimmed.to_string()));
}
}
}
}
// ── Custom-endpoint backends ─────────────────────────────────────────────
// Ollama, llama.cpp and the OpenAI-Compatible gateway all point Claude Code
// at a non-Anthropic server via ANTHROPIC_BASE_URL. Each resolves its model
// id here; the model-alias vars are emitted once below, from
// `alias_model` / `alias_haiku`, so the three backends cannot drift apart.
let mut alias_model: Option<String> = None;
let mut alias_haiku: Option<String> = None;
// Ollama configuration
if project.backend == Backend::Ollama {
if let Some(ref ollama) = project.ollama_config {
if let Some(url) = resolve_with_global(
Some(&ollama.base_url),
global_ollama.base_url.as_deref(),
) {
env.push(("ANTHROPIC_BASE_URL".to_string(), url.to_string()));
}
env.push(("ANTHROPIC_AUTH_TOKEN".to_string(), "ollama".to_string()));
if let Some(model) = resolve_with_global(
ollama.model_id.as_deref(),
global_ollama.default_model_id.as_deref(),
) {
env.push(("ANTHROPIC_MODEL".to_string(), model.to_string()));
alias_model = Some(model.to_string());
}
alias_haiku = resolve_with_global(
ollama.haiku_model_id.as_deref(),
global_ollama.default_haiku_model_id.as_deref(),
)
.map(str::to_string);
}
}
// llama.cpp (llama-server) configuration
if project.backend == Backend::LlamaCpp {
if let Some(ref cfg) = project.llamacpp_config {
if let Some(url) = resolve_with_global(
Some(&cfg.base_url),
global_llamacpp.base_url.as_deref(),
) {
env.push(("ANTHROPIC_BASE_URL".to_string(), url.to_string()));
}
// llama-server only enforces an Authorization header when it was
// started with `--api-key` (default: none), so the value here is
// ignored in the common case. Claude Code still refuses to run
// against a custom base URL with no credential at all, so a
// placeholder is always sent — same trick as the Ollama branch
// above, which sends the literal "ollama".
env.push(("ANTHROPIC_AUTH_TOKEN".to_string(), "llama.cpp".to_string()));
if let Some(model) = resolve_with_global(
cfg.model_id.as_deref(),
global_llamacpp.default_model_id.as_deref(),
) {
env.push(("ANTHROPIC_MODEL".to_string(), model.to_string()));
alias_model = Some(model.to_string());
}
alias_haiku = resolve_with_global(
cfg.haiku_model_id.as_deref(),
global_llamacpp.default_haiku_model_id.as_deref(),
)
.map(str::to_string);
}
}
// OpenAI Compatible configuration
if project.backend == Backend::OpenAiCompatible {
if let Some(ref config) = project.openai_compatible_config {
if let Some(url) = resolve_with_global(
Some(&config.base_url),
global_openai_compatible.base_url.as_deref(),
) {
env.push(("ANTHROPIC_BASE_URL".to_string(), url.to_string()));
}
if let Some(ref key) = config.api_key {
env.push(("ANTHROPIC_AUTH_TOKEN".to_string(), key.to_string()));
}
if let Some(model) = resolve_with_global(
config.model_id.as_deref(),
global_openai_compatible.default_model_id.as_deref(),
) {
env.push(("ANTHROPIC_MODEL".to_string(), model.to_string()));
alias_model = Some(model.to_string());
}
alias_haiku = resolve_with_global(
config.haiku_model_id.as_deref(),
global_openai_compatible.default_haiku_model_id.as_deref(),
)
.map(str::to_string);
}
}
// Model aliases — the fix for background Claude Code calls against a local
// server. Only for backends that talk to a custom endpoint: Anthropic and
// Bedrock reach servers that really do host the Anthropic model ids, so
// they keep Claude Code's own defaults. Anything not emitted here is
// blanked by the MANAGED_AUTH_KEYS pass below, so switching *away* from a
// custom endpoint clears the aliases out of the snapshot image too.
if project.backend.uses_custom_endpoint() {
for (key, value) in
compute_model_aliases(alias_model.as_deref(), alias_haiku.as_deref())
{
env.push((key.to_string(), value));
}
}
// 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.
if let Some(token) = shared_claude_token {
env.push((CLAUDE_OAUTH_TOKEN_ENV.to_string(), token.to_string()));
}
// ── Corporate CA certificates ───────────────────────────────────────────
// Resolved here (rather than down with the mounts) so the env vars land
// *before* the neutralization pass below and are seen as already-set.
//
// A bad path is a hard error, not a warning: behind a TLS-terminating
// proxy a container without the CA fails every HTTPS call — npm, pip, git,
// and Claude Code's own API requests — each in its own confusing way. One
// message naming the path is far kinder.
//
// The values are set here rather than exported by the entrypoint because a
// terminal session is a `docker exec`, which sees the container's
// configured env and nothing the entrypoint exported. Same lesson as
// `$BROWSER` and the URL relay shim.
for (key, value) in ca_certs::ca_env_vars(resolved_ca) {
env.push((key.to_string(), value));
}
// ── Neutralize stale backend auth env vars ──────────────────────────────
// When a project switches backends (e.g. Bedrock → Anthropic) the container
// is recreated *from a snapshot image* committed off the previous container,
// and `docker commit` copies that container's full ENV into the image. So
// any auth var set under the old backend (e.g. CLAUDE_CODE_USE_BEDROCK=1,
// AWS_PROFILE, a model alias) survives in the image ENV and stays active
// unless we explicitly override it at create time.
//
// This pass is about *staleness*, not secrecy. It fixes the container it is
// building and does nothing to the image, so it is not — and never was —
// a defence against a credential baked into a snapshot. That is
// `commit_container_snapshot`'s job, via SECRET_ENV_KEYS.
// Create-time env takes precedence over image ENV, so we set every managed
// auth key the *current* backend did NOT set to an empty value, clearing the
// stale baked-in one.
const MANAGED_AUTH_KEYS: &[&str] = &[
"CLAUDE_CODE_USE_BEDROCK",
"AWS_REGION",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"AWS_SESSION_TOKEN",
"AWS_PROFILE",
"AWS_BEARER_TOKEN_BEDROCK",
"AWS_SSO_AUTH_REFRESH_CMD",
"ANTHROPIC_BASE_URL",
"ANTHROPIC_AUTH_TOKEN",
"ANTHROPIC_MODEL",
"DISABLE_PROMPT_CACHING",
"ANTHROPIC_BEDROCK_SERVICE_TIER",
// Switching from a custom-endpoint backend to Anthropic or Bedrock must
// *clear* the aliases, not merely stop setting them: a stale
// ANTHROPIC_DEFAULT_HAIKU_MODEL baked into the snapshot image would
// keep pointing background calls at a model id the new backend has
// never heard of.
ANTHROPIC_DEFAULT_OPUS_MODEL,
ANTHROPIC_DEFAULT_SONNET_MODEL,
ANTHROPIC_DEFAULT_HAIKU_MODEL,
ANTHROPIC_DEFAULT_FABLE_MODEL,
// 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,
];
// Same reasoning for the CA vars — `ca_env` already emits them empty
// when no CA is configured, so this list is belt-and-braces for a snapshot
// committed by a build that predates the feature.
let managed_keys: Vec<&str> = MANAGED_AUTH_KEYS
.iter()
.copied()
.chain(ca_certs::CA_ENV_KEYS.iter().copied())
.collect();
let already_set: std::collections::HashSet<String> =
env.iter().map(|(k, _)| k.clone()).collect();
for key in &managed_keys {
if !already_set.contains(*key) {
env.push((key.to_string(), String::new()));
}
}
// 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);
for env_var in &merged_env {
let key = env_var.key.trim();
if key.is_empty() {
continue;
}
if is_reserved_env_key(key) {
log::warn!("Skipping reserved env var: {}", key);
continue;
}
env.push((key.to_string(), env_var.value.clone()));
}
let custom_env_fingerprint = compute_env_fingerprint(&merged_env);
env.push(("TRIPLE_C_CUSTOM_ENV".to_string(), custom_env_fingerprint.to_string()));
// Container timezone
if let Some(tz) = timezone {
if !tz.is_empty() {
env.push(("TZ".to_string(), tz.to_string()));
}
}
// Mission Control env var
if project.mission_control_enabled {
env.push(("MISSION_CONTROL_ENABLED".to_string(), "1".to_string()));
}
env.push(split_pair(&vpn_env_var(project.vpn_support_enabled)));
// Permission mode — read by triple-c-task-runner for scheduled (headless)
// Claude Code runs. Interactive terminals get the flags directly instead.
env.push((
"TRIPLE_C_PERMISSION_MODE".to_string(),
project.effective_permission_mode().as_env_value().to_string(),
));
// Claude instructions (global + per-project, plus port mapping info + scheduler docs)
let combined_instructions = build_claude_instructions(
global_claude_instructions,
project.claude_instructions.as_deref(),
&project.port_mappings,
project.mission_control_enabled,
project.sandbox_mode_enabled,
);
if let Some(ref instructions) = combined_instructions {
env.push(("CLAUDE_INSTRUCTIONS".to_string(), instructions.to_string()));
}
// Claude Code settings (global + per-project merged)
let merged_cc_settings = merge_claude_code_settings(
global_claude_code_settings,
project.claude_code_settings.as_ref(),
);
// Env-var-based settings, read directly by Claude Code. Extracted and unit
// tested for the `vpn_host_config` reason: a container is created once, by
// a very long function, and a variable emitted with the wrong value here is
// invisible until someone wonders why a switch does nothing.
env.extend(
claude_code_env_vars(merged_cc_settings.as_ref())
.iter()
.map(|entry| split_pair(entry)),
);
// settings.json-based settings (applied by the entrypoint). Always emitted,
// even with no `ClaudeCodeSettings` struct present: the payload asserts the
// *whole* managed key set, so "no settings" still has to be stated over a
// settings.json left behind on the config volume by a previous config.
// Split so the payload is safe under an older entrypoint that has never
// heard of the null-means-delete convention — see
// `split_claude_code_settings_payload`.
let (cc_settings_set, cc_settings_clear) = split_claude_code_settings_payload(
&build_claude_code_settings_json(merged_cc_settings.as_ref(), project.sandbox_mode_enabled),
);
env.push(("CLAUDE_CODE_SETTINGS_JSON".to_string(), cc_settings_set.to_string()));
env.push(("CLAUDE_CODE_SETTINGS_CLEAR".to_string(), cc_settings_clear.to_string()));
env
}
/// [`workspace_env`] with its inputs resolved from `settings` exactly as
/// `create_container` resolves them (the CA from disk, the shared Claude
/// token from the keychain), for a host that does not create a Docker
/// container. Also returns the resolved CA, whose files the caller ships.
pub(crate) fn workspace_env_from_settings(
project: &Project,
settings: &crate::models::AppSettings,
) -> Result<crate::host::aws_host::AwsEnv, String> {
let shared_claude = super::container::shared_claude_auth(project);
let effective_ca_path =
resolve_with_global(project.ca_cert_path.as_deref(), settings.ca_cert_path.as_deref());
let resolved_ca = ca_certs::resolve(effective_ca_path)?;
let pairs = workspace_env(
project,
&WorkspaceEnvInputs {
global_aws: &settings.global_aws,
global_ollama: &settings.global_ollama,
global_llamacpp: &settings.global_llamacpp,
global_openai_compatible: &settings.global_openai_compatible,
global_claude_instructions: settings.global_claude_instructions.as_deref(),
global_custom_env_vars: &settings.global_custom_env_vars,
timezone: settings.timezone.as_deref(),
global_claude_code_settings: settings.global_claude_code_settings.as_ref(),
default_git_user_name: settings.default_git_user_name.as_deref(),
default_git_user_email: settings.default_git_user_email.as_deref(),
resolved_ca: resolved_ca.as_ref(),
shared_claude_token: shared_claude.as_ref().map(|(token, _)| token.as_str()),
},
);
Ok((pairs, resolved_ca))
}
#[cfg(test)]
mod tests {
use super::super::ca_certs::ResolvedCa;
use crate::models::*;
use std::path::PathBuf;
/// Every input the env block reads, owned, so a table row is one value.
pub(crate) struct Case {
pub name: &'static str,
pub project: Project,
pub global_aws: GlobalAwsSettings,
pub global_ollama: GlobalOllamaSettings,
pub global_llamacpp: GlobalLlamaCppSettings,
pub global_openai: GlobalOpenAiCompatibleSettings,
pub global_instructions: Option<&'static str>,
pub global_env: Vec<EnvVar>,
pub timezone: Option<&'static str>,
pub global_cc: Option<ClaudeCodeSettings>,
pub default_git_name: Option<&'static str>,
pub default_git_email: Option<&'static str>,
pub ca: Option<ResolvedCa>,
pub shared_token: Option<(String, String)>,
}
fn case(name: &'static str, project: Project) -> Case {
Case {
name,
project,
global_aws: GlobalAwsSettings::default(),
global_ollama: GlobalOllamaSettings::default(),
global_llamacpp: GlobalLlamaCppSettings::default(),
global_openai: GlobalOpenAiCompatibleSettings::default(),
global_instructions: None,
global_env: Vec::new(),
timezone: None,
global_cc: None,
default_git_name: None,
default_git_email: None,
ca: None,
shared_token: None,
}
}
fn proj(backend: Backend) -> Project {
let mut p = Project::new("demo".to_string(), Vec::new());
p.backend = backend;
p
}
fn bedrock(method: BedrockAuthMethod) -> BedrockConfig {
BedrockConfig {
auth_method: method,
aws_region: "us-east-1".into(),
aws_access_key_id: Some("AKIAFAKE".into()),
aws_secret_access_key: Some("secretfake".into()),
aws_session_token: None,
aws_profile: Some("proj-profile".into()),
aws_bearer_token: Some("bearerfake".into()),
model_id: Some("anthropic.claude-x".into()),
disable_prompt_caching: true,
service_tier: Some(" priority ".into()),
}
}
pub(crate) fn cases() -> Vec<Case> {
let mut v = Vec::new();
let mut c = case("anthropic_shared_token", proj(Backend::Anthropic));
c.shared_token = Some(("sk-shared-token".into(), "v7".into()));
v.push(c);
v.push(case("anthropic_plain", proj(Backend::Anthropic)));
let mut p = proj(Backend::Bedrock);
p.bedrock_config = Some(bedrock(BedrockAuthMethod::StaticCredentials));
let mut c = case("bedrock_static_keys", p);
c.global_aws.default_model_id = Some("global-model".into());
v.push(c);
let mut p = proj(Backend::Bedrock);
let mut b = bedrock(BedrockAuthMethod::Profile);
b.aws_region = String::new();
b.aws_profile = None;
b.model_id = None;
b.disable_prompt_caching = false;
b.service_tier = Some(" ".into());
p.bedrock_config = Some(b);
let mut c = case("bedrock_profile_global_fallbacks", p);
c.global_aws.aws_region = Some("eu-west-1".into());
c.global_aws.aws_profile = Some("global-profile".into());
c.global_aws.default_model_id = Some("global-model".into());
v.push(c);
let mut p = proj(Backend::Bedrock);
p.bedrock_config = Some(bedrock(BedrockAuthMethod::BearerToken));
v.push(case("bedrock_bearer", p));
let mut p = proj(Backend::Ollama);
p.ollama_config = Some(OllamaConfig {
base_url: "http://ollama.local:11434".into(),
model_id: Some("qwen3".into()),
haiku_model_id: None,
});
let mut c = case("ollama", p);
c.global_ollama.default_haiku_model_id = Some("tiny".into());
v.push(c);
let mut p = proj(Backend::LlamaCpp);
p.llamacpp_config = Some(LlamaCppConfig {
base_url: String::new(),
model_id: None,
haiku_model_id: Some("llama-small".into()),
});
let mut c = case("llamacpp_global_url", p);
c.global_llamacpp.base_url = Some("http://llama:8080".into());
c.global_llamacpp.default_model_id = Some("llama-big".into());
v.push(c);
let mut p = proj(Backend::OpenAiCompatible);
p.openai_compatible_config = Some(OpenAiCompatibleConfig {
base_url: "https://gw.example/v1".into(),
api_key: Some("sk-gateway".into()),
model_id: Some("gpt-x".into()),
haiku_model_id: Some("gpt-mini".into()),
});
v.push(case("openai_compatible", p));
let mut p = proj(Backend::Anthropic);
p.custom_env_vars = vec![
EnvVar { key: "FOO".into(), value: "project".into() },
EnvVar { key: " SPACED ".into(), value: "x y".into() },
EnvVar { key: "".into(), value: "dropped".into() },
EnvVar { key: "HOME".into(), value: "reserved".into() },
EnvVar { key: "CLAUDE_CODE_OAUTH_TOKEN".into(), value: "reserved".into() },
];
let mut c = case("custom_env", p);
c.global_env = vec![
EnvVar { key: "FOO".into(), value: "global".into() },
EnvVar { key: "BAR".into(), value: "b".into() },
];
v.push(c);
let mut p = proj(Backend::Anthropic);
p.claude_instructions = Some("project rules".into());
p.mission_control_enabled = true;
p.sandbox_mode_enabled = true;
p.port_mappings = vec![PortMapping {
host_port: 8080,
container_port: 3000,
protocol: "tcp".into(),
}];
let mut c = case("instructions_and_mission_control", p);
c.global_instructions = Some("global rules\nline two");
v.push(c);
let mut p = proj(Backend::Anthropic);
p.claude_code_settings = Some(ClaudeCodeSettings {
effort: Some("high".into()),
focus_mode: Some(false),
..Default::default()
});
let mut c = case("claude_code_settings", p);
c.global_cc = Some(ClaudeCodeSettings {
tui_mode: Some("fullscreen".into()),
env_scrub: Some(true),
prompt_caching_1h: Some(true),
..Default::default()
});
v.push(c);
let mut p = proj(Backend::Anthropic);
p.vpn_support_enabled = true;
p.git_token = Some("ghp_faketoken".into());
p.git_user_name = Some("Project User".into());
let mut c = case("vpn_git_timezone", p);
c.timezone = Some("Europe/Berlin");
c.default_git_name = Some("Default Name");
c.default_git_email = Some("default@example.com");
v.push(c);
let mut c = case("corporate_ca", proj(Backend::Anthropic));
c.ca = Some(ResolvedCa {
host_path: "/certs".into(),
is_dir: true,
mount_target: "/tmp/.host-ca".into(),
cert_files: vec![PathBuf::from("/certs/a.crt")],
});
v.push(c);
v
}
fn golden_path(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("src/docker/workspace_env_golden")
.join(format!("{name}.txt"))
}
/// `merge_custom_env_vars` collects a `HashMap`, so the custom variables
/// come out in a different order every run (before the extraction as
/// well). Sort that one run — between the last managed blank and the
/// fingerprint — so the rest of the order is still compared exactly.
fn normalise(mut env: Vec<String>) -> Vec<String> {
let end = env.iter().position(|e| e.starts_with("TRIPLE_C_CUSTOM_ENV=")).unwrap();
let start = env.iter().position(|e| e.starts_with("CLAUDE_CODE_OAUTH_TOKEN=")).unwrap() + 1;
env[start..end].sort();
env
}
/// The pre-refactor block's output, recorded before the extraction (see
/// `workspace_env_golden/`), must be reproduced exactly, order included.
#[test]
fn workspace_env_matches_what_create_container_built_before_the_extraction() {
for c in cases() {
let inputs = super::WorkspaceEnvInputs {
global_aws: &c.global_aws,
global_ollama: &c.global_ollama,
global_llamacpp: &c.global_llamacpp,
global_openai_compatible: &c.global_openai,
global_claude_instructions: c.global_instructions,
global_custom_env_vars: &c.global_env,
timezone: c.timezone,
global_claude_code_settings: c.global_cc.as_ref(),
default_git_user_name: c.default_git_name,
default_git_user_email: c.default_git_email,
resolved_ca: c.ca.as_ref(),
shared_claude_token: c.shared_token.as_ref().map(|(t, _)| t.as_str()),
};
let got: Vec<String> = super::workspace_env(&c.project, &inputs)
.into_iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
let want = std::fs::read_to_string(golden_path(c.name)).unwrap();
let want: Vec<String> = want
.lines()
.filter(|l| *l != "[" && *l != "]")
.map(|l| {
let l = l.trim().trim_end_matches(',');
serde_json::from_str::<String>(l).unwrap_or_else(|_| panic!("{l}"))
})
.collect();
assert_eq!(normalise(got), normalise(want), "case {}", c.name);
}
}
}
@@ -0,0 +1,33 @@
[
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_MODEL=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"CLAUDE_CODE_OAUTH_TOKEN=sk-shared-token",
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_MODEL=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"CLAUDE_CODE_USE_BEDROCK=1",
"AWS_REGION=us-east-1",
"AWS_BEARER_TOKEN_BEDROCK=bearerfake",
"ANTHROPIC_MODEL=anthropic.claude-x",
"DISABLE_PROMPT_CACHING=1",
"ANTHROPIC_BEDROCK_SERVICE_TIER=priority",
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"CLAUDE_CODE_USE_BEDROCK=1",
"AWS_REGION=eu-west-1",
"AWS_PROFILE=global-profile",
"AWS_SSO_AUTH_REFRESH_CMD=triple-c-sso-refresh",
"ANTHROPIC_MODEL=global-model",
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_BEARER_TOKEN_BEDROCK=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"CLAUDE_CODE_USE_BEDROCK=1",
"AWS_REGION=us-east-1",
"ANTHROPIC_MODEL=anthropic.claude-x",
"DISABLE_PROMPT_CACHING=1",
"ANTHROPIC_BEDROCK_SERVICE_TIER=priority",
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_MODEL=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=1",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1",
"ENABLE_PROMPT_CACHING_1H=1",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"effortLevel\":\"high\",\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false,\"tui\":\"fullscreen\"}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"NODE_EXTRA_CA_CERTS=/etc/ssl/certs/ca-certificates.crt",
"REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt",
"SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_MODEL=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,37 @@
[
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_MODEL=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"BAR=b",
"FOO=project",
"SPACED=x y",
"HOME=reserved",
"TRIPLE_C_CUSTOM_ENV=63ce864a8c48a386cb039d4878e3885d5a823d4bb52047ba0e18cb87b9f3035b",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,34 @@
[
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_MODEL=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"MISSION_CONTROL_ENABLED=1",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=global rules\nline two\n\n## Mission Control\n\nThe `/workspace/mission-control/` directory contains **Flight Control** — an AI-first development methodology for structured project management. Use it for all project work.\n\n### How It Works\n\n- **Mission Control is a tool, not a project.** It provides skills and methodology for managing other projects.\n- All Flight Control skills are installed as personal skills in `~/.claude/skills/` and are automatically available as `/slash-commands`\n- The methodology docs and project registry live in `/workspace/mission-control/`\n\n### When to Use\n\nWhen working on any project that has a `.flightops/` directory, follow the Flight Control methodology:\n1. Read the project's `.flightops/ARTIFACTS.md` to understand artifact storage\n2. Read `.flightops/FLIGHT_OPERATIONS.md` for the implementation workflow\n3. Use Mission Control skills for planning and execution\n\n### Available Skills\n\n| Skill | When to Use |\n|-------|-------------|\n| `/init-project` | Setting up a new project for Flight Control |\n| `/mission` | Defining new work outcomes (days-to-weeks scope) |\n| `/flight` | Creating technical specs from missions (hours-to-days scope) |\n| `/leg` | Generating implementation steps from flights (minutes-to-hours scope) |\n| `/agentic-workflow` | Executing legs with multi-agent workflow (implement, review, commit) |\n| `/flight-debrief` | Post-flight analysis after a flight lands |\n| `/mission-debrief` | Post-mission retrospective after completion |\n| `/daily-briefing` | Cross-project status report |\n\n### Key Rules\n\n- **Planning skills produce artifacts only** — never modify source code directly\n- **Phase gates require human confirmation** — missions before flights, flights before legs\n- **Legs are immutable once in-flight** — create new ones instead of modifying\n- **`/agentic-workflow` orchestrates implementation** — it spawns separate Developer and Reviewer agents\n- **Artifacts live in the target project** — not in mission-control\n\nproject rules\n\n## Flight Operations\n\nThis project uses **Flight Control** (bundled with Triple-C) for structured development.\n\n**Before any mission/flight/leg work, read these files in order:**\n1. `.flightops/README.md` — What the flightops directory contains\n2. `.flightops/FLIGHT_OPERATIONS.md` — **The workflow you MUST follow**\n3. `.flightops/ARTIFACTS.md` — Where all artifacts are stored\n4. `.flightops/agent-crews/` — Project crew definitions for each phase (read the relevant crew file)\n\n## Available Port Mappings\nThe following ports are mapped from the host to this container. Use these container ports when starting services that need to be accessible from the host:\n- Host port 8080 -> Container port 3000 (tcp)\n\n## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relLine truncated
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"allowUnsandboxedCommands\":false,\"enableWeakerNestedSandbox\":true,\"enabled\":true},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"ANTHROPIC_BASE_URL=http://llama:8080",
"ANTHROPIC_AUTH_TOKEN=llama.cpp",
"ANTHROPIC_MODEL=llama-big",
"ANTHROPIC_DEFAULT_OPUS_MODEL=llama-big",
"ANTHROPIC_DEFAULT_SONNET_MODEL=llama-big",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=llama-small",
"ANTHROPIC_DEFAULT_FABLE_MODEL=llama-big",
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"ANTHROPIC_BASE_URL=http://ollama.local:11434",
"ANTHROPIC_AUTH_TOKEN=ollama",
"ANTHROPIC_MODEL=qwen3",
"ANTHROPIC_DEFAULT_OPUS_MODEL=qwen3",
"ANTHROPIC_DEFAULT_SONNET_MODEL=qwen3",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=tiny",
"ANTHROPIC_DEFAULT_FABLE_MODEL=qwen3",
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,33 @@
[
"ANTHROPIC_BASE_URL=https://gw.example/v1",
"ANTHROPIC_AUTH_TOKEN=sk-gateway",
"ANTHROPIC_MODEL=gpt-x",
"ANTHROPIC_DEFAULT_OPUS_MODEL=gpt-x",
"ANTHROPIC_DEFAULT_SONNET_MODEL=gpt-x",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=gpt-mini",
"ANTHROPIC_DEFAULT_FABLE_MODEL=gpt-x",
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"VPN_SUPPORT_ENABLED=0",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
@@ -0,0 +1,37 @@
[
"GIT_TOKEN=ghp_faketoken",
"GIT_USER_NAME=Project User",
"GIT_USER_EMAIL=default@example.com",
"NODE_EXTRA_CA_CERTS=",
"REQUESTS_CA_BUNDLE=",
"SSL_CERT_FILE=",
"CLAUDE_CODE_USE_BEDROCK=",
"AWS_REGION=",
"AWS_ACCESS_KEY_ID=",
"AWS_SECRET_ACCESS_KEY=",
"AWS_SESSION_TOKEN=",
"AWS_PROFILE=",
"AWS_BEARER_TOKEN_BEDROCK=",
"AWS_SSO_AUTH_REFRESH_CMD=",
"ANTHROPIC_BASE_URL=",
"ANTHROPIC_AUTH_TOKEN=",
"ANTHROPIC_MODEL=",
"DISABLE_PROMPT_CACHING=",
"ANTHROPIC_BEDROCK_SERVICE_TIER=",
"ANTHROPIC_DEFAULT_OPUS_MODEL=",
"ANTHROPIC_DEFAULT_SONNET_MODEL=",
"ANTHROPIC_DEFAULT_HAIKU_MODEL=",
"ANTHROPIC_DEFAULT_FABLE_MODEL=",
"CLAUDE_CODE_OAUTH_TOKEN=",
"TRIPLE_C_CUSTOM_ENV=",
"TZ=Europe/Berlin",
"VPN_SUPPORT_ENABLED=1",
"TRIPLE_C_PERMISSION_MODE=default",
"CLAUDE_INSTRUCTIONS=## Scheduled Tasks\n\nThis container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents.\n\n### Commands\n- `triple-c-scheduler add --name \"NAME\" --schedule \"CRON\" --prompt \"TASK\"` — Add a recurring task\n- `triple-c-scheduler add --name \"NAME\" --at \"YYYY-MM-DD HH:MM\" --prompt \"TASK\"` — Add a one-time task\n- `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column\n- `triple-c-scheduler remove --id ID` — Remove a task\n- `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks\n- `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long\n- `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs\n- `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log)\n- `triple-c-scheduler notifications [--clear]` — View or clear completion notifications\n\n### Cron format\nStandard 5-field cron: `minute hour day-of-month month day-of-week`\nExamples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours)\n\n### One-time tasks\nUse `--at \"YYYY-MM-DD HH:MM\"` instead of `--schedule`. The task automatically removes itself after execution.\n\n### Working directory\nUse `--working-dir /workspace/project` to set where the task runs (default: /workspace).\n\n### Checking results\nWhile a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`.\n\n### Timezone\nScheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used.\n\n## Referring to files\n\nThe user can click a file path in this terminal to open it in a viewer (while a program holds the mouse: Shift+click, or Option+click on macOS). Paths relative to the project work. When you mention a file outside the project (for example in `/tmp`, including your scratchpad directory, or under `~`), print its full absolute path, not a shortened or relative one, so it can be opened.",
"CLAUDE_CODE_NO_FLICKER=",
"CLAUDE_CODE_ENABLE_AWAY_SUMMARY=",
"CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0",
"ENABLE_PROMPT_CACHING_1H=0",
"CLAUDE_CODE_SETTINGS_JSON={\"autoScrollEnabled\":true,\"sandbox\":{\"enabled\":false},\"showThinkingSummaries\":false}",
"CLAUDE_CODE_SETTINGS_CLEAR=[\"awaySummaryEnabled\",\"effortLevel\",\"tui\",\"viewMode\"]",
]
+3 -1
View File
@@ -51,8 +51,10 @@ pub async fn poll_file(
"poll".to_string(),
container_path.to_string(),
];
// A background poll: an open viewer must not keep an idle AWS workspace
// up. Opening and saving a file are the user's own actions and count.
let (stdout, stderr, code) = container
.exec_oneshot_streams_as("claude", cmd, Vec::new())
.exec_oneshot_streams_background("claude", cmd)
.await?;
if code != 0 && code != 4 {
return Err(format!(
+46 -8
View File
@@ -277,20 +277,35 @@ async fn exec_oneshot_raw(
cmd: Vec<String>,
env: Vec<String>,
limit: usize,
) -> Result<OneshotOutput, String> {
exec_oneshot_raw_marked(ep, user, cmd, env, limit, false).await
}
/// The agent's background marker (protocol spec, "Activity"): a request that
/// carries it never counts as activity for idle stop.
pub const BACKGROUND_HEADER: &str = "X-Triple-C-Background";
async fn exec_oneshot_raw_marked(
ep: &AgentEndpoint,
user: &str,
cmd: Vec<String>,
env: Vec<String>,
limit: usize,
background: bool,
) -> Result<OneshotOutput, String> {
const CONTEXT: &str = "Failed to start exec";
let spec = ExecSpec::new(cmd).user(user).working_dir(None).env(env).tty(false);
let mut body = spec_json(&spec);
body.insert("limit".into(), serde_json::json!(limit));
let resp = send(
CONTEXT,
http()
.post(ep.url("v1/exec"))
.header(reqwest::header::AUTHORIZATION, ep.auth())
.json(&body),
)
.await?;
let mut req = http()
.post(ep.url("v1/exec"))
.header(reqwest::header::AUTHORIZATION, ep.auth())
.json(&body);
if background {
req = req.header(BACKGROUND_HEADER, "1");
}
let resp = send(CONTEXT, req).await?;
let status = resp.status();
if status == reqwest::StatusCode::PAYLOAD_TOO_LARGE {
@@ -352,6 +367,18 @@ pub async fn exec_oneshot_limited(
Ok((out.text(), out.exit_code))
}
/// [`exec_oneshot_limited`] marked as a background poll, so it never keeps
/// an idle workspace up (the auth bridge's `/proc/net` reads).
pub async fn exec_oneshot_background(
ep: &AgentEndpoint,
user: &str,
cmd: Vec<String>,
limit: usize,
) -> Result<(String, i64), String> {
let out = exec_oneshot_raw_marked(ep, user, cmd, Vec::new(), limit, true).await?;
Ok((out.text(), out.exit_code))
}
/// `exec_oneshot_as`: combined output under [`MAX_ONESHOT_OUTPUT`].
pub async fn exec_oneshot_as(
ep: &AgentEndpoint,
@@ -373,6 +400,17 @@ pub async fn exec_oneshot_streams_as(
Ok((out.stdout(), out.stderr(), out.exit_code))
}
/// [`exec_oneshot_streams_as`] marked as a background poll (the file
/// viewer's change check), so it never keeps an idle workspace up.
pub async fn exec_oneshot_streams_background(
ep: &AgentEndpoint,
user: &str,
cmd: Vec<String>,
) -> Result<(String, String, i64), String> {
let out = exec_oneshot_raw_marked(ep, user, cmd, Vec::new(), MAX_ONESHOT_OUTPUT, true).await?;
Ok((out.stdout(), out.stderr(), out.exit_code))
}
// ── detached execs, status, resize ───────────────────────────────────────────
#[derive(Deserialize)]
+36 -1
View File
@@ -22,6 +22,8 @@ const TOKEN: &str = "fake-agent-token-for-unit-tests-only-0000";
struct Seen {
auth: Vec<String>,
exec_bodies: Vec<Value>,
/// The background marker of each `/v1/exec`, if any.
exec_background: Vec<Option<String>>,
detached_bodies: Vec<Value>,
status_polls: u32,
resizes: Vec<(String, Value)>,
@@ -62,7 +64,13 @@ async fn exec(State(f): St, h: HeaderMap, Json(body): Json<Value>) -> Response {
if !f.authed(&h) {
return unauthorized();
}
f.seen.lock().unwrap().exec_bodies.push(body.clone());
{
let mut seen = f.seen.lock().unwrap();
seen.exec_bodies.push(body.clone());
seen.exec_background.push(
h.get("x-triple-c-background").and_then(|v| v.to_str().ok()).map(str::to_string),
);
}
match body["cmd"][0].as_str().unwrap_or("") {
"sh" => Json(json!({"chunks": [{"s": "out", "d": b64(b"1000\n1001\n")}], "exit_code": 0}))
.into_response(),
@@ -304,6 +312,33 @@ async fn other_errors_carry_the_agents_message_and_no_token() {
assert_eq!(e, "Failed to start exec: boom");
}
#[tokio::test]
async fn only_a_background_poll_carries_the_background_marker() {
let (ep, fake) = fake_agent().await;
let t = target(&ep);
t.exec_oneshot_limited("claude", cmd("sh"), 1000).await.unwrap();
t.exec_oneshot_background("claude", cmd("sh"), 1000).await.unwrap();
let seen = fake.seen.lock().unwrap();
assert_eq!(seen.exec_background, [None, Some("1".to_string())]);
assert_eq!(seen.exec_bodies[0], seen.exec_bodies[1], "the request is otherwise the same");
}
#[tokio::test]
async fn the_file_viewers_poll_is_a_background_request_and_its_open_and_save_are_not() {
let (ep, fake) = fake_agent().await;
let t = target(&ep);
// The 2 s change check, as the viewer runs it.
let _ = crate::file_viewer::poll::poll_file(&t, "/workspace/x").await;
t.exec_oneshot_streams_background("claude", cmd("sh")).await.unwrap();
// What opening or saving goes through: user actions, which count.
t.exec_oneshot_streams_as("claude", cmd("sh"), Vec::new()).await.unwrap();
let seen = fake.seen.lock().unwrap();
assert_eq!(seen.exec_background, [Some("1".to_string()), Some("1".to_string()), None]);
let src = |s: &str| s.contains("exec_oneshot_streams_as(");
assert!(!src(include_str!("../../file_viewer/poll.rs")), "the poll stays a background request");
assert!(src(include_str!("../../file_viewer/resolve.rs")) && src(include_str!("../../file_viewer/write.rs")));
}
// ── one-shot execs ───────────────────────────────────────────────────────────
#[tokio::test]
File diff suppressed because it is too large. Load diff
+797
View File
@@ -0,0 +1,797 @@
use std::collections::HashMap;
use std::sync::atomic::AtomicUsize;
use std::sync::Mutex;
use aws_sdk_ecs::operation::register_task_definition::RegisterTaskDefinitionInput;
use aws_sdk_ecs::operation::run_task::RunTaskInput;
use super::*;
use crate::aws::environments::Knowable;
use crate::aws::tasks::TaskInfo;
use crate::aws::workspace::{AccessPointRef, FileSystemRef, TaskDefinitionRef};
use crate::aws::AwsError;
use crate::host::lifecycle::ProjectHost;
use crate::host::tunnels::tests::{fake_tunnel, FakeTunnel};
use crate::models::{AwsPlacement, AwsWorkspaceConfig, StorageMode};
const REGION: &str = "eu-west-1";
const ACCOUNT: &str = "111122223333";
const USER: &str = "AROAEXAMPLEID:alice@example.com";
fn who() -> CallerIdentity {
CallerIdentity {
account: ACCOUNT.into(),
arn: format!("arn:aws:sts::{ACCOUNT}:assumed-role/dev/alice"),
user_id: USER.into(),
}
}
fn aws_project(storage: StorageMode) -> Project {
let mut p = Project::new("aws".into(), Vec::new());
p.host_id = Some("c1".into());
p.aws_placement = Some(AwsPlacement { region: REGION.into(), environment: "dev".into() });
p.aws = Some(AwsWorkspaceConfig { storage, ..Default::default() });
p
}
fn family(p: &Project) -> String {
task_family("dev", &owner_key(REGION, USER), &p.id)
}
fn task_arn(id: &str) -> String {
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task/triple-c-dev/{id}")
}
fn cluster_arn() -> String {
format!("arn:aws:ecs:{REGION}:{ACCOUNT}:cluster/triple-c-dev")
}
fn task(p: &Project, id: &str, last: &str, ready: bool) -> TaskInfo {
TaskInfo {
arn: task_arn(id),
last_status: last.into(),
desired_status: if last == "STOPPED" { "STOPPED" } else { "RUNNING" }.into(),
health: None,
stop_code: (last == "STOPPED").then(|| "EssentialContainerExited".into()),
stopped_reason: (last == "STOPPED").then(|| "Essential container exited".into()),
task_definition_arn: format!("arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{}:1", family(p)),
runtime_id: ready.then(|| "rt-1".into()),
exec_agent_running: ready,
exit_code: None,
owner: Some(USER.into()),
project: Some(p.id.clone()),
}
}
fn record() -> String {
serde_json::json!({
"schema": 1, "name": "dev", "template_version": 1,
"cluster_arn": cluster_arn(),
"security_group_id": "sg-0123456789abcdef0",
"subnet_ids": ["subnet-0a", "subnet-0b"],
"assign_public_ip": true,
"kms_key_arn": format!("arn:aws:kms:{REGION}:{ACCOUNT}:key/1234-abcd"),
"log_group": "/triple-c/dev", "network_mode": "public", "tenancy": "strict"
})
.to_string()
}
/// One fake for all three AWS traits and the connector, logging calls.
#[derive(Default)]
struct Fake {
calls: Mutex<Vec<String>>,
/// ListTasks answers in turn; the last repeats.
listed: Mutex<Vec<Vec<String>>>,
tasks: Mutex<HashMap<String, TaskInfo>>,
/// What RunTask starts.
run: Option<TaskInfo>,
logs: Vec<String>,
role: Option<Knowable>,
connect_fails: bool,
connect_tokens: Mutex<Vec<String>>,
secret_json: Mutex<Option<String>>,
/// A losing start rotates the secret's token while this one connects.
rotated_by_loser: bool,
/// StopTask is refused (expired credentials, say).
stop_fails: bool,
/// What `on_task` was told, in order.
recorded: Mutex<Vec<Option<String>>>,
/// `group stream limit` of each log read.
log_reads: Mutex<Vec<String>>,
}
impl Fake {
fn log(&self, s: impl Into<String>) {
self.calls.lock().unwrap().push(s.into());
}
fn calls(&self) -> Vec<String> {
self.calls.lock().unwrap().clone()
}
fn called(&self, prefix: &str) -> bool {
self.calls().iter().any(|c| c.starts_with(prefix))
}
fn with_task(self, t: TaskInfo) -> Self {
self.tasks.lock().unwrap().insert(t.arn.clone(), t);
self
}
}
impl TaskApi for Fake {
async fn run_task(&self, _req: RunTaskInput) -> Result<TaskInfo, AwsError> {
self.log("run");
let t = self.run.clone().expect("a run was expected");
self.tasks.lock().unwrap().insert(t.arn.clone(), t.clone());
Ok(t)
}
async fn describe(&self, _c: &str, arns: &[String]) -> Result<Vec<TaskInfo>, AwsError> {
let t = self.tasks.lock().unwrap();
Ok(arns.iter().filter_map(|a| t.get(a).cloned()).collect())
}
async fn list_project_tasks(&self, _c: &str, _f: &str) -> Result<Vec<String>, AwsError> {
self.log("list");
let mut l = self.listed.lock().unwrap();
Ok(if l.len() > 1 { l.remove(0) } else { l.first().cloned().unwrap_or_default() })
}
async fn stop_task(&self, _c: &str, arn: &str, reason: &str) -> Result<(), AwsError> {
self.log(format!("stop {arn} {reason}"));
if self.stop_fails {
return Err(AwsError::Other { message: "ExpiredToken".into() });
}
Ok(())
}
async fn log_tail(&self, g: &str, st: &str, l: i32) -> Result<Vec<String>, AwsError> {
self.log_reads.lock().unwrap().push(format!("{g} {st} {l}"));
Ok(self.logs.clone())
}
}
impl WorkspaceApi for Fake {
async fn find_file_system(&self, _t: &str) -> Result<Option<FileSystemRef>, AwsError> {
Ok(Some(FileSystemRef { id: "fs-1".into(), owner: Some(USER.into()) }))
}
async fn access_points(&self, _fs: &str) -> Result<Vec<AccessPointRef>, AwsError> {
Ok(Vec::new())
}
async fn create_access_point(
&self,
_fs: &str,
_root: &str,
_tags: &[(String, String)],
) -> Result<String, AwsError> {
self.log("create-ap");
Ok("fsap-new".into())
}
async fn put_project_secret(
&self,
_name: &str,
_kms: &str,
json: &str,
_tags: &[(String, String)],
) -> Result<String, AwsError> {
self.log("put-secret");
*self.secret_json.lock().unwrap() = Some(json.into());
Ok(format!("arn:aws:secretsmanager:{REGION}:{ACCOUNT}:secret:triple-c/dev/x-AbCdEf"))
}
async fn task_definition_revisions(&self, _f: &str) -> Result<Vec<String>, AwsError> {
Ok(Vec::new())
}
async fn describe_task_definition(
&self,
_arn: &str,
) -> Result<Option<TaskDefinitionRef>, AwsError> {
Ok(None)
}
async fn register_task_definition(
&self,
req: RegisterTaskDefinitionInput,
) -> Result<String, AwsError> {
self.log("register");
Ok(format!(
"arn:aws:ecs:{REGION}:{ACCOUNT}:task-definition/{}:1",
req.family().unwrap()
))
}
}
impl RuntimeApi for Fake {
async fn environment_record(&self, env: &str) -> Result<Option<String>, AwsError> {
self.log(format!("record {env}"));
Ok(Some(record()))
}
async fn role_exists(&self, _name: &str) -> Result<Knowable, AwsError> {
self.log("role");
Ok(self.role.clone().unwrap_or(Knowable::Yes))
}
async fn secret_string(&self, _name: &str) -> Result<String, AwsError> {
self.log("get-secret");
Ok(self
.secret_json
.lock()
.unwrap()
.clone()
.unwrap_or_else(|| r#"{"TRIPLEC_AGENT_TOKEN":"token-of-the-running-task"}"#.into()))
}
async fn access_point_state(&self, id: &str) -> Result<Option<String>, AwsError> {
self.log(format!("ap-state {id}"));
Ok(Some("available".into()))
}
async fn delete_secret(&self, _name: &str) -> Result<(), AwsError> {
Ok(())
}
async fn delete_access_point(&self, _id: &str) -> Result<(), AwsError> {
Ok(())
}
}
impl Connector for Fake {
async fn connect(
&self,
_task: &TaskInfo,
token: &str,
) -> Result<(Box<dyn TunnelHandle>, AgentEndpoint), String> {
self.log("connect");
self.connect_tokens.lock().unwrap().push(token.into());
if self.rotated_by_loser {
let mut j = self.secret_json.lock().unwrap();
let mut v: serde_json::Value = serde_json::from_str(j.as_deref().unwrap()).unwrap();
v["TRIPLEC_AGENT_TOKEN"] = "the-losers-token".into();
*j = Some(v.to_string());
}
if self.connect_fails {
return Err("session-manager-plugin was not found".into());
}
Ok((
Box::new(FakeTunnel(std::sync::Arc::new(AtomicUsize::new(0)))),
AgentEndpoint::loopback(61100, token),
))
}
}
fn inputs<'a>(
p: &'a Project,
who: &'a CallerIdentity,
on_task: &'a (dyn Fn(Option<&TaskRecord>) + Send + Sync),
) -> StartInputs<'a> {
StartInputs {
on_task,
project: p,
who,
env_pairs: &[],
files: &[],
image: REGISTRY_IMAGE,
wait: WaitTiming {
interval: Duration::from_millis(1),
timeout: Duration::from_millis(30),
},
access_point_wait: PollTiming {
interval: Duration::from_millis(1),
timeout: Duration::from_millis(30),
},
}
}
async fn start(fake: &Fake, p: &Project) -> (Result<Started, String>, Vec<String>) {
let w = who();
let steps = Mutex::new(Vec::new());
let progress = |m: &str| steps.lock().unwrap().push(m.to_string());
let on_task = |r: Option<&TaskRecord>| {
fake.recorded.lock().unwrap().push(r.map(|r| r.task_arn.clone()));
};
let r = start_core(fake, fake, fake, fake, &inputs(p, &w, &on_task), &progress).await;
(r, steps.into_inner().unwrap())
}
#[tokio::test]
async fn a_first_start_prepares_runs_waits_and_connects_in_that_order() {
let p = aws_project(StorageMode::Hybrid);
let fake = Fake { run: Some(task(&p, "new", "RUNNING", true)), ..Default::default() };
let (r, steps) = start(&fake, &p).await;
let started = r.unwrap();
assert!(started.created);
assert_eq!(started.access_point_id.as_deref(), Some("fsap-new"));
assert_eq!(started.task.arn, task_arn("new"));
assert_eq!(
fake.calls(),
vec![
"record dev", "role", "list", "create-ap", "put-secret", "register",
"ap-state fsap-new", "list", "run", "connect", "get-secret"
],
"look for a live task before rotating the token; the access point is available before RunTask"
);
assert_eq!(steps, vec![PROGRESS_READING, PROGRESS_PREPARING, PROGRESS_STARTING, PROGRESS_WAITING, PROGRESS_CONNECTING]);
assert_eq!(*fake.recorded.lock().unwrap(), vec![Some(task_arn("new"))], "recorded before the wait");
// The connector got the token the secret was just written with.
let secret: serde_json::Value =
serde_json::from_str(fake.secret_json.lock().unwrap().as_deref().unwrap()).unwrap();
assert_eq!(
fake.connect_tokens.lock().unwrap()[0],
secret["TRIPLEC_AGENT_TOKEN"].as_str().unwrap()
);
}
#[tokio::test]
async fn a_running_task_is_attached_with_its_own_token_and_nothing_is_rewritten() {
let p = aws_project(StorageMode::Hybrid);
let live = task(&p, "live", "RUNNING", true);
let fake = Fake {
listed: Mutex::new(vec![vec![live.arn.clone()]]),
..Default::default()
}
.with_task(live);
let (r, steps) = start(&fake, &p).await;
let started = r.unwrap();
assert!(!started.created);
assert_eq!(started.access_point_id, None);
assert_eq!(fake.calls(), vec!["record dev", "role", "list", "get-secret", "connect"]);
assert_eq!(fake.connect_tokens.lock().unwrap()[0], "token-of-the-running-task");
assert_eq!(steps, vec![PROGRESS_READING, PROGRESS_WAITING, PROGRESS_CONNECTING]);
}
#[tokio::test]
async fn losing_the_run_race_is_a_clear_error_and_nothing_is_stopped() {
let p = aws_project(StorageMode::Ephemeral);
let other = task(&p, "other", "RUNNING", true);
let fake = Fake {
// Nothing at the first look; a concurrent start's task at the second.
listed: Mutex::new(vec![vec![], vec![other.arn.clone()]]),
..Default::default()
}
.with_task(other);
let (r, _) = start(&fake, &p).await;
assert_eq!(r.err().as_deref(), Some(START_RACE));
assert_eq!(*fake.recorded.lock().unwrap(), vec![Some(task_arn("other"))], "the live task is recorded");
assert!(!fake.called("run") && !fake.called("stop") && !fake.called("connect"));
}
#[tokio::test]
async fn a_task_that_stops_while_starting_is_reported_with_its_log() {
let p = aws_project(StorageMode::Ephemeral);
let fake = Fake {
run: Some(task(&p, "dies", "STOPPED", false)),
logs: vec!["entrypoint: cannot decode TRIPLEC_FILES".into()],
..Default::default()
};
let (r, _) = start(&fake, &p).await;
let e = r.err().unwrap();
assert!(e.contains("Essential container exited") && e.contains("cannot decode"), "{e}");
assert!(!fake.called("connect"));
}
#[tokio::test]
async fn a_task_that_never_gets_ready_is_stopped_and_its_log_shown() {
let p = aws_project(StorageMode::Ephemeral);
let fake = Fake {
run: Some(task(&p, "slow", "PENDING", false)),
logs: vec!["pulling image".into()],
..Default::default()
};
let (r, _) = start(&fake, &p).await;
let e = r.err().unwrap();
assert!(e.contains("did not become ready") && e.contains("pulling image"), "{e}");
assert!(fake.calls().contains(&format!("stop {} {STOP_REASON}", task_arn("slow"))));
assert_eq!(
*fake.recorded.lock().unwrap(),
vec![Some(task_arn("slow")), None],
"the ARN is stored before the wait, and forgotten once the task is stopped"
);
}
#[tokio::test]
async fn a_tunnel_failure_stops_a_task_this_start_ran_but_never_an_attached_one() {
let p = aws_project(StorageMode::Ephemeral);
let fake = Fake {
run: Some(task(&p, "new", "RUNNING", true)),
connect_fails: true,
..Default::default()
};
let (r, _) = start(&fake, &p).await;
assert!(r.err().unwrap().contains("session-manager-plugin"));
assert!(fake.calls().contains(&format!("stop {} {STOP_REASON}", task_arn("new"))));
let live = task(&p, "live", "RUNNING", true);
let attached = Fake {
listed: Mutex::new(vec![vec![live.arn.clone()]]),
connect_fails: true,
..Default::default()
}
.with_task(live);
let (r, _) = start(&attached, &p).await;
assert!(r.is_err());
assert!(!attached.called("stop"));
assert_eq!(
*attached.recorded.lock().unwrap(),
vec![Some(task_arn("live"))],
"an attached task stays recorded: it is still running"
);
}
#[tokio::test]
async fn a_user_who_has_not_joined_is_told_before_anything_is_written() {
let p = aws_project(StorageMode::Hybrid);
let fake = Fake { role: Some(Knowable::No), ..Default::default() };
let (r, _) = start(&fake, &p).await;
assert!(r.err().unwrap().contains("not joined"));
assert_eq!(fake.calls(), vec!["record dev", "role"]);
}
// ──────────────────────────────────────────────────────────────── inputs
#[test]
fn aws_runs_registry_images_only() {
let mut s = AppSettings { image_source: ImageSource::LocalBuild, ..Default::default() };
assert_eq!(aws_image(&s).unwrap(), REGISTRY_IMAGE);
s.image_source = ImageSource::Registry;
assert_eq!(aws_image(&s).unwrap(), REGISTRY_IMAGE);
s.image_source = ImageSource::Custom;
for good in ["registry.example.com/team/img:1", "ghcr.io/x/y", "user/repo:tag", "reg:5000/a"] {
s.custom_image_name = Some(good.into());
assert_eq!(aws_image(&s).unwrap(), good);
}
for bad in ["", "triple-c:latest", "ubuntu", "localhost/x", "127.0.0.1:5000/x", "a /b", "/x"] {
s.custom_image_name = Some(bad.into());
assert!(aws_image(&s).is_err(), "{bad}");
}
}
#[test]
fn the_sandbox_is_forced_off_on_aws() {
let mut p = aws_project(StorageMode::Ephemeral);
p.sandbox_mode_enabled = true;
let (pairs, _) = aws_env(&p, &AppSettings::default()).unwrap();
let settings = &pairs.iter().find(|(k, _)| k == "CLAUDE_CODE_SETTINGS_JSON").unwrap().1;
let v: serde_json::Value = serde_json::from_str(settings).unwrap();
assert_eq!(v["sandbox"]["enabled"], false, "{settings}");
}
#[test]
fn files_for_the_secret_come_from_the_ssh_folder_without_leaving_it() {
let base = tempfile::tempdir().unwrap();
let ssh = base.path().join("ssh");
std::fs::create_dir(&ssh).unwrap();
std::fs::write(ssh.join("id_ed25519"), b"KEY").unwrap();
std::fs::write(ssh.join("config"), b"Host *").unwrap();
std::fs::create_dir(ssh.join("sub")).unwrap();
std::fs::write(ssh.join("sub/nested"), b"x").unwrap();
std::fs::write(base.path().join("outside"), b"SECRET-OUTSIDE").unwrap();
#[cfg(unix)]
{
std::os::unix::fs::symlink(base.path().join("outside"), ssh.join("escape")).unwrap();
std::os::unix::fs::symlink(ssh.join("config"), ssh.join("alias")).unwrap();
}
let got = workspace_files(Some(ssh.to_str().unwrap()), None).unwrap();
let names: Vec<&str> = got.iter().map(|(k, _)| k.as_str()).collect();
#[cfg(unix)]
assert_eq!(names, vec!["ssh/alias", "ssh/config", "ssh/id_ed25519"]);
#[cfg(not(unix))]
assert_eq!(names, vec!["ssh/config", "ssh/id_ed25519"]);
assert!(got.iter().all(|(_, v)| v != b"SECRET-OUTSIDE"));
std::fs::write(ssh.join("huge"), vec![b'x'; MAX_FILE_BYTES as usize + 1]).unwrap();
let e = workspace_files(Some(ssh.to_str().unwrap()), None).unwrap_err();
assert!(e.contains("huge") && e.contains("64 KiB"), "{e}");
assert!(workspace_files(Some("/"), None).is_err(), "a filesystem root is refused");
assert!(workspace_files(None, None).unwrap().is_empty());
}
#[test]
fn ca_files_are_what_docker_would_mount() {
let base = tempfile::tempdir().unwrap();
let dir = base.path().join("ca");
std::fs::create_dir(&dir).unwrap();
std::fs::write(dir.join("corp.pem"), b"PEM").unwrap();
std::fs::write(dir.join("README"), b"not a cert").unwrap();
let ca = crate::docker::ca_certs::resolve(Some(dir.to_str().unwrap())).unwrap().unwrap();
let got = workspace_files(None, Some(&ca)).unwrap();
assert_eq!(got, vec![("ca/corp.pem".to_string(), b"PEM".to_vec())]);
let one = base.path().join("Root CA.pem");
std::fs::write(&one, b"ONE").unwrap();
let ca = crate::docker::ca_certs::resolve(Some(one.to_str().unwrap())).unwrap().unwrap();
let got = workspace_files(None, Some(&ca)).unwrap();
assert_eq!(got, vec![("ca/Root_CA.crt".to_string(), b"ONE".to_vec())]);
}
// ───────────────────────────────────────────────── targets and reconcile
#[tokio::test]
async fn an_aws_projects_target_is_its_registered_tunnel() {
let mut p = aws_project(StorageMode::Ephemeral);
p.container_id = Some("http://127.0.0.1:61200/".into());
assert_eq!(ProjectHost::for_project(&p), ProjectHost::Aws);
assert_eq!(ContainerTarget::for_project(&p), None, "no tunnel, no target, whatever is stored");
tunnels::register(&p.id, fake_tunnel(61200, std::sync::Arc::new(AtomicUsize::new(0))));
assert_eq!(
ContainerTarget::for_project(&p),
Some(ContainerTarget::Agent(AgentEndpoint::loopback(61200, "tok")))
);
assert_eq!(
ContainerTarget::for_project_waiting(&p).await,
ContainerTarget::for_project(&p)
);
tunnels::close(&p.id).await;
let local = Project::new("local".into(), Vec::new());
assert_eq!(ProjectHost::for_project(&local), ProjectHost::Docker);
}
fn find(p: &Project) -> FindTask {
FindTask::new(p, REGION, USER)
}
fn store_with(p: &Project) -> (tempfile::TempDir, ProjectsStore) {
let dir = tempfile::tempdir().unwrap();
let store = ProjectsStore::over_file_for_test(dir.path().join("projects.json"), vec![p.clone()]);
(dir, store)
}
#[tokio::test]
async fn reconcile_marks_a_project_whose_task_stopped_as_stopped() {
let mut p = aws_project(StorageMode::Hybrid);
p.status = ProjectStatus::Running;
{
let a = p.aws.as_mut().unwrap();
a.task_arn = Some(task_arn("gone"));
a.access_point_id = Some("fsap-1".into());
a.task_definition_arn = Some("arn:td:1".into());
}
let fake = Fake::default().with_task(task(&p, "gone", "STOPPED", false));
let (_d, store) = store_with(&p);
assert_eq!(reconcile_project(&fake, &store, &p, &find(&p)).await.unwrap(), Reconciled::Gone);
let after = store.get(&p.id).unwrap();
assert_eq!(after.status, ProjectStatus::Stopped);
let a = after.aws.unwrap();
assert_eq!(a.task_arn, None, "a stopped task's ARN is cleared");
assert_eq!(a.access_point_id.as_deref(), Some("fsap-1"), "the data's access point stays");
// ECS has forgotten it: also gone.
let forgotten = Fake::default();
let (_d, store) = store_with(&p);
assert_eq!(reconcile_project(&forgotten, &store, &p, &find(&p)).await.unwrap(), Reconciled::Gone);
assert_eq!(store.get(&p.id).unwrap().status, ProjectStatus::Stopped);
}
#[tokio::test]
async fn reconcile_keeps_a_project_with_a_live_task_running() {
let mut p = aws_project(StorageMode::Hybrid);
p.status = ProjectStatus::Running;
p.aws.as_mut().unwrap().task_arn = Some(task_arn("up"));
let fake = Fake::default().with_task(task(&p, "up", "RUNNING", true));
let (_d, store) = store_with(&p);
assert!(matches!(reconcile_project(&fake, &store, &p, &find(&p)).await.unwrap(), Reconciled::Live(_)));
assert_eq!(store.get(&p.id).unwrap().status, ProjectStatus::Running);
}
#[tokio::test]
async fn the_watch_reports_a_running_aws_project_as_its_stored_target_and_confirms_a_recorded_stop() {
let mut p = aws_project(StorageMode::Ephemeral);
p.status = ProjectStatus::Running;
p.container_id = Some("http://127.0.0.1:61300/".into());
p.aws.as_mut().unwrap().task_arn = Some(task_arn("w1"));
let w = watched_task(&p).expect("watched");
assert_eq!(w.target.id(), "http://127.0.0.1:61300/", "settle's running_on matches the stored id");
assert_eq!(w.group.cluster_arn, cluster_arn());
assert_eq!(w.group.connection_id, "c1");
assert!(!w.target.has_exited().await, "nothing recorded yet");
record_stopped(std::slice::from_ref(&p), &[(task_arn("w1"), StopKind::Idle)]);
assert!(w.target.has_exited().await);
assert_eq!(crate::host::tunnels::stop_kind(w.target.id()), Some(StopKind::Idle));
let mut stopped = p.clone();
stopped.status = ProjectStatus::Stopped;
assert!(watched_task(&stopped).is_none(), "a Stopped project is not polled again");
let local = Project::new("l".into(), Vec::new());
assert!(watched_task(&local).is_none());
}
#[tokio::test]
async fn the_winner_of_a_start_race_puts_its_token_back_in_the_secret() {
let p = aws_project(StorageMode::Ephemeral);
let fake = Fake {
run: Some(task(&p, "new", "RUNNING", true)),
rotated_by_loser: true,
..Default::default()
};
let (r, _) = start(&fake, &p).await;
r.unwrap();
let ours = fake.connect_tokens.lock().unwrap()[0].clone();
let calls = fake.calls();
assert_eq!(&calls[calls.len() - 3..], ["connect", "get-secret", "put-secret"]);
let v: serde_json::Value =
serde_json::from_str(fake.secret_json.lock().unwrap().as_deref().unwrap()).unwrap();
assert_eq!(v["TRIPLEC_AGENT_TOKEN"], ours.as_str());
assert!(v.get("TRIPLEC_FILES").is_some(), "the rest of the payload is kept");
}
#[tokio::test]
async fn an_unchanged_secret_is_not_rewritten_after_a_start() {
let p = aws_project(StorageMode::Ephemeral);
let fake = Fake { run: Some(task(&p, "new", "RUNNING", true)), ..Default::default() };
start(&fake, &p).await.0.unwrap();
assert_eq!(fake.calls().iter().filter(|c| *c == "put-secret").count(), 1);
}
#[test]
fn a_refused_token_says_to_restart_the_workspace() {
assert_eq!(
refusal_message("Agent health check failed: the agent rejected the credentials (401)"),
TOKEN_MISMATCH
);
assert!(refusal_message("Agent health check failed: agent returned HTTP 500").contains("500"));
}
#[tokio::test]
async fn reconcile_finds_a_task_whose_arn_was_never_stored() {
// The app quit during "Waiting for the task" in a build that stored the
// ARN only at the end: the task is found by family and tags.
let mut p = aws_project(StorageMode::Ephemeral);
p.status = ProjectStatus::Running;
let live = task(&p, "orphan", "RUNNING", true);
let fake = Fake { listed: Mutex::new(vec![vec![live.arn.clone()]]), ..Default::default() }
.with_task(live);
let (_d, store) = store_with(&p);
assert!(matches!(
reconcile_project(&fake, &store, &p, &find(&p)).await.unwrap(),
Reconciled::Live(_)
));
let after = store.get(&p.id).unwrap();
assert_eq!(after.status, ProjectStatus::Running);
assert_eq!(after.aws.unwrap().task_arn, Some(task_arn("orphan")), "now stored");
let nothing = Fake::default();
let (_d, store) = store_with(&p);
assert_eq!(reconcile_project(&nothing, &store, &p, &find(&p)).await.unwrap(), Reconciled::Gone);
assert_eq!(store.get(&p.id).unwrap().status, ProjectStatus::Stopped);
}
#[test]
fn a_reattach_registers_only_while_the_project_still_runs_that_task() {
let mut p = aws_project(StorageMode::Ephemeral);
p.status = ProjectStatus::Running;
p.aws.as_mut().unwrap().task_arn = Some(task_arn("t"));
let (_d, store) = store_with(&p);
assert!(reattach_still_wanted(&store, &p.id, &task_arn("t")));
assert!(!reattach_still_wanted(&store, &p.id, &task_arn("other")));
store.update_status(&p.id, ProjectStatus::Stopping).unwrap();
assert!(!reattach_still_wanted(&store, &p.id, &task_arn("t")));
store.remove(&p.id).unwrap();
assert!(!reattach_still_wanted(&store, &p.id, &task_arn("t")));
}
#[test]
fn a_start_records_its_task_and_keeps_the_stored_handles_it_does_not_know() {
let mut p = aws_project(StorageMode::Hybrid);
p.aws.as_mut().unwrap().access_point_id = Some("fsap-old".into());
let (_d, store) = store_with(&p);
record_task(
&store,
&p.id,
Some(&TaskRecord { task_arn: "arn:t".into(), access_point_id: None, task_definition_arn: Some("arn:td:2".into()) }),
);
let a = store.get(&p.id).unwrap().aws.unwrap();
assert_eq!((a.task_arn.as_deref(), a.access_point_id.as_deref(), a.task_definition_arn.as_deref()),
(Some("arn:t"), Some("fsap-old"), Some("arn:td:2")));
record_task(&store, &p.id, None);
let a = store.get(&p.id).unwrap().aws.unwrap();
assert_eq!((a.task_arn, a.access_point_id.as_deref()), (None, Some("fsap-old")));
}
#[tokio::test]
async fn a_task_that_could_not_be_stopped_after_a_failed_start_stays_recorded() {
let p = aws_project(StorageMode::Ephemeral);
let fake = Fake {
run: Some(task(&p, "slow", "PENDING", false)),
stop_fails: true,
..Default::default()
};
assert!(start(&fake, &p).await.0.is_err());
assert!(fake.called("stop"));
assert_eq!(*fake.recorded.lock().unwrap(), vec![Some(task_arn("slow"))], "still findable");
let fake = Fake {
run: Some(task(&p, "new", "RUNNING", true)),
connect_fails: true,
stop_fails: true,
..Default::default()
};
assert!(start(&fake, &p).await.0.is_err());
assert_eq!(*fake.recorded.lock().unwrap(), vec![Some(task_arn("new"))]);
}
#[tokio::test]
async fn the_task_log_reads_the_tasks_stream_in_the_records_log_group() {
let p = aws_project(StorageMode::Hybrid);
let fake = Fake { logs: vec!["line 1".into(), "line 2".into()], ..Default::default() };
let lines = task_log_lines(&fake, &fake, &p, &who(), REGION, &task_arn("abc"), 20).await.unwrap();
assert_eq!(lines, vec!["line 1", "line 2"]);
let prefix = log_stream_prefix(&owner_key(REGION, USER), &p.id);
assert_eq!(
*fake.log_reads.lock().unwrap(),
vec![format!("/triple-c/dev {prefix}/workspace/abc 20")]
);
}
#[test]
fn the_log_task_is_the_stored_one_else_the_last_one_a_start_saw() {
let mut p = aws_project(StorageMode::Hybrid);
p.id = "log-task-test-project".into();
assert_eq!(log_task_arn(&p), None);
let (_d, store) = store_with(&p);
record_task(
&store,
&p.id,
Some(&TaskRecord { task_arn: "arn:first".into(), access_point_id: None, task_definition_arn: None }),
);
record_task(&store, &p.id, None);
assert_eq!(log_task_arn(&p).as_deref(), Some("arn:first"), "a cleared ARN still has a log");
p.aws.as_mut().unwrap().task_arn = Some("arn:current".into());
assert_eq!(log_task_arn(&p).as_deref(), Some("arn:current"));
}
#[tokio::test]
async fn reconcile_falls_back_to_a_newer_live_task_when_the_stored_one_stopped() {
// m3: another machine restarted the project; the stored ARN is history.
let mut p = aws_project(StorageMode::Ephemeral);
p.status = ProjectStatus::Running;
p.aws.as_mut().unwrap().task_arn = Some(task_arn("old"));
let newer = task(&p, "newer", "RUNNING", true);
let fake = Fake { listed: Mutex::new(vec![vec![newer.arn.clone()]]), ..Default::default() }
.with_task(task(&p, "old", "STOPPED", false))
.with_task(newer);
let (_d, store) = store_with(&p);
assert!(matches!(
reconcile_project(&fake, &store, &p, &find(&p)).await.unwrap(),
Reconciled::Live(t) if t.arn == task_arn("newer")
));
let after = store.get(&p.id).unwrap();
assert_eq!(after.status, ProjectStatus::Running);
assert_eq!(after.aws.unwrap().task_arn, Some(task_arn("newer")));
// ECS forgot the stored one and nothing else runs: Gone, after looking.
let fake = Fake::default();
let (_d, store) = store_with(&p);
assert_eq!(reconcile_project(&fake, &store, &p, &find(&p)).await.unwrap(), Reconciled::Gone);
assert!(fake.called("list"), "it looked for another task first");
}
#[tokio::test]
async fn reconcile_forgets_a_stale_stop_on_the_unattached_id_before_reusing_it() {
use crate::host::tunnels;
let mut p = aws_project(StorageMode::Ephemeral);
p.status = ProjectStatus::Running;
p.aws.as_mut().unwrap().task_arn = Some(task_arn("u2"));
let placeholder = tunnels::unattached_id(&p.id);
// A past unattached spell's task was seen stopped under this id.
tunnels::mark_stopped(&placeholder, StopKind::Spot);
p.container_id = Some("http://127.0.0.1:61400/".into());
assert_eq!(prepare_unattached(&p), Some(placeholder.clone()));
assert!(!tunnels::is_stopped(&placeholder), "the live task must not read as stopped");
// Already on the placeholder: nothing to store, the mark still goes.
p.container_id = Some(placeholder.clone());
tunnels::mark_stopped(&placeholder, StopKind::Spot);
assert_eq!(prepare_unattached(&p), None);
assert!(!tunnels::is_stopped(&placeholder));
assert_eq!(prepare_unattached(&Project::new("l".into(), Vec::new())), None);
}
#[tokio::test]
async fn an_unattached_aws_project_gets_a_target_id_no_tunnel_can_have() {
// m9: the last run's loopback port may belong to another project's
// tunnel now.
let mut p = aws_project(StorageMode::Ephemeral);
p.status = ProjectStatus::Running;
p.container_id = Some("http://127.0.0.1:61400/".into());
p.aws.as_mut().unwrap().task_arn = Some(task_arn("u1"));
let id = unattached_container_id(&p).expect("replaced");
assert_eq!(id, format!("http://unattached.invalid/{}/", p.id));
p.container_id = Some(id.clone());
assert_eq!(unattached_container_id(&p), None, "idempotent");
// The watch still reports it, by that id, and a registered tunnel on the
// old port can't be confused with it.
let w = watched_task(&p).expect("still watched");
assert_eq!(w.target.id(), id);
p.container_id = None;
assert_eq!(unattached_container_id(&p), None, "nothing stored, nothing to replace");
let local = Project::new("l".into(), Vec::new());
assert_eq!(unattached_container_id(&local), None);
}
+66 -8
View File
@@ -17,12 +17,15 @@ use super::ContainerTarget;
use crate::docker;
use crate::models::{AppSettings, Project};
use crate::models::container_config;
use crate::storage::projects_store::ProjectsStore;
/// The host a project runs on. One variant today; an AWS variant will carry
/// the connection, region and environment (see the spec's data model).
/// The host a project runs on: the local Docker daemon, or an ECS Fargate
/// task in an AWS environment (`aws_host.rs`; the connection, region and
/// environment come from the project).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectHost {
Docker,
Aws,
}
/// An agent target is a way *into* a container, not a handle on its
@@ -41,8 +44,12 @@ pub struct DiscardLeftovers {
}
impl ProjectHost {
pub fn for_project(_project: &Project) -> Self {
ProjectHost::Docker
pub fn for_project(project: &Project) -> Self {
if project.is_aws() {
ProjectHost::Aws
} else {
ProjectHost::Docker
}
}
/// Make sure the project's container exists, matches the project's
@@ -50,16 +57,20 @@ impl ProjectHost {
///
/// `progress` receives the same human-readable steps the start view has
/// always shown. Failure leaves the caller to reset the project status.
/// `store`: the AWS host records a task's ARN in it as soon as the task
/// exists, so a crash during the long wait leaves it findable.
pub async fn ensure_started(
&self,
project: &Project,
settings: &AppSettings,
store: &ProjectsStore,
progress: &(dyn Fn(&str) + Send + Sync),
) -> Result<ContainerTarget, String> {
match self {
ProjectHost::Docker => docker_ensure_started(project, settings, progress)
.await
.map(ContainerTarget::docker),
ProjectHost::Aws => super::aws_host::ensure_started(project, settings, store, progress).await,
}
}
@@ -72,24 +83,66 @@ impl ProjectHost {
ProjectHost::Docker => Ok(docker::find_existing_container(project)
.await?
.map(ContainerTarget::docker)),
// The tunnel registry: an AWS project's target exists while its
// tunnel is open.
ProjectHost::Aws => Ok(ContainerTarget::for_project(project)),
}
}
/// Stop the container behind `target`. For an agent target that is the
/// ECS task behind a registered tunnel (`StopTask`, reason "Stopped from
/// Triple-C"), and the tunnel is closed.
pub async fn stop(&self, target: &ContainerTarget) -> Result<(), String> {
match target {
ContainerTarget::Docker { container_id } => docker::stop_container(container_id).await,
ContainerTarget::Agent(_) => Err(AGENT_LIFECYCLE.replace("{op}", "Stopping")),
ContainerTarget::Agent(ep) => super::aws_host::stop_endpoint(ep)
.await
.unwrap_or_else(|| Err(AGENT_LIFECYCLE.replace("{op}", "Stopping"))),
}
}
/// Stop a project's container whether or not the app holds a target for
/// it. Docker: the stored container. AWS: the tunnel's task, else the
/// stored task ARN, else the project's live task — a project whose
/// tunnel could not be re-opened must still be stoppable.
pub async fn stop_project(&self, project: &Project, settings: &AppSettings) -> Result<(), String> {
match self {
ProjectHost::Docker => match ContainerTarget::for_project(project) {
Some(t) => self.stop(&t).await,
None => Ok(()),
},
ProjectHost::Aws => super::aws_host::stop_project(project, settings).await,
}
}
/// Stop (errors ignored — a stopped container is the goal) and remove.
/// An agent target is stopped; its resources go with
/// [`Self::remove_aws_resources`].
pub async fn remove(&self, target: &ContainerTarget) -> Result<(), String> {
match target {
ContainerTarget::Docker { container_id } => {
let _ = docker::stop_container(container_id).await;
docker::remove_container(container_id).await
}
ContainerTarget::Agent(_) => Err(AGENT_LIFECYCLE.replace("{op}", "Removing")),
ContainerTarget::Agent(ep) => super::aws_host::stop_endpoint(ep)
.await
.unwrap_or_else(|| Err(AGENT_LIFECYCLE.replace("{op}", "Removing"))),
}
}
/// AWS: stop the task and remove the project's resources — task
/// definition revisions, the secret (deleted at once) and, only
/// with `discard_data`, the EFS access point (not its files). Docker: nothing (its state
/// goes with [`Self::discard_project_state`]).
pub async fn remove_aws_resources(
&self,
project: &Project,
settings: &AppSettings,
discard_data: bool,
) -> Result<(), String> {
match self {
ProjectHost::Docker => Ok(()),
ProjectHost::Aws => super::aws_host::remove_resources(project, settings, discard_data).await,
}
}
@@ -107,6 +160,8 @@ impl ProjectHost {
left.volumes = docker::remove_project_volumes(project).await;
left
}
// Removed by `remove_aws_resources`, which needs the settings.
ProjectHost::Aws => DiscardLeftovers::default(),
}
}
@@ -118,6 +173,7 @@ impl ProjectHost {
docker::remove_legacy_mcp_containers(&project.id).await;
docker::remove_legacy_project_network(&project.id).await;
}
ProjectHost::Aws => {}
}
}
}
@@ -277,6 +333,8 @@ mod tests {
async fn a_project_container_round_trips_through_the_host() {
let project = Project::new("lifecycle-live-test".to_string(), Vec::new());
let settings = AppSettings::default();
let store_dir = tempfile::tempdir().expect("temp dir");
let store = ProjectsStore::over_file_for_test(store_dir.path().join("projects.json"), Vec::new());
let host = ProjectHost::for_project(&project);
let steps = std::sync::Mutex::new(Vec::<String>::new());
let progress = |m: &str| steps.lock().unwrap().push(m.to_string());
@@ -289,7 +347,7 @@ mod tests {
let outcome = async {
check(host.find_current(&project).await?.is_none(), "no container before the first start")?;
let first = host.ensure_started(&project, &settings, &progress).await?;
let first = host.ensure_started(&project, &settings, &store, &progress).await?;
check(first.is_running().await?, "running after start")?;
let (out, code) = first
.exec_oneshot_env_status(vec!["id".into(), "-un".into()], vec![])
@@ -301,7 +359,7 @@ mod tests {
check(first.has_exited().await, "exited after stop")?;
// Same config, so the existing container is started, not recreated.
let second = host.ensure_started(&project, &settings, &progress).await?;
let second = host.ensure_started(&project, &settings, &store, &progress).await?;
check(second == first, "restart reuses the container")?;
check(second.is_running().await?, "running after restart")?;
+53 -4
View File
@@ -28,12 +28,11 @@
//! may still do so.
pub mod agent;
pub mod aws_host;
pub mod lifecycle;
pub mod sessions;
// Nothing in the app opens an SSM tunnel until the AWS host lands (phase 5 of
// the AWS spec); its tests exercise it meanwhile. Remove this allow then.
#[allow(dead_code)]
pub mod ssm;
pub mod tunnels;
pub mod watch;
pub use crate::docker::exec::{
@@ -154,11 +153,28 @@ impl ContainerTarget {
}
}
/// The target for a project's container, if it has one yet.
/// The target for a project's container, if it has one yet. An AWS
/// project's is its registered tunnel's agent endpoint (`tunnels.rs`):
/// none while no tunnel is open.
pub fn for_project(project: &Project) -> Option<Self> {
if project.is_aws() {
return tunnels::get_endpoint(&project.id).map(ContainerTarget::Agent);
}
project.container_id.as_deref().map(Self::docker)
}
/// [`Self::for_project`], waiting (up to `aws_host::REATTACH_WAIT`) for an
/// AWS project whose tunnel is being re-opened in the background after a
/// restart. For a Docker project it is `for_project`.
pub async fn for_project_waiting(project: &Project) -> Option<Self> {
if project.is_aws() {
return tunnels::wait_endpoint(&project.id, aws_host::REATTACH_WAIT)
.await
.map(ContainerTarget::Agent);
}
Self::for_project(project)
}
/// The host-specific identifier (a Docker container id today). For logs
/// and for keying per-container state; never parse it.
pub fn id(&self) -> &str {
@@ -254,6 +270,23 @@ impl ContainerTarget {
}
}
/// [`Self::exec_oneshot_limited`] for a background poll: on the agent it
/// carries the background marker, so it never counts as activity for
/// idle stop. Docker has no idle stop; the call is the same there.
pub async fn exec_oneshot_background(
&self,
user: &str,
cmd: Vec<String>,
limit: usize,
) -> Result<(String, i64), String> {
match self {
ContainerTarget::Docker { container_id } => {
docker::exec::exec_oneshot_limited(container_id, user, cmd, limit).await
}
ContainerTarget::Agent(ep) => agent::exec_oneshot_background(ep, user, cmd, limit).await,
}
}
/// stdout and stderr kept apart: `(stdout, stderr, exit_code)`.
pub async fn exec_oneshot_streams_as(
&self,
@@ -269,6 +302,22 @@ impl ContainerTarget {
}
}
/// [`Self::exec_oneshot_streams_as`] for a background poll (the file
/// viewer's change check): on the agent it carries the background marker,
/// so it never counts as activity for idle stop. The same call on Docker.
pub async fn exec_oneshot_streams_background(
&self,
user: &str,
cmd: Vec<String>,
) -> Result<(String, String, i64), String> {
match self {
ContainerTarget::Docker { container_id } => {
docker::exec::exec_oneshot_streams_as(container_id, user, cmd, Vec::new()).await
}
ContainerTarget::Agent(ep) => agent::exec_oneshot_streams_background(ep, user, cmd).await,
}
}
/// Start a command and return without waiting or reading its output.
/// Returns the exec id.
pub async fn exec_detached(&self, spec: ExecSpec) -> Result<String, String> {
+9
View File
@@ -115,6 +115,10 @@ impl EcsTask {
/// ARN), and check it can take a session now: the task is running and
/// its ECS Exec agent is up. Fargate starts that agent a few seconds after
/// the container, so "not ready yet" is a normal answer just after start.
///
/// The AWS host builds its target from `aws::tasks::wait_ready`'s answer
/// instead (`aws_host::ecs_task`); this stays for the live tests.
#[allow(dead_code)]
pub async fn resolve(
ecs: &aws_sdk_ecs::Client,
cluster: &str,
@@ -175,6 +179,7 @@ impl EcsTask {
/// The part of an ARN after the last `marker` (`.../cluster/name` → `name`),
/// or the whole string when it is not an ARN.
#[allow(dead_code)] // `EcsTask::resolve`
fn last_arn_segment<'a>(s: &'a str, marker: &str) -> &'a str {
if !s.starts_with("arn:") {
return s;
@@ -606,6 +611,7 @@ pub enum TunnelState {
pub struct PortForward {
local_port: u16,
state: watch::Receiver<TunnelState>,
#[allow(dead_code)] // `plugin_pid()`, for diagnostics and the tests
plugin_pid: watch::Receiver<Option<u32>>,
supervisor: Option<tokio::task::JoinHandle<()>>,
_cancel: DropGuard,
@@ -678,6 +684,7 @@ impl PortForward {
}
}
#[allow(dead_code)] // diagnostics and the tests (Task 8 may show the state)
pub fn local_port(&self) -> u16 {
self.local_port
}
@@ -688,11 +695,13 @@ impl PortForward {
AgentEndpoint::loopback(self.local_port, token)
}
#[allow(dead_code)] // diagnostics and the tests (Task 8 may show the state)
pub fn state(&self) -> watch::Receiver<TunnelState> {
self.state.clone()
}
/// The running plugin's process id, if one is running.
#[allow(dead_code)] // diagnostics and the tests (Task 8 may show the state)
pub fn plugin_pid(&self) -> Option<u32> {
*self.plugin_pid.borrow()
}
+480
View File
@@ -0,0 +1,480 @@
//! The live SSM tunnels to AWS projects' agents, by project id.
//!
//! An AWS project's [`ContainerTarget`](super::ContainerTarget) is an agent
//! endpoint at the loopback end of a [`PortForward`](super::ssm::PortForward);
//! this registry is where `ContainerTarget::for_project` finds it, where
//! `ProjectHost::stop` finds the task behind an endpoint, and what the
//! shutdown path closes (every forward runs a `session-manager-plugin` child
//! that would otherwise outlive the app — see `ssm.rs`).
//!
//! It also remembers which targets the AWS death watch found **stopped**, so
//! `ContainerTarget::has_exited` can answer for an agent target (R3): only
//! the host that runs the task can confirm a death, never the agent.
use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
use std::time::Duration;
use aws_config::SdkConfig;
use futures_util::future::BoxFuture;
use tokio::sync::watch;
use super::agent::AgentEndpoint;
use crate::aws::tasks::StopKind;
use super::ssm::{EcsTask, PortForward};
/// Something that owns a tunnel's resources: the real [`PortForward`], or a
/// test stand-in.
pub trait TunnelHandle: Send + Sync {
fn close(self: Box<Self>) -> BoxFuture<'static, ()>;
}
impl TunnelHandle for PortForward {
fn close(self: Box<Self>) -> BoxFuture<'static, ()> {
Box::pin(async move { (*self).close().await })
}
}
/// One project's tunnel and the task it reaches.
pub struct LiveTunnel {
/// The SSM target (kept for diagnostics; the forward already uses it).
#[allow(dead_code)]
pub task: EcsTask,
pub task_arn: String,
pub cluster_arn: String,
pub connection_id: String,
pub region: String,
/// The connection's SDK config, so a stop needs no settings lookup.
pub sdk: SdkConfig,
pub forward: Box<dyn TunnelHandle>,
pub endpoint: AgentEndpoint,
/// Runtime handles for the store (`set_aws_runtime`).
pub access_point_id: Option<String>,
pub task_definition_arn: String,
}
/// Where an endpoint's task is: `(connection, region, cluster, task ARN)`.
pub type TaskOf = (String, String, String, String);
#[derive(Default)]
struct Registry {
live: HashMap<String, LiveTunnel>,
/// Target ids (endpoint base URLs) whose task the AWS watch saw STOPPED,
/// and why.
stopped: HashMap<String, StopKind>,
/// Projects whose tunnel is being re-opened in the background.
pending: HashSet<String>,
/// Bumped by every [`close`] (a stop or remove), every [`register`] (a
/// start's own tunnel) and [`cancel_reattach`]: a background re-attach
/// that began under an older generation must never register.
generation: HashMap<String, u64>,
}
fn registry() -> &'static Mutex<Registry> {
static R: std::sync::OnceLock<Mutex<Registry>> = std::sync::OnceLock::new();
R.get_or_init(Default::default)
}
fn lock() -> std::sync::MutexGuard<'static, Registry> {
registry().lock().unwrap_or_else(|e| e.into_inner())
}
/// Wakes [`wait_endpoint`] callers when the registry changes.
fn changed() -> &'static watch::Sender<u64> {
static C: std::sync::OnceLock<watch::Sender<u64>> = std::sync::OnceLock::new();
C.get_or_init(|| watch::channel(0).0)
}
fn notify() {
changed().send_modify(|n| *n = n.wrapping_add(1));
}
/// The target id an AWS project has while no tunnel is registered for it
/// (see `aws_host::unattached_container_id`): never a loopback URL, so a
/// port a new tunnel reuses can't be confused with it.
pub fn unattached_id(project_id: &str) -> String {
format!("http://unattached.invalid/{project_id}/")
}
/// Forget that the watch saw the task behind `target_id` stopped. For a
/// project's [`unattached_id`], which (unlike an endpoint) is reused by
/// every later unattached spell of the same project: a stale entry would
/// make a later live task read as stopped.
pub fn forget_stopped(target_id: &str) {
lock().stopped.remove(target_id);
}
/// Register `tunnel` for `project_id`, returning the one it replaces (the
/// caller closes it).
pub fn register(project_id: &str, tunnel: LiveTunnel) -> Option<LiveTunnel> {
let old = {
let mut r = lock();
*r.generation.entry(project_id.to_string()).or_default() += 1;
r.stopped.remove(tunnel.endpoint.base_url.as_str());
r.stopped.remove(&unattached_id(project_id));
r.pending.remove(project_id);
r.live.insert(project_id.to_string(), tunnel)
};
notify();
old
}
pub fn get_endpoint(project_id: &str) -> Option<AgentEndpoint> {
lock().live.get(project_id).map(|t| t.endpoint.clone())
}
/// `(task ARN, access point id, task definition ARN)` of the project's tunnel.
pub fn runtime(project_id: &str) -> Option<(String, Option<String>, String)> {
lock().live.get(project_id).map(|t| {
(
t.task_arn.clone(),
t.access_point_id.clone(),
t.task_definition_arn.clone(),
)
})
}
/// The project whose tunnel is `ep` and its task.
pub fn task_of(ep: &AgentEndpoint) -> Option<TaskOf> {
lock().live.values().find(|t| t.endpoint.base_url == ep.base_url).map(|t| {
(
t.connection_id.clone(),
t.region.clone(),
t.cluster_arn.clone(),
t.task_arn.clone(),
)
})
}
/// The project id and SDK config behind `ep`.
pub(crate) fn owner_of(ep: &AgentEndpoint) -> Option<(String, SdkConfig)> {
lock()
.live
.iter()
.find(|(_, t)| t.endpoint.base_url == ep.base_url)
.map(|(id, t)| (id.clone(), t.sdk.clone()))
}
/// A background re-attach of `project_id` begins: marks it pending and
/// returns the generation [`register_if_current`] must still see.
pub fn begin_reattach(project_id: &str) -> u64 {
let g = {
let mut r = lock();
r.pending.insert(project_id.to_string());
*r.generation.entry(project_id.to_string()).or_default()
};
notify();
g
}
/// [`register`], unless the project was closed (stopped, removed) since
/// `generation` was taken: then the tunnel is handed back for the caller to
/// close, and nothing is registered.
pub fn register_if_current(
project_id: &str,
generation: u64,
tunnel: LiveTunnel,
) -> Result<Option<LiveTunnel>, Box<LiveTunnel>> {
let old = {
let mut r = lock();
if r.generation.get(project_id).copied().unwrap_or_default() != generation {
return Err(Box::new(tunnel));
}
r.stopped.remove(tunnel.endpoint.base_url.as_str());
r.stopped.remove(&unattached_id(project_id));
r.pending.remove(project_id);
r.live.insert(project_id.to_string(), tunnel)
};
notify();
Ok(old)
}
/// [`close`], but only when the registered tunnel leads to `task_arn` (a
/// death report about an older task must not close a newer one's tunnel).
pub async fn close_if_task(project_id: &str, task_arn: &str) {
let taken = {
let mut r = lock();
if !r.live.get(project_id).is_some_and(|t| t.task_arn == task_arn) {
return;
}
take(&mut r, project_id)
};
notify();
if let Some(t) = taken {
t.forward.close().await;
}
}
/// Under the lock: invalidate a re-attach in flight and take the tunnel out.
fn take(r: &mut Registry, project_id: &str) -> Option<LiveTunnel> {
r.pending.remove(project_id);
*r.generation.entry(project_id.to_string()).or_default() += 1;
let t = r.live.remove(project_id);
if let Some(ref t) = t {
r.stopped.remove(t.endpoint.base_url.as_str());
}
t
}
/// A start is about to attach itself: any background re-attach in flight
/// is cancelled (it will hand its tunnel back and close it).
pub fn cancel_reattach(project_id: &str) {
{
let mut r = lock();
r.pending.remove(project_id);
*r.generation.entry(project_id.to_string()).or_default() += 1;
}
notify();
}
/// A background re-attach that began at `generation` gave up: clear the
/// pending flag, unless something newer has taken over since.
pub fn end_reattach(project_id: &str, generation: u64) {
{
let mut r = lock();
if r.generation.get(project_id).copied().unwrap_or_default() == generation {
r.pending.remove(project_id);
}
}
notify();
}
/// Take the project's tunnel out and close it, and invalidate a background
/// re-attach in flight.
pub async fn close(project_id: &str) {
let taken = take(&mut lock(), project_id);
notify();
if let Some(t) = taken {
t.forward.close().await;
}
}
/// Close every tunnel, concurrently. The shutdown path's step.
pub async fn close_all() {
let all: Vec<LiveTunnel> = {
let mut r = lock();
r.pending.clear();
r.stopped.clear();
for g in r.generation.values_mut() {
*g += 1;
}
r.live.drain().map(|(_, t)| t).collect()
};
notify();
futures_util::future::join_all(all.into_iter().map(|t| t.forward.close())).await;
}
/// The AWS watch saw the task behind target `target_id` STOPPED, for `why`.
pub fn mark_stopped(target_id: &str, why: StopKind) {
lock().stopped.insert(target_id.to_string(), why);
}
/// Whether the AWS watch has confirmed the task behind `target_id` stopped.
pub fn is_stopped(target_id: &str) -> bool {
lock().stopped.contains_key(target_id)
}
/// Why the task behind `target_id` stopped, once the watch has seen it.
pub fn stop_kind(target_id: &str) -> Option<StopKind> {
lock().stopped.get(target_id).cloned()
}
pub fn is_pending(project_id: &str) -> bool {
lock().pending.contains(project_id)
}
/// The project's endpoint, waiting up to `timeout` while a background
/// re-attach is still opening it. `None` when there is none.
pub async fn wait_endpoint(project_id: &str, timeout: Duration) -> Option<AgentEndpoint> {
let mut rx = changed().subscribe();
let deadline = tokio::time::Instant::now() + timeout;
loop {
if let Some(ep) = get_endpoint(project_id) {
return Some(ep);
}
if !is_pending(project_id) {
return None;
}
if tokio::time::timeout_at(deadline, rx.changed()).await.is_err() {
return None;
}
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
/// A stand-in tunnel that counts its closes.
pub(crate) struct FakeTunnel(pub Arc<AtomicUsize>);
impl TunnelHandle for FakeTunnel {
fn close(self: Box<Self>) -> BoxFuture<'static, ()> {
let n = self.0.clone();
Box::pin(async move {
n.fetch_add(1, Ordering::SeqCst);
})
}
}
pub(crate) fn fake_tunnel(port: u16, closes: Arc<AtomicUsize>) -> LiveTunnel {
LiveTunnel {
task: EcsTask {
cluster: "triple-c-dev".into(),
task_id: format!("t{port}"),
runtime_id: "r".into(),
},
task_arn: format!("arn:aws:ecs:eu-west-1:111122223333:task/triple-c-dev/t{port}"),
cluster_arn: "arn:aws:ecs:eu-west-1:111122223333:cluster/triple-c-dev".into(),
connection_id: "c1".into(),
region: "eu-west-1".into(),
sdk: SdkConfig::builder().build(),
forward: Box::new(FakeTunnel(closes)),
endpoint: AgentEndpoint::loopback(port, "tok"),
access_point_id: Some("fsap-1".into()),
task_definition_arn: "arn:td:1".into(),
}
}
fn pid(tag: &str) -> String {
format!("tunnels-test-{tag}-{}", uuid::Uuid::new_v4())
}
#[tokio::test]
async fn a_registered_tunnel_is_found_by_project_and_by_endpoint_and_closed_once() {
let closes = Arc::new(AtomicUsize::new(0));
let p = pid("reg");
assert!(get_endpoint(&p).is_none());
assert!(register(&p, fake_tunnel(61001, closes.clone())).is_none());
let ep = get_endpoint(&p).unwrap();
assert_eq!(ep, AgentEndpoint::loopback(61001, "tok"));
let (conn, region, _, arn) = task_of(&ep).unwrap();
assert_eq!((conn.as_str(), region.as_str()), ("c1", "eu-west-1"));
assert!(arn.ends_with("/t61001"));
assert_eq!(runtime(&p).unwrap().1.as_deref(), Some("fsap-1"));
close(&p).await;
close(&p).await;
assert_eq!(closes.load(Ordering::SeqCst), 1);
assert!(get_endpoint(&p).is_none() && task_of(&ep).is_none());
}
#[tokio::test]
async fn re_registering_hands_back_the_old_tunnel_and_clears_a_stale_stop() {
let closes = Arc::new(AtomicUsize::new(0));
let p = pid("rereg");
register(&p, fake_tunnel(61002, closes.clone()));
let id = AgentEndpoint::loopback(61003, "tok").base_url.to_string();
mark_stopped(&id, StopKind::Spot);
assert_eq!(stop_kind(&id), Some(StopKind::Spot));
let old = register(&p, fake_tunnel(61003, closes.clone())).unwrap();
assert_eq!(old.endpoint.base_url.port(), Some(61002));
assert!(!is_stopped(&id), "a new task on a reused port is not stopped");
old.forward.close().await;
close(&p).await;
assert_eq!(closes.load(Ordering::SeqCst), 2);
}
#[tokio::test]
async fn a_registering_tunnel_clears_a_stop_seen_under_the_projects_unattached_id() {
let p = pid("unattached-stale");
let placeholder = unattached_id(&p);
mark_stopped(&placeholder, StopKind::Spot);
let closes = Arc::new(AtomicUsize::new(0));
register(&p, fake_tunnel(61301, closes.clone()));
assert!(!is_stopped(&placeholder), "a later unattached spell must not read as stopped");
close(&p).await;
// A re-attach registering clears it too; and it can be forgotten directly.
let q = pid("unattached-stale-reattach");
mark_stopped(&unattached_id(&q), StopKind::Spot);
let g = begin_reattach(&q);
assert!(register_if_current(&q, g, fake_tunnel(61302, closes.clone())).is_ok());
assert!(!is_stopped(&unattached_id(&q)));
close(&q).await;
mark_stopped(&unattached_id(&q), StopKind::Idle);
forget_stopped(&unattached_id(&q));
assert!(!is_stopped(&unattached_id(&q)));
}
#[tokio::test]
async fn a_reattach_that_began_before_a_stop_does_not_register() {
let closes = Arc::new(AtomicUsize::new(0));
let p = pid("gen");
let g = begin_reattach(&p);
assert!(is_pending(&p));
close(&p).await; // the user stopped the project meanwhile
let back = register_if_current(&p, g, fake_tunnel(61005, closes.clone()));
let t = back.err().expect("handed back, not registered");
assert!(get_endpoint(&p).is_none() && !is_pending(&p));
t.forward.close().await;
assert_eq!(closes.load(Ordering::SeqCst), 1);
let g = begin_reattach(&p);
assert!(register_if_current(&p, g, fake_tunnel(61006, closes.clone())).is_ok());
assert!(get_endpoint(&p).is_some());
close(&p).await;
}
#[tokio::test]
async fn a_starts_tunnel_survives_a_reattach_that_finishes_after_it() {
let closes = Arc::new(AtomicUsize::new(0));
// Start cancels the pending re-attach, then registers its own.
let p = pid("start-wins");
let g = begin_reattach(&p);
cancel_reattach(&p);
assert!(!is_pending(&p));
register(&p, fake_tunnel(61010, closes.clone()));
let late = register_if_current(&p, g, fake_tunnel(61011, closes.clone()));
late.err().expect("the late re-attach is refused").forward.close().await;
assert_eq!(get_endpoint(&p).unwrap().base_url.port(), Some(61010), "Start's tunnel stays");
assert_eq!(closes.load(Ordering::SeqCst), 1, "only the late tunnel was closed");
// A stale end of that re-attach does not clear a newer one's pending flag.
let g2 = begin_reattach(&p);
end_reattach(&p, g);
assert!(is_pending(&p));
end_reattach(&p, g2);
assert!(!is_pending(&p));
close(&p).await;
// Even without a cancel, a plain register makes an older re-attach stale.
let p = pid("register-bumps");
let g = begin_reattach(&p);
register(&p, fake_tunnel(61012, closes.clone()));
assert!(register_if_current(&p, g, fake_tunnel(61013, closes.clone())).is_err());
assert_eq!(get_endpoint(&p).unwrap().base_url.port(), Some(61012));
close(&p).await;
}
#[tokio::test]
async fn a_death_report_closes_only_the_tunnel_of_the_task_that_died() {
let closes = Arc::new(AtomicUsize::new(0));
let p = pid("died");
register(&p, fake_tunnel(61007, closes.clone()));
close_if_task(&p, "arn:aws:ecs:eu-west-1:111122223333:task/triple-c-dev/older").await;
assert!(get_endpoint(&p).is_some(), "a newer task's tunnel stays");
close_if_task(&p, "arn:aws:ecs:eu-west-1:111122223333:task/triple-c-dev/t61007").await;
assert!(get_endpoint(&p).is_none());
assert_eq!(closes.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn waiting_for_an_endpoint_ends_when_it_is_registered_or_the_reattach_gives_up() {
let p = pid("wait");
assert!(wait_endpoint(&p, Duration::from_secs(5)).await.is_none(), "nothing pending");
begin_reattach(&p);
let p2 = p.clone();
let waiter = tokio::spawn(async move { wait_endpoint(&p2, Duration::from_secs(5)).await });
tokio::time::sleep(Duration::from_millis(20)).await;
register(&p, fake_tunnel(61004, Arc::new(AtomicUsize::new(0))));
assert_eq!(waiter.await.unwrap().unwrap().base_url.port(), Some(61004));
close(&p).await;
let g = begin_reattach(&p);
let p2 = p.clone();
let waiter = tokio::spawn(async move { wait_endpoint(&p2, Duration::from_secs(5)).await });
tokio::time::sleep(Duration::from_millis(20)).await;
end_reattach(&p, g);
assert!(waiter.await.unwrap().is_none());
}
}
+283 -9
View File
@@ -3,21 +3,140 @@
//! reported dead (replayable from a point in time), and a positive-exit check
//! used to confirm each report before anything changes.
//!
//! Docker pushes `die` events. An AWS host will have no push stream from the
//! app's point of view; its [`deaths`] will be a `DescribeTasks` poll that
//! yields stopped tasks, which `container_watch` handles the same way because
//! every report is confirmed with [`ContainerTarget::has_exited`] anyway.
//! Docker pushes `die` events. AWS has no push stream from the app's point of
//! view; its [`ExitSource::deaths`] is a `DescribeTasks` poll (every 15 s) over
//! the tasks of Running AWS projects that yields the stopped ones, which
//! `container_watch` handles the same way because every report is confirmed
//! with [`ContainerTarget::has_exited`] anyway.
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
use std::time::Duration;
use futures_util::future::BoxFuture;
use futures_util::{Stream, StreamExt};
use std::pin::Pin;
use super::ContainerTarget;
use crate::docker;
/// Which host's deaths to watch. One variant today.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// How often the AWS watch asks ECS (spec, "Lifecycle and status").
pub const AWS_POLL_INTERVAL: Duration = Duration::from_secs(15);
/// Which host's deaths to watch.
#[derive(Clone)]
pub enum ExitSource {
Docker,
Aws(AwsWatch),
}
impl std::fmt::Debug for ExitSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ExitSource::Docker => f.write_str("Docker"),
ExitSource::Aws(w) => write!(f, "Aws(every {:?})", w.interval),
}
}
}
/// Where a task's DescribeTasks goes: the connection and region its
/// credentials and endpoint come from, and the cluster.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TaskGroup {
pub connection_id: String,
pub region: String,
pub cluster_arn: String,
}
/// A Running AWS project's task, and the target a death is reported as.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WatchedTask {
pub target: ContainerTarget,
pub group: TaskGroup,
pub task_arn: String,
}
/// The project-to-task lookup the AWS watch runs on, injected so it can be
/// faked (Task 6 backs it with the tunnel registry / project store and
/// `aws::tasks::stopped_among`).
pub trait AwsTaskLookup: Send + Sync {
/// The tasks of the projects that are Running now. Read on every poll.
fn running_tasks(&self) -> Vec<WatchedTask>;
/// Of `arns` (all in `group`, at most 100), the ones that are STOPPED or
/// gone. `Err` when ECS could not be asked.
fn stopped<'a>(
&'a self,
group: &'a TaskGroup,
arns: &'a [String],
) -> BoxFuture<'a, Result<Vec<String>, String>>;
}
/// The AWS death poll: a lookup and how often to run it.
#[derive(Clone)]
pub struct AwsWatch {
lookup: Arc<dyn AwsTaskLookup>,
interval: Duration,
}
impl AwsWatch {
pub fn new(lookup: Arc<dyn AwsTaskLookup>) -> Self {
Self::every(lookup, AWS_POLL_INTERVAL)
}
pub fn every(lookup: Arc<dyn AwsTaskLookup>, interval: Duration) -> Self {
AwsWatch { lookup, interval }
}
}
/// DescribeTasks' batch limit.
const DESCRIBE_BATCH: usize = 100;
/// One poll: the targets of Running projects whose task stopped. Tasks are
/// asked about per group (connection + region + cluster), 100 at a time. A
/// group that can't be asked (expired SSO, network) is logged and skipped —
/// it confirms nothing, and the other groups are still watched; the next
/// poll asks again.
pub async fn poll_stopped(lookup: &dyn AwsTaskLookup) -> Vec<ContainerTarget> {
let mut groups: HashMap<TaskGroup, Vec<WatchedTask>> = HashMap::new();
for t in lookup.running_tasks() {
groups.entry(t.group.clone()).or_default().push(t);
}
let mut dead = Vec::new();
for (group, tasks) in groups {
for chunk in tasks.chunks(DESCRIBE_BATCH) {
let arns: Vec<String> = chunk.iter().map(|t| t.task_arn.clone()).collect();
match lookup.stopped(&group, &arns).await {
Ok(stopped) => dead.extend(
chunk
.iter()
.filter(|t| stopped.contains(&t.task_arn))
.map(|t| t.target.clone()),
),
Err(e) => log::warn!(
"Container watch: could not check AWS tasks in {} ({}): {e}",
group.region,
group.cluster_arn
),
}
}
}
dead
}
/// Polls forever, `interval` apart (the first after one interval: the
/// watcher sweeps on connect), yielding each stopped task's target.
fn aws_deaths(watch: AwsWatch) -> DeathStream {
Box::pin(futures_util::stream::unfold(
(watch, VecDeque::new()),
|(watch, mut queue)| async move {
loop {
if let Some(t) = queue.pop_front() {
return Some((Ok(t), (watch, queue)));
}
tokio::time::sleep(watch.interval).await;
queue.extend(poll_stopped(&*watch.lookup).await);
}
},
))
}
pub type DeathStream = Pin<Box<dyn Stream<Item = Result<ContainerTarget, String>> + Send>>;
@@ -28,6 +147,9 @@ impl ExitSource {
pub async fn reachable(&self) -> bool {
match self {
ExitSource::Docker => docker::events::ping().await,
// No one endpoint to ping: each poll asks every group, and a
// group that fails is skipped rather than ending the stream.
ExitSource::Aws(_) => true,
}
}
@@ -38,6 +160,9 @@ impl ExitSource {
ExitSource::Docker => Box::pin(
docker::events::container_deaths(since).map(|r| r.map(ContainerTarget::docker)),
),
// ECS has no replay: a task that stopped while the stream was
// down is still STOPPED (or gone) on the next poll.
ExitSource::Aws(watch) => aws_deaths(watch.clone()),
}
}
}
@@ -52,9 +177,158 @@ impl ContainerTarget {
ContainerTarget::Docker { container_id } => docker::events::has_exited(container_id).await,
// The agent can only say "I answer" or "I don't"; silence is not a
// positive exit (an SSM blip looks the same). Only the host that
// runs the container can confirm a death — an AWS host answers
// from ECS — so through the agent alone this never confirms one.
ContainerTarget::Agent(_) => false,
// runs the container can confirm a death: the AWS watch records
// the targets whose task ECS reports STOPPED in the tunnel
// registry (R3), and nothing else ever confirms one.
ContainerTarget::Agent(ep) => super::tunnels::is_stopped(ep.base_url.as_str()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
fn group(conn: &str, region: &str) -> TaskGroup {
TaskGroup {
connection_id: conn.into(),
region: region.into(),
cluster_arn: format!("arn:aws:ecs:{region}:111122223333:cluster/triple-c-dev"),
}
}
fn task(n: usize, g: &TaskGroup) -> WatchedTask {
WatchedTask {
target: ContainerTarget::docker(format!("target-{:012}", n)),
group: g.clone(),
task_arn: format!("arn:aws:ecs:{}:111122223333:task/triple-c-dev/t{n}", g.region),
}
}
/// Running tasks are fixed; `dead` are the stopped ARNs; a group whose
/// region is `failing` errors. Every `stopped` call is recorded.
struct FakeLookup {
tasks: Mutex<Vec<WatchedTask>>,
dead: Vec<String>,
failing: &'static str,
asked: Mutex<Vec<(TaskGroup, usize)>>,
polls: Mutex<usize>,
}
impl FakeLookup {
fn new(tasks: Vec<WatchedTask>, dead: Vec<String>) -> Self {
FakeLookup {
tasks: Mutex::new(tasks),
dead,
failing: "",
asked: Mutex::new(Vec::new()),
polls: Mutex::new(0),
}
}
}
impl AwsTaskLookup for FakeLookup {
fn running_tasks(&self) -> Vec<WatchedTask> {
*self.polls.lock().unwrap() += 1;
self.tasks.lock().unwrap().clone()
}
fn stopped<'a>(
&'a self,
group: &'a TaskGroup,
arns: &'a [String],
) -> BoxFuture<'a, Result<Vec<String>, String>> {
Box::pin(async move {
self.asked.lock().unwrap().push((group.clone(), arns.len()));
if group.region == self.failing {
return Err("SSO session expired".into());
}
Ok(arns.iter().filter(|a| self.dead.contains(a)).cloned().collect())
})
}
}
#[tokio::test]
async fn a_poll_asks_each_group_once_and_reports_only_stopped_tasks() {
let (a, b) = (group("c1", "eu-west-1"), group("c2", "us-east-1"));
let tasks = vec![task(1, &a), task(2, &b), task(3, &a)];
let dead = vec![tasks[0].task_arn.clone(), tasks[1].task_arn.clone()];
let lookup = FakeLookup::new(tasks.clone(), dead);
let mut got = poll_stopped(&lookup).await;
got.sort_by(|x, y| x.id().cmp(y.id()));
assert_eq!(got, vec![tasks[0].target.clone(), tasks[1].target.clone()]);
let mut asked = lookup.asked.lock().unwrap().clone();
asked.sort_by(|x, y| x.0.region.cmp(&y.0.region));
assert_eq!(asked, vec![(a, 2), (b, 1)]);
}
#[tokio::test]
async fn a_group_that_cannot_be_asked_confirms_nothing_and_the_others_still_report() {
let (a, b) = (group("c1", "eu-west-1"), group("c2", "us-east-1"));
let tasks = vec![task(1, &a), task(2, &b)];
let dead = tasks.iter().map(|t| t.task_arn.clone()).collect();
let mut lookup = FakeLookup::new(tasks.clone(), dead);
lookup.failing = "eu-west-1";
assert_eq!(poll_stopped(&lookup).await, vec![tasks[1].target.clone()]);
}
#[tokio::test]
async fn tasks_are_described_a_hundred_at_a_time() {
let a = group("c1", "eu-west-1");
let lookup = FakeLookup::new((0..250).map(|n| task(n, &a)).collect(), Vec::new());
assert!(poll_stopped(&lookup).await.is_empty());
let sizes: Vec<usize> = lookup.asked.lock().unwrap().iter().map(|(_, n)| *n).collect();
assert_eq!(sizes, vec![100, 100, 50]);
}
#[tokio::test]
async fn no_running_aws_projects_means_no_aws_calls() {
let lookup = FakeLookup::new(Vec::new(), Vec::new());
assert!(poll_stopped(&lookup).await.is_empty());
assert!(lookup.asked.lock().unwrap().is_empty());
}
#[tokio::test(start_paused = true)]
async fn the_aws_stream_polls_every_interval_and_yields_each_death() {
let a = group("c1", "eu-west-1");
let tasks = vec![task(1, &a), task(2, &a)];
let lookup = Arc::new(FakeLookup::new(
tasks.clone(),
vec![tasks[0].task_arn.clone(), tasks[1].task_arn.clone()],
));
let source = ExitSource::Aws(AwsWatch::new(lookup.clone()));
assert!(source.reachable().await);
let mut deaths = source.deaths(0);
let t0 = tokio::time::Instant::now();
let first = deaths.next().await.unwrap().unwrap();
assert_eq!(t0.elapsed(), AWS_POLL_INTERVAL, "the first poll waits one interval");
let second = deaths.next().await.unwrap().unwrap();
assert_eq!(t0.elapsed(), AWS_POLL_INTERVAL, "one poll, both reported");
let mut got = vec![first, second];
got.sort_by(|x, y| x.id().cmp(y.id()));
assert_eq!(got, vec![tasks[0].target.clone(), tasks[1].target.clone()]);
assert_eq!(*lookup.polls.lock().unwrap(), 1);
// Once the projects are no longer Running, polls go on and report nothing.
lookup.tasks.lock().unwrap().clear();
let quiet = tokio::time::timeout(AWS_POLL_INTERVAL * 3 + Duration::from_secs(1), deaths.next()).await;
assert!(quiet.is_err(), "nothing to report");
assert_eq!(*lookup.polls.lock().unwrap(), 4);
}
#[test]
fn the_aws_poll_runs_every_fifteen_seconds() {
assert_eq!(AWS_POLL_INTERVAL, Duration::from_secs(15));
}
#[tokio::test]
async fn an_agent_target_never_confirms_an_exit_on_its_own() {
// R3: Task 6 wires the tunnel registry into this arm.
let ep = crate::host::agent::AgentEndpoint::new(
url::Url::parse("http://127.0.0.1:47901").unwrap(),
"fake-token",
)
.unwrap();
assert!(!ContainerTarget::Agent(ep).has_exited().await);
}
}
+21
View File
@@ -329,6 +329,20 @@ pub fn run() {
lifecycle_setup.track(container_watch::spawn(
app.handle().clone(),
projects_store_setup.clone(),
crate::host::watch::ExitSource::Docker,
lifecycle_setup.cancellation(),
));
// The same for AWS projects: a DescribeTasks poll every 15 s over
// the tasks of Running AWS projects (none: no AWS calls at all).
lifecycle_setup.track(container_watch::spawn(
app.handle().clone(),
projects_store_setup.clone(),
crate::host::watch::ExitSource::Aws(crate::host::watch::AwsWatch::new(
std::sync::Arc::new(crate::host::aws_host::StoreTaskLookup {
projects: projects_store_setup.clone(),
settings: settings_store_setup.clone(),
}),
)),
lifecycle_setup.cancellation(),
));
@@ -508,6 +522,9 @@ pub fn run() {
exec_manager.close_all_sessions(),
auth_bridge.stop_all(),
browser_view::manager().stop_all(),
// Each AWS tunnel is a session-manager-plugin
// child that `exit` would not end.
crate::host::tunnels::close_all(),
);
};
@@ -534,8 +551,12 @@ pub fn run() {
commands::project_commands::update_project,
commands::project_commands::start_project_container,
commands::project_commands::stop_project_container,
commands::project_commands::check_unsaved_work,
commands::project_commands::aws_task_log,
commands::project_commands::remove_aws_resources,
commands::project_commands::rebuild_project_container,
commands::project_commands::reconcile_project_statuses,
commands::project_commands::reconcile_aws_projects,
// Notes
commands::notes_commands::list_notes,
commands::notes_commands::save_note,
+445
View File
@@ -452,10 +452,295 @@ pub struct Project {
/// Global marketplace installs this project opts out of.
#[serde(default)]
pub marketplace_disabled: Vec<super::marketplace::MarketplaceItemRef>,
/// The host connection this project runs on. `None` is the local Docker
/// host; `Some(id)` names an entry of `AppSettings.hosts`.
#[serde(default)]
pub host_id: Option<String>,
/// Region and environment of an AWS-hosted project. Set together with
/// `host_id` and `aws`, or not at all.
#[serde(default)]
pub aws_placement: Option<AwsPlacement>,
#[serde(default)]
pub aws: Option<AwsWorkspaceConfig>,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AwsPlacement {
pub region: String,
pub environment: String,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum Arch {
#[default]
X86_64,
Arm64,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum StorageMode {
Ephemeral,
#[default]
Hybrid,
}
/// One git repository cloned into the workspace. `branch: None` means the
/// remote's default branch.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RepoSource {
pub url: String,
#[serde(default)]
pub branch: Option<String>,
pub folder: String,
}
fn default_aws_cpu() -> u32 {
1024
}
fn default_aws_memory_mib() -> u32 {
4096
}
fn default_aws_ephemeral_gib() -> u32 {
21
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AwsWorkspaceConfig {
#[serde(default = "default_aws_cpu")]
pub cpu: u32,
#[serde(default = "default_aws_memory_mib")]
pub memory_mib: u32,
#[serde(default)]
pub arch: Arch,
#[serde(default)]
pub storage: StorageMode,
#[serde(default = "default_aws_ephemeral_gib")]
pub ephemeral_gib: u32,
#[serde(default)]
pub spot: bool,
#[serde(default)]
pub idle_stop_minutes: Option<u32>,
#[serde(default)]
pub repos: Vec<RepoSource>,
/// Push uncommitted work to a WIP branch when the task stops. Defaults on.
#[serde(default = "default_full_permissions")]
pub wip_push_on_stop: bool,
/// Store-owned runtime state: see `ProjectsStore::set_aws_runtime`.
#[serde(default)]
pub task_arn: Option<String>,
#[serde(default)]
pub access_point_id: Option<String>,
#[serde(default)]
pub task_definition_arn: Option<String>,
}
impl Default for AwsWorkspaceConfig {
fn default() -> Self {
Self {
cpu: default_aws_cpu(),
memory_mib: default_aws_memory_mib(),
arch: Arch::default(),
storage: StorageMode::default(),
ephemeral_gib: default_aws_ephemeral_gib(),
spot: false,
idle_stop_minutes: None,
repos: Vec::new(),
wip_push_on_stop: true,
task_arn: None,
access_point_id: None,
task_definition_arn: None,
}
}
}
/// The valid Fargate memory sizes (MiB) for a CPU size, smallest first.
/// 256 CPU is the irregular one: 512, 1024 or 2048 only.
fn fargate_memory_sizes(cpu: u32) -> Option<Vec<u32>> {
let (min, max, step) = match cpu {
256 => return Some(vec![512, 1024, 2048]),
512 => (1024, 4096, 1024),
1024 => (2048, 8192, 1024),
2048 => (4096, 16384, 1024),
4096 => (8192, 30720, 1024),
8192 => (16384, 61440, 4096),
16384 => (32768, 122880, 8192),
_ => return None,
};
Some((min..=max).step_by(step as usize).collect())
}
fn validate_repo_url(url: &str) -> Result<(), String> {
let bad = |m: &str| Err(format!("Repository URL \"{}\": {}", url.escape_debug(), m));
if url.is_empty() || url.len() > 2048 {
return bad("must be 1 to 2048 characters");
}
if url.chars().any(|c| c.is_control() || c.is_whitespace()) {
return bad("must not contain whitespace or control characters");
}
if url.starts_with('-') {
return bad("must not start with '-'");
}
let ok = if let Some(rest) = url.strip_prefix("https://") {
// Credentials in the URL would sit in the project secret and in
// `.git/config` in the clear, and leak into every clone's remote.
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
if authority.contains('@') {
return bad(
"must not carry credentials (user:password@ or token@); put the token in the \
project's Git HTTPS token setting (Access) instead",
);
}
!rest.is_empty()
} else if let Some(rest) = url.strip_prefix("ssh://") {
!rest.is_empty()
} else if let Some((host, path)) = url.split_once(':') {
// scp-like `git@host:path`
!host.is_empty() && !host.contains('/') && !path.is_empty() && host.contains('@')
} else {
false
};
if ok {
Ok(())
} else {
bad("use https://..., ssh://... or git@host:path")
}
}
/// `git check-ref-format --branch` rules.
fn validate_branch(branch: &str) -> Result<(), String> {
let bad = |m: &str| Err(format!("Branch \"{}\": {}", branch.escape_debug(), m));
if branch.is_empty() || branch.len() > 255 {
return bad("must be 1 to 255 characters");
}
if branch.starts_with('-') || branch.starts_with('/') || branch.ends_with('/') {
return bad("must not start with '-' or start/end with '/'");
}
// `HEAD` passes check-ref-format but `git clone --branch HEAD` fails
// (and a branch named HEAD is refused by `git branch`).
if branch == "HEAD" {
return bad("HEAD is not a branch; leave the branch empty for the default branch");
}
if branch == "@" || branch.ends_with('.') || branch.contains("..") || branch.contains("@{") || branch.contains("//") {
return bad("is not a valid branch name");
}
if branch
.chars()
.any(|c| c.is_control() || c.is_whitespace() || "~^:?*[\\".contains(c))
{
return bad("contains a character git does not allow");
}
for comp in branch.split('/') {
if comp.starts_with('.') || comp.ends_with(".lock") {
return bad("components must not start with '.' or end with '.lock'");
}
}
Ok(())
}
fn validate_repo_folder(folder: &str) -> Result<(), String> {
let ok = !folder.is_empty()
&& folder.len() <= 64
&& folder != "."
&& folder != ".."
&& folder
.bytes()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'));
if ok {
Ok(())
} else {
Err(format!(
"Repository folder \"{}\" must be 1 to 64 characters of letters, digits, '.', '_' or '-', and not '.' or '..'",
folder.escape_debug()
))
}
}
/// "512, 1024 or 2048 MiB", or "2048 to 8192 MiB in steps of 1024".
fn describe_sizes(sizes: &[u32]) -> String {
let (first, last) = (sizes[0], sizes[sizes.len() - 1]);
if sizes.len() <= 3 {
let head: Vec<String> = sizes[..sizes.len() - 1].iter().map(u32::to_string).collect();
return format!("{} or {} MiB", head.join(", "), last);
}
format!("{} to {} MiB in steps of {}", first, last, sizes[1] - sizes[0])
}
pub fn validate_aws_workspace(cfg: &AwsWorkspaceConfig) -> Result<(), String> {
let sizes = fargate_memory_sizes(cfg.cpu).ok_or_else(|| {
format!(
"{} is not a Fargate CPU size (256, 512, 1024, 2048, 4096, 8192 or 16384)",
cfg.cpu
)
})?;
if !sizes.contains(&cfg.memory_mib) {
return Err(format!(
"{} MiB of memory is not valid with {} CPU units: use {}",
cfg.memory_mib,
cfg.cpu,
describe_sizes(&sizes)
));
}
if !(21..=200).contains(&cfg.ephemeral_gib) {
return Err("Ephemeral storage must be 21 to 200 GiB".into());
}
if let Some(m) = cfg.idle_stop_minutes {
if !(5..=1440).contains(&m) {
return Err("Idle stop must be 5 to 1440 minutes".into());
}
}
if cfg.repos.len() > 20 {
return Err("At most 20 repositories are allowed".into());
}
let mut seen = std::collections::HashSet::new();
for r in &cfg.repos {
validate_repo_url(&r.url)?;
if let Some(b) = &r.branch {
validate_branch(b)?;
}
validate_repo_folder(&r.folder)?;
if !seen.insert(r.folder.as_str()) {
return Err(format!("Repository folder \"{}\" is used twice", r.folder));
}
}
Ok(())
}
/// What Stop does with an AWS workspace's unsaved git work (the stop guard).
/// A local project ignores it.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum WipChoice {
/// Run `triple-c-wip-push --reason stop` first; a failure aborts the stop.
Push,
/// Stop without pushing from the app.
Discard,
}
/// One repository line of `triple-c-wip-push --dry-run`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RepoState {
pub folder: String,
pub dirty: bool,
pub unpushed: u64,
pub branch: String,
/// The start's background clone is still writing it: nothing to push.
#[serde(default)]
pub cloning: bool,
}
/// What `check_unsaved_work` found. `checked: false` (with `error`) when the
/// workspace could not be asked — the stop guard then cannot offer a push.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct UnsavedWork {
pub checked: bool,
pub repos: Vec<RepoState>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ProjectStatus {
@@ -701,6 +986,9 @@ impl Project {
renamed_session_names: HashMap::new(),
marketplace_installs: Vec::new(),
marketplace_disabled: Vec::new(),
host_id: None,
aws_placement: None,
aws: None,
created_at: now.clone(),
updated_at: now,
}
@@ -717,6 +1005,11 @@ impl Project {
})
}
/// Whether this project runs on an AWS host rather than local Docker.
pub fn is_aws(&self) -> bool {
self.host_id.is_some()
}
pub fn container_name(&self) -> String {
format!("triple-c-{}", self.id)
}
@@ -1011,4 +1304,156 @@ mod tests {
assert!(!obj.contains_key("auth_bridge_enabled"));
assert!(!obj.contains_key("browser_view_enabled"));
}
// ── AWS host ────────────────────────────────────────────────────────────
fn cfg(cpu: u32, mem: u32) -> AwsWorkspaceConfig {
AwsWorkspaceConfig { cpu, memory_mib: mem, ..Default::default() }
}
fn repo(url: &str, branch: Option<&str>, folder: &str) -> RepoSource {
RepoSource { url: url.into(), branch: branch.map(String::from), folder: folder.into() }
}
#[test]
fn an_old_project_without_host_fields_loads_as_local() {
let p = Project::new("demo".to_string(), Vec::new());
let mut v = serde_json::to_value(&p).unwrap();
let o = v.as_object_mut().unwrap();
o.remove("host_id");
o.remove("aws_placement");
o.remove("aws");
let loaded: Project = serde_json::from_value(v).unwrap();
assert_eq!(loaded.host_id, None);
assert!(loaded.aws.is_none() && loaded.aws_placement.is_none());
assert!(!loaded.is_aws());
}
#[test]
fn an_empty_aws_object_gets_the_defaults() {
let c: AwsWorkspaceConfig = serde_json::from_str("{}").unwrap();
assert!(c.wip_push_on_stop);
assert_eq!((c.cpu, c.memory_mib, c.ephemeral_gib), (1024, 4096, 21));
assert_eq!(c.arch, Arch::X86_64);
assert_eq!(c.storage, StorageMode::Hybrid);
assert!(!c.spot && c.idle_stop_minutes.is_none() && c.repos.is_empty());
assert!(validate_aws_workspace(&c).is_ok());
let off: AwsWorkspaceConfig = serde_json::from_str(r#"{"wip_push_on_stop":false}"#).unwrap();
assert!(!off.wip_push_on_stop);
}
#[test]
fn enums_serialize_snake_case_and_is_aws_follows_host_id() {
assert_eq!(serde_json::to_string(&Arch::Arm64).unwrap(), "\"arm64\"");
assert_eq!(serde_json::to_string(&Arch::X86_64).unwrap(), "\"x86_64\"");
assert_eq!(serde_json::to_string(&StorageMode::Hybrid).unwrap(), "\"hybrid\"");
let mut p = Project::new("d".into(), Vec::new());
p.host_id = Some("h1".into());
assert!(p.is_aws());
}
#[test]
fn cpu_and_memory_must_be_a_fargate_pair() {
// Shared with the frontend's copy (`lib/awsWorkspace.test.ts`).
let fixture: serde_json::Value =
serde_json::from_str(include_str!("../../../src/test/fixtures/fargate-pairs.json")).unwrap();
let pairs = |k: &str| -> Vec<(u32, u32)> {
fixture[k]
.as_array()
.unwrap()
.iter()
.map(|p| (p[0].as_u64().unwrap() as u32, p[1].as_u64().unwrap() as u32))
.collect()
};
for (c, m) in pairs("valid") {
assert!(validate_aws_workspace(&cfg(c, m)).is_ok(), "{c}/{m} should be valid");
}
for (c, m) in pairs("invalid") {
assert!(validate_aws_workspace(&cfg(c, m)).is_err(), "{c}/{m} should be rejected");
}
let e = validate_aws_workspace(&cfg(256, 1536)).unwrap_err();
assert!(e.ends_with("use 512, 1024 or 2048 MiB"), "{e}");
let e = validate_aws_workspace(&cfg(1024, 2500)).unwrap_err();
assert!(e.ends_with("use 2048 to 8192 MiB in steps of 1024"), "{e}");
}
#[test]
fn ephemeral_storage_is_21_to_200() {
for (g, ok) in [(20, false), (21, true), (200, true), (201, false)] {
let c = AwsWorkspaceConfig { ephemeral_gib: g, ..Default::default() };
assert_eq!(validate_aws_workspace(&c).is_ok(), ok, "{g}");
}
}
#[test]
fn idle_stop_is_5_to_1440_or_off() {
for (m, ok) in [(None, true), (Some(4), false), (Some(5), true), (Some(1440), true), (Some(1441), false)] {
let c = AwsWorkspaceConfig { idle_stop_minutes: m, ..Default::default() };
assert_eq!(validate_aws_workspace(&c).is_ok(), ok, "{m:?}");
}
}
fn with_repos(repos: Vec<RepoSource>) -> AwsWorkspaceConfig {
AwsWorkspaceConfig { repos, ..Default::default() }
}
#[test]
fn repo_folders_follow_the_charset_and_are_unique() {
let ok = |f: &str| validate_aws_workspace(&with_repos(vec![repo("https://h/r.git", None, f)])).is_ok();
assert!(ok("my-repo_1.x"));
assert!(ok(&"a".repeat(64)));
for bad in ["", ".", "..", "a/b", "a b", "ü", &"a".repeat(65)] {
assert!(!ok(bad), "{bad:?}");
}
let dup = with_repos(vec![repo("https://h/a", None, "x"), repo("https://h/b", None, "x")]);
assert!(validate_aws_workspace(&dup).unwrap_err().contains("twice"));
let two = with_repos(vec![repo("https://h/a", None, "x"), repo("https://h/b", None, "y")]);
assert!(validate_aws_workspace(&two).is_ok());
}
#[test]
fn repo_urls_are_https_scp_or_ssh() {
let ok = |u: &str| validate_aws_workspace(&with_repos(vec![repo(u, None, "x")])).is_ok();
for good in ["https://github.com/o/r.git", "git@github.com:o/r.git", "ssh://git@h/o/r.git"] {
assert!(ok(good), "{good}");
}
for bad in ["", "http://h/r", "file:///etc", "/local/path", "--upload-pack=x", "github.com:o/r", "https://h/r x", "ext::sh -c id", "https://"] {
assert!(!ok(bad), "{bad:?}");
}
}
#[test]
fn an_https_url_with_credentials_is_refused_pointing_at_the_token_setting() {
let check = |u: &str| validate_aws_workspace(&with_repos(vec![repo(u, None, "x")]));
for bad in [
"https://user:pass@github.com/o/r.git",
"https://ghp_abc@github.com/o/r.git",
"https://oauth2:tok@gitlab.com/o/r",
] {
let e = check(bad).unwrap_err();
assert!(e.contains("Git HTTPS token"), "{e}");
}
// An @ in the path is not userinfo; ssh and scp forms keep their user.
for good in ["https://h/o/r@v2.git", "ssh://git@h/o/r.git", "git@github.com:o/r.git"] {
assert!(check(good).is_ok(), "{good}");
}
}
#[test]
fn branches_follow_check_ref_format() {
let ok = |b: Option<&str>| validate_aws_workspace(&with_repos(vec![repo("https://h/r", b, "x")])).is_ok();
for good in [None, Some("main"), Some("feat/aws-1"), Some("v1.2.3"), Some("a@b")] {
assert!(ok(good), "{good:?}");
}
for bad in ["", "-x", "a..b", "a b", "a~1", "a^", "a:b", "a?", "a*", "a[", "a\\b", "a.lock", "x/.hidden", "a/", "/a", "a//b", "a@{1}", "@", "a.", "HEAD"] {
assert!(!ok(Some(bad)), "{bad:?}");
}
}
#[test]
fn at_most_20_repos() {
let mk = |n: usize| with_repos((0..n).map(|i| repo("https://h/r", None, &format!("r{i}"))).collect());
assert!(validate_aws_workspace(&mk(20)).is_ok());
assert!(validate_aws_workspace(&mk(21)).is_err());
}
}
@@ -440,6 +440,32 @@ impl ProjectsStore {
Ok(())
}
/// Granular setter for the AWS runtime handles of a project, store-owned
/// like `container_id`. Fails if the project is not an AWS project.
pub fn set_aws_runtime(
&self,
project_id: &str,
task_arn: Option<String>,
access_point_id: Option<String>,
task_definition_arn: Option<String>,
) -> Result<(), String> {
let mut projects = self.lock();
let p = projects
.iter_mut()
.find(|p| p.id == project_id)
.ok_or_else(|| format!("Project {} not found", project_id))?;
let aws = p
.aws
.as_mut()
.ok_or_else(|| format!("Project {} is not an AWS project", project_id))?;
aws.task_arn = task_arn;
aws.access_point_id = access_point_id;
aws.task_definition_arn = task_definition_arn;
p.updated_at = chrono::Utc::now().to_rfc3339();
self.save(&projects)?;
Ok(())
}
pub fn set_container_id(&self, project_id: &str, container_id: Option<String>) -> Result<(), String> {
let mut projects = self.lock();
if let Some(p) = projects.iter_mut().find(|p| p.id == project_id) {
@@ -847,4 +873,33 @@ mod tests {
assert!(sight_and_mark(&store, &full[..12], |_| false).is_some());
fs::remove_dir_all(&dir).ok();
}
#[test]
fn set_aws_runtime_writes_the_handles_and_only_for_aws_projects() {
let dir = temp_dir("aws-runtime");
let mut aws = Project::new("a".to_string(), Vec::new());
aws.host_id = Some("h".into());
aws.aws = Some(Default::default());
let local = Project::new("l".to_string(), Vec::new());
let (aid, lid) = (aws.id.clone(), local.id.clone());
let store = store_over(&dir, vec![aws, local]);
store
.set_aws_runtime(&aid, Some("t".into()), Some("ap".into()), Some("td".into()))
.unwrap();
let a = store.get(&aid).unwrap().aws.unwrap();
assert_eq!(
(a.task_arn.as_deref(), a.access_point_id.as_deref(), a.task_definition_arn.as_deref()),
(Some("t"), Some("ap"), Some("td"))
);
let on_disk: Vec<Project> =
serde_json::from_str(&fs::read_to_string(dir.join("projects.json")).unwrap()).unwrap();
assert_eq!(on_disk[0].aws.as_ref().unwrap().task_arn.as_deref(), Some("t"));
store.set_aws_runtime(&aid, None, None, None).unwrap();
assert!(store.get(&aid).unwrap().aws.unwrap().task_arn.is_none());
assert!(store.set_aws_runtime(&lid, None, None, None).is_err());
assert!(store.set_aws_runtime("nope", None, None, None).is_err());
fs::remove_dir_all(&dir).ok();
}
}
+2 -1
View File
@@ -295,7 +295,8 @@ async fn handle_open(
return Err(format!("Project '{}' is not running", project.name));
}
let container = crate::host::ContainerTarget::for_project(&project)
let container = crate::host::ContainerTarget::for_project_waiting(&project)
.await
.ok_or_else(|| "Container not running".to_string())?;
let cmd = match session_type {
+6 -1
View File
@@ -25,7 +25,7 @@ import { useMarketplaceSyncToasts } from "./hooks/useMarketplace";
import { useProjectStatusEvents } from "./hooks/useProjectStatusEvents";
import MarketplaceView from "./components/marketplace/MarketplaceView";
import { useAppState, isHomeTab, tabKeyId, homeTabKey, MARKETPLACE_TAB_KEY } from "./store/appState";
import { reconcileProjectStatuses } from "./lib/tauri-commands";
import { reconcileAwsProjects, reconcileProjectStatuses } from "./lib/tauri-commands";
export default function App() {
const { checkDocker, checkImage, startDockerPolling } = useDocker();
@@ -81,6 +81,11 @@ export default function App() {
// Initialize on mount
useEffect(() => {
loadSettings();
// AWS projects don't need Docker: ECS says which tasks run, and their
// tunnels re-open in the background.
reconcileAwsProjects()
.then(setProjects)
.catch((e) => console.error("Failed to reconcile AWS projects:", e));
let stopPolling: (() => void) | undefined;
checkDocker().then((available) => {
if (available) {
@@ -1,6 +1,9 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, act } from "@testing-library/react";
import AddProjectDialog from "./AddProjectDialog";
import { useAppState } from "../../store/appState";
import type { AppSettings, EnvironmentScan } from "../../lib/types";
import { environment } from "../../test/awsFixtures";
const add = vi.fn();
@@ -12,6 +15,11 @@ vi.mock("@tauri-apps/plugin-dialog", () => ({
open: vi.fn(async () => null),
}));
const detectAwsEnvironments = vi.fn();
vi.mock("../../lib/tauri-commands", () => ({
detectAwsEnvironments: (c: string, r: string) => detectAwsEnvironments(c, r),
}));
/** A promise whose resolution this test controls, so `loading` can be held open. */
function deferred() {
let resolve!: (v: unknown) => void;
@@ -116,3 +124,113 @@ describe("AddProjectDialog", () => {
expect(submitButton()).toHaveAccessibleDescription("");
});
});
describe("AddProjectDialog on AWS", () => {
const scan = (envs: EnvironmentScan["environments"]): EnvironmentScan => ({
region: "eu-west-1",
account: "111122223333",
owner_id: "AROA:alice",
owner_key: "abc",
state_bucket: "yes",
boundary: "yes",
environments: envs,
});
beforeEach(() => {
vi.clearAllMocks();
useAppState.setState({
appSettings: {
hosts: [
{
id: "c1",
name: "Work account",
kind: { type: "aws", auth: { method: "profile", name: "work" }, default_region: "eu-west-1" },
},
],
} as unknown as AppSettings,
});
});
function chooseAws() {
fireEvent.change(screen.getByLabelText("Runs on"), { target: { value: "c1" } });
}
it("sends the host, placement and workspace with repositories instead of folders", async () => {
detectAwsEnvironments.mockResolvedValue(
scan([environment("staging", "deploying", true), environment("dev", "ready", true)]),
);
add.mockResolvedValue({ id: "p1" });
const onClose = vi.fn();
render(<AddProjectDialog onClose={onClose} />);
chooseAws();
expect(screen.getByLabelText("Region")).toHaveValue("eu-west-1");
await waitFor(() => expect(screen.getByLabelText("Environment")).toHaveValue("dev"));
expect(detectAwsEnvironments).toHaveBeenCalledWith("c1", "eu-west-1");
expect(
(screen.getByRole("option", { name: /staging/ }) as HTMLOptionElement).disabled,
).toBe(true);
expect(screen.queryByLabelText("Folder 1 host path")).toBeNull();
fireEvent.change(screen.getByLabelText("Project name"), { target: { value: "api" } });
fireEvent.change(screen.getByLabelText("Repository 1 URL"), {
target: { value: "git@github.com:org/api.git" },
});
fireEvent.change(screen.getByLabelText("Repository 1 branch"), { target: { value: "develop" } });
fireEvent.click(submitButton());
await waitFor(() => expect(add).toHaveBeenCalled());
const [name, paths, host] = add.mock.calls[0];
expect(name).toBe("api");
expect(paths).toEqual([]);
expect(host.hostId).toBe("c1");
expect(host.awsPlacement).toEqual({ region: "eu-west-1", environment: "dev" });
expect(host.aws.repos).toEqual([
{ url: "git@github.com:org/api.git", branch: "develop", folder: "api" },
]);
expect(host.aws).toMatchObject({ cpu: 1024, memory_mib: 4096, wip_push_on_stop: true, task_arn: null });
await waitFor(() => expect(onClose).toHaveBeenCalled());
});
it("points at Settings → Hosts when no environment is usable", async () => {
detectAwsEnvironments.mockResolvedValue(scan([environment("dev", "ready", false)]));
render(<AddProjectDialog onClose={vi.fn()} />);
chooseAws();
expect(await screen.findByText(/Settings → Hosts/)).toBeInTheDocument();
expect(screen.queryByLabelText("Environment")).toBeNull();
fireEvent.change(screen.getByLabelText("Project name"), { target: { value: "api" } });
fireEvent.click(submitButton());
expect(await screen.findByRole("alert")).toHaveTextContent(/Choose an environment/);
expect(add).not.toHaveBeenCalled();
});
it("shows the backend's validation message when the add is refused", async () => {
detectAwsEnvironments.mockResolvedValue(scan([environment("dev", "update_available", true)]));
add.mockRejectedValue('Repository URL "ftp://x": use https://..., ssh://... or git@host:path');
render(<AddProjectDialog onClose={vi.fn()} />);
chooseAws();
await waitFor(() => expect(screen.getByLabelText("Environment")).toHaveValue("dev"));
fireEvent.change(screen.getByLabelText("Project name"), { target: { value: "api" } });
fireEvent.change(screen.getByLabelText("Repository 1 URL"), { target: { value: "ftp://x" } });
fireEvent.click(submitButton());
expect(await screen.findByRole("alert")).toHaveTextContent(/use https:\/\//);
});
it("forgets the environment when the region changes until that region's scan is done", async () => {
detectAwsEnvironments.mockResolvedValueOnce(scan([environment("dev", "ready", true)]));
let finish!: (v: EnvironmentScan) => void;
detectAwsEnvironments.mockReturnValueOnce(new Promise((r) => (finish = r)));
render(<AddProjectDialog onClose={vi.fn()} />);
chooseAws();
await waitFor(() => expect(screen.getByLabelText("Environment")).toHaveValue("dev"));
fireEvent.change(screen.getByLabelText("Project name"), { target: { value: "api" } });
const region = screen.getByLabelText("Region");
fireEvent.change(region, { target: { value: "us-east-1" } });
fireEvent.blur(region);
expect(await screen.findByText(/Looking for environments in us-east-1/)).toBeInTheDocument();
fireEvent.click(submitButton());
expect(await screen.findByRole("alert")).toHaveTextContent(/Choose an environment/);
expect(add).not.toHaveBeenCalled();
await act(async () => finish(scan([environment("prod", "ready", true)])));
expect(screen.getByLabelText("Environment")).toHaveValue("prod");
});
});
+259 -58
View File
@@ -1,10 +1,15 @@
import { useId, useRef, useState } from "react";
import { useEffect, useId, useRef, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import { useProjects } from "../../hooks/useProjects";
import type { ProjectPath } from "../../lib/types";
import type { DetectedEnvironment, HostConnection, ProjectPath, RepoSource } from "../../lib/types";
import { detectAwsEnvironments } from "../../lib/tauri-commands";
import { awsErrorMessage, toAwsError } from "../../lib/aws-error";
import { cleanRepos, defaultAwsWorkspace, environmentSelectable } from "../../lib/awsWorkspace";
import { useAppState } from "../../store/appState";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
import { inputClass, monoInputClass } from "../ui/Field";
import { inputClass, monoInputClass, selectClass } from "../ui/Field";
import { RepoRows, emptyRepo } from "./RepoListEditor";
interface Props {
onClose: () => void;
@@ -15,12 +20,36 @@ interface PathEntry {
mount_name: string;
}
/** Why an environment can't take a new project, for its disabled option. */
function unavailableReason(env: DetectedEnvironment): string {
const st = env.state.state;
if (st !== "ready" && st !== "update_available") return st.replace(/_/g, " ");
return "you have not joined it";
}
type Scan =
| { status: "idle" }
| { status: "loading" }
| { status: "error"; message: string }
| { status: "done"; environments: DetectedEnvironment[] };
function basenameFromPath(p: string): string {
return p.replace(/[/\\]$/, "").split(/[/\\]/).pop() || "";
}
/** Stable, so the store selector does not return a new array each render. */
const NO_HOSTS: HostConnection[] = [];
export default function AddProjectDialog({ onClose }: Props) {
const { add } = useProjects();
const hosts = useAppState((s) => s.appSettings?.hosts ?? NO_HOSTS);
const [hostId, setHostId] = useState<string>("");
const connection = hosts.find((h) => h.id === hostId) ?? null;
const [region, setRegion] = useState("");
const [scanRegion, setScanRegion] = useState("");
const [scan, setScan] = useState<Scan>({ status: "idle" });
const [environment, setEnvironment] = useState("");
const [repos, setRepos] = useState<RepoSource[]>([emptyRepo()]);
const [name, setName] = useState("");
const [pathEntries, setPathEntries] = useState<PathEntry[]>([
{ host_path: "", mount_name: "" },
@@ -30,6 +59,41 @@ export default function AddProjectDialog({ onClose }: Props) {
const nameInputRef = useRef<HTMLInputElement>(null);
const formId = useId();
// Look for environments when the connection or the region (on blur) changes.
useEffect(() => {
if (!connection || !scanRegion) {
setScan({ status: "idle" });
return;
}
let cancelled = false;
// An environment chosen in another region is not one in this region.
setEnvironment("");
setScan({ status: "loading" });
detectAwsEnvironments(connection.id, scanRegion).then(
(found) => {
if (cancelled) return;
setScan({ status: "done", environments: found.environments });
const first = found.environments.find(environmentSelectable);
setEnvironment(first?.name ?? "");
},
(e) => {
if (!cancelled) setScan({ status: "error", message: awsErrorMessage(toAwsError(e)) });
},
);
return () => {
cancelled = true;
};
}, [connection, scanRegion]);
const chooseHost = (id: string) => {
setHostId(id);
setEnvironment("");
const conn = hosts.find((h) => h.id === id);
const r = conn?.kind.default_region ?? "";
setRegion(r);
setScanRegion(r);
};
const handleBrowse = async (index: number) => {
const selected = await open({ directory: true, multiple: false });
if (typeof selected === "string") {
@@ -63,6 +127,39 @@ export default function AddProjectDialog({ onClose }: Props) {
setError("Project name is required");
return;
}
if (connection) {
// Only an environment from a finished scan of the region shown counts.
if (region.trim() !== scanRegion) {
setScanRegion(region.trim());
setError("Choose an environment in the new region first");
return;
}
if (scan.status !== "done" || !environment) {
setError("Choose an environment to run the project in");
return;
}
const cleaned = cleanRepos(repos);
if (cleaned.some((r) => !r.url)) {
setError("Every repository needs a URL");
return;
}
setLoading(true);
setError(null);
try {
await add(name.trim(), [], {
hostId: connection.id,
awsPlacement: { region: scanRegion, environment },
aws: { ...defaultAwsWorkspace(), repos: cleaned },
});
onClose();
} catch (err) {
// The backend's validation message (repository URL, folder, …).
setError(String(err));
} finally {
setLoading(false);
}
return;
}
const validPaths: ProjectPath[] = pathEntries
.filter((p) => p.host_path.trim())
.map((p) => ({
@@ -137,62 +234,166 @@ export default function AddProjectDialog({ onClose }: Props) {
/>
</div>
<div>
<span className="block text-[13px] font-medium mb-1">Folders</span>
<div className="space-y-2">
{pathEntries.map((entry, i) => (
<div
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
value={entry.host_path}
onChange={(e) => updateEntry(i, "host_path", e.target.value)}
placeholder="/path/to/folder"
aria-label={`Folder ${i + 1} host path`}
className={inputClass}
/>
<Button size="md" onClick={() => handleBrowse(i)}>
Browse
</Button>
{pathEntries.length > 1 && (
<Button
size="md"
variant="danger"
aria-label={`Remove folder ${i + 1}`}
onClick={() =>
setPathEntries(pathEntries.filter((_, j) => j !== i))
}
>
Remove
</Button>
)}
</div>
<div className="flex items-center gap-1.5">
<span className="text-xs text-[var(--text-secondary)] flex-shrink-0 font-mono">
/workspace/
</span>
<input
value={entry.mount_name}
onChange={(e) => updateEntry(i, "mount_name", e.target.value)}
placeholder="mount-name"
aria-label={`Folder ${i + 1} mount name`}
className={monoInputClass}
/>
</div>
</div>
))}
{hosts.length > 0 && (
<div>
<label
htmlFor={`${formId}-host`}
className="block text-[13px] font-medium mb-1"
>
Runs on
</label>
<select
id={`${formId}-host`}
value={hostId}
onChange={(e) => chooseHost(e.target.value)}
className={`w-full ${selectClass}`}
>
<option value="">This machine (Docker)</option>
{hosts.map((h) => (
<option key={h.id} value={h.id}>
{h.name} (AWS)
</option>
))}
</select>
</div>
<Button
className="mt-2"
onClick={() =>
setPathEntries([...pathEntries, { host_path: "", mount_name: "" }])
}
>
+ Add folder
</Button>
</div>
)}
{connection ? (
<>
<div>
<label
htmlFor={`${formId}-region`}
className="block text-[13px] font-medium mb-1"
>
Region
</label>
<input
id={`${formId}-region`}
value={region}
onChange={(e) => setRegion(e.target.value)}
onBlur={() => setScanRegion(region.trim())}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
setScanRegion(region.trim());
}
}}
className={monoInputClass}
/>
</div>
<div>
<label
htmlFor={`${formId}-env`}
className="block text-[13px] font-medium mb-1"
>
Environment
</label>
{scan.status === "loading" && (
<p className="text-xs text-[var(--text-secondary)]">
Looking for environments in {scanRegion}…
</p>
)}
{scan.status === "error" && (
<p className="text-xs text-[var(--error)]">{scan.message}</p>
)}
{scan.status === "done" && (
<>
{scan.environments.some(environmentSelectable) ? (
<select
id={`${formId}-env`}
value={environment}
onChange={(e) => setEnvironment(e.target.value)}
className={`w-full ${selectClass}`}
>
{scan.environments.map((env) => (
<option
key={env.name}
value={env.name}
disabled={!environmentSelectable(env)}
>
{environmentSelectable(env)
? env.name
: `${env.name} — ${unavailableReason(env)}`}
</option>
))}
</select>
) : (
<p className="text-xs text-[var(--text-secondary)]">
No environment in {scanRegion} is ready for you to use. Deploy or join
one in Settings → Hosts.
</p>
)}
</>
)}
</div>
<div>
<span className="block text-[13px] font-medium mb-1">Repositories</span>
<p className="mb-1.5 text-xs text-[var(--text-secondary)]">
Cloned into <span className="font-mono">/workspace/&lt;folder&gt;</span> when
the workspace starts. Memory, storage and the rest are in the project&rsquo;s
Config tab.
</p>
<RepoRows rows={repos} onRowsChange={setRepos} />
</div>
</>
) : (
<div>
<span className="block text-[13px] font-medium mb-1">Folders</span>
<div className="space-y-2">
{pathEntries.map((entry, i) => (
<div
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
value={entry.host_path}
onChange={(e) => updateEntry(i, "host_path", e.target.value)}
placeholder="/path/to/folder"
aria-label={`Folder ${i + 1} host path`}
className={inputClass}
/>
<Button size="md" onClick={() => handleBrowse(i)}>
Browse
</Button>
{pathEntries.length > 1 && (
<Button
size="md"
variant="danger"
aria-label={`Remove folder ${i + 1}`}
onClick={() =>
setPathEntries(pathEntries.filter((_, j) => j !== i))
}
>
Remove
</Button>
)}
</div>
<div className="flex items-center gap-1.5">
<span className="text-xs text-[var(--text-secondary)] flex-shrink-0 font-mono">
/workspace/
</span>
<input
value={entry.mount_name}
onChange={(e) => updateEntry(i, "mount_name", e.target.value)}
placeholder="mount-name"
aria-label={`Folder ${i + 1} mount name`}
className={monoInputClass}
/>
</div>
</div>
))}
</div>
<Button
className="mt-2"
onClick={() =>
setPathEntries([...pathEntries, { host_path: "", mount_name: "" }])
}
>
+ Add folder
</Button>
</div>
)}
{error && (
<div
@@ -0,0 +1,45 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import ConfirmRemoveModal, { ConfirmForgetAwsModal } from "./ConfirmRemoveModal";
describe("ConfirmRemoveModal", () => {
it("keeps an AWS workspace's access point unless asked", () => {
const onConfirm = vi.fn();
render(<ConfirmRemoveModal projectName="api" aws savedFiles onConfirm={onConfirm} onCancel={vi.fn()} />);
const box = screen.getByRole("checkbox", { name: /file-system access point/ });
expect(box).not.toBeChecked();
fireEvent.click(screen.getByRole("button", { name: "Remove" }));
fireEvent.click(box);
fireEvent.click(screen.getByRole("button", { name: "Remove" }));
expect(onConfirm.mock.calls).toEqual([[{ discardData: false }], [{ discardData: true }]]);
});
it("offers no access-point choice for an Ephemeral AWS workspace", () => {
const onConfirm = vi.fn();
render(<ConfirmRemoveModal projectName="api" aws onConfirm={onConfirm} onCancel={vi.fn()} />);
expect(screen.queryByRole("checkbox")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Remove" }));
expect(onConfirm).toHaveBeenCalledWith({ discardData: false });
});
it("offers no access-point choice for a local project", () => {
render(<ConfirmRemoveModal projectName="api" onConfirm={vi.fn()} onCancel={vi.fn()} />);
expect(screen.queryByRole("checkbox")).toBeNull();
expect(screen.getByText(/mounted in, not copied/)).toBeInTheDocument();
});
it("says what is left in AWS when the connection is gone", () => {
const onConfirm = vi.fn();
render(
<ConfirmForgetAwsModal
projectName="api"
reason="This project's AWS connection no longer exists"
onConfirm={onConfirm}
onCancel={vi.fn()}
/>,
);
expect(screen.getByText(/task definitions, its secret and its saved files/)).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Remove and leave them in AWS" }));
expect(onConfirm).toHaveBeenCalled();
});
});
@@ -1,13 +1,28 @@
import { useState } from "react";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
interface Props {
projectName: string;
onConfirm: () => void;
/** An AWS project: its task, task definitions and secret go instead of Docker state. */
aws?: boolean;
/** AWS: the workspace may have an EFS access point (offers removing it). */
savedFiles?: boolean;
onConfirm: (opts: { discardData: boolean }) => void;
onCancel: () => void;
}
export default function ConfirmRemoveModal({ projectName, onConfirm, onCancel }: Props) {
const REMOVE_CLASS =
"bg-[var(--error-emphasis)] text-white border border-transparent hover:opacity-90";
export default function ConfirmRemoveModal({
projectName,
aws = false,
savedFiles = false,
onConfirm,
onCancel,
}: Props) {
const [discardData, setDiscardData] = useState(false);
return (
<Modal
title="Remove Project"
@@ -20,32 +35,103 @@ export default function ConfirmRemoveModal({ projectName, onConfirm, onCancel }:
</Button>
<Button
size="md"
onClick={onConfirm}
className="bg-[var(--error-emphasis)] text-white border border-transparent hover:opacity-90"
onClick={() => onConfirm({ discardData: savedFiles && discardData })}
className={REMOVE_CLASS}
>
Remove
</Button>
</>
}
>
{/*
Everything remove_project() destroys, named. It removes the container,
*both* named volumes (triple-c-home-{id} and triple-c-claude-config-{id}),
the triple-c-snapshot-{id} image and the project's keychain secrets — so
an accurate warning has to reach past "the config volume". The last
sentence is the reassuring half and matters just as much: project folders
are bind mounts from the host and nothing here touches them.
*/}
<p className="text-[13px] text-[var(--text-secondary)]">
Are you sure you want to remove{" "}
<strong className="text-[var(--text-primary)]">{projectName}</strong>? This deletes
its container, both of its volumes and its saved container image — so the home
directory, the Claude login and config, installed skills, session transcripts,
scheduled tasks and any stored credentials all go with it.
</p>
{aws ? (
<>
<p className="text-[13px] text-[var(--text-secondary)]">
Are you sure you want to remove{" "}
<strong className="text-[var(--text-primary)]">{projectName}</strong>? This stops its
workspace on AWS and deletes its secret. Its task definitions stay registered (they hold no secrets and cost
nothing); an administrator can deregister them. Work that was not pushed to a
remote is lost.
</p>
{savedFiles && (
<label className="mt-3 flex items-start gap-2 text-[13px] text-[var(--text-primary)]">
<input
type="checkbox"
className="mt-0.5"
checked={discardData}
onChange={(e) => setDiscardData(e.target.checked)}
/>
<span>
Also remove the workspace&rsquo;s file-system access point
<span className="block text-xs text-[var(--text-secondary)]">
The saved files themselves (Claude login, history, SSH keys) stay on your own
EFS file system, readable only by your workspace role, until an administrator
offboards you.
</span>
</span>
</label>
)}
</>
) : (
<>
{/*
Everything remove_project() destroys, named. It removes the container,
*both* named volumes (triple-c-home-{id} and triple-c-claude-config-{id}),
the triple-c-snapshot-{id} image and the project's keychain secrets — so
an accurate warning has to reach past "the config volume". The last
sentence is the reassuring half and matters just as much: project folders
are bind mounts from the host and nothing here touches them.
*/}
<p className="text-[13px] text-[var(--text-secondary)]">
Are you sure you want to remove{" "}
<strong className="text-[var(--text-primary)]">{projectName}</strong>? This deletes
its container, both of its volumes and its saved container image — so the home
directory, the Claude login and config, installed skills, session transcripts,
scheduled tasks and any stored credentials all go with it.
</p>
<p className="mt-2 text-[13px] text-[var(--text-secondary)]">
Your project folders on this machine are mounted in, not copied, and are left
untouched.
</p>
</>
)}
</Modal>
);
}
/** The second confirm when an AWS project's connection is gone. */
export function ConfirmForgetAwsModal({
projectName,
reason,
onConfirm,
onCancel,
}: {
projectName: string;
reason: string;
onConfirm: () => void;
onCancel: () => void;
}) {
return (
<Modal
title="Remove without its AWS resources?"
onClose={onCancel}
widthClassName="w-[28rem]"
footer={
<>
<Button size="md" variant="ghost" onClick={onCancel}>
Cancel
</Button>
<Button size="md" onClick={onConfirm} className={REMOVE_CLASS}>
Remove and leave them in AWS
</Button>
</>
}
>
<p className="text-[13px] text-[var(--text-secondary)]">{reason}</p>
<p className="mt-2 text-[13px] text-[var(--text-secondary)]">
Your project folders on this machine are mounted in, not copied, and are left
untouched.
Removing <strong className="text-[var(--text-primary)]">{projectName}</strong> now
leaves its AWS resources in the account: the task (which may still be running and
billed), its task definitions, its secret and its saved files. You would have to
remove them in AWS yourself.
</p>
</Modal>
);
+23 -3
View File
@@ -4,6 +4,8 @@ import { useAppState, homeTabKey } from "../../store/appState";
import { useProjectActions } from "../../hooks/useProjectActions";
import { ProjectStatusIndicator } from "../ui/StatusIndicator";
import { useUnavailable } from "../ui/unavailable";
import { isAwsProject } from "../../lib/awsWorkspace";
import StopGuardModal from "./StopGuardModal";
interface Props {
project: Project;
@@ -23,8 +25,13 @@ export default function ProjectRow({ project }: Props) {
progress: s.containerProgress[project.id],
})),
);
const { busy, handleStart, handleStop, openClaudeTerminal } =
const { busy, handleStart, handleStop, openClaudeTerminal, stopGuard, resolveStopGuard } =
useProjectActions(project);
const aws = isAwsProject(project);
// An AWS project mounts nothing; its clones are what /workspace holds.
const folders = aws
? (project.aws?.repos ?? []).map((r) => r.folder)
: project.paths.map((pp) => pp.mount_name);
const isSelected =
activeTabKey === homeTabKey(project.id) || selectedProjectId === project.id;
@@ -64,12 +71,17 @@ export default function ProjectRow({ project }: Props) {
<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) => (
{aws && (
<div className="text-xs text-[var(--text-secondary)] truncate">
AWS · {project.aws_placement?.environment ?? "?"} ({project.aws_placement?.region ?? "?"})
</div>
)}
{folders.map((folder, i) => (
<div
key={i}
className="text-xs text-[var(--text-secondary)] truncate font-mono"
>
/workspace/{pp.mount_name}
/workspace/{folder}
</div>
))}
<div className="text-xs">
@@ -149,6 +161,14 @@ export default function ProjectRow({ project }: Props) {
</button>
{terminal.reasonNode}
</div>
{stopGuard && (
<StopGuardModal
projectName={project.name}
work={stopGuard}
wipPushOnStop={project.aws?.wip_push_on_stop ?? false}
onChoose={resolveStopGuard}
/>
)}
</div>
);
}
@@ -0,0 +1,139 @@
import { useEffect, useRef, useState } from "react";
import type { RepoSource } from "../../lib/types";
import { cleanRepos, repoFolderFromUrl } from "../../lib/awsWorkspace";
import Button from "../ui/Button";
import { inputClass, monoInputClass } from "../ui/Field";
export interface RepoRowsProps {
rows: RepoSource[];
onRowsChange: (rows: RepoSource[]) => void;
/** Called when focus leaves a field (save-on-blur editors). */
onCommit?: () => void;
disabled?: boolean;
}
export const emptyRepo = (): RepoSource => ({ url: "", branch: null, folder: "" });
/** Rows of URL / branch / folder. The folder follows the URL until it is edited. */
export function RepoRows({ rows, onRowsChange, onCommit, disabled = false }: RepoRowsProps) {
const update = (i: number, patch: Partial<RepoSource>) => {
const next = [...rows];
next[i] = { ...next[i], ...patch };
onRowsChange(next);
};
return (
<div className="space-y-2">
{rows.map((r, i) => (
<div
key={i}
className="space-y-1.5 p-2 bg-[var(--bg-primary)] rounded-[var(--radius-control)] border border-[var(--border-color)]"
>
<input
value={r.url}
aria-label={`Repository ${i + 1} URL`}
placeholder="git@github.com:org/repo.git or https://…"
disabled={disabled}
onChange={(e) => {
const url = e.target.value;
const followed = !r.folder || r.folder === repoFolderFromUrl(r.url);
update(i, { url, ...(followed ? { folder: repoFolderFromUrl(url) } : {}) });
}}
onBlur={onCommit}
className={monoInputClass}
/>
<div className="flex items-center gap-1.5">
<input
value={r.branch ?? ""}
aria-label={`Repository ${i + 1} branch`}
placeholder="default branch"
disabled={disabled}
onChange={(e) => update(i, { branch: e.target.value })}
onBlur={onCommit}
className={`w-40 ${inputClass}`}
/>
<span className="text-xs text-[var(--text-secondary)] flex-shrink-0 font-mono">
/workspace/
</span>
<input
value={r.folder}
aria-label={`Repository ${i + 1} folder`}
placeholder="folder"
disabled={disabled}
onChange={(e) => update(i, { folder: e.target.value })}
onBlur={onCommit}
className={monoInputClass}
/>
<Button
size="md"
variant="danger"
disabled={disabled}
aria-label={`Remove repository ${i + 1}`}
onClick={() => {
onRowsChange(rows.filter((_, j) => j !== i));
// A removal is a finished edit; `onRowsChange` has already
// handed the shorter list over.
onCommit?.();
}}
>
Remove
</Button>
</div>
</div>
))}
<Button disabled={disabled} onClick={() => onRowsChange([...rows, emptyRepo()])}>
+ Add repository
</Button>
</div>
);
}
function sameRepos(a: RepoSource[], b: RepoSource[]): boolean {
return (
a.length === b.length &&
a.every((r, i) => r.url === b[i].url && r.branch === b[i].branch && r.folder === b[i].folder)
);
}
/**
* The Config tab's save-on-blur repository list. Saves when every row that
* has anything in it has a URL; the backend's validation message (bad URL,
* folder used twice…) comes back through the save's toast.
*
* Rows in progress survive a refresh of the project list: they are replaced
* from `repos` only when the stored value actually changed.
*/
export default function RepoListEditor({
repos,
onSave,
disabled = false,
}: {
repos: RepoSource[];
onSave: (repos: RepoSource[]) => Promise<boolean>;
disabled?: boolean;
}) {
const [rows, setRows] = useState<RepoSource[]>(repos);
// The latest rows, so a commit right after an edit (a removal) sees them.
const rowsRef = useRef(rows);
const storedRef = useRef(repos);
useEffect(() => {
if (sameRepos(repos, storedRef.current)) return;
storedRef.current = repos;
rowsRef.current = repos;
setRows(repos);
}, [repos]);
const change = (next: RepoSource[]) => {
rowsRef.current = next;
setRows(next);
};
const commit = () => {
const cleaned = cleanRepos(rowsRef.current);
if (cleaned.some((r) => !r.url)) return;
if (sameRepos(cleaned, storedRef.current)) return;
void onSave(cleaned);
};
return <RepoRows rows={rows} onRowsChange={change} onCommit={commit} disabled={disabled} />;
}
@@ -0,0 +1,67 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import StopGuardModal from "./StopGuardModal";
import type { UnsavedWork } from "../../lib/types";
const dirty: UnsavedWork = {
checked: true,
repos: [
{ folder: "api", branch: "main", dirty: true, unpushed: 2 },
{ folder: "clean", branch: "main", dirty: false, unpushed: 0 },
],
error: null,
};
describe("StopGuardModal", () => {
it("lists the repositories at risk and defaults to pushing", async () => {
const onChoose = vi.fn();
render(<StopGuardModal projectName="api" work={dirty} onChoose={onChoose} />);
expect(screen.getByText("/workspace/api")).toBeInTheDocument();
expect(screen.getByText(/uncommitted changes, 2 unpushed commits/)).toBeInTheDocument();
expect(screen.queryByText("/workspace/clean")).toBeNull();
const push = screen.getByRole("button", { name: "Push to WIP branch and stop" });
await waitFor(() => expect(push).toHaveFocus());
fireEvent.click(push);
expect(onChoose).toHaveBeenCalledWith("push");
});
it("lists a repository still cloning as having nothing to push", () => {
const work: UnsavedWork = {
...dirty,
repos: [...dirty.repos, { folder: "big", branch: "", dirty: false, unpushed: 0, cloning: true }],
};
render(<StopGuardModal projectName="api" work={work} onChoose={vi.fn()} />);
expect(screen.getByText("/workspace/big")).toBeInTheDocument();
expect(screen.getByText("still cloning — nothing to push")).toBeInTheDocument();
expect(screen.getByText("/workspace/api")).toBeInTheDocument();
});
it("offers Stop without pushing and Cancel", () => {
const onChoose = vi.fn();
render(<StopGuardModal projectName="api" work={dirty} onChoose={onChoose} />);
fireEvent.click(screen.getByRole("button", { name: "Stop without pushing" }));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(onChoose.mock.calls).toEqual([["discard"], [null]]);
});
it("hides Push and says why when the workspace could not be checked", async () => {
const onChoose = vi.fn();
render(
<StopGuardModal
projectName="api"
work={{ checked: false, repos: [], error: "Triple-C is not connected to the workspace" }}
wipPushOnStop
onChoose={onChoose}
/>,
);
expect(screen.queryByRole("button", { name: /Push/ })).toBeNull();
expect(screen.getByText(/own push of work in progress still runs/)).toBeInTheDocument();
expect(screen.getByText("Triple-C is not connected to the workspace")).toBeInTheDocument();
expect(screen.getByText(/could not check/)).toBeInTheDocument();
const stop = screen.getByRole("button", { name: "Stop anyway" });
await waitFor(() => expect(stop).toHaveFocus());
// Nothing is recorded: the shutdown push the copy promises still runs.
fireEvent.click(stop);
expect(onChoose).toHaveBeenCalledWith("unguarded");
});
});
@@ -0,0 +1,120 @@
import { useRef } from "react";
import type { UnsavedWork, WipChoice } from "../../lib/types";
import Modal from "../ui/Modal";
import Button from "../ui/Button";
export type StopGuardChoice = WipChoice | "unguarded" | null;
interface Props {
projectName: string;
work: UnsavedWork;
/** The project's "push work in progress when the workspace stops" setting. */
wipPushOnStop?: boolean;
/** `null` = Cancel. `"unguarded"` = stop without recording any choice
* (the unchecked case: the workspace's own shutdown push still runs). */
onChoose: (choice: StopGuardChoice) => void;
}
function describeRepo(dirty: boolean, unpushed: number): string {
const parts: string[] = [];
if (dirty) parts.push("uncommitted changes");
if (unpushed > 0) parts.push(`${unpushed} unpushed commit${unpushed === 1 ? "" : "s"}`);
return parts.join(", ");
}
/**
* Asked before an AWS workspace stops when its repositories hold work no
* remote has, or when Triple-C could not check. Pushing to a WIP branch is
* the default (it has focus); it is not offered when the check could not
* run, since the push goes the same way the check did.
*/
export default function StopGuardModal({ projectName, work, wipPushOnStop = false, onChoose }: Props) {
const pushRef = useRef<HTMLButtonElement>(null);
const stopRef = useRef<HTMLButtonElement>(null);
const atRisk = work.repos.filter((r) => !r.cloning && (r.dirty || r.unpushed > 0));
const cloning = work.repos.filter((r) => r.cloning);
return (
<Modal
title="Unsaved work"
onClose={() => onChoose(null)}
widthClassName="w-[30rem]"
initialFocusRef={work.checked ? pushRef : stopRef}
footer={
<>
<Button size="md" variant="ghost" onClick={() => onChoose(null)}>
Cancel
</Button>
<Button
ref={stopRef}
size="md"
variant={work.checked ? "danger" : "primary"}
onClick={() => onChoose(work.checked ? "discard" : "unguarded")}
>
{work.checked ? "Stop without pushing" : "Stop anyway"}
</Button>
{work.checked && (
<Button ref={pushRef} size="md" variant="primary" onClick={() => onChoose("push")}>
Push to WIP branch and stop
</Button>
)}
</>
}
>
{work.checked ? (
<>
<p className="text-[13px] text-[var(--text-secondary)]">
Stopping <strong className="text-[var(--text-primary)]">{projectName}</strong> ends
its workspace. These repositories have work that no remote has yet:
</p>
<ul className="mt-2 space-y-1">
{atRisk.map((r) => (
<li key={r.folder} className="text-[13px] text-[var(--text-primary)]">
<span className="font-mono">/workspace/{r.folder}</span>{" "}
<span className="text-[var(--text-secondary)]">
({r.branch}): {describeRepo(r.dirty, r.unpushed)}
</span>
</li>
))}
{cloning.map((r) => (
<li key={r.folder} className="text-[13px] text-[var(--text-primary)]">
<span className="font-mono">/workspace/{r.folder}</span>{" "}
<span className="text-[var(--text-secondary)]">
still cloning — nothing to push
</span>
</li>
))}
</ul>
<p className="mt-3 text-[13px] text-[var(--text-secondary)]">
Push to WIP branch saves a snapshot of each repository to a{" "}
<span className="font-mono">triple-c/wip/…</span> branch on its remote, without
touching your branches. If the push fails, the workspace keeps running. Stop
without pushing skips that push, including the one the workspace would make as it
shuts down.
</p>
</>
) : (
<>
<p className="text-[13px] text-[var(--text-secondary)]">
Triple-C could not check{" "}
<strong className="text-[var(--text-primary)]">{projectName}</strong> for unsaved
work, so it can&rsquo;t push it to a WIP branch first.
</p>
{work.error && (
<p
role="note"
className="mt-2 px-2 py-1.5 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)]"
>
{work.error}
</p>
)}
<p className="mt-2 text-[13px] text-[var(--text-secondary)]">
Uncommitted or unpushed work in the workspace may be lost if you stop it now.
{wipPushOnStop &&
" The workspace's own push of work in progress still runs as it shuts down, if it can reach the remote."}
</p>
</>
)}
</Modal>
);
}
@@ -6,6 +6,8 @@ import ModelSection from "./config/ModelSection";
import AccessSection from "./config/AccessSection";
import RuntimeSection from "./config/RuntimeSection";
import MarketplaceSection from "./config/MarketplaceSection";
import HostSection from "./config/HostSection";
import { isAwsProject } from "../../../lib/awsWorkspace";
interface Props {
project: Project;
@@ -40,6 +42,9 @@ export default function ConfigTab({ project, save, saveState }: Props) {
</div>
<WorkspaceSection project={project} save={save} disabled={disabled} />
{isAwsProject(project) && (
<HostSection project={project} save={save} disabled={disabled} />
)}
<ModelSection project={project} save={save} disabled={disabled} />
<AccessSection
project={project}
@@ -0,0 +1,81 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import ProjectHome from "./ProjectHome";
import { useAppState } from "../../../store/appState";
import { awsProject } from "../../../test/awsFixtures";
import { AWS_CONNECTION_MISSING } from "../../../lib/types";
const remove = vi.fn();
const project = awsProject({ name: "api" });
vi.mock("../../../hooks/useProjects", () => ({
useProjects: () => ({ projects: [project], remove }),
}));
vi.mock("../../../hooks/useProjectActions", () => ({
useProjectActions: () => ({
busy: false,
backingUp: false,
handleStart: vi.fn(),
handleStop: vi.fn(),
handleReset: vi.fn(),
handleBackup: vi.fn(),
openClaudeTerminal: vi.fn(),
openShell: vi.fn(),
stopGuard: null,
resolveStopGuard: vi.fn(),
}),
}));
vi.mock("../../../hooks/useSaveState", () => ({
useProjectSave: () => ({ save: vi.fn(), saveState: { status: "idle", error: null } }),
}));
vi.mock("../../../hooks/useContainerMigration", () => ({
useContainerMigration: () => ({ running: false, interrupted: false, probeSettled: true, staleness: null }),
}));
vi.mock("./OverviewTab", () => ({ default: () => <div>overview</div> }));
const clean = { container: null, image: null, volumes: [], retry_scheduled: false };
beforeEach(() => {
vi.clearAllMocks();
useAppState.setState({ toasts: [] } as never);
});
async function confirmRemove(discard = false) {
render(<ProjectHome projectId={project.id} active />);
fireEvent.click(screen.getByRole("button", { name: "More actions" }));
fireEvent.click(screen.getByRole("menuitem", { name: "Remove project…" }));
const dialog = screen.getByRole("dialog");
if (discard) fireEvent.click(within(dialog).getByRole("checkbox"));
fireEvent.click(within(dialog).getByRole("button", { name: "Remove" }));
}
describe("ProjectHome removal of an AWS project", () => {
it("passes the saved-files choice", async () => {
remove.mockResolvedValue(clean);
await confirmRemove(true);
await waitFor(() => expect(remove).toHaveBeenCalledWith(project.id, { discardData: true }));
});
it("asks again when the connection is gone, then leaves the resources in AWS", async () => {
remove
.mockRejectedValueOnce(`${AWS_CONNECTION_MISSING}This project's AWS connection no longer exists, so …`)
.mockResolvedValueOnce(clean);
await confirmRemove();
const second = await screen.findByRole("dialog", { name: "Remove without its AWS resources?" });
// The marker is not shown to the user.
expect(within(second).getByText(/connection no longer exists/).textContent).not.toContain(AWS_CONNECTION_MISSING);
fireEvent.click(within(second).getByRole("button", { name: "Remove and leave them in AWS" }));
await waitFor(() =>
expect(remove).toHaveBeenLastCalledWith(project.id, { discardData: false, forgetAwsResources: true }),
);
});
it("toasts any other failure without a second confirm", async () => {
remove.mockRejectedValueOnce("Could not stop the task: ExpiredToken");
await confirmRemove();
await waitFor(() => expect(remove).toHaveBeenCalledTimes(1));
expect(screen.queryByRole("dialog")).toBeNull();
const toasts = () => (useAppState.getState() as unknown as { toasts: { detail?: string }[] }).toasts;
await waitFor(() => expect(toasts().at(-1)?.detail).toMatch(/ExpiredToken/));
});
});
@@ -9,7 +9,10 @@ import { useContainerMigration } from "../../../hooks/useContainerMigration";
import { ProjectStatusIndicator } from "../../ui/StatusIndicator";
import Button from "../../ui/Button";
import OverflowMenu from "../../ui/OverflowMenu";
import ConfirmRemoveModal from "../ConfirmRemoveModal";
import ConfirmRemoveModal, { ConfirmForgetAwsModal } from "../ConfirmRemoveModal";
import StopGuardModal from "../StopGuardModal";
import { hasSavedFiles, isAwsProject } from "../../../lib/awsWorkspace";
import { AWS_CONNECTION_MISSING, type RemoveProjectOptions } from "../../../lib/types";
import ConfirmResetModal from "../ConfirmResetModal";
import MigrateContainerModal from "../MigrateContainerModal";
import OverviewTab from "./OverviewTab";
@@ -58,6 +61,7 @@ export default function ProjectHome({ projectId, active }: Props) {
useAppState.getState().clearPendingHomeTab();
}, [pendingHomeTab, projectId]);
const [confirmRemove, setConfirmRemove] = useState(false);
const [forgetAws, setForgetAws] = useState<{ reason: string; discardData: boolean } | null>(null);
const [confirmReset, setConfirmReset] = useState(false);
const [showMigration, setShowMigration] = useState(false);
const { runningSince, progress } = useAppState(
@@ -99,6 +103,7 @@ export default function ProjectHome({ projectId, active }: Props) {
);
}
const aws = isAwsProject(project);
const isRunning = project.status === "running";
const isTransitioning =
project.status === "starting" || project.status === "stopping";
@@ -120,6 +125,44 @@ export default function ProjectHome({ projectId, active }: Props) {
migration.probeSettled &&
!!project.container_id;
/** Remove the project; an AWS project whose connection is gone asks again. */
const removeProject = async (opts: RemoveProjectOptions) => {
try {
const report = await remove(project.id, opts);
if (!projectRemovalIsClean(report)) {
const verb = leftoverVerb(report);
if (report.retry_scheduled) {
useAppState.getState().pushToast({
kind: "info",
message: `“${project.name}” was removed, but Triple-C could not confirm all its Docker resources were removed`,
detail: `Triple-C could not confirm ${describeLeftovers(report)} ${verb} removed. It will check again the next time it starts.`,
});
} else {
// The pending-cleanup record itself failed to save — no
// retry will happen, so this must not promise one.
useAppState.getState().pushToast({
kind: "error",
message: `“${project.name}” was removed, but Triple-C could not confirm its Docker resources were removed`,
detail: `Triple-C could not confirm ${describeLeftovers(report)} ${verb} removed, and could not record this for a retry. You may need to remove ${leftoverPronoun(report)} manually (\`docker rm\` / \`docker rmi\` / \`docker volume rm\`).`,
});
}
}
} catch (e) {
const text = String(e);
const missing = text.startsWith(AWS_CONNECTION_MISSING);
const reason = missing ? text.slice(AWS_CONNECTION_MISSING.length) : text;
if (missing && !opts.forgetAwsResources) {
setForgetAws({ reason, discardData: !!opts.discardData });
return;
}
useAppState.getState().pushToast({
kind: "error",
message: `Could not remove “${project.name}”`,
detail: reason,
});
}
};
return (
<div className={`flex flex-col h-full min-h-0 ${active ? "" : "hidden"}`}>
{/* Header */}
@@ -188,12 +231,13 @@ export default function ProjectHome({ projectId, active }: Props) {
{
label: "Update container base…",
onSelect: () => setShowMigration(true),
disabled: !canMigrate,
// Docker-only: the backend refuses both for an AWS project.
disabled: aws || !canMigrate,
},
{
label: "Reset container…",
onSelect: () => setConfirmReset(true),
disabled: !isStopped || actions.busy,
disabled: aws || !isStopped || actions.busy,
danger: true,
},
{
@@ -280,39 +324,35 @@ export default function ProjectHome({ projectId, active }: Props) {
}}
/>
)}
{actions.stopGuard && (
<StopGuardModal
projectName={project.name}
work={actions.stopGuard}
wipPushOnStop={project.aws?.wip_push_on_stop ?? false}
onChoose={actions.resolveStopGuard}
/>
)}
{forgetAws && (
<ConfirmForgetAwsModal
projectName={project.name}
reason={forgetAws.reason}
onCancel={() => setForgetAws(null)}
onConfirm={() => {
const { discardData } = forgetAws;
setForgetAws(null);
void removeProject({ discardData, forgetAwsResources: true });
}}
/>
)}
{confirmRemove && (
<ConfirmRemoveModal
projectName={project.name}
aws={aws}
savedFiles={hasSavedFiles(project)}
onCancel={() => setConfirmRemove(false)}
onConfirm={async () => {
onConfirm={({ discardData }) => {
setConfirmRemove(false);
try {
const report = await remove(project.id);
if (!projectRemovalIsClean(report)) {
const verb = leftoverVerb(report);
if (report.retry_scheduled) {
useAppState.getState().pushToast({
kind: "info",
message: `“${project.name}” was removed, but Triple-C could not confirm all its Docker resources were removed`,
detail: `Triple-C could not confirm ${describeLeftovers(report)} ${verb} removed. It will check again the next time it starts.`,
});
} else {
// The pending-cleanup record itself failed to save — no
// retry will happen, so this must not promise one.
useAppState.getState().pushToast({
kind: "error",
message: `“${project.name}” was removed, but Triple-C could not confirm its Docker resources were removed`,
detail: `Triple-C could not confirm ${describeLeftovers(report)} ${verb} removed, and could not record this for a retry. You may need to remove ${leftoverPronoun(report)} manually (\`docker rm\` / \`docker rmi\` / \`docker volume rm\`).`,
});
}
}
} catch (e) {
useAppState.getState().pushToast({
kind: "error",
message: `Could not remove “${project.name}”`,
detail: String(e),
});
}
void removeProject({ discardData });
}}
/>
)}
@@ -7,6 +7,7 @@ import Field, { ConfigGroup, inputClass } from "../../../ui/Field";
import CaCertPathInput from "../../../settings/CaCertPathInput";
import EnvVarsEditor from "../../EnvVarsEditor";
import PortMappingsEditor from "../../PortMappingsEditor";
import { NOT_ON_AWS, isAwsProject } from "../../../../lib/awsWorkspace";
interface Props {
project: Project;
@@ -161,16 +162,22 @@ export default function AccessSection({
<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 })}
/>
{isAwsProject(project) ? (
<p className="mt-0.5 text-xs text-[var(--text-disabled)] leading-snug">{NOT_ON_AWS}</p>
) : (
<>
<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,224 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import RuntimeSection from "./RuntimeSection";
import AccessSection from "./AccessSection";
import WorkspaceSection from "./WorkspaceSection";
import ModelSection from "./ModelSection";
import HostSection from "./HostSection";
import { awsProject, localProject } from "../../../../test/awsFixtures";
import type { AppSettings, AuthBridgeStatus, Project } from "../../../../lib/types";
import { useAppState } from "../../../../store/appState";
const OFF_BRIDGE: AuthBridgeStatus = { enabled: false, active_ports: [], conflicts: [] };
const removeAwsResources = vi.fn();
vi.mock("../../../../lib/tauri-commands", () => ({
getAuthBridgeStatus: vi.fn(async () => OFF_BRIDGE),
setAuthBridgeEnabled: vi.fn(),
inspectCaCertPath: vi.fn(async () => null),
removeAwsResources: (id: string, discard: boolean) => removeAwsResources(id, discard),
}));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => {}) }));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: vi.fn(async () => null) }));
const save = vi.fn().mockResolvedValue(true);
beforeEach(() => vi.clearAllMocks());
function toggle(name: string) {
return screen.getByRole("switch", { name });
}
describe("AWS project config", () => {
it("locks Docker access, VPN and the sandbox on AWS, saying why", () => {
render(<RuntimeSection project={awsProject()} save={save} disabled={false} />);
for (const name of ["Allow container spawning", "VPN support", "Sandbox mode"]) {
expect(toggle(name)).toBeDisabled();
expect(toggle(name)).toHaveAttribute("aria-checked", "false");
}
expect(screen.getAllByText("Not available on AWS (Fargate)")).toHaveLength(2);
expect(screen.getByText(/Off on AWS for now/)).toBeInTheDocument();
});
it("leaves those options alone for a local project", () => {
render(<RuntimeSection project={localProject()} save={save} disabled={false} />);
expect(toggle("VPN support")).not.toBeDisabled();
expect(toggle("Sandbox mode")).toHaveAttribute("aria-checked", "true");
expect(screen.queryByText("Not available on AWS (Fargate)")).toBeNull();
});
it("replaces port mappings and folders on AWS", () => {
render(<AccessSection project={awsProject()} save={save} disabled={false} />);
expect(screen.getByText("Not available on AWS (Fargate)")).toBeInTheDocument();
expect(screen.queryByText(/Expose container ports/)).toBeNull();
render(<WorkspaceSection project={awsProject()} save={save} disabled={false} />);
expect(screen.queryByText("Folders")).toBeNull();
expect(screen.getByText(/mounts no folders/)).toBeInTheDocument();
});
it("allows every custom-endpoint backend on AWS with the reachability warning", () => {
render(
<ModelSection
project={awsProject({
backend: "open_ai_compatible",
openai_compatible_config: { base_url: "https://llm.example.com", api_key: null, model_id: null, haiku_model_id: null } as never,
})}
save={save}
disabled={false}
/>,
);
const oai = screen.getByRole("option", { name: "OpenAI Compatible" }) as HTMLOptionElement;
expect(oai.disabled).toBe(false);
expect(screen.getByText(/must be reachable from the AWS task/)).toBeInTheDocument();
expect(screen.queryByText(/can't reach it/)).toBeNull();
});
it("warns when the endpoint is this machine, or the app's own gateway", () => {
const { unmount } = render(
<ModelSection project={awsProject({ backend: "ollama" })} save={save} disabled={false} />,
);
// The Ollama default is host.docker.internal.
expect(screen.getByText(/host.docker.internal is this machine/)).toBeInTheDocument();
unmount();
useAppState.setState({
appSettings: { gateway: { enabled: true, port: 4000 } } as unknown as AppSettings,
});
render(
<ModelSection
project={awsProject({
backend: "open_ai_compatible",
openai_compatible_config: { base_url: "http://127.0.0.1:4000", api_key: null, model_id: null, haiku_model_id: null } as never,
})}
save={save}
disabled={false}
/>,
);
expect(screen.getByText(/Triple-C's own LLM gateway/)).toBeInTheDocument();
useAppState.setState({ appSettings: null });
});
});
describe("HostSection", () => {
const renderHost = (p: Project = awsProject(), disabled = false) =>
render(<HostSection project={p} save={save} disabled={disabled} />);
it("saves a CPU change with a memory size valid for it", async () => {
renderHost(); // 1024 CPU / 4096 MiB
fireEvent.change(screen.getByLabelText("CPU"), { target: { value: "256" } });
await waitFor(() => expect(save).toHaveBeenCalled());
const aws = save.mock.calls[0][0].aws;
expect([aws.cpu, aws.memory_mib]).toEqual([256, 2048]);
});
it("saves a valid memory size and refuses an invalid one", async () => {
renderHost();
const mem = screen.getByLabelText("Memory (MiB)");
fireEvent.change(mem, { target: { value: "5000" } });
fireEvent.blur(mem);
expect(screen.getByRole("alert")).toHaveTextContent(/5000 MiB of memory is not valid with 1024/);
expect(save).not.toHaveBeenCalled();
fireEvent.change(mem, { target: { value: "8192" } });
fireEvent.blur(mem);
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
expect(save.mock.calls[0][0].aws).toMatchObject({ cpu: 1024, memory_mib: 8192 });
expect(screen.queryByRole("alert")).toBeNull();
});
it("warns that Ephemeral storage loses the login and history", () => {
const p = awsProject();
p.aws = { ...p.aws!, storage: "ephemeral" };
renderHost(p);
expect(screen.getByText(/Claude login and history are lost when the workspace stops/)).toBeInTheDocument();
expect(screen.getByText(/EFS .* coming later/)).toBeInTheDocument();
});
it("saves repository edits on blur", async () => {
renderHost();
fireEvent.click(screen.getByRole("button", { name: "+ Add repository" }));
const url = screen.getByLabelText("Repository 2 URL");
fireEvent.change(url, { target: { value: "git@github.com:org/web.git" } });
fireEvent.blur(url);
await waitFor(() => expect(save).toHaveBeenCalled());
expect(save.mock.calls[0][0].aws.repos).toEqual([
{ url: "https://example.com/org/api.git", branch: null, folder: "api" },
{ url: "git@github.com:org/web.git", branch: null, folder: "web" },
]);
});
it("removes AWS resources after a confirm, and only then allows moving to this machine", async () => {
const p = awsProject();
p.aws = { ...p.aws!, task_definition_arn: "arn:td:1" };
removeAwsResources.mockResolvedValue({ ...p, aws: { ...p.aws, task_definition_arn: null } });
renderHost(p);
const move = screen.getByRole("button", { name: "Run on this machine instead" });
expect(move).toHaveAttribute("aria-disabled", "true");
fireEvent.click(move);
expect(save).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Remove AWS resources…" }));
const dialog = screen.getByRole("dialog");
// Hybrid: the access point can go too (the files stay on the user's EFS).
fireEvent.click(within(dialog).getByRole("checkbox"));
fireEvent.click(within(dialog).getByRole("button", { name: "Remove" }));
await waitFor(() => expect(removeAwsResources).toHaveBeenCalledWith(p.id, true));
});
it("keeps a project whose kept files' access point remains on AWS until it is removed", () => {
const p = awsProject();
p.aws = { ...p.aws!, access_point_id: "fsap-1", task_arn: null, task_definition_arn: null };
renderHost(p);
const move = screen.getByRole("button", { name: "Run on this machine instead" });
expect(move).toHaveAttribute("aria-disabled", "true");
expect(move).toHaveAccessibleDescription(/access point is still on AWS/);
expect(screen.getByRole("button", { name: "Remove AWS resources…" })).not.toHaveAttribute(
"aria-disabled",
"true",
);
fireEvent.click(screen.getByRole("button", { name: "Remove AWS resources…" }));
expect(within(screen.getByRole("dialog")).getByText(/access point\s+stays too/)).toBeInTheDocument();
});
it("keeps the AWS resource buttons locked while the project is in Error (its task may live)", () => {
const p = awsProject({ status: "error" });
p.aws = { ...p.aws!, task_arn: "arn:task" };
renderHost(p, false);
for (const name of ["Remove AWS resources…", "Run on this machine instead"]) {
const b = screen.getByRole("button", { name });
expect(b).toHaveAttribute("aria-disabled", "true");
expect(b).toHaveAccessibleDescription(/still running/);
}
});
it("offers no saved-files choice for an Ephemeral workspace", () => {
const p = awsProject();
p.aws = { ...p.aws!, storage: "ephemeral", task_definition_arn: "arn:td:1" };
renderHost(p);
fireEvent.click(screen.getByRole("button", { name: "Remove AWS resources…" }));
expect(within(screen.getByRole("dialog")).queryByRole("checkbox")).toBeNull();
});
it("only promises the Spot push when the WIP push is on", () => {
const p = awsProject();
p.aws = { ...p.aws!, wip_push_on_stop: false };
renderHost(p);
expect(screen.getByText(/unpushed work is lost/)).toBeInTheDocument();
expect(screen.queryByText(/push below still runs/)).toBeNull();
});
it("keeps a repository being typed when the project list refreshes with the same repos", () => {
const p = awsProject();
const { rerender } = renderHost(p);
fireEvent.click(screen.getByRole("button", { name: "+ Add repository" }));
fireEvent.change(screen.getByLabelText("Repository 2 URL"), { target: { value: "git@h:o/half" } });
// A refresh hands over a new, equal array.
const refreshed = { ...p, aws: { ...p.aws!, repos: p.aws!.repos.map((r) => ({ ...r })) } };
rerender(<HostSection project={refreshed} save={save} disabled={false} />);
expect(screen.getByLabelText("Repository 2 URL")).toHaveValue("git@h:o/half");
// A real change replaces the rows.
const changed = { ...p, aws: { ...p.aws!, repos: [] } };
rerender(<HostSection project={changed} save={save} disabled={false} />);
expect(screen.queryByLabelText("Repository 1 URL")).toBeNull();
});
});
@@ -0,0 +1,445 @@
import { useEffect, useState } from "react";
import type { AwsWorkspaceConfig, HostConnection, Project, RepoSource } from "../../../../lib/types";
import * as commands from "../../../../lib/tauri-commands";
import { useAppState } from "../../../../store/appState";
import {
EPHEMERAL_WARNING,
FARGATE_CPUS,
defaultAwsWorkspace,
formatCpu,
formatMemory,
memoryError,
hasSavedFiles,
memoryOptions,
nearestMemory,
} from "../../../../lib/awsWorkspace";
import Button from "../../../ui/Button";
import Modal from "../../../ui/Modal";
import Toggle from "../../../ui/Toggle";
import SegmentedControl from "../../../ui/SegmentedControl";
import Field, { ConfigGroup, SwitchRow, inputClass, selectClass } from "../../../ui/Field";
import RepoListEditor from "../../RepoListEditor";
interface Props {
project: Project;
save: (patch: Partial<Project>) => Promise<boolean>;
disabled: boolean;
}
const DEFAULT_IDLE_MINUTES = 60;
const STILL_RUNNING = "The task is still running — stop it first.";
/**
* Where an AWS project runs and what its Fargate task looks like. Only shown
* for AWS projects; a local project's host is chosen when it is added.
*/
/** Stable, so the store selector does not return a new array each render. */
const NO_HOSTS: HostConnection[] = [];
export default function HostSection({ project, save, disabled }: Props) {
const aws: AwsWorkspaceConfig = project.aws ?? defaultAwsWorkspace();
const hosts = useAppState((s) => s.appSettings?.hosts ?? NO_HOSTS);
const connection = hosts.find((h) => h.id === project.host_id);
const [memory, setMemory] = useState(String(aws.memory_mib));
const [memoryProblem, setMemoryProblem] = useState<string | null>(null);
const [ephemeral, setEphemeral] = useState(String(aws.ephemeral_gib));
const [ephemeralProblem, setEphemeralProblem] = useState<string | null>(null);
const [idle, setIdle] = useState(String(aws.idle_stop_minutes ?? DEFAULT_IDLE_MINUTES));
const [idleProblem, setIdleProblem] = useState<string | null>(null);
const [confirmRemoveResources, setConfirmRemoveResources] = useState(false);
useEffect(() => {
setMemory(String(aws.memory_mib));
setEphemeral(String(aws.ephemeral_gib));
setIdle(String(aws.idle_stop_minutes ?? DEFAULT_IDLE_MINUTES));
}, [aws.memory_mib, aws.ephemeral_gib, aws.idle_stop_minutes]);
const saveAws = (patch: Partial<AwsWorkspaceConfig>) => save({ aws: { ...aws, ...patch } });
const hasResources = !!(aws.task_arn || aws.access_point_id || aws.task_definition_arn);
// A removal that kept the saved files keeps their access point stored.
const onlyAccessPoint = !!aws.access_point_id && !aws.task_arn && !aws.task_definition_arn;
// Not `disabled` (which also allows Error): on AWS, Error can mean a live task.
const stopped = project.status === "stopped";
const commitMemory = () => {
const value = Number(memory);
const problem = memoryError(aws.cpu, value);
setMemoryProblem(problem);
if (problem || value === aws.memory_mib) return;
void saveAws({ memory_mib: value });
};
const commitEphemeral = () => {
const value = Number(ephemeral);
const ok = Number.isInteger(value) && value >= 21 && value <= 200;
setEphemeralProblem(ok ? null : "Ephemeral storage must be 21 to 200 GiB");
if (ok && value !== aws.ephemeral_gib) void saveAws({ ephemeral_gib: value });
};
const commitIdle = () => {
const value = Number(idle);
const ok = Number.isInteger(value) && value >= 5 && value <= 1440;
setIdleProblem(ok ? null : "Idle stop must be 5 to 1440 minutes");
if (ok && value !== aws.idle_stop_minutes) void saveAws({ idle_stop_minutes: value });
};
return (
<ConfigGroup
title="Host"
description="This project runs as an AWS Fargate task. Changes apply on its next start."
>
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[13px]">
<dt className="text-[var(--text-secondary)]">Connection</dt>
<dd className="text-[var(--text-primary)]">
{connection?.name ?? (
<span className="text-[var(--warning)]">
Removed — add it again in Settings → Hosts to start this project
</span>
)}
</dd>
<dt className="text-[var(--text-secondary)]">Region</dt>
<dd className="font-mono text-[var(--text-primary)]">{project.aws_placement?.region}</dd>
<dt className="text-[var(--text-secondary)]">Environment</dt>
<dd className="font-mono text-[var(--text-primary)]">
{project.aws_placement?.environment}
</dd>
</dl>
<div className="flex flex-wrap gap-4">
<Field label="CPU">
{(id) => (
<select
id={id}
value={aws.cpu}
disabled={disabled}
className={selectClass}
onChange={(e) => {
const cpu = Number(e.target.value);
const memory_mib = memoryError(cpu, aws.memory_mib)
? nearestMemory(cpu, aws.memory_mib)
: aws.memory_mib;
setMemoryProblem(null);
void saveAws({ cpu, memory_mib });
}}
>
{FARGATE_CPUS.map((c) => (
<option key={c} value={c}>
{formatCpu(c)}
</option>
))}
</select>
)}
</Field>
<Field
label="Memory (MiB)"
hint={(() => {
const opts = memoryOptions(aws.cpu);
return `${formatMemory(opts[0])} to ${formatMemory(opts[opts.length - 1])} with ${formatCpu(aws.cpu)}.`;
})()}
>
{(id) => (
<>
<input
id={id}
inputMode="numeric"
value={memory}
disabled={disabled}
list={`${id}-options`}
aria-invalid={memoryProblem ? true : undefined}
onChange={(e) => setMemory(e.target.value)}
onBlur={commitMemory}
onKeyDown={(e) => e.key === "Enter" && commitMemory()}
className={`w-32 ${inputClass}`}
/>
<datalist id={`${id}-options`}>
{memoryOptions(aws.cpu).map((m) => (
<option key={m} value={m} />
))}
</datalist>
</>
)}
</Field>
<div>
<span className="block text-[13px] font-medium text-[var(--text-primary)] mb-1">
Architecture
</span>
<SegmentedControl
label="Architecture"
value={aws.arch}
disabled={disabled}
onChange={(arch) => void saveAws({ arch })}
segments={[
{ value: "x86_64", label: "x86_64" },
{ value: "arm64", label: "ARM64 (Graviton)" },
]}
/>
</div>
</div>
{memoryProblem && (
<p role="alert" className="text-xs text-[var(--error)]">
{memoryProblem}
</p>
)}
<div>
<span className="block text-[13px] font-medium text-[var(--text-primary)] mb-1">
Storage
</span>
<div className="flex flex-wrap items-center gap-3">
<SegmentedControl
label="Storage"
value={aws.storage}
disabled={disabled}
onChange={(storage) => void saveAws({ storage })}
segments={[
{ value: "ephemeral", label: "Ephemeral", caution: true },
{ value: "hybrid", label: "Hybrid" },
]}
/>
<span className="text-xs text-[var(--text-disabled)]">
EFS (everything persists) — coming later
</span>
</div>
{aws.storage === "ephemeral" ? (
<p
role="note"
className="mt-2 px-2 py-1.5 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)]"
>
{EPHEMERAL_WARNING} Push your work to a remote before stopping.
</p>
) : (
<p className="mt-1 text-xs text-[var(--text-secondary)]">
The Claude login, history and SSH keys are kept on EFS between starts; everything
else, repositories included, starts fresh.
</p>
)}
</div>
<Field
label="Ephemeral storage (GiB)"
hint="The task's local disk: 21 to 200 GiB. Repositories and builds live here."
>
{(id) => (
<input
id={id}
inputMode="numeric"
value={ephemeral}
disabled={disabled}
aria-invalid={ephemeralProblem ? true : undefined}
onChange={(e) => setEphemeral(e.target.value)}
onBlur={commitEphemeral}
className={`w-24 ${inputClass}`}
/>
)}
</Field>
{ephemeralProblem && (
<p role="alert" className="text-xs text-[var(--error)]">
{ephemeralProblem}
</p>
)}
<SwitchRow
label="Spot"
hint={
aws.wip_push_on_stop
? "Runs on spare capacity at up to 70% off. AWS may reclaim it with two minutes' notice; the work-in-progress push below still runs."
: "Runs on spare capacity at up to 70% off. AWS may reclaim it with two minutes' notice, and with the work-in-progress push below off, unpushed work is lost."
}
control={
<Toggle
label="Spot"
checked={aws.spot}
disabled={disabled}
onChange={(spot) => void saveAws({ spot })}
/>
}
/>
<SwitchRow
label="Stop when idle"
hint={
aws.wip_push_on_stop
? "Stops the workspace after this many minutes without terminal input or output, Claude running or a scheduled job. Unsaved git work is pushed first; if that push fails, it stays up."
: "Stops the workspace after this many minutes without terminal input or output, Claude running or a scheduled job. With the work-in-progress push off, unsaved git work keeps it running."
}
control={
<Toggle
label="Stop when idle"
checked={aws.idle_stop_minutes !== null}
disabled={disabled}
onChange={(on) =>
void saveAws({ idle_stop_minutes: on ? Number(idle) || DEFAULT_IDLE_MINUTES : null })
}
/>
}
/>
{aws.idle_stop_minutes !== null && (
<Field label="Idle minutes" hint="5 to 1440.">
{(id) => (
<input
id={id}
inputMode="numeric"
value={idle}
disabled={disabled}
aria-invalid={idleProblem ? true : undefined}
onChange={(e) => setIdle(e.target.value)}
onBlur={commitIdle}
className={`w-24 ${inputClass}`}
/>
)}
</Field>
)}
{idleProblem && (
<p role="alert" className="text-xs text-[var(--error)]">
{idleProblem}
</p>
)}
<SwitchRow
label="Push work in progress when the workspace stops"
hint="On any stop (idle, Spot, or from AWS), each repository's uncommitted and unpushed work is pushed to a triple-c/wip/… branch on its remote."
control={
<Toggle
label="Push work in progress when the workspace stops"
checked={aws.wip_push_on_stop}
disabled={disabled}
onChange={(wip_push_on_stop) => void saveAws({ wip_push_on_stop })}
/>
}
/>
<div className="pt-2 border-t border-[var(--border-color)]">
<span className="block text-[13px] font-medium text-[var(--text-primary)]">
Repositories
</span>
<p className="mt-0.5 mb-2 text-xs text-[var(--text-secondary)] leading-snug">
Cloned into <span className="font-mono">/workspace/&lt;folder&gt;</span> when the
workspace starts, with the project&rsquo;s SSH key or Git token.
</p>
<RepoListEditor
repos={aws.repos}
disabled={disabled}
onSave={(repos: RepoSource[]) => saveAws({ repos })}
/>
</div>
<div className="pt-2 border-t border-[var(--border-color)] flex flex-wrap items-center gap-2">
<Button
size="md"
variant="danger"
unavailable={!stopped || !hasResources}
unavailableReason={
!stopped
? STILL_RUNNING
: "This project has no AWS resources to remove."
}
onClick={() => setConfirmRemoveResources(true)}
>
Remove AWS resources…
</Button>
<Button
size="md"
unavailable={!stopped || hasResources}
unavailableReason={
!stopped
? STILL_RUNNING
: onlyAccessPoint
? "The saved files' access point is still on AWS. Remove the AWS resources with \u201cAlso remove the workspace\u2019s file-system access point\u201d first."
: "Remove the workspace's AWS resources first, so nothing is left running or billed."
}
onClick={() => void save({ host_id: null, aws_placement: null, aws: null })}
>
Run on this machine instead
</Button>
</div>
{confirmRemoveResources && (
<RemoveAwsResourcesModal
project={project}
onClose={() => setConfirmRemoveResources(false)}
/>
)}
</ConfigGroup>
);
}
function RemoveAwsResourcesModal({ project, onClose }: { project: Project; onClose: () => void }) {
const [discardData, setDiscardData] = useState(false);
const [running, setRunning] = useState(false);
const [error, setError] = useState<string | null>(null);
const confirm = async () => {
if (running) return;
setRunning(true);
setError(null);
try {
const updated = await commands.removeAwsResources(project.id, hasSavedFiles(project) && discardData);
useAppState.getState().updateProjectInList(updated);
onClose();
} catch (e) {
setError(String(e));
} finally {
setRunning(false);
}
};
return (
<Modal
title="Remove AWS resources"
onClose={onClose}
widthClassName="w-[28rem]"
footer={
<>
<Button size="md" variant="ghost" onClick={onClose}>
Cancel
</Button>
<Button
size="md"
variant="danger"
unavailable={running}
unavailableReason="Removing…"
onClick={() => void confirm()}
>
{running ? "Removing…" : "Remove"}
</Button>
</>
}
>
<p className="text-[13px] text-[var(--text-secondary)]">
Removes <strong className="text-[var(--text-primary)]">{project.name}</strong>&rsquo;s
secret from AWS and keeps the project, so it can run somewhere else. Its task
definitions stay registered for an administrator to deregister. Its next start on AWS
sets everything up again.
</p>
{hasSavedFiles(project) && (
<label className="mt-3 flex items-start gap-2 text-[13px] text-[var(--text-primary)]">
<input
type="checkbox"
className="mt-0.5"
checked={discardData}
onChange={(e) => setDiscardData(e.target.checked)}
/>
<span>
Also remove the workspace&rsquo;s file-system access point
<span className="block text-xs text-[var(--text-secondary)]">
The files stay on your own EFS file system (only your workspace role can read
them) until an administrator offboards you. Left unchecked, the access point
stays too: the next start here reuses it, and the project can&rsquo;t move to
another host until it is removed.
</span>
</span>
</label>
)}
{error && (
<p
role="alert"
className="mt-3 px-2 py-1.5 text-xs text-[var(--error)] bg-[var(--error-muted)] border border-[var(--error)]/30 rounded-[var(--radius-control)]"
>
{error}
</p>
)}
</Modal>
);
}
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import ModelSection, {
BEDROCK_PROFILE_ON_AWS,
DEFAULT_LLAMACPP_CONFIG,
DEFAULT_OLLAMA_CONFIG,
} from "./ModelSection";
@@ -215,3 +216,34 @@ describe("ModelSection — background (haiku) model override", () => {
expect(screen.getByText(/background work/i)).toBeInTheDocument();
});
});
describe("ModelSection — Bedrock on AWS", () => {
const bedrock = (auth_method: "profile" | "static_credentials" | "bearer_token") => ({
backend: "bedrock" as const,
bedrock_config: {
auth_method,
aws_region: "us-east-1",
aws_access_key_id: null,
aws_secret_access_key: null,
aws_session_token: null,
aws_profile: "dev",
aws_bearer_token: null,
model_id: null,
service_tier: null,
disable_prompt_caching: false,
} as unknown as Project["bedrock_config"],
});
it("warns that a named profile can't work in an AWS workspace", () => {
renderSection({ ...bedrock("profile"), host_id: "c1" } as Partial<Project>);
expect(screen.getByText(BEDROCK_PROFILE_ON_AWS)).toBeInTheDocument();
});
it("says nothing for a local project or another auth method", () => {
const { unmount } = renderSection(bedrock("profile"));
expect(screen.queryByText(BEDROCK_PROFILE_ON_AWS)).toBeNull();
unmount();
renderSection({ ...bedrock("static_credentials"), host_id: "c1" } as Partial<Project>);
expect(screen.queryByText(BEDROCK_PROFILE_ON_AWS)).toBeNull();
});
});
@@ -9,6 +9,7 @@ import type {
OpenAiCompatibleConfig,
Project,
} from "../../../../lib/types";
import { CUSTOM_ENDPOINT_BACKENDS } from "../../../../lib/types";
import Field, {
ConfigGroup,
SwitchRow,
@@ -16,6 +17,15 @@ import Field, {
selectClass,
} from "../../../ui/Field";
import Toggle from "../../../ui/Toggle";
import { isAwsProject, localEndpointProblem } from "../../../../lib/awsWorkspace";
import { useAppState } from "../../../../store/appState";
/** P6: an AWS workspace can reach a local model only over the network. */
const LOCAL_MODEL_ON_AWS =
"This project runs on AWS: the URL must be reachable from the AWS task, so host.docker.internal, localhost and this machine's LAN addresses will not work.";
export const BEDROCK_PROFILE_ON_AWS =
"This project runs on AWS: a named profile is read from ~/.aws on this machine, which the AWS workspace does not have, and an SSO login cannot be refreshed there. Use static keys or a bearer token instead.";
/** Bedrock fields held in the OS keychain, never serialized back to us. */
const BEDROCK_SECRET_KEYS = [
@@ -181,6 +191,21 @@ export default function ModelSection({ project, save, disabled }: Props) {
// that predates it, should still pick the shared token up.
const useSharedToken = project.use_shared_auth_token !== false;
const aws = isAwsProject(project);
const gateway = useAppState((s) => s.appSettings?.gateway ?? null);
const savedBaseUrl =
project.backend === "ollama"
? (project.ollama_config ?? DEFAULT_OLLAMA_CONFIG).base_url
: project.backend === "llama_cpp"
? (project.llamacpp_config ?? DEFAULT_LLAMACPP_CONFIG).base_url
: project.backend === "open_ai_compatible"
? (project.openai_compatible_config ?? DEFAULT_OPENAI_COMPATIBLE_CONFIG).base_url
: null;
const endpointProblem =
aws && savedBaseUrl
? localEndpointProblem(savedBaseUrl, gateway?.enabled ? gateway.port : null)
: null;
const handleBackendChange = (mode: Backend) => {
const patch: Partial<Project> = { backend: mode };
if (mode === "bedrock" && !project.bedrock_config)
@@ -216,6 +241,15 @@ export default function ModelSection({ project, save, disabled }: Props) {
</select>
)}
</Field>
{aws && CUSTOM_ENDPOINT_BACKENDS.includes(project.backend) && (
<div
role="note"
className="px-2 py-1.5 space-y-1 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)]"
>
<p>{LOCAL_MODEL_ON_AWS}</p>
{endpointProblem && <p>{endpointProblem}</p>}
</div>
)}
{/* Only Anthropic reads CLAUDE_CODE_OAUTH_TOKEN; the other backends
authenticate through their own credentials entirely. */}
@@ -328,6 +362,15 @@ export default function ModelSection({ project, save, disabled }: Props) {
</>
)}
{bedrock.auth_method === "profile" && aws && (
<p
role="note"
className="px-2 py-1.5 text-xs text-[var(--warning)] bg-[var(--warning-muted)] border border-[var(--warning)]/30 rounded-[var(--radius-control)]"
>
{BEDROCK_PROFILE_ON_AWS}
</p>
)}
{bedrock.auth_method === "profile" && (
<Field
label="AWS profile"
@@ -5,6 +5,7 @@ import PermissionModeControl, { permissionModePatch } from "../../PermissionMode
import ClaudeInstructionsEditor from "../../ClaudeInstructionsEditor";
import ClaudeCodeSettingsEditor from "../../ClaudeCodeSettingsEditor";
import AuthBridgeRow from "./AuthBridgeRow";
import { NOT_ON_AWS, SANDBOX_OFF_ON_AWS, isAwsProject } from "../../../../lib/awsWorkspace";
interface Props {
project: Project;
@@ -19,6 +20,7 @@ export default function RuntimeSection({
disabled,
disabledReason,
}: Props) {
const aws = isAwsProject(project);
return (
<>
<ConfigGroup
@@ -34,12 +36,16 @@ export default function RuntimeSection({
<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."
hint={
aws
? `${SANDBOX_OFF_ON_AWS}: Claude Code's bash sandbox has not been verified on Fargate yet, so an AWS workspace runs with it off whatever this says.`
: "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}
checked={aws ? false : project.sandbox_mode_enabled}
disabled={disabled || aws}
onChange={(v) => save({ sandbox_mode_enabled: v })}
/>
}
@@ -47,12 +53,16 @@ export default function RuntimeSection({
<SwitchRow
label="Allow container spawning"
hint="Mounts the Docker socket so Claude can build and run Docker containers from inside the sandbox."
hint={
aws
? NOT_ON_AWS
: "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}
checked={aws ? false : project.allow_docker_access}
disabled={disabled || aws}
onChange={(v) => save({ allow_docker_access: v })}
/>
}
@@ -60,12 +70,12 @@ export default function RuntimeSection({
<SwitchRow
label="VPN support"
hint="Grants NET_ADMIN and the /dev/net/tun device so a VPN client (PIA, WireGuard, OpenVPN) can build a tunnel inside the container. Without it a client installs and runs but its connection hangs until it times out. Anything in the container can then reconfigure the container's own network stack; the host's is untouched. Changing this recreates the container on its next start — the home and .claude volumes are preserved."
hint={aws ? NOT_ON_AWS : "Grants NET_ADMIN and the /dev/net/tun device so a VPN client (PIA, WireGuard, OpenVPN) can build a tunnel inside the container. Without it a client installs and runs but its connection hangs until it times out. Anything in the container can then reconfigure the container's own network stack; the host's is untouched. Changing this recreates the container on its next start — the home and .claude volumes are preserved."}
control={
<Toggle
label="VPN support"
checked={project.vpn_support_enabled}
disabled={disabled}
checked={aws ? false : project.vpn_support_enabled}
disabled={disabled || aws}
onChange={(v) => save({ vpn_support_enabled: v })}
/>
}
@@ -3,6 +3,7 @@ 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";
import { isAwsProject } from "../../../../lib/awsWorkspace";
interface Props {
project: Project;
@@ -73,7 +74,11 @@ export default function WorkspaceSection({ project, save, disabled }: Props) {
return (
<ConfigGroup
title="Workspace"
description="What this sandbox is called and which host folders it can see."
description={
isAwsProject(project)
? "What this sandbox is called."
: "What this sandbox is called and which host folders it can see."
}
>
<Field
label="Project name"
@@ -101,96 +106,104 @@ export default function WorkspaceSection({ project, save, disabled }: Props) {
)}
</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.
{isAwsProject(project) ? (
<p className="text-xs text-[var(--text-secondary)] leading-snug">
This project runs on AWS, so it mounts no folders from this machine: its
repositories are cloned into <span className="font-mono">/workspace</span>. Edit them
under Host below.
</p>
) : (
<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={() => saveIfComplete()}
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);
persist(updated);
}
}}
>
Browse
</Button>
<span className="text-xs text-[var(--text-secondary)] font-mono flex-shrink-0">
/workspace/
</span>
<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.mount_name}
aria-label={`Folder ${i + 1} mount name`}
value={pp.host_path}
aria-label={`Folder ${i + 1} host path`}
onChange={(e) => {
const updated = [...paths];
updated[i] = { ...updated[i], mount_name: e.target.value };
updated[i] = { ...updated[i], host_path: e.target.value };
setPaths(updated);
}}
onBlur={() => saveIfComplete()}
placeholder="name"
placeholder="/path/to/folder"
disabled={disabled}
className={`w-40 ${monoInputClass}`}
className={`flex-1 min-w-0 ${inputClass}`}
/>
{paths.length > 1 && (
<div className="flex items-center gap-1.5">
<Button
size="md"
variant="danger"
disabled={disabled}
aria-label={`Remove folder ${i + 1}`}
onClick={() => {
const updated = paths.filter((_, j) => j !== i);
setPaths(updated);
persist(updated);
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);
persist(updated);
}
}}
>
Remove
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={() => saveIfComplete()}
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);
persist(updated);
}}
>
Remove
</Button>
)}
</div>
</div>
</div>
))}
</div>
))}
</div>
<Button
className="mt-2"
disabled={disabled}
onClick={() => setPaths([...paths, { host_path: "", mount_name: "" }])}
>
+ Add folder
</Button>
</div>
<Button
className="mt-2"
disabled={disabled}
onClick={() => setPaths([...paths, { host_path: "", mount_name: "" }])}
>
+ Add folder
</Button>
</div>
)}
</ConfigGroup>
);
}
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import HostsSettings from "./HostsSettings";
import HostsSettings, { CHECK_IN_PROGRESS } from "./HostsSettings";
import { useAppState } from "../../store/appState";
import type { AppSettings, HostConnection, PermissionReport } from "../../lib/types";
@@ -140,6 +140,21 @@ describe("HostsSettings", () => {
expect(screen.getByLabelText("Secret access key")).toHaveValue("");
});
it("tells the user a permission check can take a few minutes while it runs", async () => {
let finish: (r: PermissionReport) => void = () => {};
invoke.mockImplementation(async (cmd: string) => {
if (cmd === "list_aws_profiles") return [];
if (cmd === "check_aws_permissions") return new Promise<PermissionReport>((res) => (finish = res));
throw new Error(`unexpected ${cmd}`);
});
render(<HostsSettings />);
fireEvent.click(screen.getByRole("button", { name: "Check Prod" }));
expect(await screen.findByRole("status")).toHaveTextContent(CHECK_IN_PROGRESS);
finish(report({}));
expect(await screen.findByText("Insufficient")).toBeInTheDocument();
expect(screen.queryByText(CHECK_IN_PROGRESS)).not.toBeInTheDocument();
});
it("check shows Insufficient with the denied actions and every policy file to copy", async () => {
const adminFiles = [
{ name: "environment-admin.json", json: '{"Statement":"admin"}' },
+12 -1
View File
@@ -26,6 +26,10 @@ import SegmentedControl from "../ui/SegmentedControl";
import Field, { inputClass, selectClass } from "../ui/Field";
/** AWS throttles the permission simulator; a check retries patiently instead of failing. */
export const CHECK_IN_PROGRESS =
"Checking permissions… AWS limits how fast this can run, so it can take up to a few minutes.";
const OWN_PRINCIPAL_ACTIONS = ["iam:GetRole", "iam:SimulatePrincipalPolicy"];
const SUMMARY_LABEL: Record<PermissionSummary, string> = {
@@ -184,6 +188,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
const [region, setRegion] = useState(host.kind.default_region);
const [confirmRemove, setConfirmRemove] = useState(false);
const [busy, setBusy] = useState(false);
const [checking, setChecking] = useState(false);
const [signingIn, setSigningIn] = useState(false);
const [report, setReport] = useState<PermissionReport | null>(null);
const [failure, setFailure] = useState<Failure | null>(null);
@@ -201,6 +206,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
const runCheck = async () => {
setBusy(true);
setChecking(true);
setFailure(null);
try {
setReport(await checkAwsPermissions(host.id));
@@ -208,6 +214,7 @@ function ConnectionRow({ host }: { host: HostConnection }) {
setReport(null);
setFailure({ error: toAwsError(e), retry: runCheck });
} finally {
setChecking(false);
setBusy(false);
}
};
@@ -311,7 +318,11 @@ function ConnectionRow({ host }: { host: HostConnection }) {
</Button>
</div>
)}
{busy && !editing && !confirmRemove && <p role="status" className="text-xs text-[var(--text-secondary)]">Working…</p>}
{busy && !editing && !confirmRemove && (
<p role="status" className="text-xs text-[var(--text-secondary)]">
{checking ? CHECK_IN_PROGRESS : "Working…"}
</p>
)}
{failure && <ErrorLine failure={failure} onSignIn={signIn} signingIn={signingIn} />}
{report && <PermissionReportView report={report} />}
<EnvironmentsPanel connection={host} tier={report?.summary} />
+3 -1
View File
@@ -1,4 +1,4 @@
import type { ButtonHTMLAttributes, ReactNode } from "react";
import type { ButtonHTMLAttributes, ReactNode, Ref } from "react";
import { useUnavailable } from "./unavailable";
export type ButtonVariant = "primary" | "secondary" | "danger" | "ghost";
@@ -19,6 +19,8 @@ interface Props extends ButtonHTMLAttributes<HTMLButtonElement> {
unavailable?: boolean;
/** Why the button cannot be used. Required for `unavailable` to say anything. */
unavailableReason?: string;
/** React 19 passes `ref` as a prop; it lands on the `<button>` via `rest`. */
ref?: Ref<HTMLButtonElement>;
}
/**
+150
View File
@@ -0,0 +1,150 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, renderHook } from "@testing-library/react";
import { useProjectActions } from "./useProjectActions";
import { useAppState } from "../store/appState";
import { awsProject, localProject } from "../test/awsFixtures";
import type { UnsavedWork } from "../lib/types";
const start = vi.fn();
const stop = vi.fn();
const checkUnsavedWork = vi.fn();
const awsTaskLog = vi.fn();
vi.mock("./useProjects", () => ({
useProjects: () => ({ start, stop, rebuild: vi.fn() }),
}));
vi.mock("./useTerminal", () => ({
useTerminal: () => ({ open: vi.fn(), sendInput: vi.fn() }),
}));
vi.mock("@tauri-apps/plugin-dialog", () => ({ save: vi.fn() }));
vi.mock("../lib/tauri-commands", () => ({
checkUnsavedWork: (id: string) => checkUnsavedWork(id),
awsTaskLog: (id: string, n: number) => awsTaskLog(id, n),
downloadContainerBackup: vi.fn(),
}));
const clean: UnsavedWork = { checked: true, repos: [], error: null };
const dirty: UnsavedWork = {
checked: true,
repos: [{ folder: "api", branch: "main", dirty: true, unpushed: 0 }],
error: null,
};
beforeEach(() => {
vi.clearAllMocks();
useAppState.setState({ toasts: [] } as never);
});
const toasts = () => (useAppState.getState() as unknown as { toasts: { message: string; detail?: string }[] }).toasts;
describe("useProjectActions stop guard", () => {
it("stops an AWS workspace with nothing unsaved straight away", async () => {
checkUnsavedWork.mockResolvedValue(clean);
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
await act(async () => {
await result.current.handleStop();
});
expect(stop).toHaveBeenCalledWith("p1");
expect(result.current.stopGuard).toBeNull();
});
it("asks first when there is unsaved work, then stops with the choice", async () => {
checkUnsavedWork.mockResolvedValue(dirty);
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
await act(async () => {
await result.current.handleStop();
});
expect(stop).not.toHaveBeenCalled();
expect(result.current.stopGuard).toEqual(dirty);
await act(async () => {
await result.current.resolveStopGuard("push");
});
expect(stop).toHaveBeenCalledWith("p1", "push");
expect(result.current.stopGuard).toBeNull();
});
it("asks (without a push) when the check itself fails, and Cancel stops nothing", async () => {
checkUnsavedWork.mockRejectedValue("Project p1 not found");
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
await act(async () => {
await result.current.handleStop();
});
expect(result.current.stopGuard?.checked).toBe(false);
await act(async () => {
await result.current.resolveStopGuard(null);
});
expect(stop).not.toHaveBeenCalled();
});
it("stops an unchecked workspace without sending a choice", async () => {
checkUnsavedWork.mockResolvedValue({ checked: false, repos: [], error: "dry run timed out" });
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
await act(async () => {
await result.current.handleStop();
});
await act(async () => {
await result.current.resolveStopGuard("unguarded");
});
expect(stop).toHaveBeenCalledWith("p1", undefined);
});
it("toasts a failed push or StopTask and leaves the project as it was", async () => {
checkUnsavedWork.mockResolvedValue(dirty);
stop.mockRejectedValue("Pushing unsaved work failed (exit 1), so the workspace was not stopped:\npush denied");
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
await act(async () => {
await result.current.handleStop();
});
await act(async () => {
await result.current.resolveStopGuard("push");
});
expect(toasts().at(-1)?.detail).toMatch(/push denied/);
});
it("never asks for a local project", async () => {
const { result } = renderHook(() => useProjectActions(localProject({ status: "running" })));
await act(async () => {
await result.current.handleStop();
});
expect(checkUnsavedWork).not.toHaveBeenCalled();
expect(stop).toHaveBeenCalledWith("p1");
});
});
describe("useProjectActions stop notes", () => {
it("tells the user when the choice could not be recorded in the workspace", async () => {
checkUnsavedWork.mockResolvedValue(dirty);
stop.mockResolvedValue("its own push of work in progress on shutdown may still run");
const { result } = renderHook(() => useProjectActions(awsProject({ status: "running" })));
await act(async () => {
await result.current.handleStop();
});
await act(async () => {
await result.current.resolveStopGuard("discard");
});
expect(stop).toHaveBeenCalledWith("p1", "discard");
expect(toasts().at(-1)?.detail).toMatch(/may still run/);
});
});
describe("useProjectActions start", () => {
it("adds the task's last log lines to an AWS start failure", async () => {
start.mockRejectedValue("The task stopped: Essential container exited");
awsTaskLog.mockResolvedValue(["entrypoint: clone failed", "bye"]);
const { result } = renderHook(() => useProjectActions(awsProject()));
await act(async () => {
await result.current.handleStart();
});
expect(awsTaskLog).toHaveBeenCalledWith("p1", 30);
expect(toasts().at(-1)?.detail).toMatch(/Last log lines:\nentrypoint: clone failed\nbye/);
});
it("does not read the log twice when the error already carries it", async () => {
start.mockRejectedValue("failed\nLast log lines:\nx");
const { result } = renderHook(() => useProjectActions(awsProject()));
await act(async () => {
await result.current.handleStart();
});
expect(awsTaskLog).not.toHaveBeenCalled();
});
});
+75 -9
View File
@@ -1,6 +1,7 @@
import { useCallback, useState } from "react";
import { save } from "@tauri-apps/plugin-dialog";
import type { Project } from "../lib/types";
import type { Project, UnsavedWork, WipChoice } from "../lib/types";
import { isAwsProject, stopGuardNeeded } from "../lib/awsWorkspace";
import * as commands from "../lib/tauri-commands";
import { formatBytes } from "../lib/formatBytes";
import { describeResetLeftovers, resetLeftoverPronoun } from "../lib/resetOutcome";
@@ -8,6 +9,9 @@ import { useAppState } from "../store/appState";
import { useProjects } from "./useProjects";
import { useTerminal } from "./useTerminal";
/** How many task log lines a failed AWS start shows. */
const TASK_LOG_LINES = 30;
/**
* Lifecycle + terminal actions for one project, shared by the sidebar row and
* Project Home so both surfaces behave identically. Failures raise a toast
@@ -29,13 +33,17 @@ export function useProjectActions(project: Project) {
);
const run = useCallback(
async <T,>(label: string, fn: () => Promise<T>): Promise<T | undefined> => {
async <T,>(
label: string,
fn: () => Promise<T>,
explain?: (e: unknown) => Promise<string>,
): Promise<T | undefined> => {
setBusy(true);
setContainerProgress(project.id, null);
try {
return await fn();
} catch (e) {
fail(`${label} failed for “${project.name}”`, e);
fail(`${label} failed for “${project.name}”`, explain ? await explain(e) : e);
return undefined;
} finally {
setContainerProgress(project.id, null);
@@ -45,14 +53,70 @@ export function useProjectActions(project: Project) {
[fail, project.id, project.name, setContainerProgress],
);
const handleStart = useCallback(
() => run("Start", () => start(project.id)),
[run, start, project.id],
const aws = isAwsProject(project);
/** An AWS start failure gets the task's last log lines, unless the error has them. */
const withTaskLog = useCallback(
async (e: unknown): Promise<string> => {
const text = String(e);
if (text.includes("Last log lines")) return text;
try {
const lines = await commands.awsTaskLog(project.id, TASK_LOG_LINES);
if (lines.length > 0) return `${text}\n\nLast log lines:\n${lines.join("\n")}`;
} catch {
// The log is a courtesy; the start error is what matters.
}
return text;
},
[project.id],
);
const handleStop = useCallback(
() => run("Stop", () => stop(project.id)),
[run, stop, project.id],
const handleStart = useCallback(
() => run("Start", () => start(project.id), aws ? withTaskLog : undefined),
[run, start, project.id, aws, withTaskLog],
);
/**
* The stop guard's question, set while it is asked: an AWS workspace with
* work no remote has (or one that could not be checked) is not stopped
* until the user picks Push, Stop anyway or Cancel.
*/
const [stopGuard, setStopGuard] = useState<UnsavedWork | null>(null);
const handleStop = useCallback(async () => {
// A force stop of a transition skips the question: there is nothing
// reliable to ask yet.
if (aws && project.status === "running") {
setBusy(true);
let work: UnsavedWork;
try {
work = await commands.checkUnsavedWork(project.id);
} catch (e) {
work = { checked: false, repos: [], error: String(e) };
} finally {
setBusy(false);
}
if (stopGuardNeeded(work)) {
setStopGuard(work);
return undefined;
}
}
return run("Stop", () => stop(project.id));
}, [aws, project.status, project.id, run, stop]);
const resolveStopGuard = useCallback(
(choice: WipChoice | "unguarded" | null) => {
setStopGuard(null);
if (choice === null) return undefined;
return run("Stop", async () => {
// "unguarded": no choice is sent, so nothing is recorded in the
// workspace and its own shutdown push runs as configured.
const note = await stop(project.id, choice === "unguarded" ? undefined : choice);
if (note) pushToast({ kind: "info", message: `“${project.name}” stopped`, detail: note });
return note;
});
},
[run, stop, project.id, project.name, pushToast],
);
const handleReset = useCallback(
@@ -184,6 +248,8 @@ Reset again, or remove ${resetLeftoverPronoun(outcome)} manually once stopped.`,
backingUp,
handleStart,
handleStop,
stopGuard,
resolveStopGuard,
handleReset,
handleBackup,
openClaudeTerminal,
@@ -54,6 +54,35 @@ describe("useProjectStatusEvents", () => {
expect(toasts).toHaveLength(0);
});
it("says why an AWS task stopped, and keeps a user's stop quiet", async () => {
renderHook(() => useProjectStatusEvents());
await vi.waitFor(() => expect(handler).not.toBeNull());
const fire = (stop: unknown, reason = "exited") => {
useAppState.setState({ toasts: [] });
handler!({ payload: { project: project({ status: "stopped" }), reason, stop } });
return useAppState.getState().toasts;
};
let t = fire({ kind: "spot", message: "Spot interruption" });
expect(t[0].kind).toBe("info");
expect(t[0].message).toContain("Spot interruption");
t = fire({ kind: "idle", message: null });
expect(t[0].kind).toBe("info");
expect(t[0].message).toContain("idle");
expect(fire({ kind: "user", message: null })).toHaveLength(0);
// A task that never started is news even when found at startup.
t = fire({ kind: "failed", message: "CannotPullContainerError: denied" }, "found_stopped");
expect(t[0].kind).toBe("error");
expect(t[0].detail).toContain("CannotPullContainerError");
t = fire({ kind: "exited", message: "OutOfMemoryError" });
expect(t[0].kind).toBe("error");
expect(t[0].detail).toContain("OutOfMemoryError");
});
it("stops listening on unmount", async () => {
const { unmount } = renderHook(() => useProjectStatusEvents());
await vi.waitFor(() => expect(handler).not.toBeNull());
+54 -10
View File
@@ -12,6 +12,56 @@ export interface ContainerExitedEvent {
* while the app was closed, e.g. a host reboot); nothing was interrupted.
*/
reason: "exited" | "found_stopped";
/** AWS: why ECS says the task stopped (`StopNote`); absent on Docker. */
stop?: StopNote | null;
}
/** `container_watch.rs`'s `StopNote`. */
export interface StopNote {
/** `user`: someone stopped it (console, CLI, another machine) — no toast. */
kind: "spot" | "idle" | "failed" | "user" | "exited";
message: string | null;
}
/** The toast for an exit, or null for none. */
export function exitToast(
name: string,
reason: ContainerExitedEvent["reason"],
stop: StopNote | null | undefined,
): { kind: "error" | "info"; message: string; detail?: string } | null {
if (stop?.kind === "user") return null;
if (stop?.kind === "failed") {
return {
kind: "error",
message: `The AWS workspace for “${name}” failed to start`,
detail: stop.message ?? undefined,
};
}
if (reason !== "exited") return null;
switch (stop?.kind) {
case "spot":
return {
kind: "info",
message: `“${name}” stopped: Spot interruption`,
detail:
"AWS reclaimed the Spot capacity it ran on. Start the project again to get a new workspace.",
};
case "idle":
return {
kind: "info",
message: `“${name}” stopped after being idle`,
detail: "Its AWS workspace stopped itself to save cost. Start the project again to continue.",
};
default:
return {
kind: "error",
message: `The container for “${name}” stopped`,
detail:
"It exited without Triple-C stopping it — open sessions were disconnected. " +
"Start the project again to reconnect." +
(stop?.message ? ` (${stop.message})` : ""),
};
}
}
/**
@@ -25,18 +75,12 @@ export function useProjectStatusEvents() {
let cancelled = false;
let unlisten: UnlistenFn | null = null;
listen<ContainerExitedEvent>("project-container-exited", (event) => {
const { project, reason } = event.payload;
const { project, reason, stop } = event.payload;
const state = useAppState.getState();
state.updateProjectInList(project);
if (reason !== "exited") return;
state.pushToast({
kind: "error",
message: `The container for “${project.name}” stopped`,
detail:
"It exited without Triple-C stopping it — open sessions were disconnected. " +
"Start the project again to reconnect.",
dedupeKey: `container-exited-${project.id}`,
});
const toast = exitToast(project.name, reason, stop);
if (!toast) return;
state.pushToast({ ...toast, dedupeKey: `container-exited-${project.id}` });
})
.then((fn) => {
if (cancelled) fn();
+8 -7
View File
@@ -2,7 +2,7 @@ import { useCallback } from "react";
import { useShallow } from "zustand/react/shallow";
import { useAppState } from "../store/appState";
import * as commands from "../lib/tauri-commands";
import type { ProjectPath, ProjectStatus } from "../lib/types";
import type { NewProjectHost, ProjectPath, ProjectStatus, RemoveProjectOptions, WipChoice } from "../lib/types";
export function useProjects() {
const {
@@ -31,8 +31,8 @@ export function useProjects() {
}, [setProjects]);
const add = useCallback(
async (name: string, paths: ProjectPath[]) => {
const project = await commands.addProject(name, paths);
async (name: string, paths: ProjectPath[], host?: NewProjectHost) => {
const project = await commands.addProject(name, paths, host);
// Refresh from backend to avoid stale closure issues
const list = await commands.listProjects();
setProjects(list);
@@ -43,8 +43,8 @@ export function useProjects() {
);
const remove = useCallback(
async (id: string) => {
const report = await commands.removeProject(id);
async (id: string, opts?: RemoveProjectOptions) => {
const report = await commands.removeProject(id, opts);
removeProjectFromList(id);
return report;
},
@@ -124,11 +124,12 @@ export function useProjects() {
);
const stop = useCallback(
(id: string) =>
(id: string, wip?: WipChoice) =>
withOptimisticStatus(id, "stopping", async () => {
await commands.stopProjectContainer(id);
const note = await commands.stopProjectContainer(id, wip);
const list = await commands.listProjects();
setProjects(list);
return note;
}),
[setProjects, withOptimisticStatus],
);
+6 -1
View File
@@ -1,11 +1,16 @@
import { describe, it, expect } from "vitest";
import { toAwsError } from "./aws-error";
import { awsErrorMessage, toAwsError } from "./aws-error";
describe("toAwsError", () => {
it("passes a tagged AwsError through", () => {
const e = { kind: "sso_expired", profile: "dev" };
expect(toAwsError(e)).toBe(e);
});
it("passes a quota error through with its message", () => {
const e = { kind: "quota_exceeded", message: "An account limit was reached" };
expect(toAwsError(e)).toBe(e);
expect(awsErrorMessage(toAwsError(e))).toBe("An account limit was reached");
});
it("wraps strings and Errors as other", () => {
expect(toAwsError("boom")).toEqual({ kind: "other", message: "boom" });
expect(toAwsError(new Error("bad"))).toEqual({ kind: "other", message: "bad" });
+1
View File
@@ -8,6 +8,7 @@ const KINDS: Record<AwsError["kind"], true> = {
invalid_credentials: true,
access_denied: true,
state_bucket_taken: true,
quota_exceeded: true,
other: true,
};
+61
View File
@@ -0,0 +1,61 @@
import { describe, it, expect } from "vitest";
import {
cleanRepos,
environmentSelectable,
memoryError,
memoryOptions,
nearestMemory,
repoFolderFromUrl,
stopGuardNeeded,
} from "./awsWorkspace";
import { environment } from "../test/awsFixtures";
// Shared with the Rust validator (`models/project.rs`).
import fargatePairs from "../test/fixtures/fargate-pairs.json";
describe("awsWorkspace", () => {
it("agrees with the Rust validator on every pair in the shared fixture", () => {
for (const [cpu, mem] of fargatePairs.valid) expect(memoryError(cpu, mem), `${cpu}/${mem}`).toBeNull();
for (const [cpu, mem] of fargatePairs.invalid) expect(memoryError(cpu, mem), `${cpu}/${mem}`).not.toBeNull();
});
it("words the refusal as Rust does and snaps to a valid size", () => {
expect(memoryOptions(256)).toEqual([512, 1024, 2048]);
expect(memoryError(256, 1536)).toMatch(/use 512, 1024 or 2048 MiB$/);
expect(memoryError(1024, 2500)).toMatch(/use 2048 to 8192 MiB in steps of 1024$/);
expect(memoryError(300, 1024)).toMatch(/not a Fargate CPU/);
expect(nearestMemory(256, 4096)).toBe(2048);
expect(nearestMemory(16384, 4096)).toBe(32768);
});
it("derives a clone folder from a URL", () => {
expect(repoFolderFromUrl("https://github.com/org/api.git")).toBe("api");
expect(repoFolderFromUrl("git@github.com:org/web-app.git")).toBe("web-app");
expect(repoFolderFromUrl("ssh://h/x/y z/")).toBe("y-z");
});
it("drops blank repository rows and keeps an empty branch as the default", () => {
expect(
cleanRepos([
{ url: " https://h/r.git ", branch: " ", folder: "" },
{ url: "", branch: null, folder: "" },
]),
).toEqual([{ url: "https://h/r.git", branch: null, folder: "r" }]);
});
it("guards a stop with unsaved or unknown work", () => {
const repo = { folder: "a", branch: "main", dirty: false, unpushed: 0 };
expect(stopGuardNeeded({ checked: true, repos: [repo], error: null })).toBe(false);
expect(stopGuardNeeded({ checked: true, repos: [{ ...repo, dirty: true }], error: null })).toBe(true);
expect(stopGuardNeeded({ checked: true, repos: [{ ...repo, unpushed: 1 }], error: null })).toBe(true);
expect(stopGuardNeeded({ checked: false, repos: [], error: "x" })).toBe(true);
// A repository still cloning has nothing to push.
expect(stopGuardNeeded({ checked: true, repos: [{ ...repo, cloning: true }], error: null })).toBe(false);
});
it("selects only ready environments the user joined", () => {
expect(environmentSelectable(environment("a", "ready", true))).toBe(true);
expect(environmentSelectable(environment("a", "update_available", true))).toBe(true);
expect(environmentSelectable(environment("a", "ready", false))).toBe(false);
expect(environmentSelectable(environment("a", "deploying", true))).toBe(false);
});
});
+150
View File
@@ -0,0 +1,150 @@
import type {
AwsWorkspaceConfig,
DetectedEnvironment,
Project,
RepoSource,
UnsavedWork,
} from "./types";
/** Why a Local-only option is off on an AWS project (P6). */
export const NOT_ON_AWS = "Not available on AWS (Fargate)";
/** R4: the AWS host forces Claude Code's sandbox off until it is verified on Fargate. */
export const SANDBOX_OFF_ON_AWS = "Off on AWS for now";
export const EPHEMERAL_WARNING =
"Claude login and history are lost when the workspace stops.";
export function isAwsProject(p: Pick<Project, "host_id">): boolean {
return p.host_id != null;
}
/** Fargate CPU sizes (units of 1/1024 vCPU). */
export const FARGATE_CPUS = [256, 512, 1024, 2048, 4096, 8192, 16384] as const;
/** Mirrors Rust `fargate_memory_sizes`: every memory size (MiB) valid with
* `cpu`, smallest first. 256 CPU is irregular: 512, 1024 or 2048 only. */
export function memoryOptions(cpu: number): number[] {
if (cpu === 256) return [512, 1024, 2048];
const ranges: Record<number, [number, number, number]> = {
512: [1024, 4096, 1024],
1024: [2048, 8192, 1024],
2048: [4096, 16384, 1024],
4096: [8192, 30720, 1024],
8192: [16384, 61440, 4096],
16384: [32768, 122880, 8192],
};
const range = ranges[cpu];
if (!range) return [];
const [min, max, step] = range;
const out: number[] = [];
for (let m = min; m <= max; m += step) out.push(m);
return out;
}
/** Mirrors Rust `describe_sizes`. */
function describeSizes(sizes: number[]): string {
const last = sizes[sizes.length - 1];
if (sizes.length <= 3) return `${sizes.slice(0, -1).join(", ")} or ${last} MiB`;
return `${sizes[0]} to ${last} MiB in steps of ${sizes[1] - sizes[0]}`;
}
/** Null when `memory` MiB is valid with `cpu`; otherwise the reason (as Rust words it). */
export function memoryError(cpu: number, memory: number): string | null {
const sizes = memoryOptions(cpu);
if (sizes.length === 0) return `${cpu} is not a Fargate CPU size`;
if (!sizes.includes(memory)) {
return `${memory} MiB of memory is not valid with ${cpu} CPU units: use ${describeSizes(sizes)}`;
}
return null;
}
/** The valid memory size nearest `memory` for `cpu` (used when the CPU changes). */
export function nearestMemory(cpu: number, memory: number): number {
const opts = memoryOptions(cpu);
return opts.reduce((best, m) => (Math.abs(m - memory) < Math.abs(best - memory) ? m : best), opts[0]);
}
export function formatCpu(cpu: number): string {
return `${cpu / 1024} vCPU`;
}
export function formatMemory(mib: number): string {
return mib % 1024 === 0 ? `${mib / 1024} GiB` : `${mib} MiB`;
}
/** Mirrors Rust `AwsWorkspaceConfig::default()`. */
export function defaultAwsWorkspace(): AwsWorkspaceConfig {
return {
cpu: 1024,
memory_mib: 4096,
arch: "x86_64",
storage: "hybrid",
ephemeral_gib: 21,
spot: false,
idle_stop_minutes: null,
repos: [],
wip_push_on_stop: true,
task_arn: null,
access_point_id: null,
task_definition_arn: null,
};
}
/** The folder a clone of `url` would get: its last path part without `.git`,
* reduced to the characters Rust's folder rule allows. */
export function repoFolderFromUrl(url: string): string {
const last = url.trim().replace(/\/+$/, "").split(/[/:]/).pop() ?? "";
return last.replace(/\.git$/, "").replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64);
}
/** Rows the editors hold, minus blank ones; a branch left empty is the default branch. */
export function cleanRepos(rows: RepoSource[]): RepoSource[] {
return rows
.filter((r) => r.url.trim() || r.folder.trim() || (r.branch ?? "").trim())
.map((r) => ({
url: r.url.trim(),
branch: (r.branch ?? "").trim() || null,
folder: r.folder.trim() || repoFolderFromUrl(r.url),
}));
}
/** Whether Stop must ask first (the one place this rule lives). */
export function stopGuardNeeded(work: UnsavedWork): boolean {
return !work.checked || work.repos.some((r) => !r.cloning && (r.dirty || r.unpushed > 0));
}
/** An environment a project can be placed in: ready (or merely behind) and joined. */
export function environmentSelectable(env: DetectedEnvironment): boolean {
const ready = env.state.state === "ready" || env.state.state === "update_available";
return ready && env.onboarding?.state === "joined";
}
/** Whether an AWS project may have saved files on EFS (Hybrid now, or an
* access point left from when it was). Ephemeral-only projects have none. */
export function hasSavedFiles(p: Pick<Project, "aws">): boolean {
return p.aws?.storage === "hybrid" || !!p.aws?.access_point_id;
}
/** Hosts that only mean something on this machine or its Docker bridge. */
const LOCAL_HOSTS = /^(localhost|127(\.\d{1,3}){3}|0\.0\.0\.0|\[?::1\]?|host\.docker\.internal|172\.17\.0\.1)$/i;
/**
* Why `url` cannot work from an AWS task, or null: a loopback / Docker-host
* address, or the app's own LLM gateway (it runs on this machine).
*/
export function localEndpointProblem(url: string, gatewayPort: number | null): string | null {
let parsed: URL;
try {
parsed = new URL(url.trim());
} catch {
return null;
}
const host = parsed.hostname;
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
if (LOCAL_HOSTS.test(host)) {
if (gatewayPort !== null && port === gatewayPort) {
return "This is Triple-C's own LLM gateway, which runs on this machine; an AWS workspace can't reach it.";
}
return `${host} is this machine (or its Docker host) — an AWS workspace can't reach it.`;
}
return null;
}
+28 -7
View File
@@ -1,5 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
import type { Project, ProjectPath, ProjectRemovalReport, ProjectResetOutcome, ContainerInfo, AppSettings, SettingsImportPreview, SettingsImportOutcome, UpdateInfo, ImageUpdateInfo, FileEntry, FileContents, WebTerminalInfo, SttStatus, GatewayStatus, InstallOptions, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, Tier, EnvironmentScan, NetworkChoice, ModuleKind } from "./types";
import type { Project, ProjectPath, NewProjectHost, RemoveProjectOptions, WipChoice, UnsavedWork, ProjectRemovalReport, ProjectResetOutcome, ContainerInfo, AppSettings, SettingsImportPreview, SettingsImportOutcome, UpdateInfo, ImageUpdateInfo, FileEntry, FileContents, WebTerminalInfo, SttStatus, GatewayStatus, InstallOptions, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, Tier, EnvironmentScan, NetworkChoice, ModuleKind } from "./types";
// Docker
export const checkDocker = () => invoke<boolean>("check_docker");
@@ -10,20 +10,41 @@ export const getContainerInfo = (projectId: string) =>
// Projects
export const listProjects = () => invoke<Project[]>("list_projects");
export const addProject = (name: string, paths: ProjectPath[]) =>
invoke<Project>("add_project", { name, paths });
export const removeProject = (projectId: string) =>
invoke<ProjectRemovalReport>("remove_project", { projectId });
export const addProject = (name: string, paths: ProjectPath[], host?: NewProjectHost) =>
invoke<Project>("add_project", {
name,
paths,
hostId: host?.hostId ?? null,
awsPlacement: host?.awsPlacement ?? null,
aws: host?.aws ?? null,
});
export const removeProject = (projectId: string, opts: RemoveProjectOptions = {}) =>
invoke<ProjectRemovalReport>("remove_project", {
projectId,
discardData: opts.discardData ?? null,
forgetAwsResources: opts.forgetAwsResources ?? null,
});
export const updateProject = (project: Project) =>
invoke<Project>("update_project", { project });
export const startProjectContainer = (projectId: string) =>
invoke<Project>("start_project_container", { projectId });
export const stopProjectContainer = (projectId: string) =>
invoke<void>("stop_project_container", { projectId });
/** `wip` is the stop guard's choice for an AWS project (a local one ignores it).
* Resolves to a note when the choice could not be recorded in the workspace
* (its own shutdown push may then still run), else null. */
export const stopProjectContainer = (projectId: string, wip?: WipChoice) =>
invoke<string | null>("stop_project_container", { projectId, wip: wip ?? null });
export const checkUnsavedWork = (projectId: string) =>
invoke<UnsavedWork>("check_unsaved_work", { projectId });
export const awsTaskLog = (projectId: string, limit: number) =>
invoke<string[]>("aws_task_log", { projectId, limit });
export const removeAwsResources = (projectId: string, discardData: boolean) =>
invoke<Project>("remove_aws_resources", { projectId, discardData });
export const rebuildProjectContainer = (projectId: string) =>
invoke<ProjectResetOutcome>("rebuild_project_container", { projectId });
export const reconcileProjectStatuses = () =>
invoke<Project[]>("reconcile_project_statuses");
/** AWS projects against ECS; run at startup whether or not Docker answers. */
export const reconcileAwsProjects = () => invoke<Project[]>("reconcile_aws_projects");
// Notes — per-project, host-side, readable with the container stopped.
export const listNotes = (projectId: string) =>
+77
View File
@@ -68,10 +68,86 @@ export interface Project {
renamed_session_names: Record<string, string>;
marketplace_installs: MarketplaceInstall[];
marketplace_disabled: MarketplaceItemRef[];
/** Host connection id this project runs on; null = local Docker. */
host_id: string | null;
aws_placement: AwsPlacement | null;
aws: AwsWorkspaceConfig | null;
created_at: string;
updated_at: string;
}
export interface AwsPlacement {
region: string;
environment: string;
}
export type Arch = "x86_64" | "arm64";
export type StorageMode = "ephemeral" | "hybrid";
export interface RepoSource {
url: string;
/** null = the remote's default branch. */
branch: string | null;
folder: string;
}
export interface AwsWorkspaceConfig {
cpu: number;
memory_mib: number;
arch: Arch;
storage: StorageMode;
ephemeral_gib: number;
spot: boolean;
idle_stop_minutes: number | null;
repos: RepoSource[];
wip_push_on_stop: boolean;
/** Store-owned runtime handles; a save cannot change them. */
task_arn: string | null;
access_point_id: string | null;
task_definition_arn: string | null;
}
/** Where a new project runs: omitted (or all null) = local Docker. An AWS
* project passes all three and no folders. */
export interface NewProjectHost {
hostId: string | null;
awsPlacement: AwsPlacement | null;
aws: AwsWorkspaceConfig | null;
}
export interface RemoveProjectOptions {
/** AWS: also remove the workspace's EFS access point (the files stay on the
* user's own file system until offboarding). */
discardData?: boolean;
/** AWS: the connection is gone; remove the project and leave its AWS resources. */
forgetAwsResources?: boolean;
}
/** Prefix of `remove_project`'s refusal when an AWS project's connection is
* gone (Rust `AWS_CONNECTION_MISSING`; a Rust test pins the two together). */
export const AWS_CONNECTION_MISSING = "AWS_CONNECTION_MISSING: ";
/** What Stop does with an AWS workspace's unsaved git work (Rust `WipChoice`). */
export type WipChoice = "push" | "discard";
/** One repository line of `triple-c-wip-push --dry-run` (Rust `RepoState`). */
export interface RepoState {
folder: string;
dirty: boolean;
unpushed: number;
branch: string;
/** The start's background clone is still writing it: nothing to push. */
cloning?: boolean;
}
/** What `checkUnsavedWork` found (Rust `UnsavedWork`). `checked: false` (with
* `error`) when the workspace could not be asked. */
export interface UnsavedWork {
checked: boolean;
repos: RepoState[];
error: string | null;
}
export type ProjectStatus =
| "stopped"
| "starting"
@@ -1149,6 +1225,7 @@ export type AwsError =
| { kind: "invalid_credentials"; message: string }
| { kind: "access_denied"; action: string; message: string }
| { kind: "state_bucket_taken"; bucket: string }
| { kind: "quota_exceeded"; message: string }
| { kind: "other"; message: string };
export interface CallerIdentity {
+76
View File
@@ -0,0 +1,76 @@
import type { DetectedEnvironment, Project } from "../lib/types";
import { defaultAwsWorkspace } from "../lib/awsWorkspace";
/** A complete local project for component tests. */
export function localProject(over: Partial<Project> = {}): Project {
return {
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,
llamacpp_config: null,
openai_compatible_config: null,
allow_docker_access: true,
sandbox_mode_enabled: true,
mission_control_enabled: false,
auth_bridge_enabled: false,
browser_view_enabled: false,
vpn_support_enabled: true,
use_shared_auth_token: true,
full_permissions: false,
permission_mode: null,
ssh_key_path: null,
ca_cert_path: null,
git_token: null,
git_user_name: null,
git_user_email: null,
custom_env_vars: [],
port_mappings: [{ host_port: 3000, container_port: 3000, protocol: "tcp" }],
claude_instructions: null,
claude_code_settings: null,
renamed_session_names: {},
marketplace_installs: [],
marketplace_disabled: [],
host_id: null,
aws_placement: null,
aws: null,
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
...over,
};
}
/** The same project placed on an AWS connection `c1`. */
export function awsProject(over: Partial<Project> = {}): Project {
return localProject({
paths: [],
host_id: "c1",
aws_placement: { region: "eu-west-1", environment: "dev" },
aws: {
...defaultAwsWorkspace(),
repos: [{ url: "https://example.com/org/api.git", branch: null, folder: "api" }],
},
...over,
});
}
export function environment(
name: string,
state: DetectedEnvironment["state"]["state"],
joined: boolean,
): DetectedEnvironment {
return {
name,
template_version: 1,
state: { state } as DetectedEnvironment["state"],
actions: [],
info: null,
onboarding: joined ? { state: "joined" } : { state: "not_joined" },
onboarding_actions: [],
onboarded_users: 1,
};
}
+22
View File
@@ -0,0 +1,22 @@
{
"_comment": "Fargate CPU/memory pairs, read by both models/project.rs (Rust) and lib/awsWorkspace.test.ts. Keep the two validators agreeing on every line.",
"valid": [
[256, 512], [256, 1024], [256, 2048],
[512, 1024], [512, 2048], [512, 3072], [512, 4096],
[1024, 2048], [1024, 3072], [1024, 4096], [1024, 8192],
[2048, 4096], [2048, 5120], [2048, 16384],
[4096, 8192], [4096, 9216], [4096, 30720],
[8192, 16384], [8192, 20480], [8192, 61440],
[16384, 32768], [16384, 40960], [16384, 122880]
],
"invalid": [
[256, 256], [256, 1536], [256, 3072], [256, 4096],
[512, 512], [512, 1536], [512, 5120],
[1024, 1024], [1024, 2500], [1024, 9216],
[2048, 2048], [2048, 4608], [2048, 17408],
[4096, 7168], [4096, 31744],
[8192, 18432], [8192, 65536],
[16384, 36864], [16384, 122881], [16384, 131072],
[300, 1024], [0, 512], [32768, 65536]
]
}
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff. Show more