Skip to content

Commit e3f7495

Browse files
sahrizviclaude
andauthored
feat: post-scan Workspaces prompt + altimate-code link subcommand (#1099)
* feat: add Workspaces post-scan prompt + `altimate link` subcommand Adds the CLI half of the Workspaces pilot: after the first-run scan completes and the CLI is authenticated with Altimate, prompt the user once to create a new workspace or attach the project to an existing one. The link is a direct authenticated call — no device flow — and the browser opens after create so the user can configure integrations / knowledge in the SaaS. Fork-owned TuiPlugin per docs/internal/2026-06-23-tui-fork-features- as-plugins-adr.md: single file at `packages/opencode/src/plugin/tui/altimate/workspace.tsx`, added to the existing `altimateTuiPlugins()` aggregator. Upstream `packages/tui/**` stays byte-for-byte upstream. Uses the real `api.ui.*` / `api.keymap.registerLayer` / `api.state.path.directory` / `api.kv` (persistent) surface. Shared modules under `packages/opencode/src/altimate/workspace/` so the plugin and the `altimate link` subcommand can't drift on request shape or error handling: - `api-client.ts` — typed errors (Conflict/Precondition/NotFound/ Forbidden/NotConfigured/Api), FastAPI `{"detail": {...}}` parsing, 15s abort timeout, credentials re-read on every call so an account switch is picked up without restart. - `detect.ts` — `detectProjectRemote` + `projectNameFromRemote`; reuses `stripGitRemoteCredentials` (now exported from `project-scan.ts` so the two callers can't drift). - `state.ts` — local binding cache scoped to (tenant, apiUrl) with atomic write + post-write `chmod 0o600` + corruption recovery. Trigger: `onboarding-telemetry.ts` `tool.execute.after` hook publishes `TuiEvent.CommandExecute` with `"altimate.workspace.postScan"` when `project_scan` completes, gated on the new `Flag.ALTIMATE_WORKSPACE` and `AltimateApi.isConfigured()` (BYOK users are silently skipped — no place to send them). Never blocks onboarding on a publish failure. Server-authoritative pre-check via `GET /datamate-project-bindings/ by-remote`; local cache used only as an offline fallback, and the fallback path renders a mandatory "unverified" banner rather than silently trusting stale data. Browser-open failure surfaces a copyable-URL toast rather than swallowing silently. 7-day Skip latch lives in `api.kv` keyed by SHA-1(remote) — UTC rolling window; `altimate link` (user-initiated) deliberately bypasses the latch. New `altimate-code link` subcommand runs the same three-way flow outside a TUI session via `@clack/prompts` for scripting / catch-up after a Skip. Bails early with helpful messages when credentials are missing or no git remote is set. Tests: 17 unit tests covering project-name parsing, git detection graceful failure, cache read/write + chmod + tenant-scoping (account- switch invalidation), and Skip latch TTL semantics with UTC boundary. Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_01Q8FGy89Qpr39k8nCSpCcK2 * fix(workspace): drop hard dependency on git remote + defer post-scan prompt Two user-flagged issues on the Workspaces post-scan prompt landed in 7c7e17f: 1. Post-scan dialog raced the LLM's onboarding-menu streaming — the dialog painted while text was still generating, and Enter didn't register until streaming finished. Fix: arm a one-shot `session.idle` listener via `EventV2Bridge` from `onboarding-telemetry.ts` and publish `TuiEvent.CommandExecute` only after the session settles. Costs a few seconds of latency; kills the race. 2. `resolveProjectRemote` returned undefined for projects without a git remote (materialized sample dbt scaffolds, fresh scratch dirs), so the post-scan prompt and `altimate-code link` both bailed silently. Fix: new `resolveProjectIdentifier` in `workspace/detect.ts` always returns a `{repoRemote?, projectPath}` pair (path is symlink-resolved `realpath`). `ProjectIdentifier` type threads through `WorkspaceApi`, the TuiPlugin dialogs, and the `link` subcommand — remote is preferred when available (stronger identity, survives directory moves); path is the fallback the backend indexes symmetrically. Also: `projectNameFromPath` fallback for auto-naming (derives from directory basename when no remote); Skip-latch key hashes remote-or-path so path-only projects also get the 7-day suppression; `runFlow` and `runOnDemandPicker` reworked to use `WorkspaceApi.getBindingForProject` (tries remote first, then path); `CachedBinding` in state.ts extended with `projectPath: string | null`. Tests updated + one new latch test covers the path-only case. `bun test test/altimate/plugin/workspace.test.ts` → 18/18. * fix(workspace): consensus review — flag gating, orphan-safe create, matched-identifier rebind, req() hardening Addresses the review findings that belong to this PR's commits (7c7e17f + 76de5a9). The three remaining findings introduced by the stacked browser-handoff PR are fixed on that branch. - Gate the LinkCommand registration in src/index.ts AND the Workspace TUI plugin registration behind Flag.ALTIMATE_WORKSPACE. Previously the flag gated only the post-scan trigger publish, so the palette command, altimate-code link subcommand, and post-scan handler shipped to 100% of users regardless of the flag setting. (M1) - createAndBindInline / createAndBind now accept an "already linked" outcome and rebind after create. Before this, "+ Create a new workspace" on an already-linked project silently orphaned the freshly-created workspace in the SaaS — a real (billable) resource the CLI knew nothing about. On rebind failure the error message tells the user the workspace exists and how to recover. (M2) - getBindingForProject now returns which identifier arm matched (remote or path) via a new ``matchedBy`` field. AlreadyLinkedDialog, PickerDialog, bindOrRebindInline, and cli/cmd/link.ts all use matched-identifier for the rebind endpoint — not the CURRENT identifier — so a repo whose remote was renamed still repairs via its path binding instead of 404'ing on rebindByRemote. hasDrift is now computed from matched-vs-current identifier instead of hardcoded false. (M3) - listDatamates now routes through req() (via a new ``base`` option) so it inherits the 15s abort, typed error mapping, empty-body guard, and detail parsing every other endpoint gets. Non-integer / non-positive ids are filtered out at the boundary. (M5) - req() throws WorkspaceApiError on an empty 2xx body (previously returned undefined as T, producing a downstream TypeError the typed switches couldn't classify). ``allowEmptyBody`` opt-in for 204 endpoints. (m7) - AbortError is now distinguished from a network failure — the 15s abort produces "Request timed out after 15s" instead of the generic "Cannot reach" message. (m8) - Session-idle listener now captures the unsubscribe from events.listen() and tears itself down when the pending-sessions Set drains. Previously the listener was permanently installed for the process lifetime, and a failed install could leave a duplicate handler behind that fired workspace prompts twice. (m4) - Failed pre-check in cli/cmd/link.ts now retries a bindExisting → 409 as an unconditional rebind, so a user whose pre-check network-flaked isn't stuck at "Already linked to X" with no next step. (m10) Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): bot-review round 1 — GitGuardian unblock + null-body guard + safe manage_url open - Replace token-shaped documentation example in detect.ts with a generic <username>/<token> placeholder so GitGuardian's "Basic Auth String" detector stops flagging the comment. Not a real credential; the swap is cosmetic + pipeline-unblocking. (CR + GitGuardian) - req() empty-body guard now uses ``== null`` so a literal JSON ``null`` response (which parses to the JS null, not undefined) is rejected too. Previously ``json === undefined`` missed the null case and returned ``null as T``, producing a downstream ``TypeError: Cannot read properties of null`` that the typed switches couldn't classify. (CR) - Both open(manage_url) call sites now validate the URL parses as http(s) before handing to open(). ``open`` delegates to the OS scheme handler, so a rogue server-supplied protocol could launch an unrelated application. Extracted a tiny ``isSafeHttpUrl`` helper (duplicated in each file — the modules deliberately don't cross-import). (CR) Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): bot-review round 2 — timeout-through-body-read, cache shape validation, listener install race, fire-and-forget catch, test isolation - Keep the AbortController timeout ACTIVE while ``req()`` reads the response body. ``fetch()`` resolves after headers arrive; a server can send headers and then stall the body stream forever, and clearing the timer in the first ``finally`` broke the 15s cap. Move ``res.text()`` inside the same try/finally so both the fetch AND the body read fire the same ``AbortError``. (CR) - ``readCache()`` runs a runtime shape check on the parsed JSON before returning — validates version, string tenant/apiUrl, object bindings, and each binding's field types. Previously ``{"version":1,"bindings":null}`` would pass the type assertion and then throw a ``TypeError`` on ``cache.bindings[k]``. (CR) - ``armWorkspacePromptOnSessionIdle`` serializes concurrent install attempts via a shared in-flight promise. Previously two concurrent scans could both pass the ``!workspacePromptUnsubscribe`` check before either install completed, both would install a listener, and the later assignment would overwrite the first disposer — leaking the first listener for the process lifetime. (CR) - The keymap ``run()`` callbacks now attach a ``.catch(reportFlowFailure)`` to the returned promises instead of dropping them with ``void``. An unhandled rejection from ``recordApprovedBinding`` / ``readLocalBinding`` / anything else awaited inside would otherwise terminate the TUI process. (CR) - Test isolation: workspace.test.ts now restores ``XDG_STATE_HOME`` in ``afterAll`` and cleans up its SANDBOX tempdir; ``detectProjectRemote`` test uses a freshly-created empty dir under SANDBOX instead of ``os.tmpdir()`` (which can be inside a git worktree, causing the "not a git repo" assertion to fail on ``git remote get-url``). (CR) Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): bot-review round 3 — listDatamates shape, teardown Effect, body-read abort, cache best-effort, skip-latch tenant scope - listDatamates() now accepts three response envelopes — today's {datamates: [...]}, a bare array, and a generic {data: [...]} — so a backend contract change or compat layer doesn't silently empty the workspace picker. Also filters non-string names alongside the existing integer/positive id guard. (cubic P1) - events.listen() returns an Effect, not a callable — the earlier teardown cast to (() => void) would have thrown on drain, leaving the listener installed. Store the Effect and run it via AppRuntime.runPromise on teardown. Also drain EVERY session that awaited the shared install promise on install failure, not just the one caller — later waiters see success from the promise and stop retrying, leaving permanently-stale entries otherwise. (cubic P2) - req() body-read: dropped the .catch(() => "") wrapper on res.text(). It swallowed the AbortError from the timeout firing during the body read and turned a stalled response into a false "empty body". Any read rejection now rethrows into the outer catch and is classified there (AbortError → timeout WorkspaceApiError). (cubic P2) - recordApprovedBinding() is now best-effort: cache-write failures (read-only state dir, disk full) are logged and swallowed so the caller doesn't report the server-side link as failed and prompt a duplicate retry. (cubic P2) - isValidCacheFile rejects rows with BOTH repoRemote and projectPath null/empty — the offline-fallback render path would otherwise present a phantom workspace with no identity to verify against. (cubic P2) - Skip latch key now includes (tenant, apiUrl) scope, matching the local binding cache. Otherwise a Skip in one Altimate account suppresses the post-scan prompt for the same project in every other account for 7 days. Scope is resolved once by runFlow (currentLatchScope) and threaded into OfferDialog so its sync onSelect can call recordSkip without a mid-render await. (cubic P3) - projectNameFromRemote handles foo.git/ (trailing slash after .git) — earlier .git$ → /$ pipeline missed it because the final / wasn't .git any more. (cubic P2) - Test isolation follow-up: use GIT_CEILING_DIRECTORIES in the detectProjectRemote test so git can't walk up out of SANDBOX and return an ancestor repo's remote. New cross-tenant Skip-latch test. Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): bot-review round 4 — Array.isArray guard on listDatamates envelope fields If ``/datamates`` returns ``{datamates: <non-array>}`` or ``{data: <non-array>}`` (object, string, null — e.g. from a legacy proxy or a schema mismatch), the round-3 unguarded assignment would let a non-array reach ``.map`` and crash the picker before it rendered. ``Array.isArray`` on each envelope field falls back to ``[]`` instead. (cubic round 4.) Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): bot-review round 5 — pre-map null-row guard, contain fire-and-forget rejection Two cycle-5 findings on files shared with #1100: - **api-client.ts listDatamates** (Kilo warning) — a single ``null`` element in an otherwise-valid rows array threw ``TypeError`` on ``d.id`` before the post-map filter could drop it. That's the exact picker-down failure the round-3/4 envelope guards were added to prevent, just per-element. Filter valid row objects BEFORE the map. - **workspace.tsx createAndBindInline** (Kilo warning) — the post-success tail (``recordApprovedBinding`` + ``open()`` + toasts) sat outside any try inside a fire-and-forget entry point. An unhandled rejection could take the TUI down. Contain the tail in a try/catch that falls back to a plain info toast so the user still sees the URL. Test suite green (33 pass in workspace suites, no regressions in the wider altimate test set). Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): bot-review round 6 — flag opt-in, skip clock rewind, cred guard, canonical cache key, placeholder rows, 409-fallback endpoint Six correctness fixes landed on the branch; a seventh finding (already-linked "Create new" → orphaned workspace) is documented as deferred because a CLI-only fix isn't possible without a new backend endpoint. - **``ALTIMATE_WORKSPACE`` opt-in only** (Kilo warning) — was routed through ``enabledByExperimental`` and silently inherited ``OPENCODE_EXPERIMENTAL``. Users opted into other experimental features were getting the Workspaces pilot turned on for them, contradicting the "off by default" rollout. Swap to bare ``truthy("ALTIMATE_WORKSPACE")``. - **Skip latch rejects future timestamps** (CodeRabbit minor) — a clock rewind after ``recordSkip`` would produce ``nowMs - skippedAt < 0``, trivially under the 7-day TTL, and suppress the prompt indefinitely. Treat future timestamps as corrupt and re-offer on the next scan. - **``tenantKey`` guards ``getCredentials``** (Kilo warning) — the helper can throw ``SyntaxError`` / ``ZodError`` / raw ``Error`` on corrupt or drifted credentials; those were escaping the "best effort" contract of the state module and terminating fire-and-forget callers. Wrap in try/catch and log-warn. - **``link.ts`` cache key uses canonical identifier** (Kilo warning) — was ``recordApprovedBinding(args.directory, ...)`` which stored under the raw --directory arg; ``altimate-code link -d ./myproj`` and its symlink-resolved twin produced two separate cache rows. Prefer ``identifier.projectPath`` (canonicalized by ``resolveProjectIdentifier``). - **Placeholder rows no longer filtered** (Kilo warning) — ``DialogSelect`` drops ``disabled: true`` options, so the "Loading workspaces..." and "No workspaces yet..." rows never rendered and the picker showed an empty list. Remove ``disabled: true``; the ``value === -1`` guard in ``onSelect`` already closes the dialog on selection. - **409-fallback rebind picks endpoint from conflict detail** (Kilo warning) — was keying off the current project identifier, reproducing the M3 hazard: a path-keyed legacy binding hit ``rebindByRemote`` and 404'd. Derive the endpoint from ``err.detail.project_path`` / ``err.detail.repo_remote`` which the server sends for exactly this purpose. **Deferred to follow-up ticket:** - chatgpt-codex P1 "Create new workspace when already-linked → orphan" needs either a new backend endpoint that creates without binding, or a CLI refactor that calls the plain ``POST /datamates/`` route + rebind. Both are more than a bot-review-cycle fix. Noting so the ticket can be scheduled explicitly. Test suite: green (4058 pass, 0 fail across the altimate suite). Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): bot-review round 7 — canonical cache key, picker submit-guard, dead-param removal, non-TTY guard Five focused fixes from bot triage against #1099, verified against the current tip (`7207840e69`); earlier rounds (4/5/6) landed everything else. All 4058 altimate tests pass. - **state.ts** `canonicalDirKey` normalizes directory keys via `path.resolve` + `realpathSync` so `/tmp/foo`, `/private/tmp/foo` (macOS symlink), `/tmp/foo/`, and relative paths hit one row. Two clients pointing at the same project via different path spellings no longer see split cache rows. Falls back to resolved-only when the path doesn't exist yet. (cubic + kilo cycle 6.) - **workspace.tsx `PickerDialog`** adds a `submitting` latch inside `pick()`. `DialogSelect` delivers `onSelect` synchronously per Enter, and a second Enter before the network call resolved would fire a duplicate bind whose 409 toast then contradicts the first call's success toast. (kilo cycle 6.) - **workspace.tsx conflict-toast copy** used to say *"pick Re-link from the offer"* but `OfferDialog` has no Re-link row — a dead referral in the middle of a user's first bad experience. Points at the actual next action (`altimate-code link`) instead. (kilo cycle 6.) - **workspace.tsx `suppressLatch` removed** everywhere. `runFlow` never gets called with `suppressLatch: true` — the palette command `altimate.workspace.link` uses `runOnDemandPicker`, not `runFlow` — so the whole prop chain (interface field, ternary description, guard around `recordSkip`, `runFlow` opts, two threading sites into `OfferDialog`) was dead code. (kilo cycle 6.) - **link.ts non-TTY fail-fast** at handler top: `!process.stdin.isTTY` → error out immediately with a clear message pointing to the TUI palette alternative. Piped or redirected stdin (CI runner, background job, `< /dev/null`) would otherwise hang forever on the first `prompts.select` with no output. (kilo cycle 6.) Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * feat(workspace): --workspace <name> launch flag (AI-8504 item 1) Add a top-level `--workspace <name>` yargs option to `altimate-code` that pins the session to the workspace this directory is linked to, by name. Groundwork for AI-8397 / AI-8434 (memory RW to mem0 scoped to Workspace), where the resolved workspace id becomes the input to "which workspace am I in?" lookups. **Files:** - `altimate/workspace/session-context.ts` — env-var handoff so the main-thread resolver's result reaches the TUI worker subprocess. Same mechanism `ALTIMATE_LAUNCH_ID` uses (the existing worker-spawn `env: { ...process.env, ... }` spread in `cli/cmd/tui.ts` carries the resolved workspace id across for free). Guards against a malformed env-var value poisoning callers with NaN. - `altimate/workspace/launch-resolve.ts` — the resolver. `nameMatches(name, binding)` is case-insensitive + whitespace-trimmed, exact match only, no fuzzy match, no backend name search (same-directory-only per the AI-8504 spec and Path A reference on `feature/workspace-link-onboarding`). Missing binding → prints an error and returns without setting the env var. Wrong name against an existing binding → prints a note and attaches to the linked workspace anyway (ticket's explicit choice: "print a note and continue with the currently-linked one"). The flag is gated on `Flag.ALTIMATE_WORKSPACE` so it's invisible to non-pilot users. - `cli/cmd/tui.ts` — adds the yargs option and calls the resolver after `cwd` is resolved but before `new Worker(...)`. Wrapped in a try/catch that logs and continues so a resolver failure can never block launch. - `test/altimate/workspace/launch-resolve.test.ts` — 13 unit tests covering `nameMatches` (exact / case / whitespace / mismatch / substring), `resolveWorkspaceForLaunch` (no arg, flag off, matching name, case-insensitive match, mismatch-still-attaches, unlinked dir), and the session-context env-var round trip (set/get/clear, malformed value returns null). **Manual smoke:** Rebuilt binary, seeded a test binding, ran end-to-end against a temp directory: matching name prints `Attached to workspace "Growth"`, wrong name prints the note + attaches to the linked workspace, unlinked dir errors cleanly, and `ALTIMATE_WORKSPACE=0` makes the flag silent-no-op. All observed as designed. **No consumer on #1099** — the sidebar tile that reads "current workspace" lives on the #1100 branch. This PR ships the flag + resolver + env-var infrastructure; a follow-up commit on #1100 wires the sidebar to prefer `getResolvedWorkspaceId()` over its current on-disk binding read. **Drift resolver (AI-8504 item 2) is NOT included** — it needs a backend PATCH-binding endpoint that doesn't exist yet, plus a conflict-of-interest to think through with the post-scan drift prompt already shipped in `workspace.tsx`. Tracked separately. Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): satisfy Marker Guard — insert --workspace option BEFORE --agent Marker Guard failed on b193a5c because the --workspace option was chained AFTER .option("agent"), which required moving the upstream trailing comma. Marker Guard flagged the modified upstream line as "new code without marker" even though a marker was placed above it. Fix: insert .option("workspace") BEFORE .option("agent") in the yargs chain so the upstream .option("agent") closer stays byte-for- byte unchanged. Wrap the new option in a paired altimate_change start/end marker. Behaviour-free — same set of options with the same behavior; just different insertion point in the builder chain. Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * docs(workspace): address altimate-harness-bot review — cross-refs + SessionEvent.Idle NOTE Three trivial doc additions from bot review (altimate-code #1099): 1. `isSafeHttpUrl` in link.ts now points to its verbatim copy in workspace.tsx ("keep in sync when the allowed-protocol set changes"). 2. `rebindByMatchedIdentifier` in link.ts now points to its verbatim copy in workspace.tsx ("keep in sync when the M3 endpoint-selection logic changes"). 3. Added an inline NOTE at the `event.type !== SessionEvent.Idle.type` check explaining that `SessionEvent` here is the module-local alias for the MODERN `Event` (EventV2.define), not the deprecated `LegacyEvent.Idle`. Bots have flagged this token as "deprecated" twice in review; defusing it in-source so it doesn't come up again. Comments only. Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM * fix(workspace): address harness-bot round 8 — Event.Status + clear() on install fail Two findings on packages/opencode/src/altimate/plugin/onboarding-telemetry.ts: 1. Subscribe to Event.Status with status.type === "idle" instead of the deprecated Event.Idle. session/status.ts:49 marks Event.Idle as `// deprecated`; the non-deprecated path is Event.Status filtered on the idle status shape (matching what session/status.ts:176 uses for the legacy Bus SSE mirror). Replaces the earlier NOTE that only asserted "not the deprecated LegacyEvent" — the NOTE was technically correct but deflected from the fact that Event.Idle itself is deprecated too. (altimate-harness-bot #1099 comment 3837907427.) 2. Drain the pending set with pendingWorkspacePromptSessions.clear() on install failure instead of iterating an install-time snapshot. A second scan calling armWorkspacePromptOnSessionIdle after the snapshot but before the install fails would otherwise leave its sessionID as a permanent orphan in the pending set — no listener would ever fire for it, so its post-scan workspace prompt would silently never arm. (altimate-harness-bot #1099 comment 3837907105, P2.) --------- Co-authored-by: Haider <[email protected]> Co-authored-by: Claude Opus 4.7 <[email protected]>
1 parent 96e59ba commit e3f7495

