Skip to content

V2 terminal env#3184

Merged
Kitenite merged 23 commits into
mainfrom
refine-plan
Apr 5, 2026
Merged

V2 terminal env#3184
Kitenite merged 23 commits into
mainfrom
refine-plan

Conversation

@Kitenite
Copy link
Copy Markdown
Collaborator

@Kitenite Kitenite commented Apr 5, 2026

Description

Related Issues

Type of Change

  • Bug fix
  • New feature
  • Documentation
  • Refactor
  • Other (please describe):

Testing

Screenshots (if applicable)

Additional Notes


Summary by cubic

Builds the v2 terminal env end to end. Adds theme‑aware color hints and a macOS TLS cert fallback, and locks PTYs to a preserved, shell‑derived base env for reliable CLI behavior.

  • New Features

    • Host‑service terminal env module with clean shell snapshot resolver/cache, runtime env stripping, UTF‑8 locale, shell launch config, and v2 PTY env builder; exported as @superset/host-service/terminal-env.
    • PTYs are built from the preserved snapshot (never live process.env), inject TERM_PROGRAM=Superset/version, UTF‑8 LANG, PWD, v2 metadata (SUPERSET_TERMINAL_ID, SUPERSET_WORKSPACE_ID/_PATH, SUPERSET_ROOT_PATH, SUPERSET_ENV, SUPERSET_AGENT_HOOK_PORT/_VERSION), and preserve user tooling like SSH_AUTH_SOCK; non‑Windows falls back to /bin/sh.
    • Shell launch config: zsh via ZDOTDIR wrapper, bash rcfile or -l, fish --init-command; unsupported shells launch natively.
    • Renderer passes the active theme type when opening a terminal; PTYs set COLORFGBG (dark by default, light when requested). On macOS, PTYs set SSL_CERT_FILE=/etc/ssl/cert.pem when available to avoid Keychain TLS issues.
  • Tests

    • New host‑service tests cover base env preservation, denylisted env stripping (ELECTRON_*, npm_*, VITE_*, HOST_*), UTF‑8 locale, shell args/bootstrap, fallback behavior, v2 metadata, theme hinting, macOS cert fallback, and fail‑closed when the snapshot is missing.
    • Desktop tests verify concurrent start dedupe and that host‑service spawns use the shell‑snapshot env plus explicit keys (SUPERSET_HOME_DIR, hook port/version, DESKTOP_VITE_PORT, auth/cloud) without leaking dev/Electron/runtime secrets.

Written for commit f3da34c. Summary will update on new commits.

Summary by CodeRabbit

  • Documentation
    • Added a v2 terminal environment specification describing shell integration, PTY env contract, allowed metadata, and locale/TERM defaults.
  • New Features
    • Terminals now use a preserved shell-derived base snapshot plus explicit terminal/agent metadata rather than inheriting live runtime env.
  • Bug Fixes
    • PTYs launch deterministically with configured shells, fail closed on unresolved shell env, and no longer leak runtime secrets or legacy vars.
  • Tests
    • New tests cover shell resolution, UTF‑8 locale selection, env filtering, bootstrap args, and the v2 PTY contract.

@Kitenite Kitenite changed the title v2 terminal env plan poc - v2 terminal env plan Apr 5, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 5, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Introduces a v2 terminal env boundary: desktop resolves a strict shell-derived snapshot and launches host-service with that snapshot plus explicit runtime keys; host-service preserves a stripped terminal base env, provides deterministic shell bootstrap/launch semantics, and composes final PTY envs with a minimal terminal surface and v2 Superset metadata.

Changes

