Stabilize dashboard runtime proxy
This commit is contained in:
+4
-1
@@ -22,6 +22,9 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# local runtime state
|
||||
/.runtime/
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
|
||||
@@ -30,4 +33,4 @@ yarn-error.log*
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
next-env.d.ts
|
||||
|
||||
@@ -0,0 +1,575 @@
|
||||
# NemoClaw Web Service Coding BIBLE
|
||||
|
||||
## Purpose
|
||||
|
||||
This document is the operating doctrine for the NemoClaw web service.
|
||||
|
||||
Its job is to prevent three failure classes that already caused drift:
|
||||
|
||||
1. **authority drift** — multiple competing sources of truth
|
||||
2. **ownership drift** — multiple processes/services thinking they own the same runtime surface
|
||||
3. **runtime-truth confusion** — dashboards or probes looking green while describing the wrong process, wrong route owner, or wrong machine state
|
||||
|
||||
This is not philosophy. These are build and run rules.
|
||||
|
||||
---
|
||||
|
||||
## 0. Canonical names and lanes
|
||||
|
||||
### 0.1 Canonical code lane
|
||||
The canonical editable codebase is:
|
||||
|
||||
- `/home/nvidia/.openclaw/workspace/projects/nemoclaw-dashboard`
|
||||
|
||||
All feature work, bug fixes, route changes, and tests must start here.
|
||||
|
||||
### 0.2 Canonical live runtime lane
|
||||
The canonical live runtime tree is:
|
||||
|
||||
- `/home/nvidia/nemoclaw-dashboard`
|
||||
|
||||
This path is a deployment target, not the primary authoring lane.
|
||||
|
||||
### 0.3 Runtime owner
|
||||
The intended runtime owner is:
|
||||
|
||||
- `nemoclaw-dashboard.service`
|
||||
|
||||
Anything else listening on the production ports is drift unless explicitly documented as a temporary diagnostic with start/stop bounds.
|
||||
|
||||
### 0.4 Intended listeners
|
||||
The intended listeners are:
|
||||
|
||||
- `:3000` → dashboard HTTP/WebSocket entrypoint
|
||||
- `:3011` → loopback terminal server
|
||||
|
||||
Per current runtime design:
|
||||
|
||||
- `:3000` must be owned by the dashboard service path under `/home/nvidia/nemoclaw-dashboard`
|
||||
- `:3011` must be owned by the terminal server started under dashboard supervisor control
|
||||
|
||||
If these ports are owned by a workspace `next dev`, a random shell, or a second service, that is **not success**. It is drift.
|
||||
|
||||
---
|
||||
|
||||
## 1. Source-of-truth doctrine
|
||||
|
||||
## 1.1 One truth per concern
|
||||
Every concern must have exactly one canonical authority.
|
||||
|
||||
Use this mapping:
|
||||
|
||||
- **Editable application code truth** → `projects/nemoclaw-dashboard`
|
||||
- **Live executable runtime truth** → `/home/nvidia/nemoclaw-dashboard` + `nemoclaw-dashboard.service`
|
||||
- **Port ownership truth** → PID/socket inspection, not browser success alone
|
||||
- **Terminal session transport truth** → `terminal-server.mjs` on `127.0.0.1:3011`
|
||||
- **Dashboard-to-terminal bridge truth** → `server.mjs` proxy path `/api/openshell/terminal/live/ws`
|
||||
- **OpenClaw instance registry truth** → `app/lib/openclawInstances.ts` environment-driven registry
|
||||
- **Dashboard browser session identity truth** → `app/lib/dashboardSession.ts`
|
||||
|
||||
No feature may silently invent a second authority for the same concern.
|
||||
|
||||
## 1.2 Browser-visible truth is not runtime truth
|
||||
A page returning HTTP 200 from `:3000` is insufficient evidence.
|
||||
|
||||
A claim like “dashboard is up” is valid only if all are true:
|
||||
|
||||
- the expected port is listening
|
||||
- the owning PID belongs to the intended runtime path/service
|
||||
- the service state matches the port state
|
||||
- the deployed code path matches the claimed release lane
|
||||
|
||||
If one of those is missing, report degraded or unknown, not healthy.
|
||||
|
||||
## 1.3 Environment defaults may bootstrap, not silently redefine truth
|
||||
Defaults such as:
|
||||
|
||||
- `OPENCLAW_DASHBOARD_URL`
|
||||
- `TERMINAL_SERVER_URL`
|
||||
- `OPENCLAW_INSTANCE_REGISTRY_JSON`
|
||||
- `OPENCLAW_SANDBOX_INSTANCE_MAP_JSON`
|
||||
|
||||
may provide bootstrap behavior, but they must not create silent semantic rewrites.
|
||||
|
||||
If an env var changes authority, routing, loopback policy, or instance selection, the UI and logs must expose that fact.
|
||||
|
||||
---
|
||||
|
||||
## 2. Route ownership doctrine
|
||||
|
||||
## 2.1 Each route has one owner module
|
||||
Each API route or transport path must have one clearly named owner.
|
||||
|
||||
Current ownership model:
|
||||
|
||||
- Next.js app routes under `app/api/**` own user-facing HTTP API semantics
|
||||
- `server.mjs` owns the outer HTTP/WebSocket server and terminal bridge upgrade path
|
||||
- `terminal-server.mjs` owns terminal session creation, buffering, resize/input handling, and process lifecycle
|
||||
- `app/lib/*` owns shared authority/identity resolution logic, not ad hoc route-local copies
|
||||
|
||||
Do not duplicate resolution logic inside multiple route handlers when a shared module already exists.
|
||||
|
||||
## 2.2 No split-brain route semantics
|
||||
If the same conceptual operation is available in multiple places, one path must be canonical and the others must either:
|
||||
|
||||
- delegate directly to it, or
|
||||
- be removed
|
||||
|
||||
Example:
|
||||
|
||||
- terminal live WebSocket entrypoint must be treated as owned by `server.mjs` proxy path `/api/openshell/terminal/live/ws`
|
||||
- direct client assumptions that bypass this owner path are not allowed unless the architecture is intentionally changed and this BIBLE is updated
|
||||
|
||||
## 2.3 UI state is not authority
|
||||
UI-selected sandbox, browser sessionStorage, or client memory can express **intent**, but not authoritative backend fact.
|
||||
|
||||
Specifically:
|
||||
|
||||
- `dashboardSessionId` is correlation state, not backend truth
|
||||
- `selectedSandboxId` is operator intent, not proof that the backend session is attached to the correct target
|
||||
|
||||
Backends must validate and log the actual resolved identity.
|
||||
|
||||
## 2.4 Shared resolution logic must live in library code
|
||||
The following classes of logic must live in shared modules, not repeated inline:
|
||||
|
||||
- instance resolution
|
||||
- sandbox-to-instance mapping
|
||||
- dashboard session identity construction
|
||||
- host/runtime probing
|
||||
- normalized phase/status naming
|
||||
|
||||
If a contributor copies logic from `app/lib/openclawInstances.ts`, `app/lib/dashboardSession.ts`, or `app/lib/openshellHost.ts` into route files, that is a doctrine violation.
|
||||
|
||||
---
|
||||
|
||||
## 3. Runtime ownership doctrine
|
||||
|
||||
## 3.1 Single supervised owner for live runtime
|
||||
Live runtime on Spark must be single-owner and supervised.
|
||||
|
||||
That means:
|
||||
|
||||
- `nemoclaw-dashboard.service` is the owner
|
||||
- its supervisor script controls process startup/cleanup
|
||||
- `terminal-server.mjs` is not independently service-owned in normal operation
|
||||
|
||||
The disabled oneshot `tmp_nemoclaw_terminal.service` pattern reflects the correct doctrine: terminal runtime is subordinate to the dashboard supervisor, not a co-equal long-running owner.
|
||||
|
||||
## 3.2 Manual `next dev` on production ports is drift
|
||||
A manually launched workspace process on `:3000` or `:3011` is drift when the service is supposed to own those ports.
|
||||
|
||||
This includes:
|
||||
|
||||
- `npm run dev`
|
||||
- `next dev`
|
||||
- `node server.mjs` from the wrong tree
|
||||
- shell-started `terminal-server.mjs`
|
||||
|
||||
Manual processes are allowed only for bounded diagnostics when all are true:
|
||||
|
||||
- the service is stopped or intentionally isolated
|
||||
- the operator explicitly says diagnostic mode is active
|
||||
- the ports and owning path are checked before and after
|
||||
- the process is removed after diagnosis
|
||||
|
||||
## 3.3 Supervisor owns child lifecycle
|
||||
The dashboard supervisor must remain responsible for:
|
||||
|
||||
- preflight port guarding
|
||||
- starting terminal server
|
||||
- waiting for terminal `/healthz`
|
||||
- starting dashboard HTTP owner
|
||||
- cleanup of child terminal PID
|
||||
- cleanup of both ports on exit
|
||||
|
||||
Do not move those responsibilities piecemeal into random shell scripts or route handlers.
|
||||
|
||||
## 3.4 Loopback-only terminal server is intentional
|
||||
`terminal-server.mjs` defaulting to `127.0.0.1:3011` is a security and ownership feature.
|
||||
|
||||
Do not expose `:3011` directly on public interfaces as a convenience shortcut.
|
||||
|
||||
External clients must go through the dashboard-owned bridge unless the architecture is explicitly redesigned.
|
||||
|
||||
## 3.5 Preserve runtime helpers across deploys
|
||||
The live tree’s `.runtime/*` contents are part of runtime ownership.
|
||||
|
||||
Per local notes, do not delete or clobber runtime helper scripts during sync/deploy.
|
||||
|
||||
At minimum preserve:
|
||||
|
||||
- supervisor scripts
|
||||
- port guards
|
||||
- PID/log/runtime state files needed by the service contract
|
||||
|
||||
A deploy that replaces app code but destroys ownership tooling is a broken deploy.
|
||||
|
||||
---
|
||||
|
||||
## 4. Deploy and release discipline
|
||||
|
||||
## 4.1 Build in projects, run in live
|
||||
Required flow:
|
||||
|
||||
1. change code in `/home/nvidia/.openclaw/workspace/projects/nemoclaw-dashboard`
|
||||
2. validate there
|
||||
3. sync/promote intentionally into `/home/nvidia/nemoclaw-dashboard`
|
||||
4. restart or reload via the owning service
|
||||
5. verify runtime ownership after deploy
|
||||
|
||||
Do not “hotfix the live tree and maybe backport later.” That creates untraceable truth forks.
|
||||
|
||||
## 4.2 Every deployment must answer four questions
|
||||
Before claiming deploy success, record:
|
||||
|
||||
- what commit/content was deployed
|
||||
- from which source path it came
|
||||
- which service/process now owns `:3000` and `:3011`
|
||||
- which verification checks passed
|
||||
|
||||
If these are not known, the deploy is not complete.
|
||||
|
||||
## 4.3 Production mode must be explicit
|
||||
The supervisor currently selects:
|
||||
|
||||
- production mode if `.next/BUILD_ID` exists
|
||||
- development mode otherwise
|
||||
|
||||
This fallback is operationally useful, but dangerous because it can make drift look normal.
|
||||
|
||||
Doctrine:
|
||||
|
||||
- intended service mode must be explicit in deploy notes/logs
|
||||
- production claims require proof that production artifacts existed and were used
|
||||
- if the service falls back to `next dev`, that state must be treated as degraded, not equivalent to production
|
||||
|
||||
## 4.4 No invisible lane crossing
|
||||
If code is copied/synced from workspace to live tree, that action must be deliberate and logged.
|
||||
|
||||
Allowed:
|
||||
|
||||
- controlled sync scripts
|
||||
- documented rsync/copy steps
|
||||
- release commits/tags
|
||||
|
||||
Not allowed:
|
||||
|
||||
- ad hoc manual edits in both trees
|
||||
- partial file copying without manifest or explanation
|
||||
- “I think live matches workspace” with no evidence
|
||||
|
||||
---
|
||||
|
||||
## 5. Fallback and degraded-mode honesty
|
||||
|
||||
## 5.1 Fallbacks must announce themselves
|
||||
A fallback path must never present itself as canonical success.
|
||||
|
||||
Examples:
|
||||
|
||||
- default instance chosen because requested instance was missing
|
||||
- default dashboard session created because client session was absent
|
||||
- terminal transport falling back from PTY to stream
|
||||
- service using dev mode because build artifacts were absent
|
||||
|
||||
All of these are legal only if they are observable.
|
||||
|
||||
## 5.2 Honesty rule
|
||||
When the system is using fallback or degraded behavior, it must say one of:
|
||||
|
||||
- `fallback-active`
|
||||
- `degraded`
|
||||
- `defaulted`
|
||||
- `unknown-owner`
|
||||
- `unverified`
|
||||
|
||||
It must not say only `ok`, `healthy`, or `connected` if the canonical target was not proven.
|
||||
|
||||
## 5.3 Transport downgrade is not neutral
|
||||
If terminal runtime drops from PTY to stream mode, treat it as a material runtime fact.
|
||||
|
||||
Expose it in:
|
||||
|
||||
- `/healthz` payloads where relevant
|
||||
- session init response
|
||||
- logs
|
||||
- test expectations
|
||||
|
||||
Do not hide transport downgrades; they affect operator behavior and bug interpretation.
|
||||
|
||||
## 5.4 Missing target must fail closed where authority matters
|
||||
If a requested instance, sandbox, or runtime owner cannot be proven, then:
|
||||
|
||||
- read paths may return explicit unknown/degraded state
|
||||
- mutating/interactive paths must prefer explicit failure over silent retargeting
|
||||
|
||||
Silent retargeting is how authority drift becomes data loss or operator deception.
|
||||
|
||||
---
|
||||
|
||||
## 6. Logging and provenance doctrine
|
||||
|
||||
## 6.1 Logs must prove who did what, where
|
||||
Every meaningful runtime action should be attributable across these axes:
|
||||
|
||||
- timestamp
|
||||
- owning component
|
||||
- route/path/event
|
||||
- dashboard session id if present
|
||||
- sandbox id or instance id if relevant
|
||||
- resolved target actually used
|
||||
- transport/runtime mode if relevant
|
||||
|
||||
## 6.2 Distinguish requested identity from resolved identity
|
||||
Whenever user input can be remapped, logs must preserve both:
|
||||
|
||||
- requested sandbox/instance/session
|
||||
- resolved sandbox/instance/session
|
||||
|
||||
Never overwrite requested identity and keep only the resolved one. That destroys forensic value.
|
||||
|
||||
## 6.3 Ownership logs beat cosmetic logs
|
||||
Prefer logs that answer:
|
||||
|
||||
- which PID owned the port
|
||||
- which path launched the process
|
||||
- which service unit was active
|
||||
- which upstream terminal URL was bridged
|
||||
|
||||
over decorative logs that only say “connected” or “success”.
|
||||
|
||||
## 6.4 Bridge/proxy logs are mandatory for multiplexed terminal behavior
|
||||
Because `server.mjs` proxies terminal WebSockets, bridge logs are part of runtime truth.
|
||||
|
||||
Required for connection lifecycle events:
|
||||
|
||||
- bridge id
|
||||
- client path
|
||||
- upstream URL
|
||||
- close source
|
||||
- close code/reason
|
||||
- frame counters or equivalent activity signal
|
||||
|
||||
That pattern already exists and must remain.
|
||||
|
||||
---
|
||||
|
||||
## 7. Testing and acceptance gates
|
||||
|
||||
## 7.1 A web-service change is not done until authority is tested
|
||||
Tests must validate not only feature output, but authority correctness.
|
||||
|
||||
Minimum acceptance for runtime-affecting changes:
|
||||
|
||||
1. route/feature behaves as intended
|
||||
2. resolved authority matches expected authority
|
||||
3. fallback/degraded states are explicit
|
||||
4. logs contain provenance fields
|
||||
5. runtime owner on ports remains correct after deploy
|
||||
|
||||
## 7.2 Required verification classes
|
||||
Any non-trivial change touching routing, instance selection, terminal bridging, or deploy logic must include checks from these classes:
|
||||
|
||||
### A. Static ownership checks
|
||||
- confirm owner module was changed in one place, not duplicated in several
|
||||
- confirm shared resolution logic still comes from `app/lib/*`
|
||||
|
||||
### B. Behavior checks
|
||||
- valid request to intended sandbox/instance
|
||||
- invalid/missing target request
|
||||
- fallback activation path
|
||||
- degraded transport path if applicable
|
||||
|
||||
### C. Runtime checks
|
||||
- service status
|
||||
- listener presence on `:3000` and `:3011`
|
||||
- PID/path ownership for both ports
|
||||
- dashboard bridge path still functional
|
||||
- terminal server `/healthz` still functional
|
||||
|
||||
### D. Honesty checks
|
||||
- UI/API response does not call fallback state healthy without qualification
|
||||
- logs reveal requested vs resolved target
|
||||
|
||||
## 7.3 No green-by-HTTP-only acceptance
|
||||
A test bundle that checks only:
|
||||
|
||||
- page loads
|
||||
- API returns 200
|
||||
- WebSocket connects
|
||||
|
||||
is insufficient for this service.
|
||||
|
||||
At least one acceptance step must verify owner identity beyond network reachability.
|
||||
|
||||
## 7.4 Promotion gate
|
||||
Do not promote workspace changes into live runtime unless all apply:
|
||||
|
||||
- build or intentional dev-mode rationale is documented
|
||||
- tests passed in workspace lane
|
||||
- sync target is identified
|
||||
- ownership verification plan exists
|
||||
- post-deploy owner verification completed
|
||||
|
||||
---
|
||||
|
||||
## 8. No-go anti-patterns
|
||||
|
||||
These are banned unless this BIBLE is explicitly amended.
|
||||
|
||||
## 8.1 Split truth planes
|
||||
- showing dashboard state from one source while actions hit another
|
||||
- inventory from one registry and terminal attach from a hidden different registry
|
||||
- route owner changed in one layer but old path still appears canonical elsewhere
|
||||
|
||||
## 8.2 Silent default authority
|
||||
- missing requested instance silently replaced with default for a mutating action
|
||||
- absent sandbox silently converted to host shell without explicit operator visibility
|
||||
- production claim made while actually running fallback dev mode
|
||||
|
||||
## 8.3 Cosmetic health
|
||||
- declaring service healthy from HTTP 200 alone
|
||||
- using successful UI render as proof of correct owner
|
||||
- treating any listener on `:3000` as acceptable
|
||||
|
||||
## 8.4 Live-tree hand editing
|
||||
- editing `/home/nvidia/nemoclaw-dashboard` directly as the normal development path
|
||||
- patching runtime helper scripts ad hoc without backporting and documenting
|
||||
|
||||
## 8.5 Ownership multiplication
|
||||
- separate long-lived service for terminal server without deliberate architecture decision
|
||||
- parallel dashboard launchers fighting over `:3000`
|
||||
- supervisor plus manual shell process both trying to own the same port
|
||||
|
||||
## 8.6 Logic cloning
|
||||
- duplicating instance resolution logic in route handlers
|
||||
- duplicating dashboard session semantics in UI pages and API routes independently
|
||||
- separate, inconsistent normalization of sandbox phase names
|
||||
|
||||
## 8.7 Lying fallbacks
|
||||
- fallback used but not logged
|
||||
- degraded state shown as normal
|
||||
- unknown owner reported as healthy
|
||||
|
||||
---
|
||||
|
||||
## 9. Change protocol for contributors and agents
|
||||
|
||||
## 9.1 Before changing anything, classify the change
|
||||
Every contributor must first state which doctrine area is affected:
|
||||
|
||||
- source of truth
|
||||
- route ownership
|
||||
- runtime ownership
|
||||
- deploy/release
|
||||
- fallback/degraded behavior
|
||||
- logging/provenance
|
||||
- tests/acceptance
|
||||
|
||||
If the change crosses more than one, say so up front.
|
||||
|
||||
## 9.2 For any authority-affecting change, write the invariant first
|
||||
Before editing code, write the invariant in one sentence.
|
||||
|
||||
Examples:
|
||||
|
||||
- “dashboard WebSocket clients must only reach terminal sessions through `server.mjs` proxy ownership”
|
||||
- “requested sandbox identity must be preserved in logs even when remapped”
|
||||
- “service-owned runtime on `:3000` must not be replaceable by stray workspace dev server without detection”
|
||||
|
||||
If you cannot state the invariant, you are not ready to edit.
|
||||
|
||||
## 9.3 Touch the owner, not a symptom surface
|
||||
Fix problems in the owning layer.
|
||||
|
||||
Examples:
|
||||
|
||||
- instance-selection bug → fix `app/lib/openclawInstances.ts`, not several callers
|
||||
- terminal bridge bug → fix `server.mjs` or `terminal-server.mjs`, not UI hacks pretending the bridge is fine
|
||||
- runtime drift → fix deploy/supervisor/service ownership, not status wording alone
|
||||
|
||||
## 9.4 Any new fallback requires four things
|
||||
If you add a fallback path, you must also add:
|
||||
|
||||
1. explicit trigger condition
|
||||
2. explicit log field/message
|
||||
3. explicit degraded/defaulted outward state where relevant
|
||||
4. test coverage proving fallback honesty
|
||||
|
||||
No silent convenience fallbacks.
|
||||
|
||||
## 9.5 Any new route must declare ownership and authority inputs
|
||||
For every new route or socket path, document:
|
||||
|
||||
- owner file
|
||||
- inputs that affect target resolution
|
||||
- canonical backend authority it depends on
|
||||
- fallback behavior
|
||||
- logging fields
|
||||
- acceptance checks
|
||||
|
||||
## 9.6 Any runtime/deploy change must verify ownership before and after
|
||||
Before changing service/deploy/runtime scripts:
|
||||
|
||||
- capture current owner of `:3000` and `:3011`
|
||||
- capture current service state
|
||||
|
||||
After change:
|
||||
|
||||
- recapture owner of `:3000` and `:3011`
|
||||
- verify expected service and path ownership
|
||||
- verify HTTP plus ownership, not HTTP alone
|
||||
|
||||
## 9.7 If architecture changes, update this document in the same work packet
|
||||
This BIBLE is part of the codebase contract.
|
||||
|
||||
If you change:
|
||||
|
||||
- who owns ports
|
||||
- how terminal transport is exposed
|
||||
- what the canonical code/live lanes are
|
||||
- what module owns instance resolution
|
||||
- whether `server.mjs` remains the sole bridge owner
|
||||
|
||||
then update this file in the same change.
|
||||
|
||||
Code and doctrine must ship together.
|
||||
|
||||
---
|
||||
|
||||
## 10. Operational truth checklist
|
||||
|
||||
Use this checklist before saying “NemoClaw web service is healthy.”
|
||||
|
||||
- [ ] code change originated from `projects/nemoclaw-dashboard`
|
||||
- [ ] live tree sync target is known
|
||||
- [ ] `nemoclaw-dashboard.service` state is known
|
||||
- [ ] `:3000` listener exists and owner PID/path is correct
|
||||
- [ ] `:3011` listener exists and owner PID/path is correct
|
||||
- [ ] terminal `/healthz` passes
|
||||
- [ ] dashboard root responds
|
||||
- [ ] terminal bridge path works through the dashboard owner
|
||||
- [ ] any fallback/degraded mode is explicitly visible
|
||||
- [ ] logs show requested and resolved target identity where applicable
|
||||
|
||||
If any box is unchecked, the correct status is not healthy. It is partial, degraded, unknown, or failed.
|
||||
|
||||
---
|
||||
|
||||
## 11. Non-negotiable service invariants
|
||||
|
||||
These are the core invariants future work must preserve unless deliberately replaced.
|
||||
|
||||
1. **One editable code authority**: `projects/nemoclaw-dashboard`
|
||||
2. **One live runtime authority**: `/home/nvidia/nemoclaw-dashboard` under `nemoclaw-dashboard.service`
|
||||
3. **One owner for terminal exposure**: dashboard bridge in `server.mjs`
|
||||
4. **One owner for terminal session lifecycle**: `terminal-server.mjs`
|
||||
5. **One owner for instance registry logic**: `app/lib/openclawInstances.ts`
|
||||
6. **One owner for dashboard session identity logic**: `app/lib/dashboardSession.ts`
|
||||
7. **HTTP success alone never proves runtime truth**
|
||||
8. **Fallbacks must announce themselves**
|
||||
9. **Port ownership outranks appearance**
|
||||
10. **Doctrine must be updated when architecture changes**
|
||||
|
||||
If a proposed change violates one of these, stop and redesign instead of papering over it.
|
||||
@@ -1,14 +1,108 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getOpenClawDashboardUrl } from '../../../../lib/openshellHost'
|
||||
import { getDefaultOpenClawDashboardInstanceId, getOpenClawDashboardUrl, probeOpenClawDashboard } from '../../../../lib/openshellHost'
|
||||
import { getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, resolveOpenClawInstanceForSandbox } from '../../../../lib/openclawInstances'
|
||||
import { resolveRuntimeAuthority } from '../../../../lib/runtimeAuthority'
|
||||
|
||||
function parseInventoryCount(requestUrl: URL) {
|
||||
const raw = requestUrl.searchParams.get('inventoryCount')
|
||||
if (raw == null) return null
|
||||
const count = Number.parseInt(raw, 10)
|
||||
return Number.isFinite(count) && count >= 0 ? count : null
|
||||
}
|
||||
|
||||
function buildLaunchUrl(proxiedUrl: string, bootstrapUrl: string | null) {
|
||||
if (!bootstrapUrl) return proxiedUrl
|
||||
|
||||
const bootstrap = new URL(bootstrapUrl)
|
||||
const browserHash = bootstrap.hash
|
||||
bootstrap.hash = ''
|
||||
|
||||
const params = new URLSearchParams({
|
||||
path: '/',
|
||||
bootstrapUrl: bootstrap.toString(),
|
||||
})
|
||||
|
||||
return `${proxiedUrl}?${params.toString()}${browserHash}`
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const requestUrl = new URL(request.url)
|
||||
const sandboxId = requestUrl.searchParams.get('sandboxId')
|
||||
const requestedInstanceId = requestUrl.searchParams.get('instanceId')
|
||||
const inventoryCount = parseInventoryCount(requestUrl)
|
||||
const mappedSandboxInstanceId = getOpenClawInstanceIdForSandbox(sandboxId)
|
||||
const instance = requestedInstanceId
|
||||
? resolveOpenClawInstance(requestedInstanceId)
|
||||
: resolveOpenClawInstanceForSandbox(sandboxId)
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId,
|
||||
instanceId: requestedInstanceId,
|
||||
})
|
||||
const probe = await probeOpenClawDashboard(authority.openclaw.id)
|
||||
const instanceQualifiedProxyBase = `/api/openshell/instances/${encodeURIComponent(instance.id)}/dashboard/proxy`
|
||||
const zeroInventoryMappedDashboard = Boolean(
|
||||
inventoryCount === 0 &&
|
||||
sandboxId &&
|
||||
authority.bridgeActive &&
|
||||
probe.reachable
|
||||
)
|
||||
const truthState = zeroInventoryMappedDashboard
|
||||
? 'degraded'
|
||||
: probe.bootstrapAuthority === 'tokenized-cli'
|
||||
? 'tokenized'
|
||||
: authority.bridgeActive
|
||||
? 'bridged'
|
||||
: 'verified'
|
||||
|
||||
const proxiedUrl = authority.explicitInstanceOverride ? instanceQualifiedProxyBase : '/api/openshell/dashboard/proxy'
|
||||
const launchUrl = buildLaunchUrl(proxiedUrl, probe.bootstrapUrl)
|
||||
|
||||
export async function GET() {
|
||||
const dashboardUrl = getOpenClawDashboardUrl()
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
dashboardUrl,
|
||||
proxiedUrl: '/api/openshell/dashboard/proxy',
|
||||
sandboxId,
|
||||
sandboxInstanceId: mappedSandboxInstanceId,
|
||||
instanceId: instance.id,
|
||||
inventoryCount,
|
||||
truthState,
|
||||
degraded: zeroInventoryMappedDashboard,
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
authorityMode: authority.authorityMode,
|
||||
provenance: authority.provenance,
|
||||
bridgeActive: authority.bridgeActive,
|
||||
bridgeReason: authority.bridgeReason,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
},
|
||||
defaultInstanceId: getDefaultOpenClawDashboardInstanceId(),
|
||||
dashboardUrl: getOpenClawDashboardUrl(authority.openclaw.id),
|
||||
bootstrapUrl: probe.bootstrapUrl,
|
||||
bootstrapTokenPresent: probe.bootstrapTokenPresent,
|
||||
bootstrapSource: probe.bootstrapSource,
|
||||
bootstrapAuthority: probe.bootstrapAuthority,
|
||||
proxiedUrl,
|
||||
launchUrl,
|
||||
instanceQualifiedProxiedUrl: instanceQualifiedProxyBase,
|
||||
openInNewTab: true,
|
||||
loopbackOnly: true,
|
||||
note: 'OpenClaw Dashboard is loopback-only on the host, so the web UI uses a local proxy route to expose it.'
|
||||
loopbackOnly: authority.openclaw.loopbackOnly,
|
||||
reachable: probe.reachable,
|
||||
upstreamStatus: probe.status,
|
||||
upstreamStatusText: probe.statusText,
|
||||
listenerPresent: probe.listenerPresent,
|
||||
listenerSummary: probe.listenerSummary,
|
||||
note: zeroInventoryMappedDashboard
|
||||
? 'Degraded truth: live OpenShell inventory is zero, but a bridged OpenClaw dashboard upstream is still reachable. Treat this dashboard as a fallback operator surface, not proof that the sandbox currently exists.'
|
||||
: probe.bootstrapAuthority === 'tokenized-cli'
|
||||
? 'Tokenized bootstrap available: the bridge resolved a dashboard URL from `openclaw dashboard --no-open`, so the proxy can carry the real OpenClaw session contract instead of treating raw loopback fetch as sufficient truth.'
|
||||
: authority.bridgeActive
|
||||
? authority.bridgeReason || 'Bridge-active: this dashboard action is using an explicit upstream OpenClaw bridge instead of assuming same-lane loopback ownership.'
|
||||
: authority.openclaw.loopbackOnly
|
||||
? 'OpenClaw Dashboard is loopback-only on the host, so the web UI uses a local proxy route to expose it.'
|
||||
: 'OpenClaw Dashboard is reachable directly for this instance.'
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { proxyErrorResponse, proxyOpenClawDashboard } from '../shared'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
return await proxyOpenClawDashboard(request)
|
||||
} catch (error) {
|
||||
return proxyErrorResponse(error)
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,9 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
const OPENCLAW_LOCAL_DASHBOARD = 'http://127.0.0.1:18789/'
|
||||
import { proxyErrorResponse, proxyOpenClawDashboard } from './shared'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const url = new URL(request.url)
|
||||
const targetPath = url.searchParams.get('path') || ''
|
||||
const target = new URL(targetPath, OPENCLAW_LOCAL_DASHBOARD)
|
||||
|
||||
const upstream = await fetch(target.toString(), {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
accept: 'text/html,application/json;q=0.9,*/*;q=0.8'
|
||||
},
|
||||
cache: 'no-store'
|
||||
})
|
||||
|
||||
const contentType = upstream.headers.get('content-type') || 'text/html; charset=utf-8'
|
||||
const body = await upstream.text()
|
||||
|
||||
return new NextResponse(body, {
|
||||
status: upstream.status,
|
||||
headers: {
|
||||
'content-type': contentType,
|
||||
'cache-control': 'no-store'
|
||||
}
|
||||
})
|
||||
return await proxyOpenClawDashboard(request)
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to proxy OpenClaw dashboard'
|
||||
}, { status: 500 })
|
||||
return proxyErrorResponse(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getDefaultOpenClawDashboardInstanceId } from '@/app/lib/openshellHost'
|
||||
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
|
||||
|
||||
const LEGACY_PROXY_PREFIX = '/api/openshell/dashboard/proxy'
|
||||
const INSTANCES_PREFIX = '/api/openshell/instances/'
|
||||
const DASHBOARD_PROXY_SUFFIX = '/dashboard/proxy'
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'accept-encoding',
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'te',
|
||||
'trailer',
|
||||
'transfer-encoding',
|
||||
'upgrade',
|
||||
'content-length',
|
||||
])
|
||||
|
||||
type ProxyTargetResolution = {
|
||||
instanceId: string | null
|
||||
proxyPrefix: string
|
||||
targetBaseUrl: string
|
||||
authorityMode: 'direct-host' | 'bridged-sandbox-map' | 'bridged-instance-override'
|
||||
bridgeActive: boolean
|
||||
}
|
||||
|
||||
function normalizeDashboardProxyInstanceId(instanceId: string | null) {
|
||||
if (!instanceId) return null
|
||||
return instanceId === getDefaultOpenClawDashboardInstanceId() ? null : instanceId
|
||||
}
|
||||
|
||||
function resolveProxyTarget(requestUrl: URL): ProxyTargetResolution {
|
||||
const pathname = requestUrl.pathname
|
||||
|
||||
if (pathname.startsWith(INSTANCES_PREFIX)) {
|
||||
const suffixIndex = pathname.indexOf(DASHBOARD_PROXY_SUFFIX, INSTANCES_PREFIX.length)
|
||||
if (suffixIndex !== -1) {
|
||||
const rawInstanceId = pathname.slice(INSTANCES_PREFIX.length, suffixIndex)
|
||||
const decodedInstanceId = decodeURIComponent(rawInstanceId)
|
||||
const normalizedInstanceId = normalizeDashboardProxyInstanceId(decodedInstanceId)
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId: requestUrl.searchParams.get('sandboxId'),
|
||||
instanceId: normalizedInstanceId,
|
||||
})
|
||||
return {
|
||||
instanceId: authority.openclaw.id,
|
||||
proxyPrefix: `/api/openshell/instances/${encodeURIComponent(decodedInstanceId)}/dashboard/proxy`,
|
||||
targetBaseUrl: authority.openclaw.dashboardUrl,
|
||||
authorityMode: authority.authorityMode,
|
||||
bridgeActive: authority.bridgeActive,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId: requestUrl.searchParams.get('sandboxId'),
|
||||
})
|
||||
|
||||
return {
|
||||
instanceId: authority.bridgeActive ? authority.openclaw.id : null,
|
||||
proxyPrefix: LEGACY_PROXY_PREFIX,
|
||||
targetBaseUrl: authority.openclaw.dashboardUrl,
|
||||
authorityMode: authority.authorityMode,
|
||||
bridgeActive: authority.bridgeActive,
|
||||
}
|
||||
}
|
||||
|
||||
function buildTargetUrl(requestUrl: URL) {
|
||||
const { proxyPrefix, targetBaseUrl, authorityMode, bridgeActive } = resolveProxyTarget(requestUrl)
|
||||
const pathParam = requestUrl.searchParams.get('path')
|
||||
const bootstrapUrl = requestUrl.searchParams.get('bootstrapUrl')
|
||||
const pathname = requestUrl.pathname.startsWith(proxyPrefix)
|
||||
? requestUrl.pathname.slice(proxyPrefix.length)
|
||||
: '/'
|
||||
const upstreamPath = pathParam ?? pathname ?? '/'
|
||||
const normalizedPath = upstreamPath.startsWith('/') ? upstreamPath : `/${upstreamPath}`
|
||||
const target = bootstrapUrl
|
||||
? new URL(bootstrapUrl)
|
||||
: new URL(normalizedPath, targetBaseUrl)
|
||||
|
||||
if (!bootstrapUrl) {
|
||||
requestUrl.searchParams.forEach((value, key) => {
|
||||
if (key !== 'path') target.searchParams.append(key, value)
|
||||
})
|
||||
}
|
||||
|
||||
return { target, proxyPrefix, authorityMode, bridgeActive }
|
||||
}
|
||||
|
||||
function copyRequestHeaders(request: Request, target: URL) {
|
||||
const headers = new Headers()
|
||||
|
||||
request.headers.forEach((value, key) => {
|
||||
if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase()) && key.toLowerCase() !== 'host') {
|
||||
headers.set(key, value)
|
||||
}
|
||||
})
|
||||
|
||||
headers.set('host', target.host)
|
||||
return headers
|
||||
}
|
||||
|
||||
function copyResponseHeaders(upstream: Response) {
|
||||
const headers = new Headers()
|
||||
|
||||
upstream.headers.forEach((value, key) => {
|
||||
if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase())) {
|
||||
headers.set(key, value)
|
||||
}
|
||||
})
|
||||
|
||||
headers.set('cache-control', 'no-store')
|
||||
return headers
|
||||
}
|
||||
|
||||
function proxiedAssetPath(value: string, proxyPrefix: string) {
|
||||
if (
|
||||
!value ||
|
||||
value.startsWith('#') ||
|
||||
value.startsWith('//') ||
|
||||
/^[a-z][a-z\d+.-]*:/i.test(value)
|
||||
) {
|
||||
return value
|
||||
}
|
||||
|
||||
const normalized = value.startsWith('./')
|
||||
? value.slice(2)
|
||||
: value.startsWith('/')
|
||||
? value.slice(1)
|
||||
: value
|
||||
|
||||
return `${proxyPrefix}/${normalized}`
|
||||
}
|
||||
|
||||
function rewriteHtml(body: string, proxyPrefix: string) {
|
||||
return body.replace(
|
||||
/(<(?:script|img|link)\b[^>]*\s(?:src|href)=)(["'])([^"']+)(["'])/gi,
|
||||
(_match, prefix: string, quote: string, value: string, suffix: string) =>
|
||||
`${prefix}${quote}${proxiedAssetPath(value, proxyPrefix)}${suffix}`
|
||||
)
|
||||
}
|
||||
|
||||
export async function proxyOpenClawDashboard(request: Request) {
|
||||
const requestUrl = new URL(request.url)
|
||||
const { target, proxyPrefix, authorityMode, bridgeActive } = buildTargetUrl(requestUrl)
|
||||
const method = request.method.toUpperCase()
|
||||
const headers = copyRequestHeaders(request, target)
|
||||
const shouldSendBody = !['GET', 'HEAD'].includes(method)
|
||||
const upstreamInit: RequestInit & { duplex?: 'half' } = {
|
||||
method,
|
||||
headers,
|
||||
body: shouldSendBody ? request.body : undefined,
|
||||
redirect: 'manual',
|
||||
cache: 'no-store',
|
||||
}
|
||||
|
||||
if (shouldSendBody) {
|
||||
upstreamInit.duplex = 'half'
|
||||
}
|
||||
|
||||
const upstream = await fetch(target.toString(), {
|
||||
...upstreamInit,
|
||||
})
|
||||
|
||||
const responseHeaders = copyResponseHeaders(upstream)
|
||||
responseHeaders.set('x-openclaw-authority-mode', authorityMode)
|
||||
responseHeaders.set('x-openclaw-bridge-active', bridgeActive ? 'true' : 'false')
|
||||
responseHeaders.set('x-openclaw-dashboard-bootstrap-contract', 'tokenized-openclaw-dashboard')
|
||||
const location = upstream.headers.get('location')
|
||||
if (location) {
|
||||
responseHeaders.set('location', location.startsWith('/') ? `${proxyPrefix}${location}` : location)
|
||||
}
|
||||
const contentType = upstream.headers.get('content-type') || 'application/octet-stream'
|
||||
|
||||
if (contentType.includes('text/html')) {
|
||||
const body = rewriteHtml(await upstream.text(), proxyPrefix)
|
||||
responseHeaders.set('content-type', contentType)
|
||||
return new NextResponse(body, {
|
||||
status: upstream.status,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
return new NextResponse(upstream.body, {
|
||||
status: upstream.status,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
|
||||
export function proxyErrorResponse(error: unknown) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to proxy OpenClaw dashboard',
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { proxyErrorResponse, proxyOpenClawDashboard } from '../../../../../dashboard/proxy/shared'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
return await proxyOpenClawDashboard(request)
|
||||
} catch (error) {
|
||||
return proxyErrorResponse(error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { proxyErrorResponse, proxyOpenClawDashboard } from '../../../../dashboard/proxy/shared'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
return await proxyOpenClawDashboard(request)
|
||||
} catch (error) {
|
||||
return proxyErrorResponse(error)
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { dockerExecInOpenShell, OPENSHELL_NAMESPACE } from '../../../../lib/openshellHost'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const sandboxId = searchParams.get('sandboxId')
|
||||
|
||||
if (!sandboxId) {
|
||||
return NextResponse.json({ error: 'sandboxId is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const result = await dockerExecInOpenShell(
|
||||
`kubectl -n ${OPENSHELL_NAMESPACE} get pod ${sandboxId} -o json`
|
||||
)
|
||||
|
||||
const pod = JSON.parse(result.stdout)
|
||||
const containerNames = Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.name) : []
|
||||
const containerImages = Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.image) : []
|
||||
const statusNames = Array.isArray(pod?.status?.containerStatuses) ? pod.status.containerStatuses.map((c: any) => c.name) : []
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId,
|
||||
containers: containerNames,
|
||||
images: containerImages,
|
||||
runningStatuses: statusNames,
|
||||
raw: result.stdout.trim(),
|
||||
stderr: result.stderr.trim(),
|
||||
note: 'Pod/container introspection succeeded. Use this to select the right exec target for terminal attach.'
|
||||
})
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to introspect sandbox pod'
|
||||
}, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,131 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { inspectSandbox } from '@/app/lib/openshellHost'
|
||||
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
|
||||
|
||||
const TERMINAL_SERVER_URL = process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011'
|
||||
const TERMINAL_WS_PROXY_PATH = '/api/openshell/terminal/live/ws'
|
||||
const PUBLIC_BROWSER_HOST = process.env.PUBLIC_BROWSER_HOST || process.env.PUBLIC_WS_HOST || null
|
||||
const PUBLIC_BASE_URL = process.env.PUBLIC_BASE_URL || null
|
||||
|
||||
function isNonRoutableHost(candidate: string, protocol = 'http:') {
|
||||
const normalized = candidate.trim()
|
||||
if (!normalized) return true
|
||||
|
||||
try {
|
||||
const parsed = new URL(`${protocol}//${normalized}`)
|
||||
return (
|
||||
parsed.hostname === '0.0.0.0' ||
|
||||
parsed.hostname === '::' ||
|
||||
parsed.hostname === '127.0.0.1' ||
|
||||
parsed.hostname === 'localhost' ||
|
||||
parsed.hostname === '[::1]' ||
|
||||
parsed.hostname === '::1'
|
||||
)
|
||||
} catch {
|
||||
return (
|
||||
normalized.startsWith('0.0.0.0') ||
|
||||
normalized.startsWith('[::]') ||
|
||||
normalized.startsWith('127.0.0.1') ||
|
||||
normalized.startsWith('localhost') ||
|
||||
normalized.startsWith('[::1]') ||
|
||||
normalized.startsWith('::1')
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function resolveBrowserHost(requestUrl: URL, forwardedHost: string | null) {
|
||||
const forwardedCandidate = (forwardedHost && forwardedHost.trim()) || ''
|
||||
if (forwardedCandidate && !isNonRoutableHost(forwardedCandidate, requestUrl.protocol)) {
|
||||
return forwardedCandidate
|
||||
}
|
||||
|
||||
if (PUBLIC_BROWSER_HOST && !isNonRoutableHost(PUBLIC_BROWSER_HOST, requestUrl.protocol)) {
|
||||
return PUBLIC_BROWSER_HOST.trim()
|
||||
}
|
||||
|
||||
if (PUBLIC_BASE_URL) {
|
||||
try {
|
||||
const parsed = new URL(PUBLIC_BASE_URL)
|
||||
if (!isNonRoutableHost(parsed.host, parsed.protocol)) {
|
||||
return parsed.host
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed PUBLIC_BASE_URL
|
||||
}
|
||||
}
|
||||
|
||||
const requestHostHeader = requestUrl.host
|
||||
if (!isNonRoutableHost(requestHostHeader, requestUrl.protocol)) {
|
||||
return requestHostHeader
|
||||
}
|
||||
|
||||
const hostHeader = requestUrl.hostname
|
||||
const requestPort = requestUrl.port
|
||||
if (hostHeader && !isNonRoutableHost(hostHeader, requestUrl.protocol)) {
|
||||
return requestPort ? `${hostHeader}:${requestPort}` : hostHeader
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function getBrowserWebSocketUrl(request: Request, params: {
|
||||
sessionId: string
|
||||
sandboxId: string
|
||||
dashboardSessionId: string
|
||||
}) {
|
||||
const requestUrl = new URL(request.url)
|
||||
const forwardedProto = request.headers.get('x-forwarded-proto')
|
||||
const forwardedHost = request.headers.get('x-forwarded-host')
|
||||
const host = resolveBrowserHost(requestUrl, forwardedHost)
|
||||
if (!host) {
|
||||
throw new Error('No routable browser host available for terminal websocket URL. Set PUBLIC_BROWSER_HOST or PUBLIC_BASE_URL.')
|
||||
}
|
||||
const baseProtocol = (forwardedProto && forwardedProto.trim()) || requestUrl.protocol.replace(/:$/, '')
|
||||
const protocol = baseProtocol === 'https' ? 'wss:' : 'ws:'
|
||||
const websocketUrl = new URL(TERMINAL_WS_PROXY_PATH, `${protocol}//${host}`)
|
||||
websocketUrl.searchParams.set('sessionId', params.sessionId)
|
||||
websocketUrl.searchParams.set('sandboxId', params.sandboxId)
|
||||
websocketUrl.searchParams.set('dashboardSessionId', params.dashboardSessionId)
|
||||
return websocketUrl.toString()
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
const response = await fetch(`${TERMINAL_SERVER_URL}/session`, {
|
||||
const sandboxId = typeof body?.sandboxId === 'string' ? body.sandboxId.trim() : ''
|
||||
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : ''
|
||||
const dashboardSessionId = typeof body?.dashboardSessionId === 'string' && body.dashboardSessionId.trim()
|
||||
? body.dashboardSessionId.trim()
|
||||
: 'dashboard-host'
|
||||
|
||||
const requestedSandboxId = sandboxId || 'host'
|
||||
|
||||
let inspection = null
|
||||
if (sandboxId) {
|
||||
try {
|
||||
inspection = await inspectSandbox(sandboxId)
|
||||
} catch {
|
||||
inspection = null
|
||||
}
|
||||
}
|
||||
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId,
|
||||
resolvedSandboxId: inspection?.name || null,
|
||||
instanceId: typeof body?.instanceId === 'string' ? body.instanceId.trim() : '',
|
||||
})
|
||||
const terminalServerUrl = authority.terminalServerUrl || TERMINAL_SERVER_URL
|
||||
const resolvedSandboxId = authority.resolvedSandboxId || requestedSandboxId
|
||||
|
||||
const response = await fetch(`${terminalServerUrl}/session`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sandboxId: body?.sandboxId,
|
||||
sessionId: body?.sessionId,
|
||||
sandboxId: resolvedSandboxId,
|
||||
sessionId,
|
||||
dashboardSessionId,
|
||||
}),
|
||||
cache: 'no-store',
|
||||
})
|
||||
@@ -22,13 +135,31 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ ok: false, error: result.error || 'Failed to initialize live terminal session.' }, { status: 502 })
|
||||
}
|
||||
|
||||
const wsBase = TERMINAL_SERVER_URL.replace(/^http/, 'ws')
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sessionId: result.sessionId,
|
||||
sandboxId: result.sandboxId,
|
||||
dashboardSessionId: result.dashboardSessionId || dashboardSessionId,
|
||||
replay: result.replay,
|
||||
websocketUrl: `${wsBase}/ws?sessionId=${encodeURIComponent(result.sessionId)}&sandboxId=${encodeURIComponent(result.sandboxId)}`,
|
||||
transport: result.transport,
|
||||
instanceId: authority.openclaw.id,
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
},
|
||||
sshHostAlias: inspection?.sshHostAlias || null,
|
||||
websocketUrl: getBrowserWebSocketUrl(request, {
|
||||
sessionId: result.sessionId,
|
||||
sandboxId: result.sandboxId,
|
||||
dashboardSessionId: result.dashboardSessionId || dashboardSessionId,
|
||||
}),
|
||||
degraded: !inspection,
|
||||
})
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
|
||||
@@ -16,14 +16,19 @@ export async function GET(request: Request) {
|
||||
ok: true,
|
||||
sandboxId,
|
||||
attached: true,
|
||||
output: result.stdout.trim(),
|
||||
stderr: result.stderr.trim(),
|
||||
note: 'Backend-local terminal probe succeeded. Next step is persistent interactive terminal transport.'
|
||||
name: result.name,
|
||||
resolvedId: result.id,
|
||||
namespace: result.namespace,
|
||||
phase: result.phase,
|
||||
sshHostAlias: result.sshHostAlias,
|
||||
sshConfig: result.sshConfig,
|
||||
output: result.rawDetails,
|
||||
note: 'Sandbox inspection succeeded. Next step is persistent interactive terminal transport.',
|
||||
})
|
||||
} catch (error) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to probe terminal attach'
|
||||
error: error instanceof Error ? error.message : 'Failed to probe terminal attach',
|
||||
}, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,131 +1,150 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { dockerExecInOpenShell, OPENSHELL_NAMESPACE, probeSandboxShell, validateSandboxId } from '../../../../lib/openshellHost'
|
||||
import { inspectSandbox, isOpenShellTransportError } from '@/app/lib/openshellHost'
|
||||
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
|
||||
|
||||
interface PodSummary {
|
||||
containers: string[]
|
||||
images: string[]
|
||||
runningStatuses: string[]
|
||||
phase?: string
|
||||
readyCondition?: string
|
||||
function normalizeSandboxId(value: string | null) {
|
||||
return (value || '').trim()
|
||||
}
|
||||
|
||||
const EMPTY_POD_SUMMARY: PodSummary = {
|
||||
containers: [],
|
||||
images: [],
|
||||
runningStatuses: [],
|
||||
}
|
||||
function buildAttach(alias: string, sandboxId: string) {
|
||||
const loginShell = process.platform === 'darwin' ? 'zsh' : 'bash'
|
||||
const extraPath = process.platform === 'darwin' ? '/opt/homebrew/bin' : `${process.env.HOME || '~'}/.local/bin`
|
||||
|
||||
async function inspectPod(sandboxId: string): Promise<PodSummary> {
|
||||
const result = await dockerExecInOpenShell(
|
||||
`kubectl -n ${OPENSHELL_NAMESPACE} get pod ${sandboxId} -o json`
|
||||
)
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
const failureText = `${result.stderr}\n${result.stdout}`.toLowerCase()
|
||||
if (failureText.includes('(notfound)') || failureText.includes('not found')) {
|
||||
return EMPTY_POD_SUMMARY
|
||||
}
|
||||
throw new Error(result.stderr.trim() || result.stdout.trim() || `kubectl get pod failed with exit code ${result.exitCode}`)
|
||||
}
|
||||
|
||||
if (!result.stdout.trim()) {
|
||||
throw new Error('kubectl get pod returned empty stdout')
|
||||
}
|
||||
|
||||
const pod = JSON.parse(result.stdout)
|
||||
return {
|
||||
containers: Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.name) : [],
|
||||
images: Array.isArray(pod?.spec?.containers) ? pod.spec.containers.map((c: any) => c.image) : [],
|
||||
runningStatuses: Array.isArray(pod?.status?.containerStatuses) ? pod.status.containerStatuses.map((c: any) => c.name) : [],
|
||||
phase: pod?.status?.phase,
|
||||
readyCondition: Array.isArray(pod?.status?.conditions)
|
||||
? pod.status.conditions.find((c: any) => c.type === 'Ready')?.status
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function buildAttachContract(sandboxId: string) {
|
||||
const alias = `openshell-${sandboxId}`
|
||||
return {
|
||||
alias,
|
||||
aliasCommand: `ssh ${alias}`,
|
||||
fallbackCommand: `ssh -i ~/.ssh/id_ed25519_openclaw_labmac ${alias}`,
|
||||
loginShellCommand: `env PATH=/opt/homebrew/bin:$PATH zsh -l -c 'ssh ${alias}'`,
|
||||
shellHint: 'If a non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.',
|
||||
fallbackCommand: `ssh ${alias}`,
|
||||
loginShellCommand: `env PATH=${extraPath}:$PATH ${loginShell} -l -c 'ssh ${alias}'`,
|
||||
shellHint: process.platform === 'darwin'
|
||||
? 'If your non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.'
|
||||
: 'If your non-interactive shell misses local tooling, retry from a login shell or prepend PATH=$HOME/.local/bin:$PATH before ssh.',
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
let sandboxId = 'unknown'
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const sandboxId = validateSandboxId(searchParams.get('sandboxId') || '')
|
||||
sandboxId = normalizeSandboxId(url.searchParams.get('sandboxId'))
|
||||
|
||||
const attach = buildAttachContract(sandboxId)
|
||||
const pod = await inspectPod(sandboxId)
|
||||
|
||||
let shellProbe: {
|
||||
ok: boolean
|
||||
output?: string
|
||||
stderr?: string
|
||||
error?: string
|
||||
} = { ok: false }
|
||||
|
||||
const podExists = Boolean(pod.containers.length || pod.images.length || pod.phase)
|
||||
|
||||
if (podExists) {
|
||||
try {
|
||||
const probe = await probeSandboxShell(sandboxId)
|
||||
shellProbe = {
|
||||
if (!sandboxId) {
|
||||
const authority = resolveRuntimeAuthority({ sandboxId: null })
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId: 'host',
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
terminalFallback: true,
|
||||
},
|
||||
podExists: false,
|
||||
podReady: true,
|
||||
sshReachable: true,
|
||||
degraded: true,
|
||||
attach: null,
|
||||
pod: {
|
||||
phase: 'Host',
|
||||
readyCondition: 'Host',
|
||||
containers: [],
|
||||
images: [],
|
||||
runningStatuses: [],
|
||||
},
|
||||
shellProbe: {
|
||||
ok: true,
|
||||
output: probe.stdout.trim(),
|
||||
stderr: probe.stderr.trim(),
|
||||
}
|
||||
} catch (error) {
|
||||
shellProbe = {
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Shell probe failed',
|
||||
}
|
||||
}
|
||||
} else {
|
||||
shellProbe = {
|
||||
ok: false,
|
||||
error: `Sandbox pod ${sandboxId} was not found in ${OPENSHELL_NAMESPACE}.`,
|
||||
}
|
||||
output: 'Host terminal mode active. No sandbox selected.',
|
||||
stderr: '',
|
||||
},
|
||||
note: 'Host operator terminal is ready. Sandbox context is optional.',
|
||||
})
|
||||
}
|
||||
|
||||
const podReady = pod.readyCondition === 'True' || pod.phase === 'Running'
|
||||
const sshReachable = shellProbe.ok
|
||||
const sandbox = await inspectSandbox(sandboxId)
|
||||
const authority = resolveRuntimeAuthority({
|
||||
sandboxId,
|
||||
resolvedSandboxId: sandbox.name,
|
||||
})
|
||||
const podReady = sandbox.phase === 'Running'
|
||||
const sshReachable = sandbox.phase === 'Running'
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
sandboxId,
|
||||
podExists,
|
||||
sandboxId: sandbox.name,
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
terminalFallback: false,
|
||||
},
|
||||
podExists: true,
|
||||
podReady,
|
||||
sshReachable,
|
||||
degraded: podExists && !sshReachable,
|
||||
attach,
|
||||
pod,
|
||||
shellProbe,
|
||||
note: !podExists
|
||||
? `Sandbox pod ${sandboxId} is not present in ${OPENSHELL_NAMESPACE}.`
|
||||
: sshReachable
|
||||
? 'Pod introspection and bounded shell probe both succeeded.'
|
||||
: 'Pod introspection succeeded, but bounded shell probe did not. Treat this as degraded dashboard reachability until direct SSH is confirmed.',
|
||||
degraded: !sshReachable,
|
||||
attach: buildAttach(sandbox.sshHostAlias, sandbox.name),
|
||||
pod: {
|
||||
phase: sandbox.phase,
|
||||
readyCondition: podReady ? 'True' : sandbox.rawPhase || 'Unknown',
|
||||
containers: [],
|
||||
images: [],
|
||||
runningStatuses: [],
|
||||
},
|
||||
shellProbe: {
|
||||
ok: sshReachable,
|
||||
output: sandbox.rawDetails,
|
||||
stderr: '',
|
||||
},
|
||||
note: sshReachable
|
||||
? 'Sandbox inspection succeeded and the normalized phase is Running.'
|
||||
: `Sandbox inspection succeeded, but authoritative phase is ${sandbox.rawPhase || 'Unknown'} (normalized ${sandbox.phase || 'Unknown'}).`,
|
||||
})
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to build readiness contract'
|
||||
const status = message === 'sandboxId is required'
|
||||
|| message.includes('sandboxId must be a valid lowercase DNS-style identifier')
|
||||
? 400
|
||||
: 500
|
||||
|
||||
const message = error instanceof Error ? error.message : 'Failed to inspect terminal readiness.'
|
||||
const transportError = isOpenShellTransportError(error)
|
||||
const authority = resolveRuntimeAuthority({ sandboxId })
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
ok: true,
|
||||
sandboxId: sandboxId || 'host',
|
||||
authority: {
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
requestedInstanceId: authority.requestedInstanceId,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
terminalFallback: true,
|
||||
},
|
||||
podExists: false,
|
||||
podReady: false,
|
||||
sshReachable: false,
|
||||
degraded: false,
|
||||
podReady: true,
|
||||
sshReachable: true,
|
||||
degraded: true,
|
||||
error: message,
|
||||
}, { status })
|
||||
attach: null,
|
||||
pod: {
|
||||
phase: 'Host',
|
||||
readyCondition: 'Host',
|
||||
containers: [],
|
||||
images: [],
|
||||
runningStatuses: [],
|
||||
},
|
||||
shellProbe: {
|
||||
ok: true,
|
||||
output: 'Host terminal mode active. Sandbox inspection failed, but host shell remains available.',
|
||||
stderr: message,
|
||||
},
|
||||
note: transportError ? 'OpenShell transport is unavailable for sandbox inspection; host operator terminal remains available.' : 'Sandbox inspection failed; host operator terminal remains available.',
|
||||
}, { status: 200 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { DEFAULT_EXEC_TIMEOUT_MS, MAX_COMMAND_LENGTH, runSandboxCommand, validateSandboxId, validateTerminalCommand } from '../../../lib/openshellHost'
|
||||
|
||||
type TranscriptEntry = {
|
||||
id: string
|
||||
command: string
|
||||
stdout: string
|
||||
stderr: string
|
||||
exitCode: number
|
||||
executionMode?: string
|
||||
ranAt: string
|
||||
}
|
||||
|
||||
type TerminalSession = {
|
||||
sessionId: string
|
||||
sandboxId: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
cwd?: string
|
||||
transcript: TranscriptEntry[]
|
||||
}
|
||||
|
||||
const sessions = new Map<string, TerminalSession>()
|
||||
const MAX_TRANSCRIPT = 100
|
||||
|
||||
function ensureSession(sessionId: string, sandboxId: string) {
|
||||
const existing = sessions.get(sessionId)
|
||||
if (existing) {
|
||||
if (existing.sandboxId !== sandboxId) {
|
||||
throw new Error('sessionId does not match sandboxId')
|
||||
}
|
||||
return existing
|
||||
}
|
||||
|
||||
const now = new Date().toISOString()
|
||||
const created: TerminalSession = {
|
||||
sessionId,
|
||||
sandboxId,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
cwd: undefined,
|
||||
transcript: [],
|
||||
}
|
||||
sessions.set(sessionId, created)
|
||||
return created
|
||||
}
|
||||
|
||||
function sanitizePromptPath(cwd?: string) {
|
||||
if (!cwd) return '~'
|
||||
return cwd
|
||||
}
|
||||
|
||||
function buildWrappedCommand(command: string, cwd?: string) {
|
||||
const trimmed = validateTerminalCommand(command)
|
||||
const cdPrefix = cwd ? `cd ${quoteForSingleQuotedShell(cwd)} >/dev/null 2>&1 || exit 98; ` : ''
|
||||
const shellBody = `${cdPrefix}${trimmed}; __cmd_exit=$?; printf '\n__OPENCLAW_PWD__=%s\n' "$PWD"; exit $__cmd_exit`
|
||||
return shellBody
|
||||
}
|
||||
|
||||
function quoteForSingleQuotedShell(value: string) {
|
||||
return `'${value.replace(/'/g, `'"'"'`)}'`
|
||||
}
|
||||
|
||||
function extractPwd(stdout: string) {
|
||||
const match = stdout.match(/\n__OPENCLAW_PWD__=(.*)\n?$/)
|
||||
if (!match) {
|
||||
return { cleanedStdout: stdout.trim(), cwd: undefined }
|
||||
}
|
||||
|
||||
const cwd = match[1]?.trim() || undefined
|
||||
const cleanedStdout = stdout.slice(0, match.index).trimEnd()
|
||||
return { cleanedStdout, cwd }
|
||||
}
|
||||
|
||||
function serializeSession(session: TerminalSession) {
|
||||
return {
|
||||
ok: true,
|
||||
interactive: false,
|
||||
terminalLike: true,
|
||||
mode: 'session-backed-command-terminal',
|
||||
session: {
|
||||
sessionId: session.sessionId,
|
||||
sandboxId: session.sandboxId,
|
||||
cwd: session.cwd,
|
||||
createdAt: session.createdAt,
|
||||
updatedAt: session.updatedAt,
|
||||
prompt: `${session.sandboxId}:${sanitizePromptPath(session.cwd)}$`,
|
||||
transcript: session.transcript,
|
||||
},
|
||||
limits: {
|
||||
timeoutMs: DEFAULT_EXEC_TIMEOUT_MS,
|
||||
maxCommandLength: MAX_COMMAND_LENGTH,
|
||||
},
|
||||
note: 'Dashboard terminal is session-backed and command-scoped. It preserves transcript and working directory across commands, but it is not a raw PTY stream yet.',
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const sandboxId = searchParams.get('sandboxId') || ''
|
||||
const sessionId = searchParams.get('sessionId') || ''
|
||||
|
||||
if (!sandboxId) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
interactive: false,
|
||||
mode: 'session-backed-command-terminal',
|
||||
error: 'sandboxId is required',
|
||||
}, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const validatedSandboxId = validateSandboxId(sandboxId)
|
||||
|
||||
if (!sessionId) {
|
||||
const createdSession = ensureSession(randomUUID(), validatedSandboxId)
|
||||
return NextResponse.json(serializeSession(createdSession))
|
||||
}
|
||||
|
||||
const session = sessions.get(sessionId)
|
||||
if (!session || session.sandboxId !== validatedSandboxId) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
interactive: false,
|
||||
mode: 'session-backed-command-terminal',
|
||||
error: 'session not found',
|
||||
}, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json(serializeSession(session))
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to inspect terminal session'
|
||||
const status = message.includes('sandboxId') ? 400 : 500
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
interactive: false,
|
||||
mode: 'session-backed-command-terminal',
|
||||
error: message,
|
||||
}, { status })
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
const sandboxInput = typeof body?.sandboxId === 'string' ? body.sandboxId : ''
|
||||
const sessionInput = typeof body?.sessionId === 'string' ? body.sessionId : ''
|
||||
const commandInput = typeof body?.command === 'string' ? body.command : ''
|
||||
|
||||
const sandboxId = validateSandboxId(sandboxInput)
|
||||
const command = validateTerminalCommand(commandInput)
|
||||
const sessionId = sessionInput || randomUUID()
|
||||
const session = ensureSession(sessionId, sandboxId)
|
||||
|
||||
const wrappedCommand = buildWrappedCommand(command, session.cwd)
|
||||
const result = await runSandboxCommand(sandboxId, wrappedCommand)
|
||||
const { cleanedStdout, cwd } = extractPwd(result.stdout)
|
||||
|
||||
session.cwd = cwd || session.cwd
|
||||
session.updatedAt = new Date().toISOString()
|
||||
session.transcript.push({
|
||||
id: randomUUID(),
|
||||
command,
|
||||
stdout: cleanedStdout,
|
||||
stderr: result.stderr.trim(),
|
||||
exitCode: result.exitCode,
|
||||
executionMode: result.mode,
|
||||
ranAt: session.updatedAt,
|
||||
})
|
||||
if (session.transcript.length > MAX_TRANSCRIPT) {
|
||||
session.transcript.splice(0, session.transcript.length - MAX_TRANSCRIPT)
|
||||
}
|
||||
|
||||
const ok = result.exitCode === 0
|
||||
|
||||
return NextResponse.json({
|
||||
...serializeSession(session),
|
||||
ok,
|
||||
command,
|
||||
exitCode: result.exitCode,
|
||||
executionMode: result.mode,
|
||||
stdout: cleanedStdout,
|
||||
stderr: result.stderr.trim(),
|
||||
note: ok
|
||||
? 'Command completed and terminal session state was updated.'
|
||||
: `Command exited non-zero (${result.exitCode}); transcript preserved for inspection.`,
|
||||
}, { status: ok ? 200 : 502 })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : 'Failed to run sandbox command'
|
||||
const status = message === 'sandboxId is required'
|
||||
|| message === 'command is required'
|
||||
|| message.includes('sandboxId must be a valid lowercase DNS-style identifier')
|
||||
|| message.includes('command exceeds')
|
||||
|| message.includes('sessionId does not match sandboxId')
|
||||
? 400
|
||||
: 500
|
||||
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
interactive: false,
|
||||
mode: 'session-backed-command-terminal',
|
||||
error: message,
|
||||
}, { status })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { promisify } from "node:util"
|
||||
import { inspectSandbox } from "@/app/lib/openshellHost"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const HOME = process.env.HOME || ""
|
||||
const NEMOCLAW_SETUP = process.env.NEMOCLAW_SETUP || `${HOME}/NemoClaw/scripts/setup.sh`
|
||||
const OPENSHELL_BIN = process.env.OPENSHELL_BIN || `${HOME}/.local/bin/openshell`
|
||||
const HOST_PATH = [
|
||||
`${HOME}/.local/bin`,
|
||||
`${HOME}/.nvm/versions/node/v22.22.2/bin`,
|
||||
`${HOME}/.nvm/versions/node/v22.22.1/bin`,
|
||||
"/opt/homebrew/bin",
|
||||
"/usr/local/bin",
|
||||
"/usr/bin",
|
||||
"/bin",
|
||||
"/usr/sbin",
|
||||
"/sbin",
|
||||
process.env.PATH || "",
|
||||
].filter(Boolean).join(":")
|
||||
|
||||
const GATEWAY_REUSE_POLICY = [
|
||||
"Gateway reuse policy:",
|
||||
"- reuse the existing OpenShell gateway when `openshell status` reports `Connected`",
|
||||
"- only start a fresh gateway when no healthy gateway is already connected",
|
||||
`- force non-interactive PATH to include ${HOME}/.local/bin so openshell resolves during setup`,
|
||||
].join("\n")
|
||||
|
||||
function validateSandboxName(name: string) {
|
||||
if (!name || typeof name !== "string") throw new Error("sandbox name is required")
|
||||
if (name.length > 63) throw new Error("sandbox name too long (max 63 chars)")
|
||||
if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(name)) {
|
||||
throw new Error("sandbox name must be lowercase alphanumeric with optional internal hyphens")
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
type SandboxVerification = {
|
||||
verified: boolean
|
||||
summary: string
|
||||
details?: {
|
||||
name: string
|
||||
id: string | null
|
||||
phase: string | null
|
||||
namespace: string | null
|
||||
sshHostAlias: string
|
||||
rawPhase: string | null
|
||||
rawDetails: string
|
||||
}
|
||||
error?: string
|
||||
}
|
||||
|
||||
const AUTHORITATIVE_SUCCESS_PHASE = "Ready"
|
||||
|
||||
function elapsedMs(start: number) {
|
||||
return Date.now() - start
|
||||
}
|
||||
|
||||
async function verifySandboxCreation(sandboxName: string): Promise<SandboxVerification> {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/create] verify:start sandbox=${sandboxName}`)
|
||||
try {
|
||||
const sandbox = await inspectSandbox(sandboxName)
|
||||
const phase = sandbox.phase ?? "Unknown"
|
||||
const rawPhase = sandbox.rawPhase ?? "Unknown"
|
||||
const verified = rawPhase === AUTHORITATIVE_SUCCESS_PHASE
|
||||
console.log(
|
||||
`[sandbox/create] verify:done sandbox=${sandboxName} rawPhase=${rawPhase} normalizedPhase=${phase} verified=${verified} elapsedMs=${elapsedMs(startedAt)}`,
|
||||
)
|
||||
|
||||
return {
|
||||
verified,
|
||||
summary: verified
|
||||
? `Verified via openshell sandbox get with authoritative phase (${rawPhase}).`
|
||||
: `Sandbox lookup succeeded, but authoritative phase was not ready (${rawPhase}); normalized phase=${phase}.`,
|
||||
details: {
|
||||
name: sandbox.name,
|
||||
id: sandbox.id,
|
||||
phase: sandbox.phase,
|
||||
namespace: sandbox.namespace,
|
||||
sshHostAlias: sandbox.sshHostAlias,
|
||||
rawPhase: sandbox.rawPhase,
|
||||
rawDetails: sandbox.rawDetails,
|
||||
},
|
||||
...(verified ? {} : { error: `Sandbox authoritative phase ${rawPhase} is not the required success state ${AUTHORITATIVE_SUCCESS_PHASE}.` }),
|
||||
}
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "Sandbox verification failed")
|
||||
console.log(`[sandbox/create] verify:error sandbox=${sandboxName} elapsedMs=${elapsedMs(startedAt)} message=${message}`)
|
||||
return {
|
||||
verified: false,
|
||||
summary: "Create command returned success, but post-create authoritative verification failed.",
|
||||
error: message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runCommand(file: string, args: string[], env: NodeJS.ProcessEnv) {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/create] command:start file=${file} args=${JSON.stringify(args)}`)
|
||||
console.log(`[sandbox/create] gateway-policy ${GATEWAY_REUSE_POLICY.replace(/\n/g, " | ")}`)
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(file, args, {
|
||||
env,
|
||||
maxBuffer: 20 * 1024 * 1024,
|
||||
})
|
||||
console.log(`[sandbox/create] command:done file=${file} elapsedMs=${elapsedMs(startedAt)} stdoutBytes=${String(stdout).length} stderrBytes=${String(stderr).length}`)
|
||||
return { ok: true as const, stdout: String(stdout).trim(), stderr: String(stderr).trim() }
|
||||
} catch (error: any) {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "Command failed")
|
||||
console.log(
|
||||
`[sandbox/create] command:error file=${file} elapsedMs=${elapsedMs(startedAt)} message=${message} stdoutBytes=${String(error?.stdout || "").length} stderrBytes=${String(error?.stderr || "").length}`,
|
||||
)
|
||||
return {
|
||||
ok: false as const,
|
||||
stdout: String(error?.stdout || "").trim(),
|
||||
stderr: String(error?.stderr || "").trim(),
|
||||
error: message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runCreateCommandBounded(file: string, args: string[], env: NodeJS.ProcessEnv, timeoutMs: number) {
|
||||
const startedAt = Date.now()
|
||||
console.log(`[sandbox/create] bounded-command:start file=${file} args=${JSON.stringify(args)} timeoutMs=${timeoutMs}`)
|
||||
|
||||
return await new Promise<{
|
||||
completed: boolean
|
||||
timedOut: boolean
|
||||
exitCode: number | null
|
||||
signal: NodeJS.Signals | null
|
||||
stdout: string
|
||||
stderr: string
|
||||
error?: string
|
||||
}>((resolve) => {
|
||||
const child = spawn(file, args, {
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
})
|
||||
|
||||
let stdout = ""
|
||||
let stderr = ""
|
||||
let settled = false
|
||||
|
||||
const finish = (result: {
|
||||
completed: boolean
|
||||
timedOut: boolean
|
||||
exitCode: number | null
|
||||
signal: NodeJS.Signals | null
|
||||
stdout: string
|
||||
stderr: string
|
||||
error?: string
|
||||
}) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
clearTimeout(timer)
|
||||
resolve(result)
|
||||
}
|
||||
|
||||
child.stdout?.on("data", (chunk) => {
|
||||
stdout += String(chunk)
|
||||
})
|
||||
|
||||
child.stderr?.on("data", (chunk) => {
|
||||
stderr += String(chunk)
|
||||
})
|
||||
|
||||
child.on("error", (error) => {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "Command failed")
|
||||
console.log(`[sandbox/create] bounded-command:error file=${file} elapsedMs=${elapsedMs(startedAt)} message=${message}`)
|
||||
finish({
|
||||
completed: false,
|
||||
timedOut: false,
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
error: message,
|
||||
})
|
||||
})
|
||||
|
||||
child.on("close", (code, signal) => {
|
||||
console.log(`[sandbox/create] bounded-command:close file=${file} elapsedMs=${elapsedMs(startedAt)} code=${code} signal=${signal} stdoutBytes=${stdout.length} stderrBytes=${stderr.length}`)
|
||||
finish({
|
||||
completed: true,
|
||||
timedOut: false,
|
||||
exitCode: code,
|
||||
signal,
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
...(code === 0 ? {} : { error: `Command exited with code ${code}${signal ? ` signal ${signal}` : ""}` }),
|
||||
})
|
||||
})
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
console.log(`[sandbox/create] bounded-command:timeout file=${file} elapsedMs=${elapsedMs(startedAt)} sending=SIGTERM`)
|
||||
child.kill("SIGTERM")
|
||||
setTimeout(() => {
|
||||
if (!settled) {
|
||||
console.log(`[sandbox/create] bounded-command:timeout-escalate file=${file} elapsedMs=${elapsedMs(startedAt)} sending=SIGKILL`)
|
||||
child.kill("SIGKILL")
|
||||
}
|
||||
}, 2000)
|
||||
finish({
|
||||
completed: false,
|
||||
timedOut: true,
|
||||
exitCode: null,
|
||||
signal: "SIGTERM",
|
||||
stdout: stdout.trim(),
|
||||
stderr: stderr.trim(),
|
||||
error: `Command exceeded timeout of ${timeoutMs}ms`,
|
||||
})
|
||||
}, timeoutMs)
|
||||
})
|
||||
}
|
||||
|
||||
async function waitForSandboxReady(sandboxName: string, timeoutMs: number, intervalMs: number) {
|
||||
const startedAt = Date.now()
|
||||
let lastVerification: SandboxVerification | null = null
|
||||
let attempts = 0
|
||||
|
||||
while (elapsedMs(startedAt) < timeoutMs) {
|
||||
attempts += 1
|
||||
lastVerification = await verifySandboxCreation(sandboxName)
|
||||
console.log(`[sandbox/create] readiness:attempt sandbox=${sandboxName} attempt=${attempts} verified=${lastVerification.verified} elapsedMs=${elapsedMs(startedAt)}`)
|
||||
if (lastVerification.verified) {
|
||||
return {
|
||||
verified: true as const,
|
||||
verification: lastVerification,
|
||||
attempts,
|
||||
elapsedMs: elapsedMs(startedAt),
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, intervalMs))
|
||||
}
|
||||
|
||||
return {
|
||||
verified: false as const,
|
||||
verification: lastVerification,
|
||||
attempts,
|
||||
elapsedMs: elapsedMs(startedAt),
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
blueprints: [
|
||||
{
|
||||
id: "nemoclaw-blueprint",
|
||||
label: "New NemoClaw Sandbox",
|
||||
description: "Bootstraps a full NemoClaw sandbox using the nemoclaw-blueprint workflow.",
|
||||
type: "blueprint",
|
||||
source: "~/NemoClaw/nemoclaw-blueprint/blueprint.yaml",
|
||||
supportsTailscale: true,
|
||||
},
|
||||
{
|
||||
id: "custom-sandbox",
|
||||
label: "New Custom Sandbox",
|
||||
description: "Create a generic OpenShell sandbox with a custom policy path.",
|
||||
type: "custom",
|
||||
source: "dashboard-custom",
|
||||
supportsTailscale: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestStartedAt = Date.now()
|
||||
console.log(`[sandbox/create] request:start elapsedMs=0`)
|
||||
try {
|
||||
const body = await request.json()
|
||||
const blueprint = typeof body?.blueprint === "string" ? body.blueprint : ""
|
||||
const sandboxName = validateSandboxName(typeof body?.sandboxName === "string" ? body.sandboxName.trim() : "")
|
||||
const policy = body?.policy && typeof body.policy === "object" ? body.policy : null
|
||||
const enableTailscale = Boolean(body?.enableTailscale)
|
||||
console.log(`[sandbox/create] request:parsed sandbox=${sandboxName} blueprint=${blueprint} enableTailscale=${enableTailscale} elapsedMs=${elapsedMs(requestStartedAt)}`)
|
||||
|
||||
if (!blueprint) {
|
||||
return NextResponse.json({ ok: false, error: "blueprint is required" }, { status: 400 })
|
||||
}
|
||||
|
||||
if (blueprint === "nemoclaw-blueprint") {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
NEMOCLAW_SANDBOX_NAME: sandboxName,
|
||||
}
|
||||
|
||||
if (!enableTailscale) {
|
||||
env.NVIDIA_API_KEY = env.NVIDIA_API_KEY || "optional-local-mode"
|
||||
}
|
||||
|
||||
const result = await runCommand("/bin/bash", [NEMOCLAW_SETUP, sandboxName], env)
|
||||
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: result.error,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
enableTailscale,
|
||||
}, { status: 500 })
|
||||
}
|
||||
|
||||
const verification = await verifySandboxCreation(sandboxName)
|
||||
const created = verification.verified
|
||||
console.log(`[sandbox/create] request:complete sandbox=${sandboxName} created=${created} elapsedMs=${elapsedMs(requestStartedAt)}`)
|
||||
|
||||
return NextResponse.json({
|
||||
ok: created,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
created,
|
||||
verified: verification.verified,
|
||||
verification,
|
||||
mode: "nemoclaw-blueprint",
|
||||
enableTailscale,
|
||||
gatewayReusePolicy: GATEWAY_REUSE_POLICY,
|
||||
setupPath: NEMOCLAW_SETUP,
|
||||
hostPath: HOST_PATH,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
note: created
|
||||
? (enableTailscale
|
||||
? "NemoClaw blueprint workflow completed with Tailscale-enabled prerequisites. Existing healthy OpenShell gateways are reused before any new gateway start is attempted."
|
||||
: "NemoClaw blueprint workflow completed in local/default mode. Existing healthy OpenShell gateways are reused before any new gateway start is attempted.")
|
||||
: "Blueprint command reported success, but the sandbox never reached a ready verification state afterward.",
|
||||
}, { status: created ? 200 : 502 })
|
||||
}
|
||||
|
||||
if (blueprint === "custom-sandbox") {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
PATH: HOST_PATH,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}
|
||||
const createAttempt = await runCreateCommandBounded(OPENSHELL_BIN, ["sandbox", "create", "--name", sandboxName], env, 15000)
|
||||
|
||||
if (createAttempt.completed && createAttempt.exitCode !== 0) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
error: createAttempt.error ?? `create command failed with exit code ${createAttempt.exitCode}`,
|
||||
stdout: createAttempt.stdout,
|
||||
stderr: createAttempt.stderr,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
}, { status: 500 })
|
||||
}
|
||||
|
||||
const readiness = await waitForSandboxReady(sandboxName, 90000, 2000)
|
||||
const verification = readiness.verification ?? {
|
||||
verified: false,
|
||||
summary: "Sandbox readiness polling produced no verification result.",
|
||||
error: "Sandbox readiness polling produced no verification result.",
|
||||
}
|
||||
const created = readiness.verified
|
||||
const policyPrepared = Boolean(policy)
|
||||
console.log(
|
||||
`[sandbox/create] request:complete sandbox=${sandboxName} created=${created} createTimedOut=${createAttempt.timedOut} readinessAttempts=${readiness.attempts} elapsedMs=${elapsedMs(requestStartedAt)}`,
|
||||
)
|
||||
return NextResponse.json({
|
||||
ok: created,
|
||||
blueprint,
|
||||
sandboxName,
|
||||
created,
|
||||
verified: verification.verified,
|
||||
verification,
|
||||
mode: "custom-sandbox",
|
||||
stdout: createAttempt.stdout,
|
||||
stderr: createAttempt.stderr,
|
||||
createCommand: {
|
||||
completed: createAttempt.completed,
|
||||
timedOut: createAttempt.timedOut,
|
||||
exitCode: createAttempt.exitCode,
|
||||
signal: createAttempt.signal,
|
||||
error: createAttempt.error,
|
||||
},
|
||||
readiness: {
|
||||
attempts: readiness.attempts,
|
||||
elapsedMs: readiness.elapsedMs,
|
||||
},
|
||||
policyPrepared,
|
||||
note: created
|
||||
? (createAttempt.timedOut
|
||||
? "Custom sandbox reached Ready even though the create CLI did not exit promptly."
|
||||
: (policyPrepared
|
||||
? "Custom sandbox created. Policy draft is prepared, but applying it live should be a follow-up action."
|
||||
: "Custom sandbox created."))
|
||||
: "Create command started, but the sandbox never reached a ready verification state afterward.",
|
||||
}, { status: created ? 200 : 502 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: false, error: `unknown blueprint: ${blueprint}` }, { status: 400 })
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Sandbox creation failed"
|
||||
const status = /required|must be|too long|unknown blueprint/.test(message) ? 400 : 500
|
||||
console.log(`[sandbox/create] request:error elapsedMs=${elapsedMs(requestStartedAt)} message=${message}`)
|
||||
return NextResponse.json({ ok: false, error: message }, { status })
|
||||
}
|
||||
}
|
||||
+388
-82
@@ -1,94 +1,400 @@
|
||||
import { NextResponse } from "next/server"
|
||||
import { execFile } from "node:child_process"
|
||||
import { existsSync } from "node:fs"
|
||||
import { hostname, networkInterfaces } from "node:os"
|
||||
import { promisify } from "node:util"
|
||||
import { resolveRuntimeAuthority } from "@/app/lib/runtimeAuthority"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const HOME = process.env.HOME || ""
|
||||
|
||||
const NODE_BIN_CANDIDATES = [
|
||||
process.env.NODE_BIN,
|
||||
HOME ? `${HOME}/.nvm/versions/node/v22.22.2/bin/node` : undefined,
|
||||
HOME ? `${HOME}/.nvm/versions/node/v22.22.1/bin/node` : undefined,
|
||||
"/Users/markmckeen/.nvm/versions/node/v22.22.2/bin/node",
|
||||
"/Users/markmckeen/.nvm/versions/node/v22.22.1/bin/node",
|
||||
"/opt/homebrew/bin/node",
|
||||
"/usr/local/bin/node",
|
||||
"/usr/bin/node",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
const NODE_BIN = NODE_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? NODE_BIN_CANDIDATES[0]
|
||||
const NEMOCLAW_BIN_CANDIDATES = [
|
||||
process.env.NEMOCLAW_BIN,
|
||||
HOME ? `${HOME}/.local/bin/nemoclaw` : undefined,
|
||||
HOME ? `${HOME}/.nemoclaw/source/bin/nemoclaw.js` : undefined,
|
||||
HOME ? `${HOME}/NemoClaw/bin/nemoclaw.js` : undefined,
|
||||
HOME ? `${HOME}/.nvm/versions/node/v22.22.2/bin/nemoclaw` : undefined,
|
||||
"/Users/markmckeen/.local/bin/nemoclaw",
|
||||
"/Users/markmckeen/.nemoclaw/source/bin/nemoclaw.js",
|
||||
"/Users/markmckeen/NemoClaw/bin/nemoclaw.js",
|
||||
"/Users/markmckeen/NemoClaw-mmckeen/bin/nemoclaw.js",
|
||||
"/Users/markmckeen/.nvm/versions/node/v22.22.2/bin/nemoclaw",
|
||||
"/usr/local/bin/nemoclaw",
|
||||
"/opt/homebrew/bin/nemoclaw",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
const NEMOCLAW_BIN =
|
||||
NEMOCLAW_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? NEMOCLAW_BIN_CANDIDATES[0]
|
||||
|
||||
const OPENSHELL_BIN_CANDIDATES = [
|
||||
process.env.OPENSHELL_BIN,
|
||||
HOME ? `${HOME}/.local/bin/openshell` : undefined,
|
||||
"/Users/markmckeen/.local/bin/openshell",
|
||||
"/Users/markmckeen/OpenShell/target/release/openshell",
|
||||
"/Users/markmckeen/openshell/target/release/openshell",
|
||||
"/Users/markmckeen/openshell/scripts/bin/openshell",
|
||||
"/usr/local/bin/openshell",
|
||||
"/opt/homebrew/bin/openshell",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
const OPENSHELL_BIN =
|
||||
OPENSHELL_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? OPENSHELL_BIN_CANDIDATES[0]
|
||||
|
||||
type SandboxSummary = {
|
||||
id: string
|
||||
name: string
|
||||
namespace: string
|
||||
status: string
|
||||
sshHostAlias: string
|
||||
hasSshConfig: boolean
|
||||
source: "openshell"
|
||||
isDefault: boolean
|
||||
}
|
||||
|
||||
type NemoClawSummary = {
|
||||
available: boolean
|
||||
defaultSandboxNames: string[]
|
||||
serviceLines: string[]
|
||||
summaryLines: string[]
|
||||
source: "nemoclaw-cli" | "none"
|
||||
}
|
||||
|
||||
type SandboxItem = {
|
||||
metadata: {
|
||||
name: string
|
||||
namespace: string
|
||||
labels: Record<string, string>
|
||||
}
|
||||
spec: {
|
||||
template: {
|
||||
image: string | null
|
||||
}
|
||||
}
|
||||
status: {
|
||||
phase: string
|
||||
podIP: string | null
|
||||
conditions: Array<{
|
||||
type: string
|
||||
status: string
|
||||
}>
|
||||
}
|
||||
}
|
||||
|
||||
function stripAnsi(value: string) {
|
||||
return value.replace(/\u001b\[[0-9;]*m/g, "")
|
||||
}
|
||||
|
||||
function parseField(output: string, label: string) {
|
||||
const normalizedLabel = label.toLowerCase()
|
||||
const line = output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.find((entry) => entry.toLowerCase().startsWith(`${normalizedLabel}:`))
|
||||
|
||||
return line ? line.slice(label.length + 1).trim() : null
|
||||
}
|
||||
|
||||
function parseSshHostAlias(sshConfig: string, fallbackName: string) {
|
||||
const hostLine = sshConfig
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => entry.trim())
|
||||
.find((entry) => entry.toLowerCase().startsWith("host "))
|
||||
|
||||
const alias = hostLine
|
||||
?.split(/\s+/)
|
||||
.slice(1)
|
||||
.find((entry) => entry !== "*")
|
||||
|
||||
return alias || `openshell-${fallbackName}`
|
||||
}
|
||||
|
||||
function normalizePhase(phase: string | null) {
|
||||
const value = (phase ?? "Unknown").toLowerCase()
|
||||
|
||||
switch (value) {
|
||||
case "ready":
|
||||
return "Running"
|
||||
case "provisioning":
|
||||
return "Pending"
|
||||
case "deleting":
|
||||
return "Stopping"
|
||||
case "error":
|
||||
return "Error"
|
||||
default:
|
||||
return phase ?? "Unknown"
|
||||
}
|
||||
}
|
||||
|
||||
function parseOpenShellSandboxNames(output: string) {
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry &&
|
||||
!/^name\s+/i.test(entry) &&
|
||||
!/^[\s\-=]+$/.test(entry) &&
|
||||
!/^no sandboxes found\.?$/i.test(entry)
|
||||
)
|
||||
.map((entry) => entry.split(/\s{2,}/)[0]?.trim())
|
||||
.filter((entry): entry is string => Boolean(entry))
|
||||
}
|
||||
|
||||
function parseDefaultSandboxNames(output: string) {
|
||||
return new Set(
|
||||
output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry))
|
||||
.filter((entry) => /^\s{2,}[\w.-]+(?:\s+\*)?\s*$/.test(entry) && entry.includes("*"))
|
||||
.map((entry) => entry.replace("*", "").trim())
|
||||
.filter(Boolean)
|
||||
)
|
||||
}
|
||||
|
||||
function buildNemoClawSummary(output: string | null, defaultSandboxNames: Set<string>): NemoClawSummary {
|
||||
if (!output) {
|
||||
return {
|
||||
available: false,
|
||||
defaultSandboxNames: [],
|
||||
serviceLines: [],
|
||||
summaryLines: [],
|
||||
source: "none",
|
||||
}
|
||||
}
|
||||
|
||||
const lines = output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const serviceLines = lines.filter((entry) => /\((running|stopped|failed|error|unknown)\)/i.test(entry))
|
||||
|
||||
return {
|
||||
available: true,
|
||||
defaultSandboxNames: Array.from(defaultSandboxNames),
|
||||
serviceLines,
|
||||
summaryLines: lines.slice(0, 20),
|
||||
source: "nemoclaw-cli",
|
||||
}
|
||||
}
|
||||
|
||||
async function execNemoclaw(args: string[]) {
|
||||
const env = {
|
||||
...process.env,
|
||||
PATH: `${process.env.PATH ?? ""}:${HOME ? `${HOME}/.local/bin:${HOME}/.nvm/versions/node/v22.22.2/bin:${HOME}/.nvm/versions/node/v22.22.1/bin:` : ""}/opt/homebrew/bin:/usr/local/bin:/usr/bin`,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}
|
||||
|
||||
const command = /\.(?:c?m?js|ts)$/i.test(NEMOCLAW_BIN)
|
||||
? execFileAsync(NODE_BIN, [NEMOCLAW_BIN, ...args], { env })
|
||||
: execFileAsync(NEMOCLAW_BIN, args, { env })
|
||||
|
||||
const { stdout, stderr } = await command
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
async function execOpenShell(args: string[]) {
|
||||
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
},
|
||||
})
|
||||
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
|
||||
function readHostIdentity() {
|
||||
const interfaces = networkInterfaces()
|
||||
const preferred = ["en0", "en1", "bridge0", "lo0"]
|
||||
|
||||
for (const name of preferred) {
|
||||
const entries = interfaces[name] ?? []
|
||||
const match = entries.find((entry) => entry.family === "IPv4" && !entry.internal)
|
||||
if (match?.address) {
|
||||
return { hostname: hostname(), address: match.address, interface: name }
|
||||
}
|
||||
}
|
||||
|
||||
for (const [name, entries] of Object.entries(interfaces)) {
|
||||
const match = (entries ?? []).find((entry) => entry.family === "IPv4" && !entry.internal)
|
||||
if (match?.address) {
|
||||
return { hostname: hostname(), address: match.address, interface: name }
|
||||
}
|
||||
}
|
||||
|
||||
return { hostname: hostname(), address: "127.0.0.1", interface: "lo0" }
|
||||
}
|
||||
|
||||
async function readSandbox(name: string, defaultSandboxNames: Set<string>): Promise<{ summary: SandboxSummary; pod: SandboxItem }> {
|
||||
try {
|
||||
const [{ stdout: detailsStdout }, { stdout: sshStdout }] = await Promise.all([
|
||||
execOpenShell(["sandbox", "get", name]),
|
||||
execOpenShell(["sandbox", "ssh-config", name]),
|
||||
])
|
||||
|
||||
const sandboxName = parseField(detailsStdout, "Name") ?? name
|
||||
const namespace = parseField(detailsStdout, "Namespace") ?? "openshell"
|
||||
const phase = normalizePhase(parseField(detailsStdout, "Phase"))
|
||||
const sandboxId = parseField(detailsStdout, "Id") ?? sandboxName
|
||||
const sshConfig = sshStdout.trim()
|
||||
const sshHostAlias = parseSshHostAlias(sshConfig, sandboxName)
|
||||
const isDefault = defaultSandboxNames.has(sandboxName)
|
||||
|
||||
return {
|
||||
summary: {
|
||||
id: sandboxId,
|
||||
name: sandboxName,
|
||||
namespace,
|
||||
status: phase,
|
||||
sshHostAlias,
|
||||
hasSshConfig: Boolean(sshConfig),
|
||||
source: "openshell",
|
||||
isDefault,
|
||||
},
|
||||
pod: {
|
||||
metadata: {
|
||||
name: sandboxName,
|
||||
namespace,
|
||||
labels: {
|
||||
"nemoclaw.ai/sandbox-name": sandboxName,
|
||||
...(sandboxId ? { "nemoclaw.ai/sandbox-id": sandboxId } : {}),
|
||||
...(isDefault ? { "nemoclaw.ai/default": "true" } : {}),
|
||||
},
|
||||
},
|
||||
spec: {
|
||||
template: {
|
||||
image: null,
|
||||
},
|
||||
},
|
||||
status: {
|
||||
phase,
|
||||
podIP: sshHostAlias,
|
||||
conditions: [
|
||||
{
|
||||
type: "Ready",
|
||||
status: phase === "Running" ? "True" : "False",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
const sandboxName = name
|
||||
const isDefault = defaultSandboxNames.has(sandboxName)
|
||||
return {
|
||||
summary: {
|
||||
id: sandboxName,
|
||||
name: sandboxName,
|
||||
namespace: "openshell",
|
||||
status: "Unknown",
|
||||
sshHostAlias: `openshell-${sandboxName}`,
|
||||
hasSshConfig: false,
|
||||
source: "openshell",
|
||||
isDefault,
|
||||
},
|
||||
pod: {
|
||||
metadata: {
|
||||
name: sandboxName,
|
||||
namespace: "openshell",
|
||||
labels: {
|
||||
"nemoclaw.ai/sandbox-name": sandboxName,
|
||||
"nemoclaw.ai/sandbox-id": sandboxName,
|
||||
...(isDefault ? { "nemoclaw.ai/default": "true" } : {}),
|
||||
},
|
||||
},
|
||||
spec: {
|
||||
template: {
|
||||
image: null,
|
||||
},
|
||||
},
|
||||
status: {
|
||||
phase: "Unknown",
|
||||
podIP: `openshell-${sandboxName}`,
|
||||
conditions: [
|
||||
{
|
||||
type: "Ready",
|
||||
status: "False",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
// Use docker exec with a timeout and direct kubectl inside container
|
||||
const { exec } = await import('child_process')
|
||||
const util = await import('util')
|
||||
const execPromise = util.promisify(exec)
|
||||
const [{ stdout: sandboxListStdout }, nemoclawListResult, nemoclawStatusResult] = await Promise.all([
|
||||
execOpenShell(["sandbox", "list"]),
|
||||
execNemoclaw(["list"]).catch(() => null),
|
||||
execNemoclaw(["status"]).catch(() => null),
|
||||
])
|
||||
|
||||
const dockerPath = '/Applications/Docker.app/Contents/Resources/bin/docker'
|
||||
|
||||
// Run kubectl inside container with explicit kubeconfig
|
||||
const command = `${dockerPath} exec openshell-cluster-openshell /bin/sh -c 'KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl get pods -o json -n agent-sandbox-system'`
|
||||
|
||||
const execWithTimeout = (cmd: string, timeoutMs: number): Promise<{ stdout: string; stderr: string }> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = exec(cmd, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve({ stdout, stderr })
|
||||
}
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
child.kill('SIGKILL')
|
||||
reject(new Error('Command timed out'))
|
||||
}, timeoutMs)
|
||||
})
|
||||
}
|
||||
|
||||
const { stdout, stderr } = await execWithTimeout(command, 10000)
|
||||
const defaultSandboxNames = parseDefaultSandboxNames(nemoclawListResult?.stdout ?? "")
|
||||
const names = parseOpenShellSandboxNames(sandboxListStdout)
|
||||
const results = await Promise.all(names.map((name) => readSandbox(name, defaultSandboxNames)))
|
||||
const sandboxes = results.map((result) => result.summary)
|
||||
const items = results.map((result) => result.pod)
|
||||
const nemoclaw = buildNemoClawSummary(nemoclawStatusResult?.stdout ?? null, defaultSandboxNames)
|
||||
|
||||
if (stderr && !stderr.includes('Waiting')) {
|
||||
console.error('kubectl stderr:', stderr)
|
||||
}
|
||||
const authorities = sandboxes.map((sandbox) => ({
|
||||
sandboxId: sandbox.id,
|
||||
...resolveRuntimeAuthority({ sandboxId: sandbox.id }),
|
||||
}))
|
||||
|
||||
if (!stdout.trim()) {
|
||||
throw new Error('No output from kubectl')
|
||||
}
|
||||
const inventoryCount = sandboxes.length
|
||||
const hasMappedFallbackWithoutInventory = inventoryCount === 0
|
||||
|
||||
const pods = JSON.parse(stdout)
|
||||
|
||||
// Filter to only sandbox-related pods
|
||||
const sandboxPods = pods.items
|
||||
.filter((pod: any) =>
|
||||
pod.metadata.namespace === 'agent-sandbox-system' ||
|
||||
pod.metadata.name.includes('sandbox')
|
||||
)
|
||||
.map((pod: any) => ({
|
||||
metadata: {
|
||||
name: pod.metadata.name,
|
||||
namespace: pod.metadata.namespace
|
||||
},
|
||||
status: {
|
||||
phase: pod.status.phase,
|
||||
podIP: pod.status.podIP,
|
||||
conditions: pod.status.conditions || []
|
||||
}
|
||||
}))
|
||||
|
||||
return NextResponse.json({
|
||||
pods: { items: sandboxPods },
|
||||
message: 'Real telemetry fetched from container'
|
||||
})
|
||||
} catch (error: any) {
|
||||
console.error('Error fetching real telemetry:', error.message)
|
||||
|
||||
// Fallback to mock data
|
||||
return NextResponse.json({
|
||||
pods: {
|
||||
items: [
|
||||
{
|
||||
metadata: { name: 'agent-sandbox-1', namespace: 'agent-sandbox-system' },
|
||||
status: {
|
||||
phase: 'Running',
|
||||
podIP: '10.42.0.2',
|
||||
conditions: [{ type: 'Ready', status: 'True' }]
|
||||
}
|
||||
},
|
||||
{
|
||||
metadata: { name: 'agent-sandbox-2', namespace: 'agent-sandbox-system' },
|
||||
status: {
|
||||
phase: 'Pending',
|
||||
podIP: null,
|
||||
conditions: [{ type: 'Ready', status: 'False' }]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
message: `Using mock data (${error.message})`
|
||||
sandboxes,
|
||||
pods: { items },
|
||||
nemoclaw,
|
||||
host: readHostIdentity(),
|
||||
source: "openshell-cli",
|
||||
authoritySource: "runtimeAuthority",
|
||||
truthState: hasMappedFallbackWithoutInventory ? "unverified" : "verified",
|
||||
degraded: hasMappedFallbackWithoutInventory,
|
||||
inventoryCount,
|
||||
authorities: authorities.map((authority) => ({
|
||||
sandboxId: authority.sandboxId,
|
||||
requestedSandboxId: authority.requestedSandboxId,
|
||||
resolvedSandboxId: authority.resolvedSandboxId,
|
||||
sandboxAuthority: authority.sandboxAuthority,
|
||||
instanceId: authority.openclaw.id,
|
||||
sandboxInstanceId: authority.mappedSandboxInstanceId,
|
||||
explicitInstanceOverride: authority.explicitInstanceOverride,
|
||||
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
|
||||
})),
|
||||
defaultSource: defaultSandboxNames.size > 0 ? "nemoclaw-cli" : "none",
|
||||
count: inventoryCount,
|
||||
message: hasMappedFallbackWithoutInventory
|
||||
? "Fetched live OpenShell inventory: zero sandboxes reported, so any mapped NemoClaw dashboard should be treated as fallback-only."
|
||||
: "Fetched live sandbox inventory from the clean OpenShell runtime",
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Error fetching real telemetry:", error)
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : "Failed to fetch live OpenShell sandbox inventory",
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import CompactGauge from './CompactGauge'
|
||||
|
||||
interface TelemetryData {
|
||||
@@ -9,6 +9,7 @@ interface TelemetryData {
|
||||
gpuMemoryUsed?: number
|
||||
gpuMemoryTotal?: number
|
||||
gpuTemperature?: number
|
||||
timestamp?: string
|
||||
}
|
||||
|
||||
interface Sandbox {
|
||||
@@ -30,25 +31,6 @@ export default function CompactTelemetryDisplay() {
|
||||
fetchSandboxes()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry()
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, [selectedSandbox])
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry()
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}, [selectedSandbox])
|
||||
|
||||
const fetchSandboxes = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real')
|
||||
@@ -67,7 +49,7 @@ export default function CompactTelemetryDisplay() {
|
||||
}
|
||||
}
|
||||
|
||||
const fetchTelemetry = async () => {
|
||||
const fetchTelemetry = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/combined')
|
||||
const data = await response.json()
|
||||
@@ -75,10 +57,29 @@ export default function CompactTelemetryDisplay() {
|
||||
} catch (error) {
|
||||
console.error('Error fetching telemetry:', error)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const fetchCombinedTelemetry = fetchTelemetry
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry()
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, [selectedSandbox, fetchTelemetry, fetchCombinedTelemetry])
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry()
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}, [selectedSandbox, fetchTelemetry, fetchCombinedTelemetry])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-40">
|
||||
|
||||
@@ -8,97 +8,44 @@ type EndpointTls = "" | "terminate" | "passthrough"
|
||||
type EndpointEnforcement = "" | "enforce" | "audit"
|
||||
type EndpointAccess = "" | "read-only" | "read-write" | "full"
|
||||
|
||||
interface NetworkRule {
|
||||
method: string
|
||||
path: string
|
||||
}
|
||||
|
||||
interface NetworkEndpoint {
|
||||
host: string
|
||||
port: string
|
||||
protocol: EndpointProtocol
|
||||
tls: EndpointTls
|
||||
enforcement: EndpointEnforcement
|
||||
access: EndpointAccess
|
||||
rules: NetworkRule[]
|
||||
}
|
||||
|
||||
interface NetworkBinary {
|
||||
path: string
|
||||
}
|
||||
|
||||
interface NetworkPolicyBlock {
|
||||
key: string
|
||||
name: string
|
||||
endpoints: NetworkEndpoint[]
|
||||
binaries: NetworkBinary[]
|
||||
}
|
||||
|
||||
interface NetworkRule { method: string; path: string }
|
||||
interface NetworkEndpoint { host: string; port: string; protocol: EndpointProtocol; tls: EndpointTls; enforcement: EndpointEnforcement; access: EndpointAccess; rules: NetworkRule[] }
|
||||
interface NetworkBinary { path: string }
|
||||
interface NetworkPolicyBlock { key: string; name: string; endpoints: NetworkEndpoint[]; binaries: NetworkBinary[] }
|
||||
type OpenShellPolicy = OpenShellPolicyShape
|
||||
|
||||
type BlueprintOption = {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
type: "blueprint" | "custom"
|
||||
source: string
|
||||
supportsTailscale?: boolean
|
||||
}
|
||||
|
||||
interface ConfigurationPanelProps {
|
||||
sandboxId: string
|
||||
mode?: 'existing' | 'create'
|
||||
onCreateSuccess?: (sandboxId: string) => void | Promise<void>
|
||||
onInventoryRefresh?: () => Promise<unknown>
|
||||
}
|
||||
|
||||
function FieldHelp({ text }: { text: string }) {
|
||||
return (
|
||||
<span className="ml-2 inline-flex align-middle group relative">
|
||||
<span className="w-4 h-4 rounded-full border border-[var(--foreground-dim)] text-[10px] text-[var(--foreground-dim)] flex items-center justify-center cursor-help">?</span>
|
||||
<span className="pointer-events-none absolute left-0 top-6 z-50 hidden w-80 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-panel)] p-2 text-[11px] text-[var(--foreground)] shadow-lg group-hover:block">
|
||||
{text}
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
return <span className="ml-2 inline-flex align-middle group relative"><span className="w-4 h-4 rounded-full border border-[var(--foreground-dim)] text-[10px] text-[var(--foreground-dim)] flex items-center justify-center cursor-help">?</span><span className="pointer-events-none absolute left-0 top-6 z-50 hidden w-80 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-panel)] p-2 text-[11px] text-[var(--foreground)] shadow-lg group-hover:block">{text}</span></span>
|
||||
}
|
||||
|
||||
function Badge({ children, tone }: { children: React.ReactNode; tone: "dynamic" | "static" | "danger" }) {
|
||||
const cls = tone === "dynamic"
|
||||
? "bg-[rgba(118,185,0,0.12)] text-[var(--nvidia-green)] border-[rgba(118,185,0,0.35)]"
|
||||
: tone === "danger"
|
||||
? "bg-[rgba(220,38,38,0.12)] text-red-400 border-[rgba(220,38,38,0.35)]"
|
||||
: "bg-[rgba(245,158,11,0.10)] text-amber-400 border-[rgba(245,158,11,0.35)]"
|
||||
const cls = tone === "dynamic" ? "bg-[rgba(118,185,0,0.12)] text-[var(--nvidia-green)] border-[rgba(118,185,0,0.35)]" : tone === "danger" ? "bg-[rgba(220,38,38,0.12)] text-red-400 border-[rgba(220,38,38,0.35)]" : "bg-[rgba(245,158,11,0.10)] text-amber-400 border-[rgba(245,158,11,0.35)]"
|
||||
return <span className={`text-[10px] uppercase tracking-wider border px-2 py-1 rounded-sm ${cls}`}>{children}</span>
|
||||
}
|
||||
|
||||
function TextListEditor({ label, tooltipText, value, onChange, placeholder }: {
|
||||
label: string
|
||||
tooltipText: string
|
||||
value: string[]
|
||||
onChange: (v: string[]) => void
|
||||
placeholder: string
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">
|
||||
{label}
|
||||
<FieldHelp text={tooltipText} />
|
||||
</label>
|
||||
<textarea
|
||||
value={value.join("\n")}
|
||||
onChange={(e) => onChange(e.target.value.split("\n").map(s => s.trim()).filter(Boolean))}
|
||||
placeholder={placeholder}
|
||||
rows={4}
|
||||
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)] focus:outline-none focus:border-[var(--nvidia-green)]"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
function TextListEditor({ label, tooltipText, value, onChange, placeholder }: { label: string; tooltipText: string; value: string[]; onChange: (v: string[]) => void; placeholder: string }) {
|
||||
return <div className="space-y-2"><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">{label}<FieldHelp text={tooltipText} /></label><textarea value={value.join("\n")} onChange={(e) => onChange(e.target.value.split("\n").map(s => s.trim()).filter(Boolean))} placeholder={placeholder} rows={4} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)] focus:outline-none focus:border-[var(--nvidia-green)]" /></div>
|
||||
}
|
||||
|
||||
const defaultPolicy: OpenShellPolicy = {
|
||||
version: 1,
|
||||
filesystem_policy: {
|
||||
include_workdir: true,
|
||||
read_only: ["/usr", "/lib", "/etc", "/proc", "/dev/urandom"],
|
||||
read_write: ["/sandbox", "/tmp", "/dev/null"],
|
||||
},
|
||||
landlock: {
|
||||
compatibility: "best_effort",
|
||||
},
|
||||
process: {
|
||||
run_as_user: "sandbox",
|
||||
run_as_group: "sandbox",
|
||||
},
|
||||
filesystem_policy: { include_workdir: true, read_only: ["/usr", "/lib", "/etc", "/proc", "/dev/urandom"], read_write: ["/sandbox", "/tmp", "/dev/null"] },
|
||||
landlock: { compatibility: "best_effort" },
|
||||
process: { run_as_user: "sandbox", run_as_group: "sandbox" },
|
||||
network_policies: {},
|
||||
}
|
||||
|
||||
@@ -111,67 +58,39 @@ function normalizeFromApi(data: any): OpenShellPolicy {
|
||||
read_only: Array.isArray(current.filesystem_policy?.read_only) ? current.filesystem_policy.read_only : defaultPolicy.filesystem_policy.read_only,
|
||||
read_write: Array.isArray(current.filesystem_policy?.read_write) ? current.filesystem_policy.read_write : defaultPolicy.filesystem_policy.read_write,
|
||||
},
|
||||
landlock: {
|
||||
compatibility: current.landlock?.compatibility === "hard_requirement" ? "hard_requirement" : "best_effort",
|
||||
},
|
||||
process: {
|
||||
run_as_user: String(current.process?.run_as_user ?? "sandbox"),
|
||||
run_as_group: String(current.process?.run_as_group ?? "sandbox"),
|
||||
},
|
||||
landlock: { compatibility: current.landlock?.compatibility === "hard_requirement" ? "hard_requirement" : "best_effort" },
|
||||
process: { run_as_user: String(current.process?.run_as_user ?? "sandbox"), run_as_group: String(current.process?.run_as_group ?? "sandbox") },
|
||||
network_policies: current.network_policies && typeof current.network_policies === "object" ? current.network_policies : {},
|
||||
}
|
||||
}
|
||||
|
||||
function policyBlocksFromPolicy(policy: OpenShellPolicy): NetworkPolicyBlock[] {
|
||||
return Object.entries(policy.network_policies).map(([key, value]) => ({
|
||||
key,
|
||||
name: value.name || key,
|
||||
endpoints: (value.endpoints || []).map((ep) => ({
|
||||
host: ep.host || "",
|
||||
port: String(ep.port ?? "443"),
|
||||
protocol: ep.protocol === "rest" ? "rest" : "",
|
||||
tls: ep.tls === "terminate" || ep.tls === "passthrough" ? ep.tls : "",
|
||||
enforcement: ep.enforcement === "enforce" || ep.enforcement === "audit" ? ep.enforcement : "",
|
||||
access: ep.access === "read-only" || ep.access === "read-write" || ep.access === "full" ? ep.access : "",
|
||||
rules: Array.isArray(ep.rules) ? ep.rules.map((r) => ({ method: r.allow?.method || "GET", path: r.allow?.path || "/**" })) : [],
|
||||
})),
|
||||
binaries: (value.binaries || []).map((b) => ({ path: b.path || "" })),
|
||||
}))
|
||||
return Object.entries(policy.network_policies).map(([key, value]) => ({ key, name: value.name || key, endpoints: (value.endpoints || []).map((ep) => ({ host: ep.host || "", port: String(ep.port ?? "443"), protocol: ep.protocol === "rest" ? "rest" : "", tls: ep.tls === "terminate" || ep.tls === "passthrough" ? ep.tls : "", enforcement: ep.enforcement === "enforce" || ep.enforcement === "audit" ? ep.enforcement : "", access: ep.access === "read-only" || ep.access === "read-write" || ep.access === "full" ? ep.access : "", rules: Array.isArray(ep.rules) ? ep.rules.map((r) => ({ method: r.allow?.method || "GET", path: r.allow?.path || "/**" })) : [] })), binaries: (value.binaries || []).map((b) => ({ path: b.path || "" })) }))
|
||||
}
|
||||
|
||||
function blocksToPolicy(blocks: NetworkPolicyBlock[]): OpenShellPolicy["network_policies"] {
|
||||
const out: OpenShellPolicy["network_policies"] = {}
|
||||
for (const block of blocks) {
|
||||
const key = block.key.trim()
|
||||
if (!key) continue
|
||||
out[key] = {
|
||||
name: block.name.trim() || key,
|
||||
endpoints: block.endpoints.filter((ep) => ep.host.trim() && ep.port.trim()).map((ep) => ({
|
||||
host: ep.host.trim(),
|
||||
port: Number(ep.port),
|
||||
...(ep.protocol ? { protocol: ep.protocol } : {}),
|
||||
...(ep.tls ? { tls: ep.tls } : {}),
|
||||
...(ep.enforcement ? { enforcement: ep.enforcement } : {}),
|
||||
...(ep.access ? { access: ep.access } : {}),
|
||||
...(!ep.access && ep.rules.length ? { rules: ep.rules.filter((r) => r.method.trim() && r.path.trim()).map((r) => ({ allow: { method: r.method.trim(), path: r.path.trim() } })) } : {}),
|
||||
})),
|
||||
binaries: block.binaries.filter((b) => b.path.trim()).map((b) => ({ path: b.path.trim() })),
|
||||
}
|
||||
const key = block.key.trim(); if (!key) continue
|
||||
out[key] = { name: block.name.trim() || key, endpoints: block.endpoints.filter((ep) => ep.host.trim() && ep.port.trim()).map((ep) => ({ host: ep.host.trim(), port: Number(ep.port), ...(ep.protocol ? { protocol: ep.protocol } : {}), ...(ep.tls ? { tls: ep.tls } : {}), ...(ep.enforcement ? { enforcement: ep.enforcement } : {}), ...(ep.access ? { access: ep.access } : {}), ...(!ep.access && ep.rules.length ? { rules: ep.rules.filter((r) => r.method.trim() && r.path.trim()).map((r) => ({ allow: { method: r.method.trim(), path: r.path.trim() } })) } : {}) })), binaries: block.binaries.filter((b) => b.path.trim()).map((b) => ({ path: b.path.trim() })) }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export default function ConfigurationPanel({ sandboxId, mode = 'existing' }: ConfigurationPanelProps) {
|
||||
export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCreateSuccess, onInventoryRefresh }: ConfigurationPanelProps) {
|
||||
const [policy, setPolicy] = useState<OpenShellPolicy>(defaultPolicy)
|
||||
const [blocks, setBlocks] = useState<NetworkPolicyBlock[]>([])
|
||||
const [loading, setLoading] = useState(mode === 'existing')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [message, setMessage] = useState("")
|
||||
const [selectedPreset, setSelectedPreset] = useState<SecurityPresetId | ''>('')
|
||||
const [blueprints, setBlueprints] = useState<BlueprintOption[]>([])
|
||||
const [selectedBlueprint, setSelectedBlueprint] = useState<string>('nemoclaw-blueprint')
|
||||
const [sandboxName, setSandboxName] = useState<string>('')
|
||||
const [enableTailscale, setEnableTailscale] = useState<boolean>(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'create') {
|
||||
setLoading(false)
|
||||
fetch('/api/sandbox/create', { cache: 'no-store' }).then((res) => res.json()).then((data) => { if (Array.isArray(data?.blueprints)) setBlueprints(data.blueprints) }).catch(() => {})
|
||||
return
|
||||
}
|
||||
let active = true
|
||||
@@ -197,184 +116,60 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing' }: Con
|
||||
|
||||
const assembledPolicy = useMemo(() => ({ ...policy, network_policies: blocksToPolicy(blocks) }), [policy, blocks])
|
||||
const activePreset = selectedPreset ? getSecurityPreset(selectedPreset) : null
|
||||
const showDangerWarning = activePreset?.id === 'spicy' || activePreset?.id === 'ultra-lobster'
|
||||
const activeBlueprint = blueprints.find((bp) => bp.id === selectedBlueprint)
|
||||
|
||||
function applyPreset(presetId: SecurityPresetId) {
|
||||
const preset = getSecurityPreset(presetId)
|
||||
if (!preset) return
|
||||
setSelectedPreset(presetId)
|
||||
setPolicy(preset.policy)
|
||||
setBlocks(policyBlocksFromPolicy(preset.policy))
|
||||
setMessage(`${preset.label} applied. Review before saving.${preset.id === 'spicy' || preset.id === 'ultra-lobster' ? ' Warning: this preset is intentionally permissive.' : ''}`)
|
||||
const preset = getSecurityPreset(presetId); if (!preset) return
|
||||
setSelectedPreset(presetId); setPolicy(preset.policy); setBlocks(policyBlocksFromPolicy(preset.policy)); setMessage(`${preset.label} applied. Review before saving.`)
|
||||
}
|
||||
|
||||
async function savePolicy() {
|
||||
try {
|
||||
setSaving(true)
|
||||
setMessage("")
|
||||
const res = await fetch(`/api/sandbox/${encodeURIComponent(sandboxId)}/config`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ policy: assembledPolicy, preset: selectedPreset || null, mode }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error(data.error || "Failed to save policy")
|
||||
setMessage(mode === 'create'
|
||||
? 'Preset and policy prepared for new sandbox creation. Static sections will apply at create time.'
|
||||
: 'Policy saved. Dynamic network policy can apply live; static sections require sandbox recreation.')
|
||||
setSaving(true); setMessage("")
|
||||
if (mode === 'create') {
|
||||
if (!sandboxName.trim()) throw new Error('sandbox name is required')
|
||||
const res = await fetch('/api/sandbox/create', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ blueprint: selectedBlueprint, sandboxName: sandboxName.trim(), enableTailscale, policy: assembledPolicy, preset: selectedPreset || null }) })
|
||||
const data = await res.json()
|
||||
if (!res.ok) throw new Error([data.error, data.verification?.summary, data.verification?.error, data.gatewayReusePolicy, data.stdout, data.stderr].filter(Boolean).join('\n\n'))
|
||||
const createdSandboxId = data.verification?.details?.id || data.verification?.details?.name || data.sandboxName
|
||||
if (onInventoryRefresh) {
|
||||
await onInventoryRefresh()
|
||||
}
|
||||
setMessage([
|
||||
`Sandbox '${data.sandboxName}' created via ${data.mode}.${data.enableTailscale ? ' Tailscale-enabled path requested.' : ' Tailscale disabled.'}`,
|
||||
data.verification?.summary,
|
||||
data.gatewayReusePolicy,
|
||||
'Inventory refresh requested immediately.',
|
||||
].filter(Boolean).join('\n\n'))
|
||||
if (createdSandboxId && onCreateSuccess) {
|
||||
await onCreateSuccess(createdSandboxId)
|
||||
}
|
||||
return
|
||||
}
|
||||
const res = await fetch(`/api/sandbox/${encodeURIComponent(sandboxId)}/config`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ policy: assembledPolicy, preset: selectedPreset || null, mode }) })
|
||||
const data = await res.json(); if (!res.ok) throw new Error(data.error || "Failed to save policy")
|
||||
setMessage('Policy saved. Dynamic network policy can apply live; static sections require sandbox recreation.')
|
||||
} catch (err) {
|
||||
setMessage(err instanceof Error ? err.message : "Failed to save policy")
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
} finally { setSaving(false) }
|
||||
}
|
||||
|
||||
function updateBlock(idx: number, next: NetworkPolicyBlock) {
|
||||
setBlocks((prev) => prev.map((b, i) => (i === idx ? next : b)))
|
||||
}
|
||||
|
||||
function addBlock() {
|
||||
setBlocks((prev) => [...prev, {
|
||||
key: `policy_${prev.length + 1}`,
|
||||
name: `policy-${prev.length + 1}`,
|
||||
endpoints: [{ host: "", port: "443", protocol: "", tls: "", enforcement: "", access: "read-only", rules: [] }],
|
||||
binaries: [{ path: "" }],
|
||||
}])
|
||||
}
|
||||
function updateBlock(idx: number, next: NetworkPolicyBlock) { setBlocks((prev) => prev.map((b, i) => (i === idx ? next : b))) }
|
||||
function addBlock() { setBlocks((prev) => [...prev, { key: `policy_${prev.length + 1}`, name: `policy-${prev.length + 1}`, endpoints: [{ host: "", port: "443", protocol: "", tls: "", enforcement: "", access: "read-only", rules: [] }], binaries: [{ path: "" }] }]) }
|
||||
|
||||
return (
|
||||
<div className="panel p-6 mt-6 border-t-2 border-[var(--nvidia-green)]">
|
||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)]">
|
||||
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{sandboxId} — {mode === 'create' ? 'NEW SANDBOX PRESET + POLICY' : 'OPENSHELL POLICY'}</h4>
|
||||
<div className="flex gap-2">
|
||||
<Badge tone="static">Static / Recreate Required</Badge>
|
||||
<Badge tone="dynamic">Dynamic / Apply Live</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? <div className="text-sm text-[var(--foreground-dim)]">Loading policy…</div> : (
|
||||
<div className="space-y-8">
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div>
|
||||
<h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Security Presets</h5>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-1">Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.</p>
|
||||
</div>
|
||||
<div className="min-w-[260px]">
|
||||
<select
|
||||
value={selectedPreset}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value as SecurityPresetId | ''
|
||||
setSelectedPreset(value)
|
||||
if (value) applyPreset(value)
|
||||
}}
|
||||
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)]"
|
||||
>
|
||||
<option value="">Select preset…</option>
|
||||
{SECURITY_PRESETS.map((preset) => (
|
||||
<option key={preset.id} value={preset.id}>{preset.label}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{activePreset && (
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{activePreset.label}</span>
|
||||
<Badge tone={showDangerWarning ? 'danger' : 'dynamic'}>{activePreset.danger.replace('-', ' ')}</Badge>
|
||||
{showDangerWarning && <Badge tone="danger">Dangerous / Permissive</Badge>}
|
||||
</div>
|
||||
<p className="text-sm text-[var(--foreground-dim)]">{activePreset.summary}</p>
|
||||
{(activePreset.id === 'spicy' || activePreset.id === 'ultra-lobster') && (
|
||||
<div className="rounded-sm border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-300">
|
||||
Warning: {activePreset.label} may be dangerous due to its permissive security stance. Use only on trusted lab workloads.
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-xs uppercase tracking-wider text-[var(--foreground-dim)] mb-2">Preset exec allowlist</p>
|
||||
<pre className="overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3 text-[11px] text-[var(--foreground)]">{activePreset.execAllowlist.paths.join('\n')}</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Filesystem Policy</h5><Badge tone="static">Static</Badge></div>
|
||||
<label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono">
|
||||
<input type="checkbox" checked={policy.filesystem_policy.include_workdir} onChange={(e) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, include_workdir: e.target.checked } })} />
|
||||
Include workdir
|
||||
<FieldHelp text="Automatically adds the agent working directory to read_write. Static: changing this requires recreating the sandbox." />
|
||||
</label>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<TextListEditor label="Read-only paths" tooltipText="Absolute paths the sandbox can read but not modify. Paths not listed are inaccessible." value={policy.filesystem_policy.read_only} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" />
|
||||
<TextListEditor label="Read-write paths" tooltipText="Absolute paths the sandbox can read and write. Keep this scoped; broad paths are rejected." value={policy.filesystem_policy.read_write} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Landlock + Process</h5><Badge tone="static">Static</Badge></div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Landlock compatibility<FieldHelp text="best_effort uses the highest kernel ABI available. hard_requirement fails if the required ABI is unavailable." /></label>
|
||||
<select value={policy.landlock.compatibility} onChange={(e) => setPolicy({ ...policy, landlock: { compatibility: e.target.value as LandlockCompatibility } })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono"><option value="best_effort">best_effort</option><option value="hard_requirement">hard_requirement</option></select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Run as user<FieldHelp text="OS-level user for the sandbox process. Upstream policy validation expects sandbox; root is rejected." /></label>
|
||||
<input value={policy.process.run_as_user} onChange={(e) => setPolicy({ ...policy, process: { ...policy.process, run_as_user: e.target.value } })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Run as group<FieldHelp text="OS-level group for the sandbox process. Upstream policy validation expects sandbox; root is rejected." /></label>
|
||||
<input value={policy.process.run_as_group} onChange={(e) => setPolicy({ ...policy, process: { ...policy.process, run_as_group: e.target.value } })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Network Policies</h5><Badge tone="dynamic">Dynamic</Badge></div>
|
||||
<button onClick={addBlock} className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Add policy block</button>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--foreground-dim)]">Named endpoint + binary allowlists. These are hot-reloadable on running sandboxes via policy updates.</p>
|
||||
<div className="space-y-6">
|
||||
{blocks.length === 0 && <div className="text-sm text-[var(--foreground-dim)]">No network policies defined.</div>}
|
||||
{blocks.map((block, idx) => (
|
||||
<div key={idx} className="border border-[var(--border-subtle)] rounded-sm p-4 space-y-4 bg-[var(--background-tertiary)]">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Policy key<FieldHelp text="Logical identifier in network_policies map." /></label><input value={block.key} onChange={(e) => updateBlock(idx, { ...block, key: e.target.value })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono" /></div>
|
||||
<div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Display name<FieldHelp text="Optional display name used in logs; defaults to the key." /></label><input value={block.name} onChange={(e) => updateBlock(idx, { ...block, name: e.target.value })} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono" /></div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<div className="text-xs uppercase tracking-wider text-[var(--foreground)]">Endpoints</div>
|
||||
{block.endpoints.map((ep, epIdx) => (
|
||||
<div key={epIdx} className="grid grid-cols-1 md:grid-cols-6 gap-3 border border-[var(--border-subtle)] p-3 rounded-sm">
|
||||
<input placeholder="host" value={ep.host} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, host: e.target.value }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono" />
|
||||
<input placeholder="port" value={ep.port} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, port: e.target.value }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono" />
|
||||
<select value={ep.protocol} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, protocol: e.target.value as EndpointProtocol }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono"><option value="">protocol</option><option value="rest">rest</option></select>
|
||||
<select value={ep.tls} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, tls: e.target.value as EndpointTls }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono"><option value="">tls</option><option value="terminate">terminate</option><option value="passthrough">passthrough</option></select>
|
||||
<select value={ep.enforcement} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, enforcement: e.target.value as EndpointEnforcement }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono"><option value="">enforcement</option><option value="enforce">enforce</option><option value="audit">audit</option></select>
|
||||
<select value={ep.access} onChange={(e) => { const next = [...block.endpoints]; next[epIdx] = { ...ep, access: e.target.value as EndpointAccess }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono"><option value="">rules mode</option><option value="read-only">read-only</option><option value="read-write">read-write</option><option value="full">full</option></select>
|
||||
</div>
|
||||
))}
|
||||
<button onClick={() => updateBlock(idx, { ...block, endpoints: [...block.endpoints, { host: "", port: "443", protocol: "", tls: "", enforcement: "", access: "", rules: [{ method: "GET", path: "/**" }] }] })} className="px-3 py-2 rounded-sm bg-[var(--background)] text-xs font-mono uppercase tracking-wider">Add endpoint</button>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<div className="text-xs uppercase tracking-wider text-[var(--foreground)]">Binaries</div>
|
||||
{block.binaries.map((bin, binIdx) => (<input key={binIdx} placeholder="/usr/bin/curl" value={bin.path} onChange={(e) => { const next = [...block.binaries]; next[binIdx] = { path: e.target.value }; updateBlock(idx, { ...block, binaries: next }) }} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono" />))}
|
||||
<button onClick={() => updateBlock(idx, { ...block, binaries: [...block.binaries, { path: "" }] })} className="px-3 py-2 rounded-sm bg-[var(--background)] text-xs font-mono uppercase tracking-wider">Add binary</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3">
|
||||
<div className="flex items-center justify-between"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Policy JSON Preview</h5><button onClick={savePolicy} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">{saving ? "Saving…" : mode === 'create' ? 'Use For New Sandbox' : 'Save Policy'}</button></div>
|
||||
<pre className="overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-[11px] leading-5 text-[var(--foreground)]">{JSON.stringify(assembledPolicy, null, 2)}</pre>
|
||||
{message && <div className="text-sm text-[var(--foreground-dim)]">{message}</div>}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)]"><h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{mode === 'create' ? 'CREATE SANDBOX WORKFLOW' : `${sandboxId} — OPENSHELL POLICY`}</h4><div className="flex gap-2"><Badge tone="static">Static / Recreate Required</Badge><Badge tone="dynamic">Dynamic / Apply Live</Badge></div></div>
|
||||
{loading ? <div className="text-sm text-[var(--foreground-dim)]">Loading policy…</div> : <div className="space-y-8">
|
||||
{mode === 'create' && <section className="space-y-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Create Sandbox</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Choose a blueprint-backed workflow or create a custom sandbox, then provide a sandbox name.</p></div><div className="rounded-sm border border-[rgba(118,185,0,0.25)] bg-[rgba(118,185,0,0.08)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap">Gateway reuse policy:
|
||||
- reuse the existing OpenShell gateway when `openshell status` reports `Connected`
|
||||
- only start a fresh gateway when no healthy gateway is already connected
|
||||
- force non-interactive PATH to include $HOME/.local/bin so openshell resolves during setup</div><div className="grid grid-cols-1 md:grid-cols-2 gap-4">{blueprints.map((bp) => <button key={bp.id} type="button" onClick={() => setSelectedBlueprint(bp.id)} className={`rounded-sm border p-4 text-left ${selectedBlueprint === bp.id ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background)]'}`}><div className="flex items-center justify-between gap-3"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{bp.label}</span><Badge tone={bp.type === 'custom' ? 'static' : 'dynamic'}>{bp.type}</Badge></div><p className="text-xs text-[var(--foreground-dim)] mt-2">{bp.description}</p><p className="text-[10px] font-mono text-[var(--foreground-dim)] mt-3">{bp.source}</p></button>)}</div><div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Sandbox Name<FieldHelp text="Operator-facing sandbox name used by OpenShell create/connect flows. Lowercase letters, numbers, and hyphens only." /></label><input value={sandboxName} onChange={(e) => setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" /></div>{activeBlueprint?.supportsTailscale && <label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={enableTailscale} onChange={(e) => setEnableTailscale(e.target.checked)} /> Enable Tailscale <FieldHelp text="Optional. Only enable this when you want the Tailscale/NVIDIA-backed path. This is the only case where NVIDIA_API_KEY should be required." /></label>}{enableTailscale && <div className="rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.</div>}</section>}
|
||||
<section className="space-y-4"><div className="flex items-center justify-between gap-4 flex-wrap"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Security Presets</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.</p></div><div className="min-w-[260px]"><select value={selectedPreset} onChange={(e) => { const value = e.target.value as SecurityPresetId | ''; setSelectedPreset(value); if (value) applyPreset(value) }} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)]"><option value="">Select preset…</option>{SECURITY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.label}</option>)}</select></div></div>{activePreset && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3"><div className="flex items-center gap-3 flex-wrap"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{activePreset.label}</span></div><p className="text-sm text-[var(--foreground-dim)]">{activePreset.summary}</p></div>}</section>
|
||||
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Filesystem Policy</h5><Badge tone="static">Static</Badge></div><label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={policy.filesystem_policy.include_workdir} onChange={(e) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, include_workdir: e.target.checked } })} />Include workdir<FieldHelp text="Automatically adds the agent working directory to read_write. Static: changing this requires recreating the sandbox." /></label><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><TextListEditor label="Read-only paths" tooltipText="Absolute paths the sandbox can read but not modify. Paths not listed are inaccessible." value={policy.filesystem_policy.read_only} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" /><TextListEditor label="Read-write paths" tooltipText="Absolute paths the sandbox can read and write. Keep this scoped; broad paths are rejected." value={policy.filesystem_policy.read_write} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" /></div></section>
|
||||
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Network Policies</h5><Badge tone="dynamic">Dynamic</Badge></div><button onClick={addBlock} className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Add policy block</button></section>
|
||||
<section className="space-y-3"><div className="flex items-center justify-between"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Policy JSON Preview</h5><button onClick={savePolicy} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">{saving ? "Working…" : mode === 'create' ? 'Create Sandbox' : 'Save Policy'}</button></div><pre className="overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-[11px] leading-5 text-[var(--foreground)]">{JSON.stringify(assembledPolicy, null, 2)}</pre>{message && <div className="text-sm text-[var(--foreground-dim)] whitespace-pre-wrap">{message}</div>}</section>
|
||||
</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import CompactGauge from './CompactGauge'
|
||||
|
||||
interface TelemetryData {
|
||||
@@ -9,6 +9,7 @@ interface TelemetryData {
|
||||
gpuMemoryUsed?: number
|
||||
gpuMemoryTotal?: number
|
||||
gpuTemperature?: number
|
||||
timestamp?: string
|
||||
}
|
||||
|
||||
interface SandboxConfig {
|
||||
@@ -42,15 +43,7 @@ export default function SandboxDetails({
|
||||
{ name: 'debugMode', description: 'Enable debug logging', enabled: false }
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
if (sandboxId) {
|
||||
fetchTelemetry()
|
||||
const interval = setInterval(fetchTelemetry, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [sandboxId])
|
||||
|
||||
const fetchTelemetry = async () => {
|
||||
const fetchTelemetry = useCallback(async () => {
|
||||
if (!sandboxId) return
|
||||
setLoading(true)
|
||||
try {
|
||||
@@ -62,7 +55,15 @@ export default function SandboxDetails({
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [sandboxId])
|
||||
|
||||
useEffect(() => {
|
||||
if (sandboxId) {
|
||||
fetchTelemetry()
|
||||
const interval = setInterval(fetchTelemetry, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [sandboxId, fetchTelemetry])
|
||||
|
||||
const toggleConfig = (name: string) => {
|
||||
setConfig(config.map(item =>
|
||||
|
||||
+160
-106
@@ -1,16 +1,8 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useEffect, useState } from 'react'
|
||||
import ConfigurationPanel from './ConfigurationPanel'
|
||||
|
||||
interface Sandbox {
|
||||
id: string
|
||||
name: string
|
||||
namespace: string
|
||||
ip: string
|
||||
status: 'running' | 'pending' | 'stopped' | 'unknown'
|
||||
ready: boolean
|
||||
}
|
||||
import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory'
|
||||
import { buildOperatorTerminalRoute } from '../lib/dashboardSession'
|
||||
|
||||
interface TelemetryData {
|
||||
cpu: number
|
||||
@@ -23,63 +15,68 @@ interface TelemetryData {
|
||||
}
|
||||
|
||||
interface SandboxListProps {
|
||||
selectedSandbox: string | null
|
||||
sandboxes: SandboxInventoryItem[]
|
||||
nemoclaw: NemoClawSummary | null
|
||||
dashboardSessionId: string
|
||||
selectedSandboxId: string | null
|
||||
selectedSandbox: SandboxInventoryItem | null
|
||||
onSandboxSelect: (id: string | null) => void
|
||||
isDestroyMode: boolean
|
||||
onInventoryRefresh: () => Promise<SandboxInventoryItem[]>
|
||||
}
|
||||
|
||||
function renderDashboardTruthMessage(data: any) {
|
||||
const listenerSummary = data.listenerSummary ? `\nListener: ${data.listenerSummary}` : ''
|
||||
const showUpstreamSummary = !data.reachable || data.degraded || data.truthState !== 'verified'
|
||||
const upstreamSummary = showUpstreamSummary && (data.upstreamStatus || data.upstreamStatusText)
|
||||
? `\nUpstream probe: ${data.upstreamStatus ?? 'no-status'} ${data.upstreamStatusText ?? ''}`.trimEnd()
|
||||
: ''
|
||||
const inventorySummary = typeof data.inventoryCount === 'number'
|
||||
? `Inventory visibility: ${data.inventoryCount} live sandbox${data.inventoryCount === 1 ? '' : 'es'}.`
|
||||
: 'Inventory visibility: unknown.'
|
||||
const mappingSummary = data.sandboxId
|
||||
? (data.authority?.usedMappedSandboxInstance
|
||||
? `Sandbox ${data.sandboxId} resolved to OpenClaw instance ${data.instanceId} via bridge mapping (fallback-active).`
|
||||
: `Sandbox ${data.sandboxId} resolved to OpenClaw instance ${data.instanceId}.`)
|
||||
: `OpenClaw instance: ${data.instanceId}.`
|
||||
const reachabilitySummary = data.reachable
|
||||
? `Dashboard reachability: reachable at ${data.dashboardUrl}.`
|
||||
: `Dashboard reachability: unreachable at ${data.dashboardUrl}.`
|
||||
|
||||
if (data.degraded) {
|
||||
return `${inventorySummary} ${mappingSummary} ${reachabilitySummary} Degraded truth: the dashboard is reachable, but live OpenShell inventory is zero, so mapping alone does not prove the sandbox currently exists.${listenerSummary}${upstreamSummary}`
|
||||
}
|
||||
|
||||
if (data.reachable) {
|
||||
return `${inventorySummary} ${mappingSummary} ${data.note || reachabilitySummary}`.trim()
|
||||
}
|
||||
|
||||
return `${inventorySummary} ${mappingSummary} ${data.note || `OpenClaw Dashboard at ${data.dashboardUrl} is currently unreachable from this host.`}${listenerSummary}${upstreamSummary}`
|
||||
}
|
||||
|
||||
export default function SandboxList({
|
||||
sandboxes,
|
||||
nemoclaw,
|
||||
dashboardSessionId,
|
||||
selectedSandboxId,
|
||||
selectedSandbox,
|
||||
onSandboxSelect,
|
||||
isDestroyMode
|
||||
isDestroyMode,
|
||||
onInventoryRefresh,
|
||||
}: SandboxListProps) {
|
||||
const router = useRouter()
|
||||
const [terminalMessage, setTerminalMessage] = useState<string>('')
|
||||
const [dashboardMessage, setDashboardMessage] = useState<string>('')
|
||||
const [sandboxes, setSandboxes] = useState<Sandbox[]>([])
|
||||
const [telemetry, setTelemetry] = useState<TelemetryData>({
|
||||
cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString()
|
||||
})
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
fetchSandboxes()
|
||||
const interval = setInterval(fetchSandboxes, 10000)
|
||||
return () => clearInterval(interval)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
if (selectedSandboxId) {
|
||||
fetchTelemetry()
|
||||
const interval = setInterval(fetchTelemetry, 5000)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [selectedSandbox])
|
||||
|
||||
const fetchSandboxes = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real')
|
||||
const data = await response.json()
|
||||
|
||||
const sandboxList = (data.pods?.items || [])
|
||||
.filter((pod: any) => pod.metadata?.namespace === 'agent-sandbox-system')
|
||||
.map((pod: any) => ({
|
||||
id: pod.metadata?.name || 'unknown',
|
||||
name: pod.metadata?.name || 'Unknown Sandbox',
|
||||
namespace: pod.metadata?.namespace || 'unknown',
|
||||
ip: pod.status?.podIP || 'N/A',
|
||||
status: pod.status?.phase === 'Running' ? 'running' :
|
||||
pod.status?.phase === 'Pending' ? 'pending' :
|
||||
pod.status?.phase === 'Stopped' ? 'stopped' : 'unknown' as const,
|
||||
ready: pod.status?.conditions?.find((c: any) => c.type === 'Ready')?.status === 'True'
|
||||
}))
|
||||
|
||||
setSandboxes(sandboxList)
|
||||
setLoading(false)
|
||||
} catch (error) {
|
||||
console.error('Error fetching sandboxes:', error)
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [selectedSandboxId])
|
||||
|
||||
const fetchTelemetry = async () => {
|
||||
try {
|
||||
@@ -91,16 +88,6 @@ export default function SandboxList({
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="text-xs text-[var(--foreground-dim)] font-mono uppercase tracking-wider">
|
||||
INITIALIZING...
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{sandboxes.length === 0 ? (
|
||||
@@ -110,7 +97,7 @@ export default function SandboxList({
|
||||
</svg>
|
||||
<h3 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">No Sandboxes Detected</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
No sandboxes running in agent-sandbox-system namespace
|
||||
No live OpenShell sandboxes reported yet
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
@@ -123,7 +110,52 @@ export default function SandboxList({
|
||||
REFRESH: 10s
|
||||
</span>
|
||||
</div>
|
||||
|
||||
|
||||
{!isDestroyMode && (
|
||||
<div className="panel p-4 space-y-2">
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Inventory Source</p>
|
||||
<p className="text-sm font-mono text-[var(--foreground)] mt-1">Live OpenShell gateway inventory</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">NemoClaw Operator Surface</p>
|
||||
<p className="text-sm font-mono text-[var(--foreground)] mt-1">
|
||||
{nemoclaw?.available ? 'Local registry + services' : 'Unavailable'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-2 pt-1">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground-dim)]">
|
||||
Inventory visibility: {sandboxes.length} live sandbox{sandboxes.length === 1 ? '' : 'es'}
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground-dim)]">
|
||||
Mapping truth: intent only, not proof of sandbox existence
|
||||
</div>
|
||||
<div className={`rounded-sm border px-3 py-2 text-xs font-mono ${sandboxes.length === 0 ? 'border-[var(--status-pending)] bg-[var(--status-pending-bg)] text-[var(--status-pending)]' : 'border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-[var(--foreground-dim)]'}`}>
|
||||
{sandboxes.length === 0 ? 'Truth state: degraded / unverified' : 'Truth state: verified from live inventory'}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--foreground-dim)] font-mono">
|
||||
Dashboard session: {dashboardSessionId.slice(0, 8)}
|
||||
</p>
|
||||
{nemoclaw?.defaultSandboxNames?.length ? (
|
||||
<p className="text-xs text-[var(--foreground-dim)] font-mono">
|
||||
Default sandbox marker: {nemoclaw.defaultSandboxNames.join(', ')}
|
||||
</p>
|
||||
) : null}
|
||||
{nemoclaw?.serviceLines?.length ? (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-2 pt-1">
|
||||
{nemoclaw.serviceLines.slice(0, 4).map((line) => (
|
||||
<div key={line} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground-dim)]" title={line}>
|
||||
{line}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{sandboxes.map((sandbox) => (
|
||||
<button
|
||||
@@ -132,62 +164,81 @@ export default function SandboxList({
|
||||
className={`p-4 rounded-sm text-left transition-all border-2 ${
|
||||
isDestroyMode
|
||||
? 'border-[var(--status-stopped)] hover:bg-[var(--status-stopped-bg)]'
|
||||
: selectedSandbox === sandbox.id
|
||||
: selectedSandboxId === sandbox.id
|
||||
? 'bg-[var(--nvidia-green)] text-white border-[var(--nvidia-green)]'
|
||||
: 'panel hover:border-[var(--nvidia-green)]'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className={`text-sm font-mono font-semibold truncate ${
|
||||
isDestroyMode ? 'text-[var(--status-stopped)]' : ''
|
||||
}`}>
|
||||
{sandbox.name}
|
||||
</span>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className={`text-sm font-mono font-semibold truncate ${
|
||||
isDestroyMode ? 'text-[var(--status-stopped)]' : ''
|
||||
}`}>
|
||||
{sandbox.name}
|
||||
</span>
|
||||
{sandbox.isDefault ? (
|
||||
<span className="rounded-sm border border-[var(--border-subtle)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--foreground-dim)]">default</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className={`px-2 py-0.5 rounded-sm text-[10px] font-mono uppercase ${
|
||||
isDestroyMode
|
||||
? 'bg-[var(--status-stopped)] text-white animate-pulse'
|
||||
: sandbox.status === 'running' && sandbox.ready
|
||||
? 'bg-[var(--status-running)] text-white'
|
||||
: 'bg-[var(--status-pending)] text-white'
|
||||
: sandbox.status === 'stopped'
|
||||
? 'bg-[var(--status-stopped)] text-white'
|
||||
: sandbox.status === 'error'
|
||||
? 'bg-red-500 text-white'
|
||||
: 'bg-[var(--status-pending)] text-white'
|
||||
}`}>
|
||||
{isDestroyMode ? 'DESTROY' : sandbox.status === 'running' && sandbox.ready ? 'RUNNING' : 'PENDING'}
|
||||
{isDestroyMode ? 'DESTROY' : sandbox.status === 'running' && sandbox.ready ? 'RUNNING' : sandbox.status.toUpperCase()}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">IP Address</span>
|
||||
<span className="text-xs font-mono">{sandbox.ip}</span>
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Attach Target</span>
|
||||
<span className="text-xs font-mono truncate max-w-[180px]" title={sandbox.ip}>{sandbox.ip}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Namespace</span>
|
||||
<span className="text-xs font-mono truncate max-w-[120px]">{sandbox.namespace}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Host Alias</span>
|
||||
<span className="text-xs font-mono truncate max-w-[140px]">{sandbox.sshHostAlias || 'N/A'}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Sandbox ID</span>
|
||||
<span className="text-xs font-mono truncate max-w-[140px]" title={sandbox.id}>{sandbox.id}</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Selected Sandbox Details - Technical Data Panel */}
|
||||
{!isDestroyMode && selectedSandbox && (
|
||||
<>
|
||||
<div className="panel p-6">
|
||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)] gap-4 flex-wrap">
|
||||
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
|
||||
{sandboxes.find(s => s.id === selectedSandbox)?.name} — TELEMETRY
|
||||
{selectedSandbox.name} — TELEMETRY
|
||||
</h4>
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<button
|
||||
onClick={async () => {
|
||||
try {
|
||||
const res = await fetch('/api/openshell/dashboard/open')
|
||||
const searchParams = new URLSearchParams()
|
||||
searchParams.set('sandboxId', selectedSandbox.id)
|
||||
searchParams.set('inventoryCount', String(sandboxes.length))
|
||||
const res = await fetch(`/api/openshell/dashboard/open?${searchParams.toString()}`)
|
||||
const data = await res.json()
|
||||
setDashboardMessage(data.loopbackOnly
|
||||
? `OpenClaw Dashboard detected at ${data.dashboardUrl}. Opening proxied dashboard route.`
|
||||
: `OpenClaw Dashboard: ${data.dashboardUrl}`)
|
||||
if (data.proxiedUrl) {
|
||||
window.open(data.proxiedUrl, '_blank', 'noopener,noreferrer')
|
||||
} else if (data.dashboardUrl && !data.loopbackOnly) {
|
||||
window.open(data.dashboardUrl, '_blank', 'noopener,noreferrer')
|
||||
setDashboardMessage(renderDashboardTruthMessage(data))
|
||||
if (data.reachable && data.launchUrl) {
|
||||
window.location.href = data.launchUrl
|
||||
} else if (data.reachable && data.proxiedUrl) {
|
||||
window.location.href = data.proxiedUrl
|
||||
} else if (data.reachable && data.dashboardUrl && !data.loopbackOnly) {
|
||||
window.location.href = data.dashboardUrl
|
||||
}
|
||||
} catch (error) {
|
||||
setDashboardMessage('Failed to resolve OpenClaw Dashboard endpoint.')
|
||||
@@ -199,55 +250,58 @@ export default function SandboxList({
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
router.push(`/operator-terminal?sandboxId=${encodeURIComponent(selectedSandbox)}`)
|
||||
const nextUrl = buildOperatorTerminalRoute({
|
||||
sandboxId: selectedSandbox.id,
|
||||
dashboardSessionId,
|
||||
})
|
||||
window.open(nextUrl, '_blank', 'noopener,noreferrer')
|
||||
}}
|
||||
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)]"
|
||||
>
|
||||
Open Operator Terminal
|
||||
Open Operator Terminal Path
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
await onInventoryRefresh()
|
||||
}}
|
||||
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)]"
|
||||
>
|
||||
Refresh Inventory
|
||||
</button>
|
||||
<span className="text-[10px] text-[var(--foreground-dim)] font-mono">
|
||||
LIVE
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{dashboardMessage && (
|
||||
|
||||
{(dashboardMessage || terminalMessage) && (
|
||||
<div className="mb-4 space-y-2">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{dashboardMessage}</div>
|
||||
{dashboardMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{dashboardMessage}</div>}
|
||||
{terminalMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap font-mono">{terminalMessage}</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">CPU</p>
|
||||
<p className="text-2xl font-mono text-[var(--nvidia-green)] mt-1">
|
||||
{telemetry.cpu.toFixed(1)}%
|
||||
</p>
|
||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.cpu.toFixed(1)}%</p>
|
||||
</div>
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">MEMORY</p>
|
||||
<p className="text-2xl font-mono text-[var(--nvidia-green)] mt-1">
|
||||
{telemetry.memory.toFixed(1)}%
|
||||
</p>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">MEM</p>
|
||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.memory.toFixed(1)}%</p>
|
||||
</div>
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">DISK</p>
|
||||
<p className="text-2xl font-mono text-[var(--nvidia-green)] mt-1">
|
||||
{telemetry.disk.toFixed(1)}%
|
||||
</p>
|
||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.disk.toFixed(1)}%</p>
|
||||
</div>
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">UPDATED</p>
|
||||
<p className="text-sm font-mono text-[var(--foreground)] mt-1">{new Date(telemetry.timestamp).toLocaleTimeString()}</p>
|
||||
</div>
|
||||
{telemetry.gpuTemperature && (
|
||||
<div className="metric p-4">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">GPU TEMP</p>
|
||||
<p className="text-2xl font-mono text-[var(--nvidia-green)] mt-1">
|
||||
{telemetry.gpuTemperature.toFixed(1)}°C
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfigurationPanel sandboxId={selectedSandbox} mode="existing" />
|
||||
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" onInventoryRefresh={onInventoryRefresh} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
+55
-70
@@ -1,16 +1,13 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
interface Sandbox {
|
||||
id: string
|
||||
name: string
|
||||
ip: string
|
||||
status: 'running' | 'stopped' | 'unknown'
|
||||
}
|
||||
import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory'
|
||||
|
||||
interface SidebarProps {
|
||||
hostIP: string
|
||||
selectedSandbox: string | null
|
||||
sandboxes: SandboxInventoryItem[]
|
||||
nemoclaw: NemoClawSummary | null
|
||||
dashboardSessionId: string
|
||||
selectedSandboxId: string | null
|
||||
onSandboxSelect: (id: string | null) => void
|
||||
isSubmenuOpen: boolean
|
||||
onToggleSubmenu: () => void
|
||||
@@ -26,7 +23,10 @@ interface SidebarProps {
|
||||
|
||||
export default function Sidebar({
|
||||
hostIP,
|
||||
selectedSandbox,
|
||||
sandboxes,
|
||||
nemoclaw,
|
||||
dashboardSessionId,
|
||||
selectedSandboxId,
|
||||
onSandboxSelect,
|
||||
isSubmenuOpen,
|
||||
onToggleSubmenu,
|
||||
@@ -39,49 +39,9 @@ export default function Sidebar({
|
||||
onSettingsClick,
|
||||
onExitMode
|
||||
}: SidebarProps) {
|
||||
const [sandboxes, setSandboxes] = useState<Sandbox[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSandboxes = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real')
|
||||
const data = await response.json()
|
||||
|
||||
const items = data?.pods?.items || []
|
||||
if (!Array.isArray(items)) {
|
||||
setSandboxes([])
|
||||
return
|
||||
}
|
||||
|
||||
const sandboxList = items
|
||||
.filter((pod: any) => pod?.metadata?.namespace === 'agent-sandbox-system')
|
||||
.map((pod: any) => ({
|
||||
id: pod.metadata?.name || 'unknown',
|
||||
name: pod.metadata?.name || 'Unknown Sandbox',
|
||||
ip: pod.status?.podIP || 'N/A',
|
||||
status: pod.status?.phase === 'Running' ? 'running' :
|
||||
pod.status?.phase === 'Pending' ? 'pending' :
|
||||
pod.status?.phase === 'Stopped' ? 'stopped' : 'unknown' as const
|
||||
}))
|
||||
|
||||
setSandboxes(sandboxList)
|
||||
} catch (error) {
|
||||
console.error('Error fetching sandboxes in Sidebar:', error)
|
||||
setSandboxes([])
|
||||
}
|
||||
}
|
||||
|
||||
if (isSubmenuOpen || isDestroyMode || isCreateMode) {
|
||||
fetchSandboxes()
|
||||
const interval = setInterval(fetchSandboxes, 10000)
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
}, [isSubmenuOpen, isDestroyMode, isCreateMode])
|
||||
return (
|
||||
<>
|
||||
{/* Main Sidebar */}
|
||||
<aside className="fixed left-0 top-0 h-screen w-64 bg-[var(--background-secondary)] border-r border-[var(--border-subtle)] flex flex-col z-20">
|
||||
{/* Host IP Header - Industrial Style */}
|
||||
<div className="p-4 border-b border-[var(--border-subtle)]">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-[var(--nvidia-green)] rounded-sm flex items-center justify-center">
|
||||
@@ -92,11 +52,11 @@ export default function Sidebar({
|
||||
<div>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider font-semibold">Host</p>
|
||||
<p className="text-sm font-mono text-[var(--nvidia-green)] tracking-tight">{hostIP}</p>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] font-mono mt-1">session {dashboardSessionId.slice(0, 8)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Navigation Menu - Technical */}
|
||||
<nav className="flex-1 p-2">
|
||||
<button
|
||||
onClick={onToggleSubmenu}
|
||||
@@ -112,19 +72,18 @@ export default function Sidebar({
|
||||
</svg>
|
||||
<span className="text-sm font-medium tracking-tight">Sandboxes</span>
|
||||
</span>
|
||||
<svg
|
||||
className={`w-4 h-4 transition-transform ${isSubmenuOpen ? 'rotate-90' : ''}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
<svg
|
||||
className={`w-4 h-4 transition-transform ${isSubmenuOpen ? 'rotate-90' : ''}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Quick Actions - Technical Icons */}
|
||||
<div className="mt-4 space-y-1">
|
||||
<button
|
||||
<button
|
||||
onClick={onCreateClick}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors ${
|
||||
isCreateMode
|
||||
@@ -137,8 +96,8 @@ export default function Sidebar({
|
||||
</svg>
|
||||
<span className="text-sm">Create Sandbox</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
||||
<button
|
||||
onClick={onDestroyClick}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors ${
|
||||
isDestroyMode
|
||||
@@ -153,7 +112,7 @@ export default function Sidebar({
|
||||
</button>
|
||||
|
||||
{(isCreateMode || isDestroyMode) && (
|
||||
<button
|
||||
<button
|
||||
onClick={onExitMode}
|
||||
className="w-full flex items-center gap-3 px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground-dim)] hover:bg-[var(--background-panel)] transition-colors"
|
||||
>
|
||||
@@ -163,27 +122,29 @@ export default function Sidebar({
|
||||
<span className="text-sm">Cancel</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
|
||||
<button
|
||||
onClick={onSettingsClick}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors ${
|
||||
activeView === 'settings'
|
||||
? 'bg-[var(--nvidia-green)] text-white'
|
||||
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)]'
|
||||
}`}>
|
||||
}`}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
<span className="text-sm">Settings</span>
|
||||
</button>
|
||||
<button
|
||||
<button
|
||||
onClick={onOverviewClick}
|
||||
className={`w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors ${
|
||||
activeView === 'overview'
|
||||
? 'bg-[var(--nvidia-green)] text-white'
|
||||
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)]'
|
||||
}`}>
|
||||
}`}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
@@ -192,14 +153,12 @@ export default function Sidebar({
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
{/* Footer - Technical */}
|
||||
<div className="p-4 border-t border-[var(--border-subtle)]">
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">OpenShell Control</p>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] font-mono">v1.0.0</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Slide-out Sandbox Submenu - Technical Data Panel */}
|
||||
<div
|
||||
className={`fixed left-64 top-0 h-screen w-72 bg-[var(--background)] border-r border-[var(--border-subtle)] transform transition-transform duration-200 ease-in-out z-10 ${
|
||||
isSubmenuOpen ? 'translate-x-0' : '-translate-x-full'
|
||||
@@ -213,6 +172,25 @@ export default function Sidebar({
|
||||
{isDestroyMode && 'SELECT A SANDBOX BELOW'}
|
||||
{!isCreateMode && !isDestroyMode && `${sandboxes.filter(s => s.status === 'running').length} RUNNING / ${sandboxes.length} TOTAL`}
|
||||
</p>
|
||||
{!isCreateMode && !isDestroyMode && (
|
||||
<div className="mt-3 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-2">
|
||||
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Inventory Source</p>
|
||||
<p className="mt-1 text-[11px] text-[var(--foreground)] font-mono">Live OpenShell sandboxes</p>
|
||||
<p className="mt-2 text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">NemoClaw Operator</p>
|
||||
<p className="mt-1 text-[11px] text-[var(--foreground)] font-mono">
|
||||
{nemoclaw?.available ? 'Registry/service summary available' : 'No NemoClaw summary detected'}
|
||||
</p>
|
||||
<p className="mt-1 text-[10px] text-[var(--foreground-dim)] font-mono">Dashboard session: {dashboardSessionId.slice(0, 8)}</p>
|
||||
{nemoclaw?.defaultSandboxNames?.length ? (
|
||||
<p className="mt-1 text-[10px] text-[var(--foreground-dim)] font-mono">
|
||||
Default: {nemoclaw.defaultSandboxNames.join(', ')}
|
||||
</p>
|
||||
) : null}
|
||||
{nemoclaw?.serviceLines?.slice(0, 2).map((line) => (
|
||||
<p key={line} className="mt-1 text-[10px] text-[var(--foreground-dim)] font-mono truncate" title={line}>{line}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-2 overflow-y-auto h-[calc(100vh-80px)]">
|
||||
@@ -257,7 +235,7 @@ export default function Sidebar({
|
||||
<button
|
||||
onClick={() => onSandboxSelect(null)}
|
||||
className={`w-full px-3 py-2 rounded-sm text-left transition-colors ${
|
||||
selectedSandbox === null
|
||||
selectedSandboxId === null
|
||||
? 'bg-[var(--nvidia-green)] text-white'
|
||||
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground)]'
|
||||
}`}
|
||||
@@ -275,7 +253,7 @@ export default function Sidebar({
|
||||
key={sandbox.id}
|
||||
onClick={() => onSandboxSelect(sandbox.id)}
|
||||
className={`w-full px-3 py-2 rounded-sm text-left transition-colors ${
|
||||
selectedSandbox === sandbox.id
|
||||
selectedSandboxId === sandbox.id
|
||||
? 'bg-[var(--nvidia-green)] text-white'
|
||||
: 'hover:bg-[var(--background-tertiary)] text-[var(--foreground)]'
|
||||
}`}
|
||||
@@ -286,17 +264,24 @@ export default function Sidebar({
|
||||
className={`w-2 h-2 rounded-sm ${
|
||||
sandbox.status === 'running'
|
||||
? 'bg-[var(--status-running)]'
|
||||
: 'bg-[var(--status-pending)]'
|
||||
: sandbox.status === 'stopped'
|
||||
? 'bg-[var(--status-stopped)]'
|
||||
: sandbox.status === 'error'
|
||||
? 'bg-red-500'
|
||||
: 'bg-[var(--status-pending)]'
|
||||
}`}
|
||||
/>
|
||||
<span className="text-sm font-mono truncate">{sandbox.name}</span>
|
||||
{sandbox.isDefault ? (
|
||||
<span className="rounded-sm border border-[var(--border-subtle)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--foreground-dim)]">default</span>
|
||||
) : null}
|
||||
</div>
|
||||
<svg className="w-3 h-3 opacity-75" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-[10px] text-[var(--foreground-dim)] font-mono mt-1 ml-4">
|
||||
{sandbox.ip}
|
||||
{sandbox.namespace} · {sandbox.ip}
|
||||
</p>
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client"
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import SpeedometerGauge from './SpeedometerGauge'
|
||||
|
||||
interface TelemetryData {
|
||||
@@ -36,15 +36,6 @@ export default function TelemetryDisplay() {
|
||||
fetchSandboxes()
|
||||
}, [])
|
||||
|
||||
// Fetch telemetry when sandbox changes
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry(selectedSandbox)
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, [selectedSandbox])
|
||||
|
||||
const fetchSandboxes = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real')
|
||||
@@ -64,7 +55,7 @@ export default function TelemetryDisplay() {
|
||||
}
|
||||
}
|
||||
|
||||
const fetchTelemetry = async (sandboxId: string) => {
|
||||
const fetchTelemetry = useCallback(async (sandboxId: string) => {
|
||||
try {
|
||||
const response = await fetch(`/api/telemetry/sandbox/${sandboxId}`)
|
||||
const data = await response.json()
|
||||
@@ -72,9 +63,9 @@ export default function TelemetryDisplay() {
|
||||
} catch (error) {
|
||||
console.error('Error fetching telemetry:', error)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const fetchCombinedTelemetry = async () => {
|
||||
const fetchCombinedTelemetry = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/combined')
|
||||
const data = await response.json()
|
||||
@@ -82,11 +73,20 @@ export default function TelemetryDisplay() {
|
||||
} catch (error) {
|
||||
console.error('Error fetching telemetry:', error)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleSandboxClick = (sandboxId: string | null) => {
|
||||
setSelectedSandbox(current => current === sandboxId ? null : sandboxId)
|
||||
}
|
||||
|
||||
const handleSandboxClick = (sandboxId: string) => {
|
||||
setSelectedSandbox(selectedSandbox === sandboxId ? null : sandboxId)
|
||||
}
|
||||
// Fetch telemetry when sandbox changes
|
||||
useEffect(() => {
|
||||
if (selectedSandbox) {
|
||||
fetchTelemetry(selectedSandbox)
|
||||
} else {
|
||||
fetchCombinedTelemetry()
|
||||
}
|
||||
}, [selectedSandbox, fetchTelemetry, fetchCombinedTelemetry])
|
||||
|
||||
if (loading) {
|
||||
return <div className="text-center text-gray-600 dark:text-gray-400">Loading telemetry...</div>
|
||||
@@ -165,7 +165,7 @@ export default function TelemetryDisplay() {
|
||||
</div>
|
||||
|
||||
{/* Additional Metrics */}
|
||||
{telemetry.gpuTemperature && (
|
||||
{telemetry.gpuTemperature !== undefined && telemetry.gpuMemoryUsed !== undefined && telemetry.gpuMemoryTotal !== undefined && (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<h3 className="text-lg font-semibold mb-4 dark:text-white">GPU Metrics</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
|
||||
+15
-15
@@ -3,6 +3,7 @@
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
/* NVIDIA Industrial Design System */
|
||||
--nvidia-green: #76B900;
|
||||
--nvidia-green-hover: #5d9600;
|
||||
@@ -33,23 +34,22 @@
|
||||
--metric-border: #2a2a2a;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
/* Light mode - still professional */
|
||||
--background: #f5f5f5;
|
||||
--background-secondary: #eeeeee;
|
||||
--background-tertiary: #e5e5e5;
|
||||
--background-panel: #ffffff;
|
||||
--foreground: #171717;
|
||||
--foreground-dim: #525252;
|
||||
--border-subtle: #d4d4d4;
|
||||
--border-medium: #a3a3a3;
|
||||
--metric-bg: #fafafa;
|
||||
--metric-border: #e5e5e5;
|
||||
}
|
||||
html[data-theme="light"] {
|
||||
color-scheme: light;
|
||||
--background: #f5f5f5;
|
||||
--background-secondary: #eeeeee;
|
||||
--background-tertiary: #e5e5e5;
|
||||
--background-panel: #ffffff;
|
||||
--foreground: #171717;
|
||||
--foreground-dim: #525252;
|
||||
--border-subtle: #d4d4d4;
|
||||
--border-medium: #a3a3a3;
|
||||
--metric-bg: #fafafa;
|
||||
--metric-border: #e5e5e5;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
@@ -113,4 +113,4 @@ body {
|
||||
border: 1px solid var(--metric-border);
|
||||
border-radius: 3px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
|
||||
export interface SandboxInventoryItem {
|
||||
id: string
|
||||
name: string
|
||||
namespace: string
|
||||
ip: string
|
||||
status: 'running' | 'pending' | 'stopped' | 'unknown' | 'error'
|
||||
ready: boolean
|
||||
sshHostAlias?: string
|
||||
isDefault?: boolean
|
||||
}
|
||||
|
||||
export interface NemoClawSummary {
|
||||
available: boolean
|
||||
defaultSandboxNames: string[]
|
||||
serviceLines: string[]
|
||||
summaryLines: string[]
|
||||
source: 'nemoclaw-cli' | 'none'
|
||||
}
|
||||
|
||||
interface InventoryResponse {
|
||||
sandboxes?: any[]
|
||||
pods?: { items?: any[] }
|
||||
nemoclaw?: NemoClawSummary | null
|
||||
}
|
||||
|
||||
function normalizeStatus(status: unknown): SandboxInventoryItem['status'] {
|
||||
const value = typeof status === 'string' ? status.toLowerCase() : 'unknown'
|
||||
if (value === 'running' || value === 'pending' || value === 'stopped' || value === 'error') return value
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
function mapSandboxSummary(sandbox: any): SandboxInventoryItem {
|
||||
const status = normalizeStatus(sandbox.status)
|
||||
return {
|
||||
id: sandbox.id || sandbox.name || 'unknown',
|
||||
name: sandbox.name || 'Unknown Sandbox',
|
||||
namespace: sandbox.namespace || 'openshell',
|
||||
ip: sandbox.sshHostAlias || 'N/A',
|
||||
status,
|
||||
ready: status === 'running',
|
||||
sshHostAlias: sandbox.sshHostAlias || undefined,
|
||||
isDefault: Boolean(sandbox.isDefault),
|
||||
}
|
||||
}
|
||||
|
||||
function mapPodItem(pod: any): SandboxInventoryItem {
|
||||
const status = normalizeStatus(pod.status?.phase)
|
||||
return {
|
||||
id: pod.metadata?.labels?.['nemoclaw.ai/sandbox-id'] || pod.metadata?.name || 'unknown',
|
||||
name: pod.metadata?.labels?.['nemoclaw.ai/sandbox-name'] || pod.metadata?.name || 'Unknown Sandbox',
|
||||
namespace: pod.metadata?.namespace || 'unknown',
|
||||
ip: pod.status?.podIP || 'N/A',
|
||||
status,
|
||||
ready: pod.status?.conditions?.find((c: any) => c.type === 'Ready')?.status === 'True',
|
||||
sshHostAlias: pod.status?.podIP || undefined,
|
||||
isDefault: pod.metadata?.labels?.['nemoclaw.ai/default'] === 'true',
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeFromResponse(data: InventoryResponse): SandboxInventoryItem[] {
|
||||
if (Array.isArray(data?.sandboxes)) {
|
||||
return data.sandboxes.map(mapSandboxSummary)
|
||||
}
|
||||
|
||||
return (data?.pods?.items || [])
|
||||
.filter((pod: any) => Boolean(pod?.metadata?.name))
|
||||
.map(mapPodItem)
|
||||
}
|
||||
|
||||
export function useSandboxInventory(options?: { enabled?: boolean; refreshIntervalMs?: number }) {
|
||||
const enabled = options?.enabled ?? true
|
||||
const refreshIntervalMs = options?.refreshIntervalMs ?? 10000
|
||||
const [sandboxes, setSandboxes] = useState<SandboxInventoryItem[]>([])
|
||||
const [nemoclaw, setNemoclaw] = useState<NemoClawSummary | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const inFlightRef = useRef<Promise<SandboxInventoryItem[]> | null>(null)
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (inFlightRef.current) {
|
||||
return inFlightRef.current
|
||||
}
|
||||
|
||||
const run = (async () => {
|
||||
try {
|
||||
const response = await fetch('/api/telemetry/real', { cache: 'no-store' })
|
||||
const data: InventoryResponse & { error?: string } = await response.json()
|
||||
if (!response.ok) throw new Error(data.error || 'Failed to fetch sandbox inventory')
|
||||
|
||||
const nextSandboxes = normalizeFromResponse(data)
|
||||
setSandboxes(nextSandboxes)
|
||||
setNemoclaw(data?.nemoclaw ?? null)
|
||||
setError(null)
|
||||
return nextSandboxes
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to fetch sandbox inventory'
|
||||
setSandboxes([])
|
||||
setNemoclaw(null)
|
||||
setError(message)
|
||||
throw err
|
||||
} finally {
|
||||
setLoading(false)
|
||||
inFlightRef.current = null
|
||||
}
|
||||
})()
|
||||
|
||||
inFlightRef.current = run
|
||||
return run
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
let active = true
|
||||
setLoading(true)
|
||||
refresh().catch(() => {
|
||||
if (!active) return
|
||||
})
|
||||
|
||||
const interval = window.setInterval(() => {
|
||||
refresh().catch(() => {})
|
||||
}, refreshIntervalMs)
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
window.clearInterval(interval)
|
||||
}
|
||||
}, [enabled, refresh, refreshIntervalMs])
|
||||
|
||||
const byId = useMemo(() => {
|
||||
const map = new Map<string, SandboxInventoryItem>()
|
||||
for (const sandbox of sandboxes) map.set(sandbox.id, sandbox)
|
||||
return map
|
||||
}, [sandboxes])
|
||||
|
||||
return {
|
||||
sandboxes,
|
||||
nemoclaw,
|
||||
loading,
|
||||
error,
|
||||
refresh,
|
||||
byId,
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -4,6 +4,10 @@ import "./globals.css"
|
||||
export const metadata: Metadata = {
|
||||
title: "OpenShell/NemoClaw Dashboard",
|
||||
description: "Control plane dashboard for OpenShell and NemoClaw",
|
||||
icons: {
|
||||
icon: "/favicon.ico",
|
||||
shortcut: "/favicon.ico",
|
||||
},
|
||||
}
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -12,8 +16,8 @@ export default function RootLayout({
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<html lang="en" data-theme="dark">
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
const DASHBOARD_SESSION_STORAGE_KEY = 'nemoclaw-dashboard-session-id'
|
||||
export const HYDRATION_SAFE_DASHBOARD_SESSION_ID = 'dashboard-session'
|
||||
|
||||
export interface DashboardSessionState {
|
||||
dashboardSessionId: string
|
||||
selectedSandboxId: string | null
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
function generateDashboardSessionId() {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
|
||||
return `dashboard-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
|
||||
}
|
||||
|
||||
export function createDashboardSessionState(selectedSandboxId: string | null = null): DashboardSessionState {
|
||||
return {
|
||||
dashboardSessionId: generateDashboardSessionId(),
|
||||
selectedSandboxId,
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
export function createHydrationSafeDashboardSessionState(
|
||||
selectedSandboxId: string | null = null
|
||||
): DashboardSessionState {
|
||||
return {
|
||||
dashboardSessionId: HYDRATION_SAFE_DASHBOARD_SESSION_ID,
|
||||
selectedSandboxId,
|
||||
updatedAt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function updateDashboardSessionSelection(
|
||||
session: DashboardSessionState,
|
||||
selectedSandboxId: string | null
|
||||
): DashboardSessionState {
|
||||
return {
|
||||
...session,
|
||||
selectedSandboxId,
|
||||
updatedAt: Date.now(),
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureDashboardSessionId(existingId: string | null | undefined) {
|
||||
return existingId && existingId.trim() ? existingId.trim() : generateDashboardSessionId()
|
||||
}
|
||||
|
||||
export function loadDashboardSessionState(): DashboardSessionState {
|
||||
if (typeof window === 'undefined') {
|
||||
return createHydrationSafeDashboardSessionState()
|
||||
}
|
||||
|
||||
const stored = window.sessionStorage.getItem(DASHBOARD_SESSION_STORAGE_KEY)
|
||||
if (!stored) {
|
||||
return createDashboardSessionState()
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(stored) as Partial<DashboardSessionState>
|
||||
return {
|
||||
dashboardSessionId: ensureDashboardSessionId(parsed.dashboardSessionId),
|
||||
selectedSandboxId: typeof parsed.selectedSandboxId === 'string' ? parsed.selectedSandboxId : null,
|
||||
updatedAt: typeof parsed.updatedAt === 'number' ? parsed.updatedAt : Date.now(),
|
||||
}
|
||||
} catch {
|
||||
return createDashboardSessionState()
|
||||
}
|
||||
}
|
||||
|
||||
export function persistDashboardSessionState(session: DashboardSessionState) {
|
||||
if (typeof window === 'undefined') return
|
||||
window.sessionStorage.setItem(DASHBOARD_SESSION_STORAGE_KEY, JSON.stringify(session))
|
||||
}
|
||||
|
||||
export function buildOperatorTerminalRoute(params: {
|
||||
sandboxId?: string | null
|
||||
dashboardSessionId: string
|
||||
}) {
|
||||
const searchParams = new URLSearchParams()
|
||||
if (params.sandboxId) {
|
||||
searchParams.set('sandboxId', params.sandboxId)
|
||||
}
|
||||
searchParams.set('dashboardSessionId', params.dashboardSessionId)
|
||||
const query = searchParams.toString()
|
||||
return query ? `/operator-terminal?${query}` : '/operator-terminal'
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
export type OpenClawInstanceRecord = {
|
||||
id: string
|
||||
label: string
|
||||
dashboardUrl: string
|
||||
terminalServerUrl?: string | null
|
||||
loopbackOnly: boolean
|
||||
default?: boolean
|
||||
}
|
||||
|
||||
const DEFAULT_OPENCLAW_DASHBOARD_URL = 'http://127.0.0.1:18789/'
|
||||
const DEFAULT_TERMINAL_SERVER_URL = process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011'
|
||||
const DEFAULT_INSTANCE_ID = 'default'
|
||||
|
||||
const DEFAULT_INSTANCE: OpenClawInstanceRecord = {
|
||||
id: DEFAULT_INSTANCE_ID,
|
||||
label: 'Default local OpenClaw',
|
||||
dashboardUrl: process.env.OPENCLAW_DASHBOARD_URL || DEFAULT_OPENCLAW_DASHBOARD_URL,
|
||||
terminalServerUrl: DEFAULT_TERMINAL_SERVER_URL,
|
||||
loopbackOnly: true,
|
||||
default: true,
|
||||
}
|
||||
|
||||
function parseBoolean(value: string | undefined, fallback: boolean) {
|
||||
if (typeof value !== 'string') return fallback
|
||||
const normalized = value.trim().toLowerCase()
|
||||
if (!normalized) return fallback
|
||||
if (['1', 'true', 'yes', 'on'].includes(normalized)) return true
|
||||
if (['0', 'false', 'no', 'off'].includes(normalized)) return false
|
||||
return fallback
|
||||
}
|
||||
|
||||
function parseRegistryFromEnv(): OpenClawInstanceRecord[] {
|
||||
const raw = process.env.OPENCLAW_INSTANCE_REGISTRY_JSON?.trim()
|
||||
if (!raw) return [DEFAULT_INSTANCE]
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return [DEFAULT_INSTANCE]
|
||||
|
||||
const normalized = parsed
|
||||
.map((entry): OpenClawInstanceRecord | null => {
|
||||
if (!entry || typeof entry !== 'object') return null
|
||||
|
||||
const id = typeof entry.id === 'string' && entry.id.trim() ? entry.id.trim() : null
|
||||
const dashboardUrl = typeof entry.dashboardUrl === 'string' && entry.dashboardUrl.trim() ? entry.dashboardUrl.trim() : null
|
||||
if (!id || !dashboardUrl) return null
|
||||
|
||||
return {
|
||||
id,
|
||||
label: typeof entry.label === 'string' && entry.label.trim() ? entry.label.trim() : id,
|
||||
dashboardUrl,
|
||||
terminalServerUrl: typeof entry.terminalServerUrl === 'string' && entry.terminalServerUrl.trim() ? entry.terminalServerUrl.trim() : DEFAULT_TERMINAL_SERVER_URL,
|
||||
loopbackOnly: parseBoolean(typeof entry.loopbackOnly === 'string' ? entry.loopbackOnly : undefined, entry.loopbackOnly ?? true),
|
||||
default: Boolean(entry.default),
|
||||
}
|
||||
})
|
||||
.filter((entry): entry is OpenClawInstanceRecord => Boolean(entry))
|
||||
|
||||
if (normalized.length === 0) return [DEFAULT_INSTANCE]
|
||||
|
||||
const hasDefault = normalized.some((entry) => entry.default || entry.id === DEFAULT_INSTANCE_ID)
|
||||
if (!hasDefault) {
|
||||
normalized.unshift(DEFAULT_INSTANCE)
|
||||
} else if (!normalized.some((entry) => entry.id === DEFAULT_INSTANCE_ID)) {
|
||||
normalized.unshift({ ...DEFAULT_INSTANCE, default: false })
|
||||
}
|
||||
|
||||
return normalized
|
||||
} catch {
|
||||
return [DEFAULT_INSTANCE]
|
||||
}
|
||||
}
|
||||
|
||||
const OPENCLAW_INSTANCE_REGISTRY = parseRegistryFromEnv()
|
||||
const DEFAULT_SANDBOX_INSTANCE_MAP = process.env.MY_ASSISTANT_OPENCLAW_INSTANCE_ID?.trim()
|
||||
? { 'my-assistant': process.env.MY_ASSISTANT_OPENCLAW_INSTANCE_ID.trim() }
|
||||
: { 'my-assistant': DEFAULT_INSTANCE_ID }
|
||||
|
||||
function parseSandboxInstanceMapFromEnv(): Record<string, string> {
|
||||
const raw = process.env.OPENCLAW_SANDBOX_INSTANCE_MAP_JSON?.trim()
|
||||
if (!raw) return DEFAULT_SANDBOX_INSTANCE_MAP
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return DEFAULT_SANDBOX_INSTANCE_MAP
|
||||
}
|
||||
|
||||
const normalized = Object.entries(parsed).reduce<Record<string, string>>((acc, [sandboxId, instanceId]) => {
|
||||
const normalizedSandboxId = typeof sandboxId === 'string' ? sandboxId.trim() : ''
|
||||
const normalizedInstanceId = typeof instanceId === 'string' ? instanceId.trim() : ''
|
||||
if (normalizedSandboxId && normalizedInstanceId) {
|
||||
acc[normalizedSandboxId] = normalizedInstanceId
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
return Object.keys(normalized).length > 0
|
||||
? { ...DEFAULT_SANDBOX_INSTANCE_MAP, ...normalized }
|
||||
: DEFAULT_SANDBOX_INSTANCE_MAP
|
||||
} catch {
|
||||
return DEFAULT_SANDBOX_INSTANCE_MAP
|
||||
}
|
||||
}
|
||||
|
||||
const OPENCLAW_SANDBOX_INSTANCE_MAP = parseSandboxInstanceMapFromEnv()
|
||||
|
||||
export function listOpenClawInstances() {
|
||||
return OPENCLAW_INSTANCE_REGISTRY.map((entry) => ({ ...entry }))
|
||||
}
|
||||
|
||||
export function getDefaultOpenClawInstance() {
|
||||
return OPENCLAW_INSTANCE_REGISTRY.find((entry) => entry.default) || OPENCLAW_INSTANCE_REGISTRY[0] || DEFAULT_INSTANCE
|
||||
}
|
||||
|
||||
export function resolveOpenClawInstance(instanceId?: string | null) {
|
||||
const requested = typeof instanceId === 'string' ? instanceId.trim() : ''
|
||||
if (!requested) return getDefaultOpenClawInstance()
|
||||
return OPENCLAW_INSTANCE_REGISTRY.find((entry) => entry.id === requested) || getDefaultOpenClawInstance()
|
||||
}
|
||||
|
||||
export function getOpenClawInstanceIdForSandbox(sandboxId?: string | null) {
|
||||
const requestedSandboxId = typeof sandboxId === 'string' ? sandboxId.trim() : ''
|
||||
if (!requestedSandboxId) return null
|
||||
return OPENCLAW_SANDBOX_INSTANCE_MAP[requestedSandboxId] || null
|
||||
}
|
||||
|
||||
export function resolveOpenClawInstanceForSandbox(sandboxId?: string | null) {
|
||||
const mappedInstanceId = getOpenClawInstanceIdForSandbox(sandboxId)
|
||||
return mappedInstanceId ? resolveOpenClawInstance(mappedInstanceId) : getDefaultOpenClawInstance()
|
||||
}
|
||||
+404
-121
@@ -1,160 +1,443 @@
|
||||
import { execFile } from 'node:child_process'
|
||||
import type { ExecFileException } from 'node:child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { existsSync } from "node:fs"
|
||||
import { promisify } from "node:util"
|
||||
import { getDefaultOpenClawInstance, resolveOpenClawInstance } from "./openclawInstances"
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const DOCKER_BIN = '/Applications/Docker.app/Contents/Resources/bin/docker'
|
||||
const OPENSHELL_CONTAINER = 'openshell-cluster-openshell'
|
||||
const OPENSHELL_NAMESPACE = 'agent-sandbox-system'
|
||||
const OPENCLAW_DASHBOARD_URL = 'http://127.0.0.1:18789/'
|
||||
const DEFAULT_EXEC_TIMEOUT_MS = 10000
|
||||
const MAX_COMMAND_LENGTH = 400
|
||||
const SANDBOX_ID_PATTERN = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/
|
||||
const OPENSHELL_BIN_CANDIDATES = [
|
||||
process.env.OPENSHELL_BIN,
|
||||
process.env.HOME ? `${process.env.HOME}/.local/bin/openshell` : undefined,
|
||||
"/Users/markmckeen/.local/bin/openshell",
|
||||
"/Users/markmckeen/OpenShell/target/release/openshell",
|
||||
"/Users/markmckeen/openshell/target/release/openshell",
|
||||
"/Users/markmckeen/openshell/scripts/bin/openshell",
|
||||
"/usr/local/bin/openshell",
|
||||
"/opt/homebrew/bin/openshell",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
|
||||
type ExecResult = {
|
||||
stdout: string
|
||||
stderr: string
|
||||
exitCode: number
|
||||
const OPENCLAW_BIN_CANDIDATES = [
|
||||
process.env.OPENCLAW_BIN,
|
||||
process.env.HOME ? `${process.env.HOME}/NemoClaw/node_modules/.bin/openclaw` : undefined,
|
||||
process.env.HOME ? `${process.env.HOME}/.local/bin/openclaw` : undefined,
|
||||
"/usr/local/bin/openclaw",
|
||||
"/opt/homebrew/bin/openclaw",
|
||||
].filter((value): value is string => Boolean(value))
|
||||
|
||||
const OPENSHELL_BIN =
|
||||
OPENSHELL_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? OPENSHELL_BIN_CANDIDATES[0]
|
||||
const OPENCLAW_BIN =
|
||||
OPENCLAW_BIN_CANDIDATES.find((candidate) => existsSync(candidate)) ?? OPENCLAW_BIN_CANDIDATES[0] ?? "openclaw"
|
||||
const OPENSHELL_GATEWAY = process.env.OPENSHELL_GATEWAY || "openshell"
|
||||
const OPENSHELL_NAMESPACE = "agent-sandbox-system"
|
||||
|
||||
export type HostTelemetry = {
|
||||
cpu: number
|
||||
memory: number
|
||||
disk: number
|
||||
gpuMemoryUsed?: number
|
||||
gpuMemoryTotal?: number
|
||||
gpuTemperature?: number
|
||||
timestamp: string
|
||||
source: "macos-host"
|
||||
}
|
||||
|
||||
function normalizeExecError(error: unknown): ExecResult {
|
||||
const execError = error as ExecFileException & { stdout?: string, stderr?: string, code?: number | string | null }
|
||||
type SandboxInspection = {
|
||||
name: string
|
||||
id: string | null
|
||||
namespace: string | null
|
||||
phase: string | null
|
||||
rawPhase: string | null
|
||||
sshHostAlias: string
|
||||
sshConfig: string
|
||||
rawDetails: string
|
||||
}
|
||||
|
||||
export type DashboardProbe = {
|
||||
reachable: boolean
|
||||
status: number | null
|
||||
statusText: string
|
||||
listenerPresent: boolean
|
||||
listenerSummary: string | null
|
||||
bootstrapUrl: string | null
|
||||
bootstrapTokenPresent: boolean
|
||||
bootstrapSource: 'openclaw-cli' | 'static-dashboard-url' | 'unavailable'
|
||||
bootstrapAuthority: 'tokenized-cli' | 'static-fallback' | 'none'
|
||||
}
|
||||
|
||||
export async function execOpenShell(args: string[]) {
|
||||
const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
},
|
||||
})
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
function buildOpenClawEnv() {
|
||||
const pathEntries = [
|
||||
process.env.HOME ? `${process.env.HOME}/NemoClaw/node_modules/.bin` : null,
|
||||
process.env.HOME ? `${process.env.HOME}/.local/bin` : null,
|
||||
process.env.PATH,
|
||||
].filter(Boolean)
|
||||
|
||||
return {
|
||||
stdout: typeof execError?.stdout === 'string' ? execError.stdout : '',
|
||||
stderr: typeof execError?.stderr === 'string' ? execError.stderr : '',
|
||||
exitCode: typeof execError?.code === 'number' ? execError.code : -1,
|
||||
...process.env,
|
||||
PATH: pathEntries.join(":"),
|
||||
NO_COLOR: "1",
|
||||
CLICOLOR: "0",
|
||||
CLICOLOR_FORCE: "0",
|
||||
}
|
||||
}
|
||||
|
||||
export async function dockerExecInOpenShell(command: string, timeoutMs = DEFAULT_EXEC_TIMEOUT_MS): Promise<ExecResult> {
|
||||
async function execOpenClaw(args: string[]) {
|
||||
const { stdout, stderr } = await execFileAsync(OPENCLAW_BIN, args, {
|
||||
env: buildOpenClawEnv(),
|
||||
})
|
||||
return { stdout, stderr }
|
||||
}
|
||||
|
||||
async function execBash(command: string) {
|
||||
const { stdout } = await execFileAsync("/bin/bash", ["-lc", command])
|
||||
return stdout.trim()
|
||||
}
|
||||
|
||||
function clampPercentage(value: number) {
|
||||
if (!Number.isFinite(value)) return 0
|
||||
return Math.max(0, Math.min(100, value))
|
||||
}
|
||||
|
||||
function stripAnsi(value: string) {
|
||||
return value.replace(/\u001b\[[0-9;]*m/g, "")
|
||||
}
|
||||
|
||||
function parseField(output: string, label: string) {
|
||||
const normalizedLabel = label.toLowerCase()
|
||||
const line = output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.find((entry) => entry.toLowerCase().startsWith(`${normalizedLabel}:`))
|
||||
|
||||
return line ? line.slice(label.length + 1).trim() : null
|
||||
}
|
||||
|
||||
function parseSshHostAlias(sshConfig: string, fallbackName: string) {
|
||||
const hostLine = sshConfig
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => entry.trim())
|
||||
.find((entry) => entry.toLowerCase().startsWith("host "))
|
||||
|
||||
const alias = hostLine
|
||||
?.split(/\s+/)
|
||||
.slice(1)
|
||||
.find((entry) => entry !== "*")
|
||||
|
||||
return alias || `openshell-${fallbackName}`
|
||||
}
|
||||
|
||||
function parseOpenShellSandboxNames(output: string) {
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => stripAnsi(entry).trim())
|
||||
.filter((entry) => entry && !/^name\s+/i.test(entry) && !/^[-=]+$/.test(entry))
|
||||
.map((entry) => entry.split(/\s{2,}/)[0]?.trim())
|
||||
.filter((entry): entry is string => Boolean(entry))
|
||||
}
|
||||
|
||||
export async function resolveSandboxRef(ref: string) {
|
||||
const requested = ref.trim()
|
||||
|
||||
try {
|
||||
const { stdout, stderr } = await execFileAsync(
|
||||
DOCKER_BIN,
|
||||
[
|
||||
'exec',
|
||||
OPENSHELL_CONTAINER,
|
||||
'sh',
|
||||
'-lc',
|
||||
command,
|
||||
],
|
||||
{
|
||||
timeout: timeoutMs,
|
||||
maxBuffer: 1024 * 1024,
|
||||
}
|
||||
)
|
||||
return { stdout, stderr, exitCode: 0 }
|
||||
} catch (error) {
|
||||
const normalized = normalizeExecError(error)
|
||||
if (normalized.exitCode !== -1 || normalized.stdout || normalized.stderr) {
|
||||
return normalized
|
||||
const { stdout } = await execOpenShell(["sandbox", "get", requested])
|
||||
return {
|
||||
requested,
|
||||
name: parseField(stdout, "Name") ?? requested,
|
||||
id: parseField(stdout, "Id") ?? requested,
|
||||
details: stdout.trim(),
|
||||
resolvedBy: "direct" as const,
|
||||
}
|
||||
throw error
|
||||
} catch (directError) {
|
||||
const { stdout: sandboxListStdout } = await execOpenShell(["sandbox", "list"])
|
||||
const names = parseOpenShellSandboxNames(sandboxListStdout)
|
||||
|
||||
for (const name of names) {
|
||||
try {
|
||||
const { stdout } = await execOpenShell(["sandbox", "get", name])
|
||||
const sandboxId = parseField(stdout, "Id")
|
||||
const sandboxName = parseField(stdout, "Name") ?? name
|
||||
|
||||
if (requested === sandboxId || requested === sandboxName) {
|
||||
return {
|
||||
requested,
|
||||
name: sandboxName,
|
||||
id: sandboxId ?? sandboxName,
|
||||
details: stdout.trim(),
|
||||
resolvedBy: requested === sandboxName ? ("list-name" as const) : ("list-id" as const),
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore individual sandbox lookup failures while resolving a ref.
|
||||
}
|
||||
}
|
||||
|
||||
throw directError
|
||||
}
|
||||
}
|
||||
|
||||
type SandboxExecPlan = {
|
||||
command: string
|
||||
mode: 'shell' | 'env'
|
||||
export function normalizeSandboxPhase(phase: string | null) {
|
||||
const value = (phase ?? "Unknown").toLowerCase()
|
||||
|
||||
switch (value) {
|
||||
case "ready":
|
||||
return "Running"
|
||||
case "provisioning":
|
||||
return "Pending"
|
||||
case "deleting":
|
||||
return "Stopping"
|
||||
case "error":
|
||||
return "Error"
|
||||
default:
|
||||
return phase ?? "Unknown"
|
||||
}
|
||||
}
|
||||
|
||||
function buildSandboxExecPlans(podName: string, shellCommand: string, options?: { allowEnvFallback?: boolean }): SandboxExecPlan[] {
|
||||
const escaped = quoteForSingleQuotedShell(shellCommand)
|
||||
const attempts: SandboxExecPlan[] = [
|
||||
{
|
||||
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- /bin/sh -lc '${escaped}'`,
|
||||
mode: 'shell',
|
||||
},
|
||||
{
|
||||
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- /busybox/sh -lc '${escaped}'`,
|
||||
mode: 'shell',
|
||||
},
|
||||
]
|
||||
async function readCpuUsage() {
|
||||
const output = await execBash("top -l 1 -n 0 | grep CPU")
|
||||
const match = output.match(/([\d.]+)% idle/)
|
||||
const idle = match ? Number.parseFloat(match[1]) : 0
|
||||
return clampPercentage(100 - idle)
|
||||
}
|
||||
|
||||
if (options?.allowEnvFallback) {
|
||||
attempts.push({
|
||||
command: `kubectl -n ${OPENSHELL_NAMESPACE} exec ${podName} -- env`,
|
||||
mode: 'env',
|
||||
async function readMemoryUsage() {
|
||||
const output = await execBash("vm_stat")
|
||||
const pageSize = Number.parseInt(output.match(/page size of (\d+) bytes/i)?.[1] ?? "4096", 10)
|
||||
const valueFor = (label: string) => {
|
||||
const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
|
||||
const match = output.match(new RegExp(`${escaped}:\\s+(\\d+)\\.?`, "i"))
|
||||
return Number.parseInt(match?.[1] ?? "0", 10)
|
||||
}
|
||||
|
||||
const active = valueFor("Pages active")
|
||||
const wired = valueFor("Pages wired down")
|
||||
const compressed = valueFor("Pages occupied by compressor")
|
||||
const speculative = valueFor("Pages speculative")
|
||||
const inactive = valueFor("Pages inactive")
|
||||
const free = valueFor("Pages free")
|
||||
const totalPages = active + wired + compressed + speculative + inactive + free
|
||||
const usedPages = active + wired + compressed + speculative
|
||||
|
||||
if (totalPages === 0) {
|
||||
return 0
|
||||
}
|
||||
|
||||
return clampPercentage((usedPages * pageSize * 100) / (totalPages * pageSize))
|
||||
}
|
||||
|
||||
async function readDiskUsage() {
|
||||
const output = await execBash("df -k / | tail -1")
|
||||
const columns = output.split(/\s+/)
|
||||
const usedPercent = columns[4]?.replace("%", "") ?? "0"
|
||||
return clampPercentage(Number.parseFloat(usedPercent))
|
||||
}
|
||||
|
||||
async function inspectListeningPort(port: number) {
|
||||
const summary = await execBash(`lsof -nP -iTCP:${port} -sTCP:LISTEN 2>/dev/null || true`)
|
||||
|
||||
return {
|
||||
listenerPresent: summary.length > 0,
|
||||
listenerSummary: summary || null,
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
async function waitForListeningPort(port: number, timeoutMs = 5000) {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
let latest = await inspectListeningPort(port)
|
||||
|
||||
while (!latest.listenerPresent && Date.now() < deadline) {
|
||||
await sleep(250)
|
||||
latest = await inspectListeningPort(port)
|
||||
}
|
||||
|
||||
return latest
|
||||
}
|
||||
|
||||
function normalizeDashboardBootstrapUrl(value: string) {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return null
|
||||
const match = trimmed.match(/https?:\/\/\S+/)
|
||||
return match ? match[0] : null
|
||||
}
|
||||
|
||||
function hasDashboardToken(value: string | null) {
|
||||
if (!value) return false
|
||||
try {
|
||||
const parsed = new URL(value)
|
||||
return parsed.hash.includes('token=') || parsed.searchParams.has('token')
|
||||
} catch {
|
||||
return /[#?&]token=/.test(value)
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveOpenClawDashboardBootstrap(instanceId?: string | null) {
|
||||
const instance = resolveOpenClawInstance(instanceId)
|
||||
const defaultInstance = getDefaultOpenClawInstance()
|
||||
const canMintBootstrapFromCli = instance.id === defaultInstance.id
|
||||
|
||||
if (canMintBootstrapFromCli) {
|
||||
try {
|
||||
const { stdout, stderr } = await execOpenClaw(['dashboard', '--no-open'])
|
||||
const combined = `${stdout}\n${stderr}`
|
||||
const bootstrapUrl = normalizeDashboardBootstrapUrl(combined)
|
||||
const bootstrapTokenPresent = hasDashboardToken(bootstrapUrl)
|
||||
|
||||
if (bootstrapUrl) {
|
||||
return {
|
||||
bootstrapUrl,
|
||||
bootstrapTokenPresent,
|
||||
bootstrapSource: 'openclaw-cli' as const,
|
||||
bootstrapAuthority: bootstrapTokenPresent ? ('tokenized-cli' as const) : ('static-fallback' as const),
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Fall through to configured instance URL when CLI minting is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
const bootstrapTokenPresent = hasDashboardToken(instance.dashboardUrl)
|
||||
return {
|
||||
bootstrapUrl: instance.dashboardUrl,
|
||||
bootstrapTokenPresent,
|
||||
bootstrapSource: instance.dashboardUrl ? ('static-dashboard-url' as const) : ('unavailable' as const),
|
||||
bootstrapAuthority: instance.dashboardUrl
|
||||
? (bootstrapTokenPresent ? ('tokenized-cli' as const) : ('static-fallback' as const))
|
||||
: ('none' as const),
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureOpenClawDashboardListener(instanceId: string, port: number) {
|
||||
const instance = resolveOpenClawInstance(instanceId)
|
||||
const defaultInstance = getDefaultOpenClawInstance()
|
||||
if (instance.id !== defaultInstance.id) return inspectListeningPort(port)
|
||||
|
||||
const initial = await inspectListeningPort(port)
|
||||
if (initial.listenerPresent) return initial
|
||||
|
||||
const child = spawn(OPENCLAW_BIN, ['gateway', 'run', '--allow-unconfigured', '--bind', 'loopback', '--port', String(port)], {
|
||||
detached: true,
|
||||
env: buildOpenClawEnv(),
|
||||
stdio: 'ignore',
|
||||
})
|
||||
child.unref()
|
||||
|
||||
return waitForListeningPort(port)
|
||||
}
|
||||
|
||||
export async function probeOpenClawDashboard(instanceId?: string | null): Promise<DashboardProbe> {
|
||||
const instance = resolveOpenClawInstance(instanceId)
|
||||
const target = new URL(instance.dashboardUrl)
|
||||
const port = Number.parseInt(target.port || (target.protocol === 'https:' ? '443' : '80'), 10)
|
||||
const listener = await ensureOpenClawDashboardListener(instance.id, port)
|
||||
const bootstrap = await resolveOpenClawDashboardBootstrap(instance.id)
|
||||
|
||||
try {
|
||||
const response = await fetch(instance.dashboardUrl, {
|
||||
method: 'GET',
|
||||
cache: 'no-store',
|
||||
headers: {
|
||||
accept: 'text/html,application/json;q=0.9,*/*;q=0.8',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return attempts
|
||||
}
|
||||
|
||||
async function execInSandboxWithFallback(podName: string, shellCommand: string, options?: { allowEnvFallback?: boolean }) {
|
||||
const attempts = buildSandboxExecPlans(podName, shellCommand, options)
|
||||
|
||||
let lastFailure: ({ mode: SandboxExecPlan['mode'] } & ExecResult) | undefined
|
||||
for (const plan of attempts) {
|
||||
const result = await dockerExecInOpenShell(plan.command)
|
||||
if (result.exitCode === 0) {
|
||||
return {
|
||||
...result,
|
||||
mode: plan.mode,
|
||||
}
|
||||
return {
|
||||
reachable: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
listenerPresent: listener.listenerPresent,
|
||||
listenerSummary: listener.listenerSummary,
|
||||
bootstrapUrl: bootstrap.bootstrapUrl,
|
||||
bootstrapTokenPresent: bootstrap.bootstrapTokenPresent,
|
||||
bootstrapSource: bootstrap.bootstrapSource,
|
||||
bootstrapAuthority: bootstrap.bootstrapAuthority,
|
||||
}
|
||||
|
||||
lastFailure = {
|
||||
...result,
|
||||
mode: plan.mode,
|
||||
} catch (error) {
|
||||
return {
|
||||
reachable: false,
|
||||
status: null,
|
||||
statusText: error instanceof Error ? error.message : 'Dashboard probe failed',
|
||||
listenerPresent: listener.listenerPresent,
|
||||
listenerSummary: listener.listenerSummary,
|
||||
bootstrapUrl: bootstrap.bootstrapUrl,
|
||||
bootstrapTokenPresent: bootstrap.bootstrapTokenPresent,
|
||||
bootstrapSource: bootstrap.bootstrapSource,
|
||||
bootstrapAuthority: bootstrap.bootstrapAuthority,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (lastFailure) {
|
||||
return lastFailure
|
||||
export async function readHostTelemetry(): Promise<HostTelemetry> {
|
||||
const [cpu, memory, disk] = await Promise.all([readCpuUsage(), readMemoryUsage(), readDiskUsage()])
|
||||
|
||||
return {
|
||||
cpu,
|
||||
memory,
|
||||
disk,
|
||||
timestamp: new Date().toISOString(),
|
||||
source: "macos-host",
|
||||
}
|
||||
|
||||
throw new Error('Failed to probe sandbox shell')
|
||||
}
|
||||
|
||||
export async function probeSandboxShell(podName: string) {
|
||||
const result = await execInSandboxWithFallback(podName, 'echo OPENSHELL_OK && pwd && whoami', { allowEnvFallback: true })
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(result.stderr.trim() || result.stdout.trim() || `Shell probe failed with exit code ${result.exitCode}`)
|
||||
export async function inspectSandbox(ref: string): Promise<SandboxInspection> {
|
||||
const resolved = await resolveSandboxRef(ref)
|
||||
const [{ stdout: detailsStdout }, { stdout: sshStdout }] = await Promise.all([
|
||||
Promise.resolve({ stdout: resolved.details }),
|
||||
execOpenShell(["sandbox", "ssh-config", resolved.name]),
|
||||
])
|
||||
|
||||
const sshConfig = sshStdout.trim()
|
||||
|
||||
const rawPhase = parseField(detailsStdout, "Phase")
|
||||
|
||||
return {
|
||||
name: parseField(detailsStdout, "Name") ?? resolved.name,
|
||||
id: parseField(detailsStdout, "Id") ?? resolved.id,
|
||||
namespace: parseField(detailsStdout, "Namespace"),
|
||||
phase: normalizeSandboxPhase(rawPhase),
|
||||
rawPhase,
|
||||
sshHostAlias: parseSshHostAlias(sshConfig, resolved.name),
|
||||
sshConfig,
|
||||
rawDetails: detailsStdout.trim(),
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function quoteForSingleQuotedShell(command: string) {
|
||||
return command.replace(/'/g, `'"'"'`)
|
||||
export async function probeSandboxShell(name: string) {
|
||||
return inspectSandbox(name)
|
||||
}
|
||||
|
||||
export function validateSandboxId(sandboxId: string) {
|
||||
const trimmed = sandboxId.trim()
|
||||
export function isOpenShellTransportError(error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error ?? "")
|
||||
const normalized = message.toLowerCase()
|
||||
|
||||
if (!trimmed) {
|
||||
throw new Error('sandboxId is required')
|
||||
}
|
||||
|
||||
if (!SANDBOX_ID_PATTERN.test(trimmed)) {
|
||||
throw new Error('sandboxId must be a valid lowercase DNS-style identifier')
|
||||
}
|
||||
|
||||
return trimmed
|
||||
return (
|
||||
normalized.includes("transport error") ||
|
||||
normalized.includes("connection refused") ||
|
||||
normalized.includes("tcp connect error")
|
||||
)
|
||||
}
|
||||
|
||||
export function validateTerminalCommand(command: string) {
|
||||
const trimmed = command.trim()
|
||||
|
||||
if (!trimmed) {
|
||||
throw new Error('command is required')
|
||||
}
|
||||
|
||||
if (trimmed.length > MAX_COMMAND_LENGTH) {
|
||||
throw new Error(`command exceeds ${MAX_COMMAND_LENGTH} characters`)
|
||||
}
|
||||
|
||||
return trimmed
|
||||
export function getOpenClawDashboardUrl(instanceId?: string | null) {
|
||||
return resolveOpenClawInstance(instanceId).dashboardUrl
|
||||
}
|
||||
|
||||
export async function runSandboxCommand(podName: string, command: string) {
|
||||
const trimmed = validateTerminalCommand(command)
|
||||
|
||||
return await execInSandboxWithFallback(podName, trimmed)
|
||||
export function getDefaultOpenClawDashboardInstanceId() {
|
||||
return getDefaultOpenClawInstance().id
|
||||
}
|
||||
|
||||
export function getOpenClawDashboardUrl() {
|
||||
return OPENCLAW_DASHBOARD_URL
|
||||
}
|
||||
|
||||
export { DEFAULT_EXEC_TIMEOUT_MS, DOCKER_BIN, MAX_COMMAND_LENGTH, OPENSHELL_CONTAINER, OPENSHELL_NAMESPACE }
|
||||
export { OPENSHELL_BIN, OPENSHELL_GATEWAY, OPENSHELL_NAMESPACE }
|
||||
export { OPENCLAW_BIN }
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { getDefaultOpenClawInstance, getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, type OpenClawInstanceRecord } from './openclawInstances'
|
||||
|
||||
export type RuntimeAuthorityResolution = {
|
||||
requestedSandboxId: string | null
|
||||
resolvedSandboxId: string | null
|
||||
sandboxAuthority: 'host' | 'sandbox'
|
||||
authorityMode: 'direct-host' | 'bridged-sandbox-map' | 'bridged-instance-override'
|
||||
provenance: 'default-instance' | 'sandbox-instance-map' | 'explicit-instance'
|
||||
bridgeActive: boolean
|
||||
bridgeReason: string | null
|
||||
openclaw: OpenClawInstanceRecord
|
||||
mappedSandboxInstanceId: string | null
|
||||
usedMappedSandboxInstance: boolean
|
||||
requestedInstanceId: string | null
|
||||
explicitInstanceOverride: boolean
|
||||
terminalServerUrl: string | null
|
||||
}
|
||||
|
||||
function normalizeId(value: string | null | undefined) {
|
||||
if (typeof value !== 'string') return null
|
||||
const trimmed = value.trim()
|
||||
return trimmed || null
|
||||
}
|
||||
|
||||
export function resolveRuntimeAuthority(params?: {
|
||||
sandboxId?: string | null
|
||||
resolvedSandboxId?: string | null
|
||||
instanceId?: string | null
|
||||
}): RuntimeAuthorityResolution {
|
||||
const requestedSandboxId = normalizeId(params?.sandboxId)
|
||||
const resolvedSandboxId = normalizeId(params?.resolvedSandboxId) ?? requestedSandboxId
|
||||
const requestedInstanceId = normalizeId(params?.instanceId)
|
||||
const sandboxAuthority: RuntimeAuthorityResolution['sandboxAuthority'] = resolvedSandboxId ? 'sandbox' : 'host'
|
||||
const mappedSandboxInstanceId = getOpenClawInstanceIdForSandbox(resolvedSandboxId)
|
||||
const explicitInstanceOverride = Boolean(requestedInstanceId)
|
||||
const openclaw = requestedInstanceId
|
||||
? resolveOpenClawInstance(requestedInstanceId)
|
||||
: mappedSandboxInstanceId
|
||||
? resolveOpenClawInstance(mappedSandboxInstanceId)
|
||||
: getDefaultOpenClawInstance()
|
||||
const usedMappedSandboxInstance = Boolean(!requestedInstanceId && mappedSandboxInstanceId)
|
||||
const bridgeActive = Boolean(requestedInstanceId || usedMappedSandboxInstance)
|
||||
const authorityMode: RuntimeAuthorityResolution['authorityMode'] = requestedInstanceId
|
||||
? 'bridged-instance-override'
|
||||
: usedMappedSandboxInstance
|
||||
? 'bridged-sandbox-map'
|
||||
: 'direct-host'
|
||||
const provenance: RuntimeAuthorityResolution['provenance'] = requestedInstanceId
|
||||
? 'explicit-instance'
|
||||
: usedMappedSandboxInstance
|
||||
? 'sandbox-instance-map'
|
||||
: 'default-instance'
|
||||
const bridgeReason = requestedInstanceId
|
||||
? 'Explicit instance override selected a bridged OpenClaw upstream for this dashboard action.'
|
||||
: usedMappedSandboxInstance
|
||||
? 'Sandbox-to-instance mapping selected a bridged OpenClaw upstream for this sandbox context.'
|
||||
: null
|
||||
|
||||
return {
|
||||
requestedSandboxId,
|
||||
resolvedSandboxId,
|
||||
sandboxAuthority,
|
||||
authorityMode,
|
||||
provenance,
|
||||
bridgeActive,
|
||||
bridgeReason,
|
||||
openclaw,
|
||||
mappedSandboxInstanceId,
|
||||
usedMappedSandboxInstance,
|
||||
requestedInstanceId,
|
||||
explicitInstanceOverride,
|
||||
terminalServerUrl: openclaw.terminalServerUrl || null,
|
||||
}
|
||||
}
|
||||
+85
-277
@@ -1,9 +1,10 @@
|
||||
"use client"
|
||||
|
||||
import Link from 'next/link'
|
||||
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import 'xterm/css/xterm.css'
|
||||
import { ensureDashboardSessionId, HYDRATION_SAFE_DASHBOARD_SESSION_ID } from '../lib/dashboardSession'
|
||||
|
||||
interface ReadinessPodSummary {
|
||||
containers?: string[]
|
||||
@@ -41,25 +42,30 @@ interface ReadinessResponse {
|
||||
interface LiveTerminalSession {
|
||||
sessionId: string
|
||||
sandboxId: string
|
||||
dashboardSessionId: string
|
||||
replay?: string
|
||||
websocketUrl: string
|
||||
sshHostAlias?: string
|
||||
}
|
||||
|
||||
type XTermModule = typeof import('xterm')
|
||||
type FitAddonModule = typeof import('xterm-addon-fit')
|
||||
type XTermInstance = InstanceType<XTermModule['Terminal']>
|
||||
type FitAddonInstance = InstanceType<FitAddonModule['FitAddon']>
|
||||
|
||||
type LoadState = 'idle' | 'loading' | 'ready' | 'error'
|
||||
|
||||
const defaultAlias = (sandboxId: string | null) => `ssh openshell-${sandboxId || 'my-assistant'}`
|
||||
const defaultFallback = (sandboxId: string | null) => `ssh -i ~/.ssh/id_ed25519_openclaw_labmac openshell-${sandboxId || 'my-assistant'}`
|
||||
const defaultLoginShell = (sandboxId: string | null) => `env PATH=/opt/homebrew/bin:$PATH zsh -l -c 'ssh openshell-${sandboxId || 'my-assistant'}'`
|
||||
const DEFAULT_SHELL_HINT = 'If your non-interactive shell misses Homebrew tooling, retry from a login shell or prepend PATH=/opt/homebrew/bin:$PATH before ssh.'
|
||||
const defaultFallback = (sandboxId: string | null) => `ssh openshell-${sandboxId || 'my-assistant'}`
|
||||
const defaultLoginShell = (sandboxId: string | null) => `env PATH=$HOME/.local/bin:$PATH bash -l -c 'ssh openshell-${sandboxId || 'my-assistant'}'`
|
||||
const DEFAULT_SHELL_HINT = 'If your non-interactive shell misses local tooling, retry from a login shell or prepend PATH=$HOME/.local/bin:$PATH before ssh.'
|
||||
|
||||
export default function OperatorTerminalPage() {
|
||||
function OperatorTerminalInner() {
|
||||
const searchParams = useSearchParams()
|
||||
const sandboxId = searchParams.get('sandboxId')
|
||||
const requestedDashboardSessionId = searchParams.get('dashboardSessionId')
|
||||
const [dashboardSessionId, setDashboardSessionId] = useState(
|
||||
() => requestedDashboardSessionId?.trim() || HYDRATION_SAFE_DASHBOARD_SESSION_ID
|
||||
)
|
||||
const [state, setState] = useState<LoadState>(sandboxId ? 'loading' : 'idle')
|
||||
const [data, setData] = useState<ReadinessResponse | null>(null)
|
||||
const [lastCheckedAt, setLastCheckedAt] = useState<string | null>(null)
|
||||
@@ -73,6 +79,10 @@ export default function OperatorTerminalPage() {
|
||||
const fitAddonRef = useRef<FitAddonInstance | null>(null)
|
||||
const socketRef = useRef<WebSocket | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
setDashboardSessionId(ensureDashboardSessionId(requestedDashboardSessionId))
|
||||
}, [requestedDashboardSessionId])
|
||||
|
||||
const refreshReadiness = useCallback(async () => {
|
||||
if (!sandboxId) {
|
||||
setState('idle')
|
||||
@@ -84,43 +94,29 @@ export default function OperatorTerminalPage() {
|
||||
setCopyMessage('')
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/openshell/terminal/readiness?sandboxId=${encodeURIComponent(sandboxId)}`, {
|
||||
cache: 'no-store',
|
||||
})
|
||||
const response = await fetch(`/api/openshell/terminal/readiness?sandboxId=${encodeURIComponent(sandboxId)}`, { cache: 'no-store' })
|
||||
const result: ReadinessResponse = await response.json()
|
||||
setData(result)
|
||||
setState(response.ok && result.ok ? 'ready' : 'error')
|
||||
setLastCheckedAt(new Date().toLocaleTimeString())
|
||||
} catch (error) {
|
||||
setData({
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to inspect sandbox readiness.',
|
||||
})
|
||||
setData({ ok: false, error: error instanceof Error ? error.message : 'Failed to inspect sandbox readiness.' })
|
||||
setState('error')
|
||||
setLastCheckedAt(new Date().toLocaleTimeString())
|
||||
}
|
||||
}, [sandboxId])
|
||||
|
||||
const ensureLiveSession = useCallback(async () => {
|
||||
if (!sandboxId) {
|
||||
setLiveSession(null)
|
||||
setTerminalState('idle')
|
||||
return
|
||||
}
|
||||
|
||||
setTerminalState('connecting')
|
||||
setTerminalStatus('Initializing live PTY session…')
|
||||
setTerminalStatus(sandboxId
|
||||
? `Initializing live terminal session for ${sandboxId}…`
|
||||
: 'Initializing host-mode live terminal session…')
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/openshell/terminal/live', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sandboxId,
|
||||
sessionId: liveSession?.sessionId,
|
||||
}),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sandboxId, sessionId: liveSession?.sessionId, dashboardSessionId }),
|
||||
})
|
||||
const result = await response.json()
|
||||
if (!response.ok || !result.ok) {
|
||||
@@ -129,50 +125,34 @@ export default function OperatorTerminalPage() {
|
||||
setLiveSession({
|
||||
sessionId: result.sessionId,
|
||||
sandboxId: result.sandboxId,
|
||||
dashboardSessionId: result.dashboardSessionId || dashboardSessionId,
|
||||
replay: result.replay,
|
||||
websocketUrl: result.websocketUrl,
|
||||
sshHostAlias: result.sshHostAlias,
|
||||
})
|
||||
} catch (error) {
|
||||
setTerminalState('error')
|
||||
setTerminalStatus(error instanceof Error ? error.message : 'Failed to initialize live terminal session.')
|
||||
}
|
||||
}, [sandboxId, liveSession?.sessionId])
|
||||
}, [dashboardSessionId, sandboxId, liveSession?.sessionId])
|
||||
|
||||
useEffect(() => { refreshReadiness() }, [refreshReadiness])
|
||||
useEffect(() => { ensureLiveSession() }, [ensureLiveSession])
|
||||
|
||||
useEffect(() => {
|
||||
refreshReadiness()
|
||||
}, [refreshReadiness])
|
||||
|
||||
useEffect(() => {
|
||||
ensureLiveSession()
|
||||
}, [ensureLiveSession])
|
||||
|
||||
useEffect(() => {
|
||||
if (!terminalContainerRef.current || terminalRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!terminalContainerRef.current || terminalRef.current) return
|
||||
let disposed = false
|
||||
let cleanupResize: (() => void) | null = null
|
||||
|
||||
;(async () => {
|
||||
const [{ Terminal }, { FitAddon }] = await Promise.all([
|
||||
import('xterm'),
|
||||
import('xterm-addon-fit'),
|
||||
])
|
||||
|
||||
if (disposed || !terminalContainerRef.current) {
|
||||
return
|
||||
}
|
||||
const [{ Terminal }, { FitAddon }] = await Promise.all([import('xterm'), import('xterm-addon-fit')])
|
||||
if (disposed || !terminalContainerRef.current) return
|
||||
|
||||
const term = new Terminal({
|
||||
cursorBlink: true,
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
|
||||
fontSize: 13,
|
||||
theme: {
|
||||
background: '#000000',
|
||||
foreground: '#f5f5f5',
|
||||
cursor: '#76b900',
|
||||
},
|
||||
theme: { background: '#000000', foreground: '#f5f5f5', cursor: '#76b900' },
|
||||
scrollback: 5000,
|
||||
allowTransparency: false,
|
||||
})
|
||||
@@ -180,23 +160,24 @@ export default function OperatorTerminalPage() {
|
||||
term.loadAddon(fitAddon)
|
||||
term.open(terminalContainerRef.current)
|
||||
fitAddon.fit()
|
||||
|
||||
term.focus()
|
||||
terminalRef.current = term
|
||||
fitAddonRef.current = fitAddon
|
||||
|
||||
const focusTerminal = () => term.focus()
|
||||
terminalContainerRef.current.addEventListener('click', focusTerminal)
|
||||
|
||||
const handleResize = () => {
|
||||
fitAddon.fit()
|
||||
if (socketRef.current?.readyState === WebSocket.OPEN) {
|
||||
socketRef.current.send(JSON.stringify({
|
||||
type: 'resize',
|
||||
cols: term.cols,
|
||||
rows: term.rows,
|
||||
}))
|
||||
socketRef.current.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('resize', handleResize)
|
||||
cleanupResize = () => window.removeEventListener('resize', handleResize)
|
||||
cleanupResize = () => {
|
||||
window.removeEventListener('resize', handleResize)
|
||||
terminalContainerRef.current?.removeEventListener('click', focusTerminal)
|
||||
}
|
||||
})().catch((error) => {
|
||||
setTerminalState('error')
|
||||
setTerminalStatus(error instanceof Error ? error.message : 'Failed to load terminal renderer.')
|
||||
@@ -213,46 +194,31 @@ export default function OperatorTerminalPage() {
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!liveSession?.websocketUrl || !terminalRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!liveSession?.websocketUrl || !terminalRef.current) return
|
||||
const term = terminalRef.current
|
||||
term.reset()
|
||||
if (liveSession.replay) {
|
||||
term.write(liveSession.replay)
|
||||
}
|
||||
if (liveSession.replay) term.write(liveSession.replay)
|
||||
|
||||
const socket = new WebSocket(liveSession.websocketUrl)
|
||||
socketRef.current = socket
|
||||
|
||||
const inputDisposable = term.onData((data) => {
|
||||
if (socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'input', data }))
|
||||
}
|
||||
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: 'input', data }))
|
||||
})
|
||||
|
||||
socket.addEventListener('open', () => {
|
||||
setTerminalState('connected')
|
||||
setTerminalStatus(`Live PTY connected for ${liveSession.sandboxId}.`)
|
||||
if (fitAddonRef.current) {
|
||||
fitAddonRef.current.fit()
|
||||
}
|
||||
socket.send(JSON.stringify({
|
||||
type: 'resize',
|
||||
cols: term.cols,
|
||||
rows: term.rows,
|
||||
}))
|
||||
setTerminalStatus(`Live terminal connected for ${liveSession.sandboxId} in dashboard session ${liveSession.dashboardSessionId.slice(0, 8)}.`)
|
||||
fitAddonRef.current?.fit()
|
||||
term.focus()
|
||||
socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
||||
})
|
||||
|
||||
socket.addEventListener('message', (event) => {
|
||||
try {
|
||||
const message = JSON.parse(event.data)
|
||||
if (message.type === 'ready') {
|
||||
if (message.replay) {
|
||||
term.reset()
|
||||
term.write(message.replay)
|
||||
}
|
||||
if (message.type === 'ready' && message.replay) {
|
||||
term.reset()
|
||||
term.write(message.replay)
|
||||
} else if (message.type === 'data' && typeof message.data === 'string') {
|
||||
term.write(message.data)
|
||||
} else if (message.type === 'exit') {
|
||||
@@ -277,67 +243,22 @@ export default function OperatorTerminalPage() {
|
||||
return () => {
|
||||
inputDisposable.dispose()
|
||||
socket.close()
|
||||
if (socketRef.current === socket) {
|
||||
socketRef.current = null
|
||||
}
|
||||
if (socketRef.current === socket) socketRef.current = null
|
||||
}
|
||||
}, [liveSession])
|
||||
|
||||
const readiness = useMemo(() => {
|
||||
if (!sandboxId) {
|
||||
return {
|
||||
tone: 'border-[var(--status-pending)] text-[var(--status-pending)]',
|
||||
label: 'NO SANDBOX SELECTED',
|
||||
detail: 'Return to the dashboard and choose a sandbox before opening Operator Terminal.',
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'loading') {
|
||||
return {
|
||||
tone: 'border-[var(--status-pending)] text-[var(--status-pending)]',
|
||||
label: 'CHECKING READINESS',
|
||||
detail: 'Verifying pod metadata and bounded shell reachability so the page can report terminal truth in one pass.',
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'ready' && data?.ok && data?.podReady && data?.sshReachable) {
|
||||
return {
|
||||
tone: 'border-[var(--status-running)] text-[var(--status-running)]',
|
||||
label: 'LIVE TERMINAL PATH VERIFIED',
|
||||
detail: 'The backend confirmed pod readiness and shell reachability, and the dashboard is now wired for a live PTY transport.',
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'ready' && data?.ok && data?.podExists && data?.degraded) {
|
||||
return {
|
||||
tone: 'border-[var(--status-pending)] text-[var(--status-pending)]',
|
||||
label: 'DEGRADED: POD UP, SHELL UNCONFIRMED',
|
||||
detail: 'The pod exists, but the readiness probe did not fully succeed. The live terminal may still connect, but direct SSH remains the stronger fallback.',
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'ready' && data?.ok && data?.podExists) {
|
||||
return {
|
||||
tone: 'border-[var(--status-running)] text-[var(--status-running)]',
|
||||
label: 'READY FOR LIVE TERMINAL',
|
||||
detail: 'Pod metadata is present and the dashboard live terminal can attempt a real PTY session.',
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
tone: 'border-[var(--status-stopped)] text-[var(--status-stopped)]',
|
||||
label: 'READINESS CHECK FAILED',
|
||||
detail: 'The dashboard could not confirm pod metadata or shell reachability. Use the recovery commands below, then retry.',
|
||||
}
|
||||
if (!sandboxId) return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'HOST MODE', detail: 'No sandbox query was provided. The dashboard terminal stays in host mode and keeps dashboard-session diagnostics for reconnect behavior.' }
|
||||
if (state === 'loading') return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'CHECKING READINESS', detail: 'Verifying pod metadata and shell reachability.' }
|
||||
if (state === 'ready' && data?.ok && data?.podReady && data?.sshReachable) return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', label: 'LIVE TERMINAL PATH VERIFIED', detail: 'The backend confirmed pod readiness and shell reachability, and the dashboard is wired for a live terminal transport.' }
|
||||
if (state === 'ready' && data?.ok && data?.podExists && data?.degraded) return { tone: 'border-[var(--status-pending)] text-[var(--status-pending)]', label: 'DEGRADED: POD UP, SHELL UNCONFIRMED', detail: 'The pod exists, but the readiness probe did not fully succeed. The live terminal may still connect, but direct SSH remains the stronger fallback.' }
|
||||
if (state === 'ready' && data?.ok && data?.podExists) return { tone: 'border-[var(--status-running)] text-[var(--status-running)]', label: 'READY FOR LIVE TERMINAL', detail: 'Pod metadata is present and the dashboard live terminal can attempt a real shell session.' }
|
||||
return { tone: 'border-[var(--status-stopped)] text-[var(--status-stopped)]', label: 'READINESS CHECK FAILED', detail: 'The dashboard could not confirm pod metadata or shell reachability. Use the recovery commands below, then retry.' }
|
||||
}, [sandboxId, state, data])
|
||||
|
||||
const copyCommand = useCallback(async (command: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(command)
|
||||
setCopyMessage(`Copied: ${command}`)
|
||||
} catch {
|
||||
setCopyMessage(`Copy failed. Use: ${command}`)
|
||||
}
|
||||
try { await navigator.clipboard.writeText(command); setCopyMessage(`Copied: ${command}`) }
|
||||
catch { setCopyMessage(`Copy failed. Use: ${command}`) }
|
||||
}, [])
|
||||
|
||||
const aliasCommand = data?.attach?.aliasCommand || defaultAlias(sandboxId)
|
||||
@@ -352,169 +273,56 @@ export default function OperatorTerminalPage() {
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-[0.25em] text-[var(--foreground-dim)] font-mono">Operator path</p>
|
||||
<h1 className="text-2xl font-semibold uppercase tracking-wider mt-2">Operator Terminal</h1>
|
||||
<p className="text-sm text-[var(--foreground-dim)] mt-3 max-w-3xl">
|
||||
Real live terminal surface for the selected sandbox. Browser keys flow into a PTY-backed shell process and output streams back live into the dashboard.
|
||||
</p>
|
||||
<p className="text-sm text-[var(--foreground-dim)] mt-3 max-w-3xl">{sandboxId ? 'Live operator terminal for the selected sandbox, brokered through the dashboard-owned terminal bridge.' : 'Live operator terminal for host mode, brokered through the dashboard-owned terminal bridge.'}</p>
|
||||
<p className="text-[11px] text-[var(--foreground-dim)] font-mono mt-2">Dashboard session {dashboardSessionId.slice(0, 8)}</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/"
|
||||
className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]"
|
||||
>
|
||||
Back to Dashboard
|
||||
</Link>
|
||||
<Link href="/" className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Back to Dashboard</Link>
|
||||
</div>
|
||||
|
||||
<section className={`panel p-6 border-2 ${readiness.tone}`}>
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Sandbox</p>
|
||||
<h2 className="text-lg font-semibold mt-1">{sandboxId || 'UNSELECTED'}</h2>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Status</p>
|
||||
<p className="text-sm font-mono mt-1">{readiness.label}</p>
|
||||
{lastCheckedAt && <p className="text-[10px] mt-1 opacity-80">Last checked {lastCheckedAt}</p>}
|
||||
</div>
|
||||
<div><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Sandbox</p><h2 className="text-lg font-semibold mt-1">{sandboxId || 'HOST'}</h2></div>
|
||||
<div><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Dashboard Session</p><h2 className="text-lg font-semibold mt-1">{dashboardSessionId.slice(0, 8)}</h2></div>
|
||||
<div className="text-right"><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Status</p><p className="text-sm font-mono mt-1">{readiness.label}</p>{lastCheckedAt && <p className="text-[10px] mt-1 opacity-80">Last checked {lastCheckedAt}</p>}</div>
|
||||
</div>
|
||||
<p className="text-sm mt-4 text-[var(--foreground)]">{readiness.detail}</p>
|
||||
</section>
|
||||
|
||||
<section className="panel p-6 space-y-4">
|
||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold uppercase tracking-wider">Live Dashboard Terminal</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
xterm-backed live terminal. Supports typed input, streamed output, resize, and session reconnect.
|
||||
</p>
|
||||
</div>
|
||||
<div><h3 className="text-sm font-semibold uppercase tracking-wider">Live Dashboard Terminal</h3><p className="text-xs text-[var(--foreground-dim)] mt-2">Browser terminal backed by the dashboard terminal server.</p></div>
|
||||
<div className="text-[11px] text-[var(--foreground-dim)] font-mono">{terminalStatus}</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-black p-3">
|
||||
<div ref={terminalContainerRef} className="h-[520px] w-full" />
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-black p-3"><div ref={terminalContainerRef} className="h-[520px] w-full" /></div>
|
||||
<div className="flex items-center gap-3 flex-wrap">
|
||||
<button
|
||||
onClick={ensureLiveSession}
|
||||
disabled={!sandboxId || terminalState === 'connecting'}
|
||||
className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{terminalState === 'connecting' ? 'Connecting…' : 'Reconnect Live Terminal'}
|
||||
</button>
|
||||
<button
|
||||
onClick={refreshReadiness}
|
||||
className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
|
||||
>
|
||||
Refresh Readiness
|
||||
</button>
|
||||
<span className="text-[11px] text-[var(--foreground-dim)] font-mono">
|
||||
{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}
|
||||
</span>
|
||||
<button onClick={ensureLiveSession} disabled={terminalState === 'connecting'} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">{terminalState === 'connecting' ? 'Connecting…' : 'Reconnect Live Terminal'}</button>
|
||||
<button onClick={refreshReadiness} disabled={!sandboxId} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">Refresh Readiness</button>
|
||||
<span className="text-[11px] text-[var(--foreground-dim)] font-mono">{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 xl:grid-cols-[1.1fr_0.9fr] gap-6">
|
||||
<div className="panel p-6 space-y-5">
|
||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold uppercase tracking-wider">Direct Attach Fallbacks</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
If the live dashboard terminal is degraded, these remain the authoritative escape hatches.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div><h3 className="text-sm font-semibold uppercase tracking-wider">Direct Attach Fallbacks</h3><p className="text-xs text-[var(--foreground-dim)] mt-2">If the live dashboard terminal is degraded, these remain the authoritative escape hatches.</p></div>
|
||||
<div className="space-y-3">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Preferred attach command</p>
|
||||
<code className="block mt-2 text-sm font-mono text-[var(--nvidia-green)] break-all">{aliasCommand}</code>
|
||||
<button
|
||||
onClick={() => copyCommand(aliasCommand)}
|
||||
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
|
||||
>
|
||||
Copy Alias Command
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Preferred attach command</p><code className="block mt-2 text-sm font-mono text-[var(--nvidia-green)] break-all">{aliasCommand}</code><button onClick={() => copyCommand(aliasCommand)} className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">Copy Alias Command</button></div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Fallback if alias or agent config is missing</p>
|
||||
<code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{fallbackCommand}</code>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">{shellHint}</p>
|
||||
<button
|
||||
onClick={() => copyCommand(fallbackCommand)}
|
||||
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
|
||||
>
|
||||
Copy Fallback Command
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Login-shell retry for Homebrew/path issues</p>
|
||||
<code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{loginShellCommand}</code>
|
||||
<button
|
||||
onClick={() => copyCommand(loginShellCommand)}
|
||||
className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]"
|
||||
>
|
||||
Copy Login-Shell Retry
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{copyMessage && (
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">
|
||||
{copyMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="panel p-6 space-y-5">
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold uppercase tracking-wider">Readiness Evidence</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
Live pod introspection and bounded shell evidence from the backend.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 text-sm">
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Pod phase / ready</p>
|
||||
<p className="mt-2 font-mono break-words">{data?.pod?.phase || 'Unknown'} / {data?.pod?.readyCondition || 'Unknown'}</p>
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Containers</p>
|
||||
<p className="mt-2 font-mono break-words">{data?.pod?.containers?.length ? data.pod.containers.join(', ') : 'Unavailable'}</p>
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Images</p>
|
||||
<p className="mt-2 font-mono break-words">{data?.pod?.images?.length ? data.pod.images.join(', ') : 'Unavailable'}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
|
||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||
<div>
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Shell probe</p>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">Readiness-side shell evidence.</p>
|
||||
</div>
|
||||
<div className="text-[11px] text-[var(--foreground-dim)] font-mono">
|
||||
{data?.shellProbe?.ok ? 'Probe passed' : 'Probe not confirmed'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Probe stdout</p>
|
||||
<pre className="mt-2 text-xs whitespace-pre-wrap break-words font-mono text-[var(--foreground)] min-h-16">{data?.shellProbe?.output || 'No backend shell output captured yet.'}</pre>
|
||||
</div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3">
|
||||
<p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Probe stderr / status</p>
|
||||
<pre className="mt-2 text-xs whitespace-pre-wrap break-words font-mono text-[var(--foreground)] min-h-16">{data?.shellProbe?.error || data?.shellProbe?.stderr || data?.note || 'No stderr.'}</pre>
|
||||
<div><p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Fallback if alias or agent config is missing</p><code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{fallbackCommand}</code><p className="text-xs text-[var(--foreground-dim)] mt-2">{shellHint}</p><button onClick={() => copyCommand(fallbackCommand)} className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">Copy Fallback Command</button></div>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] p-3"><p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Login-shell retry for Homebrew/path issues</p><code className="block mt-2 text-sm font-mono text-[var(--foreground)] break-all">{loginShellCommand}</code><button onClick={() => copyCommand(loginShellCommand)} className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">Copy Login-Shell Retry</button></div>
|
||||
</div>
|
||||
</div>
|
||||
{copyMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{copyMessage}</div>}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
export default function OperatorTerminalPage() {
|
||||
return (
|
||||
<Suspense fallback={<main className="min-h-screen bg-[var(--background)] text-[var(--foreground)] p-8"><div className="mx-auto max-w-6xl"><div className="panel p-6">Loading operator terminal…</div></div></main>}>
|
||||
<OperatorTerminalInner />
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
+96
-21
@@ -1,19 +1,47 @@
|
||||
"use client"
|
||||
import { useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import Sidebar from './components/Sidebar'
|
||||
import SandboxList from './components/SandboxList'
|
||||
import ConfigurationPanel from './components/ConfigurationPanel'
|
||||
import { useSandboxInventory } from './hooks/useSandboxInventory'
|
||||
import {
|
||||
createHydrationSafeDashboardSessionState,
|
||||
loadDashboardSessionState,
|
||||
persistDashboardSessionState,
|
||||
updateDashboardSessionSelection,
|
||||
} from './lib/dashboardSession'
|
||||
|
||||
export default function Dashboard() {
|
||||
const [theme, setTheme] = useState<'light' | 'dark'>('dark')
|
||||
const [isSubmenuOpen, setIsSubmenuOpen] = useState(false)
|
||||
const [hostIP] = useState('192.168.50.173')
|
||||
const [selectedSandbox, setSelectedSandbox] = useState<string | null>(null)
|
||||
const [dashboardSession, setDashboardSession] = useState(() => createHydrationSafeDashboardSessionState())
|
||||
const [isCreateMode, setIsCreateMode] = useState(false)
|
||||
const [isDestroyMode, setIsDestroyMode] = useState(false)
|
||||
const [activeView, setActiveView] = useState<'overview' | 'settings' | 'sandboxes'>('sandboxes')
|
||||
const [deletingSandboxId, setDeletingSandboxId] = useState<string | null>(null)
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
|
||||
const inventoryEnabled = isSubmenuOpen || activeView === 'sandboxes' || isCreateMode || isDestroyMode
|
||||
const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({
|
||||
enabled: inventoryEnabled,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
setDashboardSession(loadDashboardSessionState())
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
persistDashboardSessionState(dashboardSession)
|
||||
}, [dashboardSession])
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme
|
||||
}, [theme])
|
||||
|
||||
const selectedSandbox = useMemo(
|
||||
() => sandboxes.find((sandbox) => sandbox.id === dashboardSession.selectedSandboxId) ?? null,
|
||||
[sandboxes, dashboardSession.selectedSandboxId]
|
||||
)
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme(theme === 'light' ? 'dark' : 'light')
|
||||
@@ -24,12 +52,25 @@ export default function Dashboard() {
|
||||
setDeletingSandboxId(id)
|
||||
setShowDeleteConfirm(true)
|
||||
} else {
|
||||
setSelectedSandbox(id)
|
||||
setDashboardSession((current) => updateDashboardSessionSelection(current, id))
|
||||
}
|
||||
}
|
||||
|
||||
const clearSelection = () => {
|
||||
setDashboardSession((current) => updateDashboardSessionSelection(current, null))
|
||||
}
|
||||
|
||||
const handleCreateSuccess = async (createdSandboxId: string) => {
|
||||
setIsCreateMode(false)
|
||||
setIsDestroyMode(false)
|
||||
setActiveView('sandboxes')
|
||||
setIsSubmenuOpen(true)
|
||||
const latest = await refresh()
|
||||
const created = latest.find((sandbox) => sandbox.id === createdSandboxId || sandbox.name === createdSandboxId)
|
||||
setDashboardSession((current) => updateDashboardSessionSelection(current, created?.id ?? createdSandboxId))
|
||||
}
|
||||
|
||||
const confirmDelete = () => {
|
||||
// TODO: Call destroy sandbox API
|
||||
console.log('Destroying sandbox:', deletingSandboxId)
|
||||
setShowDeleteConfirm(false)
|
||||
setDeletingSandboxId(null)
|
||||
@@ -49,10 +90,12 @@ export default function Dashboard() {
|
||||
: 'bg-[var(--background)] text-[var(--foreground)]'
|
||||
}`}
|
||||
>
|
||||
{/* Sidebar */}
|
||||
<Sidebar
|
||||
hostIP={hostIP}
|
||||
selectedSandbox={selectedSandbox}
|
||||
sandboxes={sandboxes}
|
||||
nemoclaw={nemoclaw}
|
||||
dashboardSessionId={dashboardSession.dashboardSessionId}
|
||||
selectedSandboxId={dashboardSession.selectedSandboxId}
|
||||
onSandboxSelect={handleSandboxSelect}
|
||||
isSubmenuOpen={isSubmenuOpen}
|
||||
onToggleSubmenu={() => {
|
||||
@@ -67,7 +110,7 @@ export default function Dashboard() {
|
||||
setActiveView('sandboxes')
|
||||
setIsCreateMode(true)
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
setIsSubmenuOpen(true)
|
||||
}}
|
||||
onDestroyClick={() => {
|
||||
@@ -80,24 +123,23 @@ export default function Dashboard() {
|
||||
setActiveView('overview')
|
||||
setIsCreateMode(false)
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
setIsSubmenuOpen(false)
|
||||
}}
|
||||
onSettingsClick={() => {
|
||||
setActiveView('settings')
|
||||
setIsCreateMode(false)
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
setIsSubmenuOpen(false)
|
||||
}}
|
||||
onExitMode={() => {
|
||||
setIsCreateMode(false)
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="ml-64 transition-all duration-300">
|
||||
<div className={isSubmenuOpen ? 'ml-72' : ''}>
|
||||
<div className="p-8">
|
||||
@@ -145,8 +187,11 @@ export default function Dashboard() {
|
||||
<p className="text-sm text-[var(--foreground-dim)] mb-6">
|
||||
Global defaults and preset-driven policy controls for this dashboard instance.
|
||||
</p>
|
||||
<p className="text-[11px] text-[var(--foreground-dim)] font-mono">
|
||||
Dashboard session {dashboardSession.dashboardSessionId.slice(0, 8)}
|
||||
</p>
|
||||
</div>
|
||||
<ConfigurationPanel sandboxId="global-settings" mode="create" />
|
||||
<ConfigurationPanel sandboxId="global-settings" mode="create" onCreateSuccess={handleCreateSuccess} onInventoryRefresh={refresh} />
|
||||
</div>
|
||||
) : isCreateMode ? (
|
||||
<div className="space-y-6">
|
||||
@@ -158,7 +203,7 @@ export default function Dashboard() {
|
||||
Start from a named security preset, then refine the OpenShell policy before creating the sandbox.
|
||||
</p>
|
||||
</div>
|
||||
<ConfigurationPanel sandboxId="new-sandbox" mode="create" />
|
||||
<ConfigurationPanel sandboxId="new-sandbox" mode="create" onCreateSuccess={handleCreateSuccess} onInventoryRefresh={refresh} />
|
||||
</div>
|
||||
) : isDestroyMode ? (
|
||||
<div className="panel p-8 border-2 border-[var(--status-stopped)]">
|
||||
@@ -172,7 +217,7 @@ export default function Dashboard() {
|
||||
<button
|
||||
onClick={() => {
|
||||
setIsDestroyMode(false)
|
||||
setSelectedSandbox(null)
|
||||
clearSelection()
|
||||
}}
|
||||
className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]"
|
||||
>
|
||||
@@ -190,6 +235,9 @@ export default function Dashboard() {
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-1">
|
||||
Real-time OpenShell sandbox monitoring
|
||||
</p>
|
||||
<p className="text-[11px] text-[var(--foreground-dim)] font-mono mt-2">
|
||||
Dashboard session {dashboardSession.dashboardSessionId.slice(0, 8)}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={toggleTheme}
|
||||
@@ -199,18 +247,45 @@ export default function Dashboard() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<SandboxList
|
||||
selectedSandbox={selectedSandbox}
|
||||
onSandboxSelect={handleSandboxSelect}
|
||||
isDestroyMode={isDestroyMode}
|
||||
/>
|
||||
{inventoryEnabled && loading ? (
|
||||
<div className="flex items-center justify-center h-64" data-testid="inventory-loading-state">
|
||||
<div className="text-xs text-[var(--foreground-dim)] font-mono uppercase tracking-wider">
|
||||
INITIALIZING...
|
||||
</div>
|
||||
</div>
|
||||
) : inventoryEnabled && error ? (
|
||||
<div className="panel p-8 text-center" data-testid="inventory-error-state">
|
||||
<h3 className="text-sm font-semibold text-[var(--status-stopped)] uppercase tracking-wider">Inventory Unavailable</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2 font-mono">{error}</p>
|
||||
</div>
|
||||
) : sandboxes.length === 0 ? (
|
||||
<div className="panel p-8 text-center" data-testid="inventory-empty-state">
|
||||
<svg className="w-12 h-12 mx-auto mb-4 text-[var(--foreground-dim)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={1.5} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
|
||||
</svg>
|
||||
<h3 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">No Sandboxes Detected</h3>
|
||||
<p className="text-xs text-[var(--foreground-dim)] mt-2">
|
||||
No live OpenShell sandboxes reported yet
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<SandboxList
|
||||
sandboxes={sandboxes}
|
||||
nemoclaw={nemoclaw}
|
||||
dashboardSessionId={dashboardSession.dashboardSessionId}
|
||||
selectedSandboxId={dashboardSession.selectedSandboxId}
|
||||
selectedSandbox={selectedSandbox}
|
||||
onSandboxSelect={handleSandboxSelect}
|
||||
isDestroyMode={isDestroyMode}
|
||||
onInventoryRefresh={refresh}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{/* Delete Confirmation Overlay */}
|
||||
{showDeleteConfirm && (
|
||||
<div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50">
|
||||
<div className="panel p-8 max-w-md border-2 border-[var(--status-stopped)]">
|
||||
@@ -244,4 +319,4 @@ export default function Dashboard() {
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -3,9 +3,10 @@
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"dev": "node server.mjs",
|
||||
"dev:proxy": "node server.mjs",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"start": "node server.mjs",
|
||||
"lint": "next lint",
|
||||
"terminal-server": "node terminal-server.mjs"
|
||||
},
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 67 B |
+418
@@ -0,0 +1,418 @@
|
||||
import http from 'node:http'
|
||||
import crypto from 'node:crypto'
|
||||
import next from 'next'
|
||||
import { WebSocketServer, WebSocket } from 'ws'
|
||||
|
||||
const dev = process.env.NODE_ENV !== 'production'
|
||||
const hostname = process.env.HOSTNAME || process.env.HOST || '0.0.0.0'
|
||||
const port = Number(process.env.PORT || 3000)
|
||||
const terminalServerUrl = new URL(process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011')
|
||||
const terminalWsProtocol = terminalServerUrl.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const terminalProxyPath = '/api/openshell/terminal/live/ws'
|
||||
const legacyDashboardProxyPrefix = '/api/openshell/dashboard/proxy'
|
||||
const instancesProxyPrefix = '/api/openshell/instances/'
|
||||
const dashboardProxySuffix = '/dashboard/proxy'
|
||||
const defaultDashboardUrl = process.env.OPENCLAW_DASHBOARD_URL || 'http://127.0.0.1:18789/'
|
||||
const defaultInstanceId = 'default'
|
||||
|
||||
function now() {
|
||||
return new Date().toISOString()
|
||||
}
|
||||
|
||||
function logBridge(event, fields = {}) {
|
||||
const payload = Object.entries(fields)
|
||||
.filter(([, value]) => value !== undefined && value !== null && value !== '')
|
||||
.map(([key, value]) => `${key}=${JSON.stringify(value)}`)
|
||||
.join(' ')
|
||||
console.log(`[terminal-bridge] ts=${now()} event=${event}${payload ? ` ${payload}` : ''}`)
|
||||
}
|
||||
|
||||
function buildTerminalUpstreamUrl(req) {
|
||||
const incoming = new URL(req.url || '/', `http://${req.headers.host || `${hostname}:${port}`}`)
|
||||
const upstream = new URL('/ws', `${terminalWsProtocol}//${terminalServerUrl.host}`)
|
||||
incoming.searchParams.forEach((value, key) => upstream.searchParams.append(key, value))
|
||||
return upstream
|
||||
}
|
||||
|
||||
function copyHeaders(req) {
|
||||
const headers = {}
|
||||
for (const [key, value] of Object.entries(req.headers)) {
|
||||
if (typeof value === 'undefined') continue
|
||||
if (['connection', 'host', 'sec-websocket-key', 'sec-websocket-version', 'upgrade'].includes(key.toLowerCase())) continue
|
||||
headers[key] = Array.isArray(value) ? value.join(', ') : value
|
||||
}
|
||||
return headers
|
||||
}
|
||||
|
||||
function parseBoolean(value, fallback) {
|
||||
if (typeof value !== 'string') return fallback
|
||||
const normalized = value.trim().toLowerCase()
|
||||
if (!normalized) return fallback
|
||||
if (['1', 'true', 'yes', 'on'].includes(normalized)) return true
|
||||
if (['0', 'false', 'no', 'off'].includes(normalized)) return false
|
||||
return fallback
|
||||
}
|
||||
|
||||
function defaultOpenClawInstance() {
|
||||
return {
|
||||
id: defaultInstanceId,
|
||||
label: 'Default local OpenClaw',
|
||||
dashboardUrl: defaultDashboardUrl,
|
||||
terminalServerUrl: process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011',
|
||||
loopbackOnly: true,
|
||||
default: true,
|
||||
}
|
||||
}
|
||||
|
||||
function parseOpenClawInstanceRegistry() {
|
||||
const fallback = [defaultOpenClawInstance()]
|
||||
const raw = process.env.OPENCLAW_INSTANCE_REGISTRY_JSON?.trim()
|
||||
if (!raw) return fallback
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return fallback
|
||||
|
||||
const normalized = parsed
|
||||
.map((entry) => {
|
||||
if (!entry || typeof entry !== 'object') return null
|
||||
const id = typeof entry.id === 'string' && entry.id.trim() ? entry.id.trim() : null
|
||||
const dashboardUrl = typeof entry.dashboardUrl === 'string' && entry.dashboardUrl.trim() ? entry.dashboardUrl.trim() : null
|
||||
if (!id || !dashboardUrl) return null
|
||||
|
||||
return {
|
||||
id,
|
||||
label: typeof entry.label === 'string' && entry.label.trim() ? entry.label.trim() : id,
|
||||
dashboardUrl,
|
||||
terminalServerUrl: typeof entry.terminalServerUrl === 'string' && entry.terminalServerUrl.trim()
|
||||
? entry.terminalServerUrl.trim()
|
||||
: process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011',
|
||||
loopbackOnly: parseBoolean(typeof entry.loopbackOnly === 'string' ? entry.loopbackOnly : undefined, entry.loopbackOnly ?? true),
|
||||
default: Boolean(entry.default),
|
||||
}
|
||||
})
|
||||
.filter(Boolean)
|
||||
|
||||
if (normalized.length === 0) return fallback
|
||||
if (!normalized.some((entry) => entry.id === defaultInstanceId)) {
|
||||
normalized.unshift({ ...defaultOpenClawInstance(), default: normalized.some((entry) => entry.default) ? false : true })
|
||||
}
|
||||
return normalized
|
||||
} catch {
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
function parseSandboxInstanceMap() {
|
||||
const defaultMap = process.env.MY_ASSISTANT_OPENCLAW_INSTANCE_ID?.trim()
|
||||
? { 'my-assistant': process.env.MY_ASSISTANT_OPENCLAW_INSTANCE_ID.trim() }
|
||||
: { 'my-assistant': defaultInstanceId }
|
||||
const raw = process.env.OPENCLAW_SANDBOX_INSTANCE_MAP_JSON?.trim()
|
||||
if (!raw) return defaultMap
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return defaultMap
|
||||
const normalized = Object.entries(parsed).reduce((acc, [sandboxId, instanceId]) => {
|
||||
const normalizedSandboxId = typeof sandboxId === 'string' ? sandboxId.trim() : ''
|
||||
const normalizedInstanceId = typeof instanceId === 'string' ? instanceId.trim() : ''
|
||||
if (normalizedSandboxId && normalizedInstanceId) acc[normalizedSandboxId] = normalizedInstanceId
|
||||
return acc
|
||||
}, {})
|
||||
return Object.keys(normalized).length > 0 ? { ...defaultMap, ...normalized } : defaultMap
|
||||
} catch {
|
||||
return defaultMap
|
||||
}
|
||||
}
|
||||
|
||||
const openClawInstances = parseOpenClawInstanceRegistry()
|
||||
const openClawSandboxInstanceMap = parseSandboxInstanceMap()
|
||||
|
||||
function getDefaultOpenClawInstance() {
|
||||
return openClawInstances.find((entry) => entry.default) || openClawInstances[0] || defaultOpenClawInstance()
|
||||
}
|
||||
|
||||
function resolveOpenClawInstance(instanceId) {
|
||||
const requested = typeof instanceId === 'string' ? instanceId.trim() : ''
|
||||
if (!requested) return getDefaultOpenClawInstance()
|
||||
return openClawInstances.find((entry) => entry.id === requested) || getDefaultOpenClawInstance()
|
||||
}
|
||||
|
||||
function getMappedOpenClawInstanceId(sandboxId) {
|
||||
const requested = typeof sandboxId === 'string' ? sandboxId.trim() : ''
|
||||
return requested ? openClawSandboxInstanceMap[requested] || null : null
|
||||
}
|
||||
|
||||
function resolveDashboardUpstream(req) {
|
||||
const incoming = new URL(req.url || '/', `http://${req.headers.host || `${hostname}:${port}`}`)
|
||||
const { pathname, searchParams } = incoming
|
||||
|
||||
let requestedInstanceId = null
|
||||
let proxyPrefix = legacyDashboardProxyPrefix
|
||||
|
||||
if (pathname.startsWith(instancesProxyPrefix)) {
|
||||
const suffixIndex = pathname.indexOf(dashboardProxySuffix, instancesProxyPrefix.length)
|
||||
if (suffixIndex !== -1) {
|
||||
requestedInstanceId = decodeURIComponent(pathname.slice(instancesProxyPrefix.length, suffixIndex))
|
||||
proxyPrefix = `/api/openshell/instances/${encodeURIComponent(requestedInstanceId)}/dashboard/proxy`
|
||||
}
|
||||
}
|
||||
|
||||
const sandboxId = searchParams.get('sandboxId')
|
||||
const mappedInstanceId = getMappedOpenClawInstanceId(sandboxId)
|
||||
const resolvedInstance = resolveOpenClawInstance(requestedInstanceId || mappedInstanceId)
|
||||
const upstreamHttpUrl = new URL(pathname.startsWith(proxyPrefix) ? pathname.slice(proxyPrefix.length) || '/' : '/', resolvedInstance.dashboardUrl)
|
||||
incoming.searchParams.forEach((value, key) => {
|
||||
if (key !== 'path' && key !== 'bootstrapUrl') upstreamHttpUrl.searchParams.append(key, value)
|
||||
})
|
||||
const upstreamWsUrl = new URL(upstreamHttpUrl.toString())
|
||||
upstreamWsUrl.protocol = upstreamWsUrl.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
|
||||
return {
|
||||
proxyPrefix,
|
||||
upstreamWsUrl,
|
||||
instanceId: resolvedInstance.id,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCloseCode(code) {
|
||||
return typeof code === 'number' && Number.isInteger(code) && code >= 1000 && code <= 4999 && code !== 1005 && code !== 1006 && code !== 1015
|
||||
? code
|
||||
: 1000
|
||||
}
|
||||
|
||||
const app = next({ dev, hostname, port })
|
||||
const handle = app.getRequestHandler()
|
||||
const handleUpgrade = typeof app.getUpgradeHandler === 'function'
|
||||
? app.getUpgradeHandler()
|
||||
: null
|
||||
|
||||
await app.prepare()
|
||||
|
||||
const server = http.createServer((req, res) => handle(req, res))
|
||||
const clientWss = new WebSocketServer({ noServer: true })
|
||||
const dashboardWss = new WebSocketServer({ noServer: true })
|
||||
|
||||
clientWss.on('connection', (client, req) => {
|
||||
const bridgeId = crypto.randomUUID()
|
||||
const upstreamUrl = buildTerminalUpstreamUrl(req)
|
||||
const upstream = new WebSocket(upstreamUrl, { headers: copyHeaders(req) })
|
||||
const pendingClientFrames = []
|
||||
let closing = false
|
||||
let clientFramesIn = 0
|
||||
let upstreamFramesOut = 0
|
||||
let upstreamFramesIn = 0
|
||||
let clientFramesOut = 0
|
||||
|
||||
logBridge('client-connected', {
|
||||
bridgeId,
|
||||
path: req.url || '/',
|
||||
upstreamUrl: upstreamUrl.toString(),
|
||||
remoteAddress: req.socket.remoteAddress || 'unknown',
|
||||
})
|
||||
|
||||
const flushPendingFrames = () => {
|
||||
while (pendingClientFrames.length && upstream.readyState === WebSocket.OPEN) {
|
||||
const frame = pendingClientFrames.shift()
|
||||
upstreamFramesOut += 1
|
||||
upstream.send(frame.data, { binary: frame.isBinary })
|
||||
}
|
||||
logBridge('upstream-open', {
|
||||
bridgeId,
|
||||
bufferedFramesFlushed: upstreamFramesOut,
|
||||
pendingFrames: pendingClientFrames.length,
|
||||
})
|
||||
}
|
||||
|
||||
const closeClient = (code = 1000, reason) => {
|
||||
const safeCode = normalizeCloseCode(code)
|
||||
if (client.readyState === WebSocket.OPEN) client.close(safeCode, reason)
|
||||
else if (client.readyState === WebSocket.CONNECTING) client.terminate()
|
||||
}
|
||||
|
||||
const closeUpstream = (code = 1000, reason) => {
|
||||
const safeCode = normalizeCloseCode(code)
|
||||
if (upstream.readyState === WebSocket.OPEN) upstream.close(safeCode, reason)
|
||||
else if (upstream.readyState === WebSocket.CONNECTING) upstream.terminate()
|
||||
}
|
||||
|
||||
const closeBoth = (code = 1000, reason, source = 'unknown') => {
|
||||
if (closing) return
|
||||
closing = true
|
||||
logBridge('bridge-closing', {
|
||||
bridgeId,
|
||||
source,
|
||||
code,
|
||||
reason,
|
||||
clientFramesIn,
|
||||
upstreamFramesOut,
|
||||
upstreamFramesIn,
|
||||
clientFramesOut,
|
||||
pendingFrames: pendingClientFrames.length,
|
||||
})
|
||||
closeClient(code, reason)
|
||||
closeUpstream(code, reason)
|
||||
}
|
||||
|
||||
client.on('message', (data, isBinary) => {
|
||||
clientFramesIn += 1
|
||||
if (upstream.readyState === WebSocket.OPEN) {
|
||||
upstreamFramesOut += 1
|
||||
upstream.send(data, { binary: isBinary })
|
||||
return
|
||||
}
|
||||
|
||||
if (upstream.readyState === WebSocket.CONNECTING) {
|
||||
pendingClientFrames.push({ data, isBinary })
|
||||
return
|
||||
}
|
||||
|
||||
closeBoth(1011, 'upstream unavailable', 'client-message-no-upstream')
|
||||
})
|
||||
|
||||
client.on('close', (code, reasonBuffer) => {
|
||||
const reason = Buffer.isBuffer(reasonBuffer) ? reasonBuffer.toString() : String(reasonBuffer || '')
|
||||
closeBoth(code || 1000, reason || undefined, 'client-close')
|
||||
})
|
||||
client.on('error', (error) => closeBoth(1011, error instanceof Error ? error.message : 'client error', 'client-error'))
|
||||
|
||||
upstream.on('open', () => {
|
||||
flushPendingFrames()
|
||||
})
|
||||
|
||||
upstream.on('message', (data, isBinary) => {
|
||||
upstreamFramesIn += 1
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
clientFramesOut += 1
|
||||
client.send(data, { binary: isBinary })
|
||||
}
|
||||
})
|
||||
|
||||
upstream.on('close', (code, reasonBuffer) => {
|
||||
const reason = Buffer.isBuffer(reasonBuffer) ? reasonBuffer.toString() : String(reasonBuffer || '')
|
||||
closeBoth(code || 1000, reason || undefined, 'upstream-close')
|
||||
})
|
||||
|
||||
upstream.on('error', (error) => {
|
||||
closeBoth(1011, error instanceof Error ? error.message : 'upstream error', 'upstream-error')
|
||||
})
|
||||
})
|
||||
|
||||
dashboardWss.on('connection', (client, req) => {
|
||||
const { upstreamWsUrl, instanceId } = resolveDashboardUpstream(req)
|
||||
const upstream = new WebSocket(upstreamWsUrl, { headers: copyHeaders(req) })
|
||||
const pendingClientFrames = []
|
||||
let closing = false
|
||||
|
||||
logBridge('dashboard-client-connected', {
|
||||
path: req.url || '/',
|
||||
upstreamUrl: upstreamWsUrl.toString(),
|
||||
instanceId,
|
||||
remoteAddress: req.socket.remoteAddress || 'unknown',
|
||||
})
|
||||
|
||||
const closeBoth = (code = 1000, reason, source = 'dashboard-unknown') => {
|
||||
if (closing) return
|
||||
closing = true
|
||||
logBridge('dashboard-bridge-closing', {
|
||||
path: req.url || '/',
|
||||
upstreamUrl: upstreamWsUrl.toString(),
|
||||
instanceId,
|
||||
source,
|
||||
code: normalizeCloseCode(code),
|
||||
reason,
|
||||
})
|
||||
const safeCode = normalizeCloseCode(code)
|
||||
if (client.readyState === WebSocket.OPEN) client.close(safeCode, reason)
|
||||
else if (client.readyState === WebSocket.CONNECTING) client.terminate()
|
||||
if (upstream.readyState === WebSocket.OPEN) upstream.close(safeCode, reason)
|
||||
else if (upstream.readyState === WebSocket.CONNECTING) upstream.terminate()
|
||||
}
|
||||
|
||||
client.on('message', (data, isBinary) => {
|
||||
if (upstream.readyState === WebSocket.OPEN) {
|
||||
upstream.send(data, { binary: isBinary })
|
||||
} else if (upstream.readyState === WebSocket.CONNECTING) {
|
||||
pendingClientFrames.push({ data, isBinary })
|
||||
}
|
||||
})
|
||||
client.on('close', (code, reasonBuffer) => {
|
||||
const reason = Buffer.isBuffer(reasonBuffer) ? reasonBuffer.toString() : String(reasonBuffer || '')
|
||||
closeBoth(code || 1000, reason || undefined, 'dashboard-client-close')
|
||||
})
|
||||
client.on('error', (error) => closeBoth(1011, error instanceof Error ? error.message : 'dashboard client error', 'dashboard-client-error'))
|
||||
|
||||
upstream.on('open', () => {
|
||||
while (pendingClientFrames.length && upstream.readyState === WebSocket.OPEN) {
|
||||
const frame = pendingClientFrames.shift()
|
||||
upstream.send(frame.data, { binary: frame.isBinary })
|
||||
}
|
||||
logBridge('dashboard-upstream-open', {
|
||||
path: req.url || '/',
|
||||
upstreamUrl: upstreamWsUrl.toString(),
|
||||
instanceId,
|
||||
bufferedFramesFlushed: pendingClientFrames.length,
|
||||
})
|
||||
})
|
||||
upstream.on('message', (data, isBinary) => {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(data, { binary: isBinary })
|
||||
}
|
||||
})
|
||||
upstream.on('close', (code, reasonBuffer) => {
|
||||
const reason = Buffer.isBuffer(reasonBuffer) ? reasonBuffer.toString() : String(reasonBuffer || '')
|
||||
closeBoth(code || 1000, reason || undefined, 'dashboard-upstream-close')
|
||||
})
|
||||
upstream.on('error', (error) => closeBoth(1011, error instanceof Error ? error.message : 'dashboard upstream error', 'dashboard-upstream-error'))
|
||||
})
|
||||
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
if ((req.url || '').startsWith(terminalProxyPath)) {
|
||||
logBridge('upgrade-accepted', {
|
||||
path: req.url || '/',
|
||||
remoteAddress: req.socket.remoteAddress || 'unknown',
|
||||
})
|
||||
clientWss.handleUpgrade(req, socket, head, (ws) => {
|
||||
clientWss.emit('connection', ws, req)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
|
||||
(req.url || '').startsWith(instancesProxyPrefix)
|
||||
) {
|
||||
const { upstreamWsUrl, instanceId } = resolveDashboardUpstream(req)
|
||||
logBridge('dashboard-upgrade-accepted', {
|
||||
path: req.url || '/',
|
||||
upstreamUrl: upstreamWsUrl.toString(),
|
||||
instanceId,
|
||||
remoteAddress: req.socket.remoteAddress || 'unknown',
|
||||
})
|
||||
|
||||
dashboardWss.handleUpgrade(req, socket, head, (ws) => {
|
||||
dashboardWss.emit('connection', ws, req)
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
logBridge('upgrade-rejected', {
|
||||
path: req.url || '/',
|
||||
remoteAddress: req.socket.remoteAddress || 'unknown',
|
||||
})
|
||||
if (handleUpgrade) {
|
||||
handleUpgrade(req, socket, head)
|
||||
return
|
||||
}
|
||||
socket.destroy()
|
||||
})
|
||||
|
||||
server.listen(port, hostname, () => {
|
||||
console.log(`dashboard server listening on http://${hostname}:${port}`)
|
||||
logBridge('server-listening', {
|
||||
hostname,
|
||||
port,
|
||||
terminalServerUrl: terminalServerUrl.toString(),
|
||||
soleOwnerPath: terminalProxyPath,
|
||||
})
|
||||
})
|
||||
+289
-55
@@ -1,85 +1,299 @@
|
||||
import http from 'node:http'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { WebSocketServer } from 'ws'
|
||||
import pty from 'node-pty'
|
||||
|
||||
const PORT = Number(process.env.TERMINAL_SERVER_PORT || 3011)
|
||||
const HOST = process.env.TERMINAL_SERVER_HOST || '127.0.0.1'
|
||||
const MAX_SESSIONS = 24
|
||||
const BUFFER_LIMIT = 200000
|
||||
const INITIAL_CLEANUP_LIMIT = 16384
|
||||
const sessions = new Map()
|
||||
|
||||
const runtime = await resolveRuntime()
|
||||
|
||||
function trimSessions() {
|
||||
if (sessions.size <= MAX_SESSIONS) return
|
||||
const oldest = [...sessions.values()].sort((a, b) => a.updatedAt - b.updatedAt)[0]
|
||||
if (!oldest) return
|
||||
oldest.pty.kill()
|
||||
oldest.transport.kill()
|
||||
sessions.delete(oldest.id)
|
||||
}
|
||||
|
||||
async function resolveRuntime() {
|
||||
const preferred = (process.env.TERMINAL_TRANSPORT || 'auto').trim().toLowerCase()
|
||||
if (preferred === 'stream') return { mode: 'stream' }
|
||||
|
||||
if (preferred === 'pty' || preferred === 'auto') {
|
||||
try {
|
||||
const mod = await import('node-pty')
|
||||
return { mode: 'pty', nodePty: mod.default || mod }
|
||||
} catch (error) {
|
||||
if (preferred === 'pty' || process.platform === 'darwin') {
|
||||
throw new Error(`TERMINAL_TRANSPORT=${preferred} but node-pty is unavailable on ${process.platform}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { mode: 'stream' }
|
||||
}
|
||||
|
||||
function shellCandidatesForPlatform() {
|
||||
const candidates = [
|
||||
process.env.TERMINAL_SHELL,
|
||||
process.env.SHELL,
|
||||
process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash',
|
||||
'/bin/sh',
|
||||
].filter(Boolean)
|
||||
|
||||
return [...new Set(candidates)]
|
||||
}
|
||||
|
||||
function shellForPlatform() {
|
||||
return process.env.SHELL || '/bin/bash'
|
||||
for (const candidate of shellCandidatesForPlatform()) {
|
||||
if (typeof candidate === 'string' && candidate.startsWith('/') && existsSync(candidate)) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
for (const candidate of shellCandidatesForPlatform()) {
|
||||
if (typeof candidate === 'string' && candidate.trim()) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
|
||||
return process.platform === 'darwin' ? '/bin/zsh' : '/bin/bash'
|
||||
}
|
||||
|
||||
function buildAttachCommand(sandboxId) {
|
||||
const alias = `openshell-${sandboxId}`
|
||||
return process.env.OPENSHELL_TERMINAL_ATTACH_TEMPLATE || `ssh ${alias}`
|
||||
function homebrewBinPrefix() {
|
||||
return process.platform === 'darwin' ? ['/opt/homebrew/bin', '/usr/local/bin'] : ['/usr/local/bin']
|
||||
}
|
||||
|
||||
function buildBootstrapShell(sandboxId) {
|
||||
const attachCommand = buildAttachCommand(sandboxId)
|
||||
function effectivePath() {
|
||||
return [
|
||||
`export OPENSHELL_SANDBOX_ID=${shellEscape(sandboxId)}`,
|
||||
`export PS1='[${sandboxId}] \\u@\\h:\\w\\$ '`,
|
||||
`echo '[openclaw] attaching to ${sandboxId} using: ${attachCommand}'`,
|
||||
`exec ${attachCommand}`,
|
||||
].join('; ')
|
||||
process.env.TERMINAL_EXTRA_PATH,
|
||||
...homebrewBinPrefix(),
|
||||
process.env.HOME ? `${process.env.HOME}/.local/bin` : '',
|
||||
'/usr/bin',
|
||||
'/bin',
|
||||
'/usr/sbin',
|
||||
'/sbin',
|
||||
process.env.PATH || '',
|
||||
].filter(Boolean).join(':')
|
||||
}
|
||||
|
||||
function shellEscape(value) {
|
||||
return `'${String(value).replace(/'/g, `'"'"'`)}'`
|
||||
}
|
||||
|
||||
function createSession(sandboxId) {
|
||||
trimSessions()
|
||||
const id = randomUUID()
|
||||
function openshellBin() {
|
||||
return process.env.OPENSHELL_BIN || 'openshell'
|
||||
}
|
||||
|
||||
function buildAttachCommand(sandboxId) {
|
||||
if (process.env.OPENSHELL_TERMINAL_ATTACH_TEMPLATE) {
|
||||
const alias = `openshell-${sandboxId}`
|
||||
return process.env.OPENSHELL_TERMINAL_ATTACH_TEMPLATE.replaceAll('{sandboxId}', sandboxId).replaceAll('{alias}', alias)
|
||||
}
|
||||
return shellForPlatform()
|
||||
}
|
||||
|
||||
function buildBootstrapShell(sandboxId) {
|
||||
return [
|
||||
`export PATH=${shellEscape(effectivePath())}`,
|
||||
`export OPENSHELL_SANDBOX_ID=${shellEscape(sandboxId)}`,
|
||||
`export PS1='[operator:${sandboxId || 'host'}] \\u@\\h:\\w\\$ '`,
|
||||
`exec ${shellForPlatform()} -i`,
|
||||
].join('; ')
|
||||
}
|
||||
|
||||
function stripNullBytes(value) {
|
||||
return value.replace(/\u0000/g, '')
|
||||
}
|
||||
|
||||
function stripOscSequences(value) {
|
||||
return value.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, '')
|
||||
}
|
||||
|
||||
function stripCsiSequences(value) {
|
||||
return value.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '')
|
||||
}
|
||||
|
||||
function stripOtherEscapeSequences(value) {
|
||||
return value.replace(/\u001b[@-_]/g, '')
|
||||
}
|
||||
|
||||
function normalizeLineEndings(value) {
|
||||
return value.replace(/\r\n?/g, '\n')
|
||||
}
|
||||
|
||||
function cleanInitialBurst(value) {
|
||||
return normalizeLineEndings(
|
||||
stripOtherEscapeSequences(
|
||||
stripCsiSequences(
|
||||
stripOscSequences(
|
||||
stripNullBytes(value)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
function sanitizeChunkForClient(session, data) {
|
||||
const text = typeof data === 'string' ? data : String(data ?? '')
|
||||
if (!text) return ''
|
||||
|
||||
if (!session.initialStreamSettled) {
|
||||
session.initialBytesSeen += text.length
|
||||
const cleaned = cleanInitialBurst(text)
|
||||
const hasReadableText = /[A-Za-z0-9_$>#:%~\-]/.test(cleaned)
|
||||
const hasLineBreak = cleaned.includes('\n')
|
||||
|
||||
if (hasReadableText && hasLineBreak) {
|
||||
session.initialStreamSettled = true
|
||||
session.clientReady = true
|
||||
return cleaned
|
||||
}
|
||||
|
||||
if (session.initialBytesSeen >= INITIAL_CLEANUP_LIMIT) {
|
||||
session.initialStreamSettled = true
|
||||
session.clientReady = true
|
||||
return cleaned
|
||||
}
|
||||
|
||||
return cleaned.trim() ? cleaned : ''
|
||||
}
|
||||
|
||||
return stripNullBytes(text)
|
||||
}
|
||||
|
||||
function appendBuffer(session, data) {
|
||||
const sanitized = sanitizeChunkForClient(session, data)
|
||||
if (!sanitized) return
|
||||
|
||||
session.updatedAt = Date.now()
|
||||
session.buffer += sanitized
|
||||
if (session.buffer.length > BUFFER_LIMIT) {
|
||||
session.buffer = session.buffer.slice(-BUFFER_LIMIT)
|
||||
}
|
||||
for (const socket of session.sockets) {
|
||||
if (socket.readyState === socket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'data', data: sanitized }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createPtyTransport(sandboxId) {
|
||||
const shell = shellForPlatform()
|
||||
const bootstrap = buildBootstrapShell(sandboxId)
|
||||
const proc = pty.spawn(shell, ['-lc', bootstrap], {
|
||||
name: 'xterm-256color',
|
||||
cols: 120,
|
||||
rows: 34,
|
||||
const ptyEnv = {
|
||||
...process.env,
|
||||
PATH: effectivePath(),
|
||||
OPENSHELL_SANDBOX_ID: sandboxId,
|
||||
SHELL: shell,
|
||||
}
|
||||
const requestedCwd = process.env.TERMINAL_CWD || process.env.HOME || process.cwd()
|
||||
const spawnCwd = requestedCwd && existsSync(requestedCwd) ? requestedCwd : process.cwd()
|
||||
|
||||
let proc
|
||||
try {
|
||||
proc = runtime.nodePty.spawn(shell, ['-lc', bootstrap], {
|
||||
name: 'xterm-256color',
|
||||
cols: 120,
|
||||
rows: 34,
|
||||
cwd: spawnCwd,
|
||||
env: ptyEnv,
|
||||
})
|
||||
} catch (error) {
|
||||
const context = {
|
||||
shell,
|
||||
requestedShell: process.env.TERMINAL_SHELL || process.env.SHELL || null,
|
||||
spawnCwd,
|
||||
requestedCwd,
|
||||
path: ptyEnv.PATH,
|
||||
platform: process.platform,
|
||||
}
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(`PTY spawn failed: ${detail} :: ${JSON.stringify(context)}`)
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'pty',
|
||||
write(data) { proc.write(data) },
|
||||
resize(cols, rows) { proc.resize(cols, rows) },
|
||||
kill() { proc.kill() },
|
||||
onData(handler) { proc.onData(handler) },
|
||||
onExit(handler) { proc.onExit(handler) },
|
||||
}
|
||||
}
|
||||
|
||||
function createStreamTransport(sandboxId) {
|
||||
const shell = shellForPlatform()
|
||||
const bootstrap = buildBootstrapShell(sandboxId)
|
||||
const child = spawn(shell, ['-lc', bootstrap], {
|
||||
cwd: process.env.HOME,
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: effectivePath(),
|
||||
TERM: process.env.TERM || 'xterm-256color',
|
||||
OPENSHELL_SANDBOX_ID: sandboxId,
|
||||
},
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
})
|
||||
|
||||
return {
|
||||
kind: 'stream',
|
||||
write(data) { if (!child.stdin.destroyed) child.stdin.write(data) },
|
||||
resize() {},
|
||||
kill() {
|
||||
if (!child.killed) child.kill('SIGTERM')
|
||||
if (!child.stdin.destroyed) child.stdin.end()
|
||||
},
|
||||
onData(handler) {
|
||||
child.stdout.on('data', (chunk) => handler(chunk.toString()))
|
||||
child.stderr.on('data', (chunk) => handler(chunk.toString()))
|
||||
},
|
||||
onExit(handler) {
|
||||
child.on('exit', (exitCode, signal) => handler({ exitCode, signal }))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function createTransport(sandboxId) {
|
||||
return runtime.mode === 'pty' ? createPtyTransport(sandboxId) : createStreamTransport(sandboxId)
|
||||
}
|
||||
|
||||
function createSessionIdentity(sandboxId, dashboardSessionId) {
|
||||
return {
|
||||
sandboxId,
|
||||
dashboardSessionId: dashboardSessionId && dashboardSessionId.trim() ? dashboardSessionId.trim() : 'dashboard-host',
|
||||
}
|
||||
}
|
||||
|
||||
function createSession(identity) {
|
||||
trimSessions()
|
||||
const id = randomUUID()
|
||||
const transport = createTransport(identity.sandboxId)
|
||||
|
||||
const session = {
|
||||
id,
|
||||
sandboxId,
|
||||
attachCommand: buildAttachCommand(sandboxId),
|
||||
pty: proc,
|
||||
sandboxId: identity.sandboxId,
|
||||
dashboardSessionId: identity.dashboardSessionId,
|
||||
attachCommand: buildAttachCommand(identity.sandboxId),
|
||||
transport,
|
||||
createdAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
buffer: '',
|
||||
sockets: new Set(),
|
||||
initialBytesSeen: 0,
|
||||
initialStreamSettled: false,
|
||||
clientReady: false,
|
||||
}
|
||||
|
||||
proc.onData((data) => {
|
||||
session.updatedAt = Date.now()
|
||||
session.buffer += data
|
||||
if (session.buffer.length > 200000) {
|
||||
session.buffer = session.buffer.slice(-200000)
|
||||
}
|
||||
for (const socket of session.sockets) {
|
||||
if (socket.readyState === socket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'data', data }))
|
||||
}
|
||||
}
|
||||
})
|
||||
transport.onData((data) => appendBuffer(session, data))
|
||||
|
||||
proc.onExit(({ exitCode, signal }) => {
|
||||
transport.onExit(({ exitCode, signal }) => {
|
||||
for (const socket of session.sockets) {
|
||||
if (socket.readyState === socket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: 'exit', exitCode, signal }))
|
||||
@@ -93,15 +307,33 @@ function createSession(sandboxId) {
|
||||
return session
|
||||
}
|
||||
|
||||
function getOrCreateSession(sessionId, sandboxId) {
|
||||
function getOrCreateSession(sessionId, identity) {
|
||||
if (sessionId) {
|
||||
const existing = sessions.get(sessionId)
|
||||
if (existing && existing.sandboxId === sandboxId) {
|
||||
if (
|
||||
existing &&
|
||||
existing.sandboxId === identity.sandboxId &&
|
||||
existing.dashboardSessionId === identity.dashboardSessionId
|
||||
) {
|
||||
existing.updatedAt = Date.now()
|
||||
return existing
|
||||
}
|
||||
}
|
||||
return createSession(sandboxId)
|
||||
return createSession(identity)
|
||||
}
|
||||
|
||||
function serializeSession(session) {
|
||||
return {
|
||||
ok: true,
|
||||
sessionId: session.id,
|
||||
sandboxId: session.sandboxId,
|
||||
dashboardSessionId: session.dashboardSessionId,
|
||||
attachCommand: session.attachCommand,
|
||||
replay: session.buffer,
|
||||
transport: runtime.mode,
|
||||
clientReady: session.clientReady,
|
||||
initialStreamSettled: session.initialStreamSettled,
|
||||
}
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
@@ -109,7 +341,7 @@ const server = http.createServer((req, res) => {
|
||||
|
||||
if (req.method === 'GET' && url.pathname === '/healthz') {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' })
|
||||
res.end(JSON.stringify({ ok: true, sessions: sessions.size }))
|
||||
res.end(JSON.stringify({ ok: true, sessions: sessions.size, transport: runtime.mode }))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -124,17 +356,13 @@ const server = http.createServer((req, res) => {
|
||||
req.on('end', () => {
|
||||
try {
|
||||
const parsed = body ? JSON.parse(body) : {}
|
||||
const sandboxId = typeof parsed.sandboxId === 'string' && parsed.sandboxId.trim() ? parsed.sandboxId.trim() : 'default'
|
||||
const sandboxId = typeof parsed.sandboxId === 'string' && parsed.sandboxId.trim() ? parsed.sandboxId.trim() : 'host'
|
||||
const requestedSessionId = typeof parsed.sessionId === 'string' ? parsed.sessionId.trim() : ''
|
||||
const session = getOrCreateSession(requestedSessionId, sandboxId)
|
||||
const dashboardSessionId = typeof parsed.dashboardSessionId === 'string' ? parsed.dashboardSessionId.trim() : 'dashboard-host'
|
||||
const identity = createSessionIdentity(sandboxId, dashboardSessionId)
|
||||
const session = getOrCreateSession(requestedSessionId, identity)
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' })
|
||||
res.end(JSON.stringify({
|
||||
ok: true,
|
||||
sessionId: session.id,
|
||||
sandboxId: session.sandboxId,
|
||||
attachCommand: session.attachCommand,
|
||||
replay: session.buffer,
|
||||
}))
|
||||
res.end(JSON.stringify(serializeSession(session)))
|
||||
} catch (error) {
|
||||
res.writeHead(500, { 'Content-Type': 'application/json' })
|
||||
res.end(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : 'session init failed' }))
|
||||
@@ -152,8 +380,10 @@ const wss = new WebSocketServer({ server, path: '/ws' })
|
||||
wss.on('connection', (socket, req) => {
|
||||
const url = new URL(req.url || '/', `http://${req.headers.host || `${HOST}:${PORT}`}`)
|
||||
const sessionId = url.searchParams.get('sessionId') || ''
|
||||
const sandboxId = url.searchParams.get('sandboxId') || 'default'
|
||||
const session = getOrCreateSession(sessionId, sandboxId)
|
||||
const sandboxId = url.searchParams.get('sandboxId') || 'host'
|
||||
const dashboardSessionId = url.searchParams.get('dashboardSessionId') || 'dashboard-host'
|
||||
const identity = createSessionIdentity(sandboxId, dashboardSessionId)
|
||||
const session = getOrCreateSession(sessionId, identity)
|
||||
session.sockets.add(socket)
|
||||
session.updatedAt = Date.now()
|
||||
|
||||
@@ -161,8 +391,12 @@ wss.on('connection', (socket, req) => {
|
||||
type: 'ready',
|
||||
sessionId: session.id,
|
||||
sandboxId: session.sandboxId,
|
||||
dashboardSessionId: session.dashboardSessionId,
|
||||
attachCommand: session.attachCommand,
|
||||
replay: session.buffer,
|
||||
transport: runtime.mode,
|
||||
clientReady: session.clientReady,
|
||||
initialStreamSettled: session.initialStreamSettled,
|
||||
}))
|
||||
|
||||
socket.on('message', (raw) => {
|
||||
@@ -170,14 +404,14 @@ wss.on('connection', (socket, req) => {
|
||||
const msg = JSON.parse(String(raw))
|
||||
if (msg.type === 'input' && typeof msg.data === 'string') {
|
||||
session.updatedAt = Date.now()
|
||||
session.pty.write(msg.data)
|
||||
session.transport.write(msg.data)
|
||||
} else if (msg.type === 'resize') {
|
||||
const cols = Number(msg.cols) || 120
|
||||
const rows = Number(msg.rows) || 34
|
||||
session.updatedAt = Date.now()
|
||||
session.pty.resize(cols, rows)
|
||||
session.transport.resize(cols, rows)
|
||||
} else if (msg.type === 'kill') {
|
||||
session.pty.kill()
|
||||
session.transport.kill()
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed frames
|
||||
@@ -191,5 +425,5 @@ wss.on('connection', (socket, req) => {
|
||||
})
|
||||
|
||||
server.listen(PORT, HOST, () => {
|
||||
console.log(`terminal server listening on http://${HOST}:${PORT}`)
|
||||
console.log(`terminal server listening on http://${HOST}:${PORT} transport=${runtime.mode}`)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const root = process.cwd()
|
||||
const helperPath = path.join(root, 'app/lib/dashboardSession.ts')
|
||||
const routePath = path.join(root, 'app/api/openshell/terminal/live/route.ts')
|
||||
const terminalPath = path.join(root, 'terminal-server.mjs')
|
||||
|
||||
const helperSource = await readFile(helperPath, 'utf8')
|
||||
assert.match(helperSource, /buildOperatorTerminalRoute/, 'dashboard session helper must define buildOperatorTerminalRoute')
|
||||
assert.match(helperSource, /dashboardSessionId/, 'dashboard session helper must include dashboardSessionId handling')
|
||||
assert.match(helperSource, /sessionStorage/, 'dashboard session helper should persist tab-scoped state in sessionStorage')
|
||||
assert.match(
|
||||
helperSource,
|
||||
/searchParams\.set\('dashboardSessionId', params\.dashboardSessionId\)/,
|
||||
'operator terminal route builder must thread dashboardSessionId'
|
||||
)
|
||||
|
||||
const routeSource = await readFile(routePath, 'utf8')
|
||||
assert.match(routeSource, /dashboardSessionId/, 'terminal live route must accept dashboardSessionId')
|
||||
assert.match(
|
||||
routeSource,
|
||||
/websocketUrl\.searchParams\.set\('dashboardSessionId', params\.dashboardSessionId\)/,
|
||||
'terminal websocket URL must include dashboardSessionId'
|
||||
)
|
||||
assert.match(
|
||||
routeSource,
|
||||
/body: JSON\.stringify\([\s\S]*dashboardSessionId[\s\S]*\)/,
|
||||
'terminal live route must forward dashboardSessionId to terminal server'
|
||||
)
|
||||
|
||||
const terminalSource = await readFile(terminalPath, 'utf8')
|
||||
assert.match(
|
||||
terminalSource,
|
||||
/existing\.dashboardSessionId === identity\.dashboardSessionId/,
|
||||
'terminal server must only reuse sessions when dashboardSessionId matches'
|
||||
)
|
||||
assert.match(
|
||||
terminalSource,
|
||||
/dashboardSessionId: session\.dashboardSessionId/,
|
||||
'terminal server responses must expose dashboardSessionId metadata'
|
||||
)
|
||||
|
||||
const buildOperatorTerminalRoute = ({ sandboxId, dashboardSessionId }) => {
|
||||
const searchParams = new URLSearchParams()
|
||||
if (sandboxId) searchParams.set('sandboxId', sandboxId)
|
||||
searchParams.set('dashboardSessionId', dashboardSessionId)
|
||||
const query = searchParams.toString()
|
||||
return query ? `/operator-terminal?${query}` : '/operator-terminal'
|
||||
}
|
||||
|
||||
assert.equal(
|
||||
buildOperatorTerminalRoute({ sandboxId: 'sandbox-a', dashboardSessionId: 'dash-123' }),
|
||||
'/operator-terminal?sandboxId=sandbox-a&dashboardSessionId=dash-123'
|
||||
)
|
||||
assert.equal(
|
||||
buildOperatorTerminalRoute({ sandboxId: null, dashboardSessionId: 'dash-123' }),
|
||||
'/operator-terminal?dashboardSessionId=dash-123'
|
||||
)
|
||||
|
||||
console.log('dashboard-session-check: PASS route/session scope assertions')
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
const root = process.cwd()
|
||||
const pagePath = path.join(root, 'app/page.tsx')
|
||||
const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx')
|
||||
const hookPath = path.join(root, 'app/hooks/useSandboxInventory.ts')
|
||||
|
||||
const pageSource = await readFile(pagePath, 'utf8')
|
||||
const sandboxListSource = await readFile(sandboxListPath, 'utf8')
|
||||
const hookSource = await readFile(hookPath, 'utf8')
|
||||
|
||||
assert.match(hookSource, /const \[loading, setLoading\] = useState\(false\)/, 'authoritative inventory hook must use SSR-safe loading initialization')
|
||||
assert.match(hookSource, /const \[error, setError\] = useState<string \| null>\(null\)/, 'authoritative inventory hook must own error state')
|
||||
assert.match(pageSource, /const \{ sandboxes, nemoclaw, loading, error, refresh \} = useSandboxInventory\(/, 'page must read loading and error from useSandboxInventory')
|
||||
assert.match(pageSource, /inventoryEnabled && loading \? \(/, 'page must render initializing from authoritative inventory state')
|
||||
assert.match(pageSource, /data-testid="inventory-loading-state"/, 'page must expose loading state marker')
|
||||
assert.match(pageSource, /inventoryEnabled && error \? \(/, 'page must render error state from authoritative inventory state')
|
||||
assert.match(pageSource, /data-testid="inventory-error-state"/, 'page must expose error state marker')
|
||||
assert.match(pageSource, /sandboxes\.length === 0 \? \(/, 'page must render explicit empty state when inventory is valid but empty')
|
||||
assert.match(pageSource, /data-testid="inventory-empty-state"/, 'page must expose empty state marker')
|
||||
assert.doesNotMatch(sandboxListSource, /const \[loading, setLoading\] = useState\(/, 'SandboxList must not own a local loading latch')
|
||||
assert.doesNotMatch(sandboxListSource, /INITIALIZING\.\.\./, 'SandboxList must not render initializing placeholder')
|
||||
|
||||
console.log('initializing-hang-check: PASS page-owned startup/error/empty state assertions')
|
||||
@@ -0,0 +1,81 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
const root = process.cwd()
|
||||
const instancesPath = path.join(root, 'app/lib/openclawInstances.ts')
|
||||
const routePath = path.join(root, 'app/api/openshell/dashboard/open/route.ts')
|
||||
const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx')
|
||||
|
||||
const instancesSource = await readFile(instancesPath, 'utf8')
|
||||
assert.match(
|
||||
instancesSource,
|
||||
/MY_ASSISTANT_OPENCLAW_INSTANCE_ID/,
|
||||
'openclaw instance registry should expose a dedicated my-assistant env mapping seam'
|
||||
)
|
||||
assert.match(
|
||||
instancesSource,
|
||||
/OPENCLAW_SANDBOX_INSTANCE_MAP_JSON/,
|
||||
'openclaw instance registry should allow additive sandbox->instance JSON mappings'
|
||||
)
|
||||
assert.match(
|
||||
instancesSource,
|
||||
/export function resolveOpenClawInstanceForSandbox\(sandboxId\?: string \| null\)/,
|
||||
'openclaw instance registry should expose sandbox-aware instance resolution'
|
||||
)
|
||||
assert.match(
|
||||
instancesSource,
|
||||
/getOpenClawInstanceIdForSandbox\(sandboxId\?: string \| null\)/,
|
||||
'openclaw instance registry should expose sandbox mapping lookup'
|
||||
)
|
||||
|
||||
const routeSource = await readFile(routePath, 'utf8')
|
||||
assert.match(
|
||||
routeSource,
|
||||
/const sandboxId = requestUrl\.searchParams\.get\('sandboxId'\)/,
|
||||
'dashboard open route must accept sandboxId'
|
||||
)
|
||||
assert.match(
|
||||
routeSource,
|
||||
/resolveOpenClawInstanceForSandbox\(sandboxId\)/,
|
||||
'dashboard open route must resolve instances from sandbox context when instanceId is absent'
|
||||
)
|
||||
assert.match(
|
||||
routeSource,
|
||||
/sandboxInstanceId: mappedSandboxInstanceId/,
|
||||
'dashboard open route response should expose mapped sandbox instance metadata'
|
||||
)
|
||||
assert.match(
|
||||
routeSource,
|
||||
/sandboxId,\s*\n\s*sandboxInstanceId: mappedSandboxInstanceId,\s*\n\s*instanceId: instance\.id/,
|
||||
'dashboard open route response should include sandboxId alongside resolved instance metadata'
|
||||
)
|
||||
assert.match(
|
||||
routeSource,
|
||||
/bootstrapUrl: probe\.bootstrapUrl/,
|
||||
'dashboard open route should return explicit bootstrap URL metadata'
|
||||
)
|
||||
assert.match(
|
||||
routeSource,
|
||||
/bootstrapTokenPresent: probe\.bootstrapTokenPresent/,
|
||||
'dashboard open route should expose whether the bootstrap contract is tokenized'
|
||||
)
|
||||
|
||||
const sandboxListSource = await readFile(sandboxListPath, 'utf8')
|
||||
assert.match(
|
||||
sandboxListSource,
|
||||
/searchParams\.set\('sandboxId', selectedSandbox\.id\)/,
|
||||
'sandbox list must pass selected sandboxId when opening the dashboard'
|
||||
)
|
||||
assert.match(
|
||||
sandboxListSource,
|
||||
/fetch\(`\/api\/openshell\/dashboard\/open\?\$\{searchParams\.toString\(\)\}`\)/,
|
||||
'sandbox list should call the sandbox-aware dashboard open route'
|
||||
)
|
||||
assert.match(
|
||||
sandboxListSource,
|
||||
/Sandbox \$\{data\.sandboxId\} resolved to OpenClaw instance \$\{data\.instanceId\}/,
|
||||
'sandbox list should surface sandbox-aware resolution feedback'
|
||||
)
|
||||
|
||||
console.log('openclaw-dashboard-instance-resolution-check: PASS sandbox-aware dashboard resolution assertions')
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
const root = process.cwd()
|
||||
const routePath = path.join(root, 'app/api/openshell/terminal/live/route.ts')
|
||||
const pagePath = path.join(root, 'app/operator-terminal/page.tsx')
|
||||
|
||||
const routeSource = await readFile(routePath, 'utf8')
|
||||
assert.match(
|
||||
routeSource,
|
||||
/throw new Error\('No routable browser host available for terminal websocket URL\. Set PUBLIC_BROWSER_HOST or PUBLIC_BASE_URL\.'\)/,
|
||||
'terminal live route must fail closed when only non-routable browser hosts are available'
|
||||
)
|
||||
assert.doesNotMatch(
|
||||
routeSource,
|
||||
/return requestUrl\.host/,
|
||||
'terminal live route must not fall back to requestUrl.host when it is non-routable'
|
||||
)
|
||||
assert.match(
|
||||
routeSource,
|
||||
/const requestHostHeader = requestUrl\.host/,
|
||||
'terminal live route should inspect request host before deciding routability'
|
||||
)
|
||||
assert.match(
|
||||
routeSource,
|
||||
/return null/,
|
||||
'terminal live route must return null when no routable browser host is available'
|
||||
)
|
||||
|
||||
const pageSource = await readFile(pagePath, 'utf8')
|
||||
assert.match(
|
||||
pageSource,
|
||||
/sandboxId \? 'Live operator terminal for the selected sandbox, brokered through the dashboard-owned terminal bridge\.'/,
|
||||
'operator terminal page must describe sandbox-scoped terminal behavior honestly'
|
||||
)
|
||||
assert.match(
|
||||
pageSource,
|
||||
/: 'Live operator terminal for host mode, brokered through the dashboard-owned terminal bridge\.'/,
|
||||
'operator terminal page must distinguish host mode from sandbox mode'
|
||||
)
|
||||
assert.doesNotMatch(
|
||||
pageSource,
|
||||
/Live operator terminal for the host machine\. The selected sandbox is preserved as context for helper commands and status lookups, but this shell is intentionally machine-scoped\./,
|
||||
'operator terminal page must not keep the stale host-machine-only description'
|
||||
)
|
||||
|
||||
console.log('post-authority-terminal-contract-check: PASS websocket host + UI honesty assertions')
|
||||
@@ -0,0 +1,58 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import path from 'node:path'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
|
||||
const root = process.cwd()
|
||||
|
||||
const runtimeAuthorityPath = path.join(root, 'app/lib/runtimeAuthority.ts')
|
||||
const dashboardOpenPath = path.join(root, 'app/api/openshell/dashboard/open/route.ts')
|
||||
const dashboardProxySharedPath = path.join(root, 'app/api/openshell/dashboard/proxy/shared.ts')
|
||||
const terminalLivePath = path.join(root, 'app/api/openshell/terminal/live/route.ts')
|
||||
const terminalReadinessPath = path.join(root, 'app/api/openshell/terminal/readiness/route.ts')
|
||||
const telemetryPath = path.join(root, 'app/api/telemetry/real/route.ts')
|
||||
const openshellHostPath = path.join(root, 'app/lib/openshellHost.ts')
|
||||
const packageJsonPath = path.join(root, 'package.json')
|
||||
const serverPath = path.join(root, 'server.mjs')
|
||||
|
||||
const [runtimeAuthoritySource, dashboardOpenSource, dashboardProxySource, terminalLiveSource, terminalReadinessSource, telemetrySource, openshellHostSource, packageJsonSource, serverSource] = await Promise.all([
|
||||
readFile(runtimeAuthorityPath, 'utf8'),
|
||||
readFile(dashboardOpenPath, 'utf8'),
|
||||
readFile(dashboardProxySharedPath, 'utf8'),
|
||||
readFile(terminalLivePath, 'utf8'),
|
||||
readFile(terminalReadinessPath, 'utf8'),
|
||||
readFile(telemetryPath, 'utf8'),
|
||||
readFile(openshellHostPath, 'utf8'),
|
||||
readFile(packageJsonPath, 'utf8'),
|
||||
readFile(serverPath, 'utf8'),
|
||||
])
|
||||
|
||||
assert.match(runtimeAuthoritySource, /export function resolveRuntimeAuthority\(/, 'runtime authority resolver must exist')
|
||||
assert.match(runtimeAuthoritySource, /mappedSandboxInstanceId = getOpenClawInstanceIdForSandbox\(resolvedSandboxId\)/, 'runtime authority must derive sandbox instance mapping from resolved sandbox id')
|
||||
assert.match(runtimeAuthoritySource, /requestedInstanceId\s*\?\s*resolveOpenClawInstance\(requestedInstanceId\)/, 'runtime authority must allow explicit instance override')
|
||||
|
||||
assert.match(dashboardOpenSource, /const sandboxId = requestUrl\.searchParams\.get\('sandboxId'\)/, 'dashboard open route must still read sandboxId explicitly')
|
||||
assert.match(dashboardOpenSource, /const authority = resolveRuntimeAuthority\(/, 'dashboard open route must use shared runtime authority resolution')
|
||||
assert.match(dashboardOpenSource, /authority:\s*\{[\s\S]*sandboxAuthority:/, 'dashboard open route must expose authority provenance')
|
||||
assert.match(dashboardOpenSource, /bootstrapUrl: probe\.bootstrapUrl/, 'dashboard open route must surface the resolved bootstrap URL explicitly')
|
||||
assert.match(dashboardOpenSource, /bootstrapAuthority: probe\.bootstrapAuthority/, 'dashboard open route must surface tokenized bootstrap authority explicitly')
|
||||
assert.match(dashboardOpenSource, /probe\.bootstrapAuthority === 'tokenized-cli'/, 'dashboard open route truth must prefer tokenized bootstrap evidence over raw loopback fetch alone')
|
||||
|
||||
assert.match(dashboardProxySource, /resolveRuntimeAuthority\(\{[\s\S]*sandboxId: requestUrl\.searchParams\.get\('sandboxId'\)/, 'dashboard proxy must resolve target from shared authority source')
|
||||
assert.match(dashboardProxySource, /x-openclaw-dashboard-bootstrap-contract/, 'dashboard proxy must mark the tokenized bootstrap bridge contract in response headers')
|
||||
assert.match(dashboardProxySource, /copyRequestHeaders/, 'dashboard proxy should forward browser request headers upstream')
|
||||
assert.match(dashboardProxySource, /upstreamInit\.duplex = 'half'/, 'dashboard proxy should forward non-GET request bodies upstream')
|
||||
|
||||
assert.match(terminalLiveSource, /const authority = resolveRuntimeAuthority\(/, 'terminal live route must use shared runtime authority resolution')
|
||||
assert.match(terminalLiveSource, /authority:\s*\{[\s\S]*usedMappedSandboxInstance:/, 'terminal live route must expose authority provenance')
|
||||
|
||||
assert.match(terminalReadinessSource, /terminalFallback: true/, 'terminal readiness must explicitly represent terminal fallback state')
|
||||
assert.match(terminalReadinessSource, /const authority = resolveRuntimeAuthority\(/, 'terminal readiness must use shared runtime authority resolution')
|
||||
|
||||
assert.match(telemetrySource, /authoritySource: "runtimeAuthority"/, 'inventory route must declare shared authority source')
|
||||
assert.match(telemetrySource, /authorities: authorities\.map\(/, 'inventory route must expose per-sandbox authority metadata')
|
||||
assert.match(openshellHostSource, /const canMintBootstrapFromCli = instance\.id === defaultInstance\.id/, 'bootstrap minting should only use CLI for the default OpenClaw instance')
|
||||
assert.match(packageJsonSource, /"dev": "node server\.mjs"/, 'development script must run through the custom server so websocket proxy bridges are active')
|
||||
assert.match(serverSource, /const dashboardWss = new WebSocketServer\(\{ noServer: true \}\)/, 'custom server must provision a dedicated dashboard websocket bridge')
|
||||
assert.match(serverSource, /dashboard-upgrade-accepted/, 'custom server must accept dashboard websocket upgrades through the proxy path')
|
||||
|
||||
console.log('runtime-authority-resolution-check: PASS shared authority resolution assertions')
|
||||
Reference in New Issue
Block a user