15 files changed

Lines changed: 2722 additions & 2 deletions

File tree

‎packages/core/src/flag/flag.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,19 @@ export const Flag = {
6363
OPENCODE_WORKSPACE_ID: process.env["OPENCODE_WORKSPACE_ID"],
6464
OPENCODE_EXPERIMENTAL_WORKSPACES: enabledByExperimental("OPENCODE_EXPERIMENTAL_WORKSPACES"),
6565

66+
// altimate_change start — pilot flag for the Workspaces feature (post-scan prompt +
67+
// altimate link subcommand). Read as a getter so tests and the runtime `--` middleware
68+
// can flip it between plugin activation and command execution.
69+
//
70+
// Opt-in only — deliberately does NOT inherit ``OPENCODE_EXPERIMENTAL`` (as
71+
// ``enabledByExperimental`` would). The pilot ships behind its own explicit
72+
// gate so users already opted into other experimental features don't get
73+
// this one turned on for them. (Kilo cycle 6.)
74+
get ALTIMATE_WORKSPACE() {
75+
return truthy("ALTIMATE_WORKSPACE")
76+
},
77+
// altimate_change end
78+
6679
// Evaluated at access time (not module load) because tests, the CLI, and
6780
// external tooling set these env vars at runtime.
6881
get OPENCODE_DISABLE_PROJECT_CONFIG() {

‎packages/opencode/src/altimate/plugin/onboarding-telemetry.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,112 @@
1212
// session loop.
1313
import type { Hooks, PluginInput } from "@opencode-ai/plugin"
1414
import * as OnboardingTelemetry from "../telemetry/onboarding"
15+
// altimate_change start — AI-8398 workspaces trigger. Reaches into the same
16+
// EventV2 bridge the server/routes/tui.ts uses to publish TuiEvent.CommandExecute
17+
// so the workspace TuiPlugin (packages/opencode/src/plugin/tui/altimate/workspace.tsx)
18+
// runs its post-scan flow. Feature-flagged via Flag.ALTIMATE_WORKSPACE.
19+
import { Effect } from "effect"
20+
import { Flag } from "@opencode-ai/core/flag/flag"
21+
import { AltimateApi } from "@/altimate/api/client"
22+
import { AppRuntime } from "@/effect/app-runtime"
23+
import { EventV2Bridge } from "@/event-v2-bridge"
24+
import { TuiEvent } from "@/server/tui-event"
25+
import { Event as SessionEvent } from "@/session/status"
26+
import { Log } from "@/altimate/util/log"
27+
28+
const workspaceLog = Log.create({ service: "altimate-workspace" })
29+
30+
/**
31+
* Publish the workspace-postScan command AFTER the session goes idle, not on
32+
* `project_scan`'s tool.execute.after. Rationale: project_scan tool RETURNS while
33+
* the LLM is still generating the activation-menu text; the dialog paints in
34+
* that window but user interactions queue behind the streaming. Waiting for
35+
* session.idle costs a few seconds of latency but sidesteps the race entirely —
36+
* the dialog appears once things are quiet.
37+
*
38+
* One-shot per sessionID: pending sessions live in a Set, and when a session
39+
* emits idle its id is removed. When the Set drains, the EventV2 listener is
40+
* torn down via the unsubscribe returned by ``events.listen()`` so a
41+
* permanently-installed no-op handler isn't left behind for the process
42+
* lifetime (m4 in the consensus review). A pending arm is dropped if a
43+
* second project_scan fires in the same session.
44+
*/
45+
const pendingWorkspacePromptSessions = new Set<string>()
46+
/** The unsubscribe returned by ``events.listen()`` is an Effect (not a plain
47+
* function) — running it removes the listener. Store the Effect and execute
48+
* it through ``AppRuntime.runPromise`` on teardown; earlier code cast it to
49+
* ``() => void`` and called it directly, which threw because Effects are not
50+
* callable as functions. (cubic-dev-ai round 3.) */
51+
let workspacePromptUnsubscribe: Effect.Effect<void, never, never> | null = null
52+
// Guard against two concurrent scans passing the ``!workspacePromptUnsubscribe``
53+
// check before either install completes — both would then install a listener
54+
// and the later assignment would overwrite the first disposer, leaking the
55+
// first listener for the process lifetime. Store the in-flight install as a
56+
// shared promise so concurrent callers await the same result. (CR round 2.)
57+
let workspacePromptInstall: Promise<void> | null = null
58+
59+
async function armWorkspacePromptOnSessionIdle(sessionID: string): Promise<void> {
60+
pendingWorkspacePromptSessions.add(sessionID)
61+
if (workspacePromptUnsubscribe) return
62+
if (workspacePromptInstall) return workspacePromptInstall
63+
64+
workspacePromptInstall = (async () => {
65+
try {
66+
const unsubscribe = await AppRuntime.runPromise(
67+
EventV2Bridge.Service.use((events) =>
68+
events.listen((event) =>
69+
Effect.gen(function* () {
70+
// Subscribe to ``Event.Status`` (session/status.ts:42, defined
71+
// via ``EventV2.define``) rather than ``Event.Idle`` — the
72+
// latter is marked ``// deprecated`` at session/status.ts:49
73+
// and is only kept around for the legacy Bus SSE mirror at
74+
// session/status.ts:176. Filtering ``event.data.status.type
75+
// === "idle"`` gives us the same trigger without riding the
76+
// deprecated event. (harness-bot round 8.)
77+
if (event.type !== SessionEvent.Status.type) return
78+
const data = event.data as
79+
| { sessionID?: string; status?: { type?: string } }
80+
| undefined
81+
if (data?.status?.type !== "idle") return
82+
const sid = data.sessionID
83+
if (!sid || !pendingWorkspacePromptSessions.has(sid)) return
84+
pendingWorkspacePromptSessions.delete(sid)
85+
yield* events.publish(TuiEvent.CommandExecute, {
86+
command: "altimate.workspace.postScan",
87+
})
88+
// Once the Set drains, tear the listener down. A later scan
89+
// that adds a new pending session re-arms it from scratch.
90+
// ``teardown`` is an Effect — run it through the app runtime,
91+
// don't call it as a function. (cubic round 3.)
92+
if (pendingWorkspacePromptSessions.size === 0 && workspacePromptUnsubscribe) {
93+
const teardown = workspacePromptUnsubscribe
94+
workspacePromptUnsubscribe = null
95+
AppRuntime.runPromise(teardown).catch((err) => {
96+
workspaceLog.warn("session-idle listener teardown failed", {
97+
err: String(err),
98+
})
99+
})
100+
}
101+
}),
102+
),
103+
),
104+
)
105+
workspacePromptUnsubscribe = unsubscribe
106+
} catch (err) {
107+
// Install failed — drain EVERY pending session, not just the ones
108+
// snapshotted at install-time. A late-arriving ``armWorkspacePromptOn
109+
// SessionIdle`` between the snapshot and the failure would otherwise
110+
// be a permanent orphan (its sessionID stays in the pending set but
111+
// no listener will ever fire for it). (harness-bot round 8.)
112+
pendingWorkspacePromptSessions.clear()
113+
workspaceLog.warn("session-idle listener install failed", { err: String(err) })
114+
} finally {
115+
workspacePromptInstall = null
116+
}
117+
})()
118+
return workspacePromptInstall
119+
}
120+
// altimate_change end
15121

16122
const ONBOARD_CONNECT = "onboard-connect"
17123

@@ -134,6 +240,14 @@ export async function OnboardingTelemetryPlugin(_input: PluginInput): Promise<Ho
134240
},
135241
input.sessionID,
136242
)
243+
// altimate_change start — AI-8398 workspaces post-scan prompt trigger.
244+
// ARM (don't publish yet) — the dialog fires when the session goes idle,
245+
// not the moment project_scan returns. See armWorkspacePromptOnSessionIdle
246+
// above for why the immediate publish raced the LLM's ongoing streaming.
247+
if (Flag.ALTIMATE_WORKSPACE && (await AltimateApi.isConfigured().catch(() => false))) {
248+
void armWorkspacePromptOnSessionIdle(input.sessionID)
249+
}
250+
// altimate_change end
137251
return
138252
}
139253

‎packages/opencode/src/altimate/tools/project-scan.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,13 @@ export async function detectGit(): Promise<GitInfo> {
173173
* SSH-form remotes (`[email protected]:owner/repo.git`) have no userinfo
174174
* concept and are left untouched. URLs we can't parse are dropped to
175175
* undefined (better to lose the breadcrumb than leak creds).
176+
*
177+
* Exported so the workspace TuiPlugin (packages/opencode/src/plugin/tui/
178+
* altimate/workspace.tsx) can reuse the exact same scrubbing rules when
179+
* deriving the project's git remote for the post-scan prompt — the alt
180+
* of duplicating the logic risks the two callers drifting.
176181
*/
177-
function stripGitRemoteCredentials(url: string): string | undefined {
182+
export function stripGitRemoteCredentials(url: string): string | undefined {
178183
if (!url) return undefined
179184
// SSH form: `git@host:path` — no creds to strip.
180185
if (/^[\w.-]+@[\w.-]+:/.test(url) && !url.includes("://")) return url

0 commit comments

Comments
 (0)