Cohort / File(s) Summary
Specification
plans/v2-terminal-env-handoff.md
New spec defining the v2 env boundary, allowed PTY surface, renamed/dropped SUPERSET_* keys, shell bootstrap/launch rules, and acceptance/test criteria.
Desktop: shell snapshot & host-service launch
apps/desktop/src/main/lib/host-service-manager.ts, apps/desktop/src/lib/trpc/routers/workspaces/utils/shell-env.ts
Desktop now resolves a strict shell-derived snapshot via getStrictShellEnvironment()/resolveTerminalShellSnapshot() and uses that snapshot (not process.env) when building host-service env; host-service runtime keys are injected explicitly; host-service spawn removed ...process.env.
Host-service: terminal env core
packages/host-service/src/terminal/env.ts, packages/host-service/src/terminal/env-strip.ts
New env core: init/preserve stripped terminal base env (initTerminalBaseEnv, getTerminalBaseEnv, resetTerminalBaseEnvForTests), normalizeUtf8Locale, stripTerminalRuntimeEnv denylist, and buildV2TerminalEnv to assemble PTY env with fixed terminal surface and v2 Superset metadata.
Host-service: shell launch helpers
packages/host-service/src/terminal/shell-launch.ts
Centralized shell resolution/launch: resolveLaunchShell, getShellLaunchArgs, getShellBootstrapEnv, getSupersetShellPaths; deterministic per-shell bootstrap for zsh, bash, fish, sh/ksh; unsupported shells left native.
Host-service: terminal runtime (spawn path) & tests
packages/host-service/src/terminal/terminal.ts, packages/host-service/src/terminal/env.test.ts
PTY spawning now calls resolveLaunchShell + getShellLaunchArgs and uses env from buildV2TerminalEnv(...); workspace rootPath queried from DB to populate metadata; extensive tests validate env stripping, locale normalization, shell args/bootstrap, and v2 env contract.
Host-service: startup
packages/host-service/src/serve.ts
Calls initTerminalBaseEnv() at startup to capture the shell-derived base env snapshot before app initialization.

Sequence Diagram(s)

sequenceDiagram
    participant Desktop as Desktop
    participant HostService as HostService
    participant DB as DB
    participant PTY as PTY

    Desktop->>Desktop: resolveTerminalShellSnapshot() (strict shell-derived env)
    Desktop->>HostService: spawn host-service (env = shell snapshot + explicit keys)
    HostService->>HostService: initTerminalBaseEnv() (store stripped baseEnv)
    HostService->>DB: query.projects(workspace.projectId) -> rootPath
    HostService->>HostService: resolveLaunchShell(baseEnv) / getShellLaunchArgs(...)
    HostService->>HostService: buildV2TerminalEnv(baseEnv, shell, rootPath, ids)
    HostService->>PTY: spawn(shell, shellArgs, env=V2Env)
    PTY-->>HostService: PTY ready / shell runs
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I nibble keys and tidy logs,
I stitch the shell in careful clogs,
Snapshot kept, secrets barred,
PTYs spring — neat and unmarred,
A rabbit hops where envs are stars.

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning PR description relies entirely on auto-generated cubic summary; all template fields (Related Issues, Type of Change, Testing, Screenshots, Additional Notes) are empty or unchecked. Complete the template: specify issue links, check the 'New feature' box, describe testing approach, and add any relevant context beyond the cubic summary.
Title check ❓ Inconclusive The title 'V2 terminal env' is vague and generic, failing to convey the specific intent of this substantial architectural change in environment handling. Consider a more descriptive title such as 'Implement v2 terminal environment with strict env boundary and shell snapshot isolation' or 'Add v2 terminal env contract with preserved shell snapshot and runtime env stripping'.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refine-plan

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented Apr 5, 2026

Greptile Summary

This PR adds plans/v2-terminal-env-handoff.md, a detailed specification and handoff document for implementing a v2 terminal environment contract in the Superset desktop application. The plan defines a clean boundary between desktop, host-service, and PTY environments to prevent runtime env leakage, introduces explicit SUPERSET_* metadata vars with renamed keys, and outlines per-shell integration behavior for zsh, bash, and fish.

  • Documentation only — no production code or schema is changed in this PR
  • Defines the v2 PTY env contract: explicit public surface (TERM_PROGRAM, COLORTERM, LANG, PWD) plus explicit Superset metadata (SUPERSET_TERMINAL_ID, SUPERSET_WORKSPACE_ID, etc.)
  • Renames v1 vars (SUPERSET_PANE_IDSUPERSET_TERMINAL_ID, SUPERSET_PORTSUPERSET_AGENT_HOOK_PORT, SUPERSET_HOOK_VERSIONSUPERSET_AGENT_HOOK_VERSION) and drops SUPERSET_TAB_ID
  • Lists primary implementation targets and a 7-step implementation direction with clear acceptance criteria and test requirements
  • Minor issue: the "Refined v2 contract" section numbering skips from ### 5 to ### 7, leaving section 6 absent

Confidence Score: 5/5

Safe to merge — documentation-only change with no runtime impact

This PR adds only a planning document. There is no executable code, database schema, or configuration change. The only finding is a minor section numbering gap in the markdown. The plan itself is thorough, well-structured, and ready to guide implementation.

plans/v2-terminal-env-handoff.md — minor section 6 numbering gap in 'Refined v2 contract'

Important Files Changed

Filename Overview
plans/v2-terminal-env-handoff.md New planning document for v2 terminal env contract; section numbering in 'Refined v2 contract' skips from 5 to 7 (section 6 missing)

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Desktop process.env] -->|shell env snapshot| B[Shell-derived Base Env]
    B -->|strip desktop / Electron vars| C[Host-Service Launch Env]
    C -->|sanitized base env| D[V2 Terminal Env Builder]
    D --> E[Public Terminal Env]
    D --> F[Superset Metadata]
    D --> G[Shell Bootstrap Env]
    E --> H[PTY]
    F --> H
    G --> H
    H --> I[User Shell Session]

    E:::note
    classDef note fill:#f9f,stroke:#333
    note1["TERM · TERM_PROGRAM · COLORTERM · LANG · PWD"] --> E
    note2["SUPERSET_TERMINAL_ID · SUPERSET_WORKSPACE_ID\nSUPERSET_WORKSPACE_PATH · SUPERSET_AGENT_HOOK_PORT"] --> F
    note3["zsh: ZDOTDIR\nbash: --rcfile\nfish: --init-command"] --> G
Loading

Reviews (1): Last reviewed commit: "Update doc" | Re-trigger Greptile

Comment thread plans/v2-terminal-env-handoff.md
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@plans/v2-terminal-env-handoff.md`:
- Line 153: SUPERSET_ENV in the v2 contract metadata list is undefined and
either needs documentation or removal; update the v2-terminal-env-handoff.md to
either (a) document SUPERSET_ENV by specifying its source/origin (who sets it,
when, valid values "development" or "production"), where it is read/used in the
system, and add acceptance criteria that verify its propagation/format, or (b)
remove SUPERSET_ENV from the metadata list so it isn’t part of the v2 contract;
reference the metadata list entry labeled SUPERSET_ENV when making the change
and update any related acceptance criteria sections to reflect the addition or
removal.
- Around line 173-261: Rename the markdown heading "### 7. Dynamic state" to
"### 6. Dynamic state" in plans/v2-terminal-env-handoff.md so the section
numbering follows "### 5. Shell behavior and integration"; update any nearby
numeric references if present to keep numbering consistent (search for "7.
Dynamic state" or "### 7." and replace with "6").
- Around line 121-128: The spec's environment block (variables like TERM,
TERM_PROGRAM, LANG, COLORTERM, PWD) must define fallback behavior for LANG
resolution: update the document to state that implementations should attempt to
derive a UTF-8 locale from the base environment and, if none is available or it
is non-UTF-8, set LANG to a safe default such as en_US.UTF-8 (or C.UTF-8 where
en_US is unavailable); explicitly note this fallback rule and the expected
precedence (use host-provided UTF-8 locale → fallback) so consumers of the spec
know to expect a consistent LANG value.
- Around line 133-134: Clarify that TERM_PROGRAM_VERSION must be the desktop app
(Superset) version rather than the host-service package or npm_package_version:
update the text and any code that sets TERM_PROGRAM_VERSION (replace uses of
npm_package_version or host-service package version) to pull the desktop app's
version identifier so the PTY presents the user-facing app version; reference
TERM_PROGRAM_VERSION, npm_package_version, and host-service in your change so
readers know which symbol to replace and which source to prefer.
- Around line 184-187: Validate inherited shell paths before using them: when
selecting the shell from the SHELL (macOS/Linux) or COMSPEC (Windows)
environment variables, check that the referenced path exists and is executable
(or on Windows, exists and is a file) and only use it if the validation
succeeds; otherwise fall back to the configured defaults (/bin/sh for Unix,
cmd.exe for Windows). Update the fallback logic described around the
SHELL/COMSPEC usage so that any invalid or non-executable environment value is
ignored and documented as such to avoid PTY spawn failures.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0f5e457a-0407-4daa-917e-fa300618826c

📥 Commits

Reviewing files that changed from the base of the PR and between 1219200 and e9b3287.

📒 Files selected for processing (1)
  • plans/v2-terminal-env-handoff.md

Comment thread plans/v2-terminal-env-handoff.md
Comment thread plans/v2-terminal-env-handoff.md
Comment thread plans/v2-terminal-env-handoff.md
Comment thread plans/v2-terminal-env-handoff.md
Comment thread plans/v2-terminal-env-handoff.md
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 1 file

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 5, 2026

🚀 Preview Deployment

🔗 Preview Links

Service Status Link
Neon Database (Neon) View Branch
Fly.io Electric (Fly.io) View App
Vercel API (Vercel) Open Preview
Vercel Web (Vercel) Open Preview
Vercel Marketing (Vercel) Open Preview
Vercel Admin (Vercel) Open Preview
Vercel Docs (Vercel) Open Preview

Preview updates automatically with new commits

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop/src/main/lib/host-service-manager.ts`:
- Around line 127-162: getShellEnvironment currently swallows errors and can't
convey whether it fell back, so modify getShellEnvironment to return { env:
Record<string,string>, source: "shell" | "fallback" } (or equivalent flag like
isFallback) and update resolveHostServiceBaseEnv to await that result and return
it directly (use the returned env and source) instead of the unreachable
try/catch; remove the dead catch block in resolveHostServiceBaseEnv, keep the
fallback filtering logic only if getShellEnvironment returns source ===
"fallback" (or rely on getShellEnvironment to already provide a filtered
fallback), and update any other callers of getShellEnvironment to handle the new
return shape.

In `@plans/v2-terminal-env-handoff.md`:
- Around line 283-298: Spec assumes a projects.repoPath column exists but the
projects table schema lacks it, breaking the derivation of SUPERSET_ROOT_PATH;
fix by either (A) adding a repoPath column to the projects schema with a DB
migration and updating any schema models, ORM mappings, tests and docs that
reference projects.repoPath and the SUPERSET_ROOT_PATH derivation, or (B) if you
prefer not to change the DB, update the spec and code that computes
SUPERSET_ROOT_PATH to use an alternate source (e.g., existing
SUPERSET_WORKSPACE_PATH or a new explicit field like projects.root or
workspace->project join logic) and update acceptance criteria, tests, and
documentation accordingly so projects.repoPath is no longer assumed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1a1f4c6c-f8c6-4b9f-bad5-d0e9bc75512f

📥 Commits

Reviewing files that changed from the base of the PR and between e9b3287 and 25e7604.

📒 Files selected for processing (5)
  • apps/desktop/src/main/lib/host-service-manager.ts
  • packages/host-service/src/terminal/env.test.ts
  • packages/host-service/src/terminal/env.ts
  • packages/host-service/src/terminal/terminal.ts
  • plans/v2-terminal-env-handoff.md

Comment thread apps/desktop/src/main/lib/host-service-manager.ts Outdated
Comment thread plans/v2-terminal-env-handoff.md
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 5 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/host-service/src/terminal/env.ts">

<violation number="1" location="packages/host-service/src/terminal/env.ts:22">
P2: Locale normalization is ordered incorrectly: `LC_ALL` has higher precedence than `LANG`, so preferring `LANG` can leave terminals on a non-UTF-8 locale.</violation>
</file>

<file name="apps/desktop/src/main/lib/host-service-manager.ts">

<violation number="1" location="apps/desktop/src/main/lib/host-service-manager.ts:139">
P2: The `catch` block appears to be unreachable. `getShellEnvironment()` has its own internal try-catch that returns a fallback env rather than throwing, so this function always takes the `try` path and returns `source: "shell"` — even when shell resolution actually failed internally. This means:
1. The fallback filtering logic (~20 lines) is dead code
2. The `source` discriminant is misleading since it can never be `"fallback"`

Either remove the dead catch block, or modify `getShellEnvironment()` to expose whether a fallback was used (e.g., return `{ env, isFallback }`) so the caller can distinguish the two cases.</violation>
</file>

<file name="packages/host-service/src/terminal/env.test.ts">

<violation number="1" location="packages/host-service/src/terminal/env.test.ts:18">
P2: This assertion is not platform-safe: it fails on Windows where `resolveLaunchShell` returns `COMSPEC`/`cmd.exe` instead of `SHELL`.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread packages/host-service/src/terminal/env.ts Outdated
Comment thread apps/desktop/src/main/lib/host-service-manager.ts Outdated
Comment thread packages/host-service/src/terminal/env.test.ts
@cubic-dev-ai
Copy link
Copy Markdown
Contributor

cubic-dev-ai Bot commented Apr 5, 2026

You're iterating quickly on this pull request. To help protect your rate limits, cubic has paused automatic reviews on new pushes for now—when you're ready for another review, comment @cubic-dev-ai review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant