Add contextual feature tours (#2734)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-01 21:20:15 -07:00
committed by GitHub
co-authored by Orca
parent d136abd10c
commit 5b1f297078
125 changed files with 10252 additions and 180 deletions
@@ -24,7 +24,7 @@ diff --git a/src/GlyphRenderer.ts b/src/GlyphRenderer.ts
index 46b8efe..4b36a78 100644
--- a/src/GlyphRenderer.ts
+++ b/src/GlyphRenderer.ts
@@ -387,8 +387,13 @@ export class GlyphRenderer extends Disposable {
@@ -387,7 +387,12 @@ export class GlyphRenderer extends Disposable {
gl.bindTexture(gl.TEXTURE_2D, this._atlasTextures[i].texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
@@ -38,4 +38,3 @@ index 46b8efe..4b36a78 100644
- gl.generateMipmap(gl.TEXTURE_2D);
this._atlasTextures[i].version = atlas.pages[i].version;
}
+3 -5
View File
@@ -1,7 +1,6 @@
# Durable Docs
Keep this folder for versioned reference docs that are meant to survive past a
single design or implementation pass.
Keep this folder for versioned reference docs that are meant to survive past a single design or implementation pass.
## What Goes Here
@@ -9,9 +8,8 @@ single design or implementation pass.
- Public-facing docs that are not part of the root README.
- Docs that other checked-in files link to.
- Telemetry availability notes that dashboard authors need after the original design or implementation branch is gone. See [Telemetry Availability](./telemetry-availability.md).
- Feature education state, interaction tracking, and retention analytics notes that define how contextual tours are persisted and measured. See [Feature Education State](./feature-education-state.md), [Feature Discovery Interaction Tracking](./feature-discovery-interaction-tracking.md), and [Feature Education Retention Analytics](./feature-education-retention-analytics.md).
## What Stays Out
Ephemeral design notes, implementation sketches, and planning docs should stay as
local Markdown files under `docs/`. They are ignored by default so they do not get
checked in accidentally.
Ephemeral design notes, implementation sketches, and planning docs should stay as local Markdown files under `docs/`. They are ignored by default so they do not get checked in accidentally.
@@ -58,6 +58,7 @@ Do not upload this state as broad analytics. Product analytics should continue t
Orca also records surface-level interactions for feature areas where opening the surface is itself a meaningful discovery signal:
- `workspace-board`: workspace board opened
- `workspace-agent-sessions`: workspace terminal surface opened with agent split controls visible
- `browser`: non-blank browser page viewed
- `tasks`: Tasks page opened
- `automations`: Automations page opened
@@ -0,0 +1,182 @@
# Feature Education Retention Analytics
This document records how Orca should use contextual-tour telemetry to evaluate retention and feature adoption.
## Decision
Track only contextual tour exposure and outcome in PostHog:
- `contextual_tour_shown`
- `contextual_tour_outcome`
Do not add broad telemetry that mirrors local education state, such as "feature interaction first recorded." Local state like `featureInteractions` exists to suppress redundant education on the user's machine; it is not the analytics source of truth.
Feature adoption analysis should join tour cohorts to existing downstream product events. Add new telemetry only for concrete user actions that are not already represented by an existing event.
Automatic contextual tours are limited to new users for this rollout. The local `contextualToursAutoEligible` flag is set once after persisted UI and onboarding state load: users still in first-run onboarding become eligible; users with closed onboarding become ineligible. This avoids surprising existing users with education for surfaces they may already understand.
## Product Questions
Use the data to answer:
- Do users who see contextual tours retain better at D1 and D7?
- Do completed tours correlate with higher downstream feature adoption than skipped or cancelled tours?
- Which tours have high skip/cancel rates and should be revised or suppressed?
- Which tours introduce features that users later use in real workflows?
## Event Contract
### `contextual_tour_shown`
Emitted once when a contextual tour first renders a measured target.
Payload:
- `tour_id`: `workspace-board`, `workspace-agent-sessions`, `browser`, `tasks`, `automations`, or `workspace-creation`
- `source`: bounded source enum from `src/shared/feature-education-telemetry.ts`
- `was_feature_previously_interacted`: boolean from local education state at the moment the tour is shown
### `contextual_tour_outcome`
Emitted once when a contextual tour ends.
Payload:
- `tour_id`: same enum as `contextual_tour_shown`
- `source`: same bounded source enum
- `outcome`: `completed`, `skipped`, or `cancelled`
- `steps_seen`: bounded integer
- `total_steps`: bounded integer
## Dashboard Plan
Create a PostHog dashboard named **Feature Education Retention**.
### Tile: Tour Exposure Volume
Question: How often are tours shown?
Insight:
- Event: `contextual_tour_shown`
- Breakdown: `tour_id`
- Visualization: stacked time series by day
Action:
- If volume is unexpectedly high, inspect gating before expanding tours.
- If a tour is never shown, verify the surface gate and target selectors.
### Tile: Tour Outcome Rate
Question: Which tours are completed, skipped, or cancelled?
Insight:
- Event: `contextual_tour_outcome`
- Breakdown: `tour_id` and `outcome`
- Visualization: stacked bar or table
Action:
- High skipped rate means copy, timing, or audience targeting needs revision.
- High cancelled rate means UI state is likely interrupting tours or targets are disappearing.
### Tile: Median Steps Seen
Question: How far do users get before leaving?
Insight:
- Event: `contextual_tour_outcome`
- Metric: median `steps_seen`
- Breakdown: `tour_id`
- Optional derived ratio: `steps_seen / total_steps`
Action:
- If most users see only step 1, shorten or reprioritize the tour.
- If later steps are rarely reached, do not rely on those steps for critical education.
### Tile: D1/D7 Retention By Tour Outcome
Question: Does tour status correlate with retention?
Insight:
- Cohort A: users with `contextual_tour_outcome` where `outcome = completed`
- Cohort B: users with `contextual_tour_outcome` where `outcome = skipped`
- Cohort C: users with `contextual_tour_outcome` where `outcome = cancelled`
- Cohort D: users with no `contextual_tour_shown`
- Retention: return to `app_opened` on day 1 and day 7
- Breakdown: `tour_id` where PostHog supports it, otherwise build one insight per tour
Action:
- Keep or expand tours whose completed cohort outperforms skipped/no-tour cohorts.
- Rework or suppress tours whose shown cohort underperforms no-tour users.
### Tile: Downstream Feature Adoption By Tour
Question: Do users later use the feature taught by the tour?
Build funnels from tour events to real product events:
- `tasks`: `contextual_tour_outcome` -> workspace creation from task-linked flows where existing telemetry exposes the source; if the current event is insufficient, add a targeted task-started-workspace event.
- `workspace-creation`: `contextual_tour_outcome` -> `workspace_created`
- `browser`: `contextual_tour_outcome` -> browser grab/annotation events. If these do not exist, add targeted events for the concrete actions, not a broad feature-interaction event.
- `automations`: `contextual_tour_outcome` -> automation creation/run events. If these do not exist, add targeted events for create/run.
- `workspace-board`: `contextual_tour_outcome` -> board-specific actions such as card moved/status changed. If these do not exist, add targeted events for those actions.
- `workspace-agent-sessions`: `contextual_tour_outcome` -> terminal pane split actions and later workspace creation.
Recommended funnel shape:
1. `contextual_tour_shown` filtered by `tour_id`
2. `contextual_tour_outcome` filtered by same `tour_id`, broken down by `outcome`
3. Downstream action event within 1 day and 7 days
Action:
- If completion improves downstream action conversion, keep the tour.
- If shown-but-skipped users still convert, the surface may be discoverable without a tour.
- If no downstream event exists, add the smallest action-specific telemetry needed for that feature.
## Telemetry Cost Rule
At 1,000 DAU, this PR should emit at most:
- One `contextual_tour_shown` per shown tour
- One `contextual_tour_outcome` per shown tour
- Currently one contextual tour per session
Expected launch volume: under 2,000 events/day at 1,000 DAU and lower for mature cohorts because existing users are not auto-eligible and `contextualToursSeenIds` fills in for eligible new users.
Do not add recurring, render-loop, polling, passive snapshot, or local-state-mirror events for this analysis.
## Privacy Rule
Payloads must remain low-cardinality and bounded. Do not include:
- prompts
- commands
- paths
- URLs
- hostnames
- repo names
- branch names
- user-entered text
- raw errors
- tokens or IDs beyond the existing anonymous telemetry identity
## Existing Users
Existing users should not receive automatic contextual tours from this rollout. We cannot reliably know whether they have already viewed or used every covered surface, so the least surprising default is to leave them alone and measure this launch on new-user cohorts.
Implementation:
- `contextualToursAutoEligible: false` for profiles whose onboarding is already closed when the rollout first runs
- `contextualToursAutoEligible: true` for profiles still in first-run onboarding when the rollout first runs
- automatic tour requests require `contextualToursAutoEligible === true`
- local `featureInteractions` still records supported surface entry for all users after UI hydration
For existing-user analysis, compare users by actual tour exposure and outcome only when they have exposure. Most existing users should fall into the no-tour baseline for this PR. If a later release adds manual tour entry points or truly new feature education, evaluate that release separately instead of reusing this rollout's eligibility rule.
+75
View File
@@ -0,0 +1,75 @@
# Feature Education State
Orca uses local persisted UI state to decide which education surfaces should appear for a user. Keep these concepts separate; they answer different questions and should not be collapsed into one flag.
For the feature-interaction catalog, see [`feature-discovery-interaction-tracking.md`](./feature-discovery-interaction-tracking.md). For retention analysis and dashboard construction, see [`feature-education-retention-analytics.md`](./feature-education-retention-analytics.md).
## State Types
`featureTipsSeenIds` answers: "Has Orca already surfaced this tip?"
Set this when a restart tip is opened, dismissed, or acted on. It prevents the same tip from reappearing after restart, crash, or dismissal. It does not mean the user used the feature.
`contextualToursSeenIds` answers: "Has Orca already surfaced this contextual tour?"
Set this after a tour has rendered a measured target, or when the user skips/completes the tour. It prevents the same tour from showing again. It does not mean the user used the feature.
`contextualToursAutoEligible` answers: "May this profile receive automatic contextual tours from this rollout?"
Missing means Orca has not classified the profile yet. On first hydrated launch after this change, the renderer sets it once:
- `true` when first-run onboarding is still open, which covers new users from this rollout forward
- `false` when onboarding is already closed, which covers existing users
Automatic contextual tours require this flag to be `true`. Existing users still get local feature interaction state recorded when they enter supported surfaces, but they are not auto-toured by this rollout.
`featureInteractions` answers: "Has the user actually interacted with this feature?"
This is the product-state signal for already-discovered features. It lives in `PersistedUIState.featureInteractions`, keyed by `FeatureInteractionId`, and stores the first local interaction timestamp plus a local interaction count:
```ts
{
tasks: {
firstInteractedAt: 1716500000000,
interactionCount: 3
}
}
```
Use this to suppress tips or tours that would teach a feature the user has already found on their own.
## Rules
- Define every trackable feature in `src/shared/feature-interactions.ts`.
- The `interaction` text must clearly state what counts as "used." Avoid vague labels like "seen" or "visited" unless passive visibility is truly the intended signal.
- Record only the first interaction. Repeated opens should not churn the user-data file.
- Record interactions only after persisted UI state is hydrated, so startup defaults cannot overwrite real user data.
- Do not rename or reuse ids. If semantics change materially, add a new id and leave the old one readable.
- Unknown or malformed persisted ids are ignored during hydration for forward/backward compatibility.
- This state is local product state, not telemetry. Analytics should use the bounded feature-education telemetry events (`contextual_tour_shown` and `contextual_tour_outcome`) plus existing downstream action events, rather than reading or uploading the persisted state blob.
- Automatic contextual tours are new-user-only for this rollout. Do not reset `contextualToursAutoEligible` for existing users unless the product decision changes for a later release.
## Adding A Tip
When a tip should not show after the user has already used the feature, add the relevant interaction id to the tip definition:
```ts
{
id: 'voice-dictation',
completedByFeatureInteractions: ['voice-dictation']
}
```
Then make sure the feature records its interaction at the meaningful product moment. For example, voice dictation records only after a session reaches `listening`, not when the settings pane opens.
## Adding A Tour
Tours still use `contextualToursSeenIds` to avoid repeating the same tour. If opening or using the toured surface should also suppress future education for that feature, call `recordFeatureInteraction(featureId)` from the surface's meaningful interaction point.
For contextual tours in this branch, `useContextualTour(...)` records the matching interaction once the surface is enabled and persisted UI is ready. Surface-specific gates decide what "enabled" means; for example, the browser tour waits for a non-blank local browser page.
## Test Profiles
Completed-onboarding E2E profiles should preseed both education exposure and feature interaction state. That keeps first-run education from covering unrelated UI under test while preserving production behavior for real profiles.
Profiles that model existing users should also set `contextualToursAutoEligible: false`; profiles that explicitly exercise contextual tours can set it to `true`.
+3 -3
View File
@@ -9,7 +9,7 @@ patchedDependencies:
hash: df21db050a4d85552cafbe583ece863d7fa19ed634a1219210a0455b986b6634
path: config/patches/@xterm__addon-ligatures@0.11.0-beta.220.patch
'@xterm/addon-webgl@0.20.0-beta.219':
hash: b7465b48cca8d596e3bf0e441f939100c95adaddef13e85df089ed0ad6f6b1ea
hash: c76ae4cd585a6b2ea39a39e3c021f125f42afdafeffd3b1a767a3200deb4ffb2
path: config/patches/@xterm__addon-webgl@0.20.0-beta.219.patch
node-pty@1.1.0:
hash: 407ae07e1e0e2ff2e8b58696449c54c31e51d87535bc6aa4a7a7b0b561407282
@@ -187,7 +187,7 @@ importers:
version: 0.13.0-beta.220(@xterm/xterm@6.1.0-beta.220)
'@xterm/addon-webgl':
specifier: 0.20.0-beta.219
version: 0.20.0-beta.219(patch_hash=b7465b48cca8d596e3bf0e441f939100c95adaddef13e85df089ed0ad6f6b1ea)(@xterm/xterm@6.1.0-beta.220)
version: 0.20.0-beta.219(patch_hash=c76ae4cd585a6b2ea39a39e3c021f125f42afdafeffd3b1a767a3200deb4ffb2)(@xterm/xterm@6.1.0-beta.220)
'@xterm/xterm':
specifier: 6.1.0-beta.220
version: 6.1.0-beta.220
@@ -8958,7 +8958,7 @@ snapshots:
dependencies:
'@xterm/xterm': 6.1.0-beta.220
'@xterm/addon-webgl@0.20.0-beta.219(patch_hash=b7465b48cca8d596e3bf0e441f939100c95adaddef13e85df089ed0ad6f6b1ea)(@xterm/xterm@6.1.0-beta.220)':
'@xterm/addon-webgl@0.20.0-beta.219(patch_hash=c76ae4cd585a6b2ea39a39e3c021f125f42afdafeffd3b1a767a3200deb4ffb2)(@xterm/xterm@6.1.0-beta.220)':
dependencies:
'@xterm/xterm': 6.1.0-beta.220
+11
View File
@@ -642,6 +642,12 @@ function sendOpenFeatureTour(targetWindow?: BrowserWindow | null): void {
webContents?.send('ui:openFeatureTour')
}
function sendOpenSetupGuide(targetWindow?: BrowserWindow | null): void {
const webContents =
targetWindow && !targetWindow.isDestroyed() ? targetWindow.webContents : mainWindow?.webContents
webContents?.send('ui:openSetupGuide')
}
function sendOpenCrashReport(targetWindow?: BrowserWindow | null): void {
const webContents =
targetWindow && !targetWindow.isDestroyed() ? targetWindow.webContents : mainWindow?.webContents
@@ -1177,6 +1183,11 @@ app.whenReady().then(async () => {
recordCrashBreadcrumb('settings_opened')
mainWindow?.webContents.send('ui:openSettings')
},
onOpenSetupGuide: (targetWindow) => {
recordCrashBreadcrumb('setup_guide_opened')
const targetBrowserWindow = targetWindow instanceof BrowserWindow ? targetWindow : null
sendOpenSetupGuide(targetBrowserWindow)
},
onOpenCrashReport: (targetWindow) => {
recordCrashBreadcrumb('crash_report_opened')
const targetBrowserWindow = targetWindow instanceof BrowserWindow ? targetWindow : null
+29 -2
View File
@@ -27,6 +27,7 @@ function buildMenuOptions() {
return {
onCheckForUpdates: vi.fn(),
onOpenSettings: vi.fn(),
onOpenSetupGuide: vi.fn(),
onOpenFeatureTour: vi.fn(),
onOpenCrashReport: vi.fn(),
onBeforeReload: vi.fn(),
@@ -197,7 +198,12 @@ describe('registerAppMenu', () => {
const helpLabels = getSubmenu(template, 'Help').map((item) => item.label)
expect(helpLabels).toEqual(
expect.arrayContaining(['Report Crash...', 'Explore Orca', 'Check for Updates...'])
expect.arrayContaining([
'Report Crash...',
'Getting Started with Orca',
'Explore Orca',
'Check for Updates...'
])
)
})
@@ -216,7 +222,28 @@ describe('registerAppMenu', () => {
expect(fileLabels).not.toContain(`Settings\t${isMac ? '⌘,' : 'Ctrl+,'}`)
expect(fileLabels).not.toContain('Exit')
const helpLabels = getSubmenu(template, 'Help').map((item) => item.label)
expect(helpLabels).toEqual(['Report Crash...', undefined, 'Explore Orca'])
expect(helpLabels).toEqual([
'Report Crash...',
undefined,
'Explore Orca',
'Getting Started with Orca'
])
})
it('routes Getting Started with Orca through its callback', () => {
const options = buildMenuOptions()
registerAppMenu(options)
const setupGuideItem = getSubmenu(getTemplate(), 'Help').find(
(entry) => entry.label === 'Getting Started with Orca'
)
expect(setupGuideItem?.accelerator).toBeUndefined()
const targetWindow = {} as Electron.BaseWindow
setupGuideItem?.click?.({} as never, targetWindow, {} as Electron.KeyboardEvent)
expect(options.onOpenSetupGuide).toHaveBeenCalledTimes(1)
expect(options.onOpenSetupGuide).toHaveBeenCalledWith(targetWindow)
})
it('routes Feature tour through its callback', () => {
+8
View File
@@ -21,6 +21,7 @@ export function getNextDefaultOnAppearanceSettingValue(current: boolean | undefi
type RegisterAppMenuOptions = {
onOpenSettings: () => void
onOpenSetupGuide: (window?: Electron.BaseWindow | null) => void
onOpenFeatureTour: (window?: Electron.BaseWindow | null) => void
onOpenCrashReport: (window?: Electron.BaseWindow | null) => void
onCheckForUpdates: (options: { includePrerelease: boolean }) => void
@@ -38,6 +39,7 @@ type RegisterAppMenuOptions = {
function buildAndApplyMenu(options: RegisterAppMenuOptions): void {
const {
onOpenSettings,
onOpenSetupGuide,
onOpenFeatureTour,
onOpenCrashReport,
onCheckForUpdates,
@@ -106,6 +108,11 @@ function buildAndApplyMenu(options: RegisterAppMenuOptions): void {
click: (_menuItem, window) => onOpenFeatureTour(window)
}
const setupGuideItem: Electron.MenuItemConstructorOptions = {
label: 'Getting Started with Orca',
click: (_menuItem, window) => onOpenSetupGuide(window)
}
const crashReportItem: Electron.MenuItemConstructorOptions = {
label: 'Report Crash...',
click: (_menuItem, window) => onOpenCrashReport(window)
@@ -284,6 +291,7 @@ function buildAndApplyMenu(options: RegisterAppMenuOptions): void {
crashReportItem,
{ type: 'separator' },
featureTourItem,
setupGuideItem,
...(isMac
? []
: ([
+15
View File
@@ -2388,6 +2388,19 @@ describe('Store', () => {
})
})
it('updateUI merges contextual tour seen ids instead of replacing stale snapshots', async () => {
const store = await createStore()
store.updateUI({
contextualToursSeenIds: ['browser']
})
store.updateUI({
contextualToursSeenIds: ['workspace-agent-sessions', 'unknown', 'browser'] as never
})
expect(store.getUI().contextualToursSeenIds).toEqual(['browser', 'workspace-agent-sessions'])
})
it('normalizes malformed persisted feature discovery state on read', async () => {
writeDataFile({
schemaVersion: 1,
@@ -2396,6 +2409,7 @@ describe('Store', () => {
settings: {},
ui: {
featureTipsSeenIds: ['voice-dictation', 'unknown-tip', 'voice-dictation'],
contextualToursSeenIds: ['tasks', 'unknown', 'tasks'] as never,
featureInteractions: {
tasks: { firstInteractedAt: 100 },
automations: { firstInteractedAt: 150, interactionCount: 4 },
@@ -2410,6 +2424,7 @@ describe('Store', () => {
const store = await createStore()
expect(store.getUI().featureTipsSeenIds).toEqual(['voice-dictation'])
expect(store.getUI().contextualToursSeenIds).toEqual(['tasks'])
expect(store.getUI().featureInteractions).toEqual({
tasks: { firstInteractedAt: 100, interactionCount: 1 },
automations: { firstInteractedAt: 150, interactionCount: 4 }
+22
View File
@@ -93,6 +93,7 @@ import {
normalizeFeatureInteractions,
type FeatureInteractionId
} from '../shared/feature-interactions'
import { normalizeContextualTourIds } from '../shared/contextual-tours'
import { normalizeFeatureTipIds } from '../shared/feature-tips'
import {
DEFAULT_WORKSPACE_STATUS_ID,
@@ -299,6 +300,17 @@ function mergeFeatureInteractions(
return merged
}
function mergeContextualTourSeenIds(
current: PersistedState['ui']['contextualToursSeenIds'],
incoming: PersistedState['ui']['contextualToursSeenIds']
): PersistedState['ui']['contextualToursSeenIds'] {
const merged = new Set(normalizeContextualTourIds(current))
for (const id of normalizeContextualTourIds(incoming)) {
merged.add(id)
}
return [...merged]
}
function normalizeSortBy(sortBy: unknown): PersistedState['ui']['sortBy'] {
if (
sortBy === 'smart' ||
@@ -2938,6 +2950,7 @@ export class Store {
this.state.ui?.showDotfilesByWorktree
),
featureTipsSeenIds: normalizeFeatureTipIds(this.state.ui?.featureTipsSeenIds),
contextualToursSeenIds: normalizeContextualTourIds(this.state.ui?.contextualToursSeenIds),
featureInteractions: normalizeFeatureInteractions(this.state.ui?.featureInteractions)
}
}
@@ -2982,6 +2995,15 @@ export class Store {
updates.featureTipsSeenIds !== undefined
? normalizeFeatureTipIds(updates.featureTipsSeenIds)
: normalizeFeatureTipIds(this.state.ui?.featureTipsSeenIds),
// Why: renderer and paired clients can mark different tours seen from
// stale UI snapshots; union them so completed tours stay suppressed.
contextualToursSeenIds:
updates.contextualToursSeenIds !== undefined
? mergeContextualTourSeenIds(
this.state.ui?.contextualToursSeenIds,
updates.contextualToursSeenIds
)
: normalizeContextualTourIds(this.state.ui?.contextualToursSeenIds),
// Why: runtime RPCs and the renderer can both record education state.
// Merge instead of replacing so a stale renderer snapshot cannot erase
// runtime-only feature interactions.
@@ -0,0 +1,151 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as Fs from 'fs'
import type * as FsPromises from 'fs/promises'
import type * as FilesystemAuth from '../ipc/filesystem-auth'
const { resolveAuthorizedPathMock, statMock, subscribeParcelWatcherMock, watchMock } = vi.hoisted(
() => ({
resolveAuthorizedPathMock: vi.fn(),
statMock: vi.fn(),
subscribeParcelWatcherMock: vi.fn(),
watchMock: vi.fn()
})
)
vi.mock('fs', async () => {
const actual = await vi.importActual<typeof Fs>('fs')
return {
...actual,
watch: watchMock
}
})
vi.mock('fs/promises', async () => {
const actual = await vi.importActual<typeof FsPromises>('fs/promises')
return {
...actual,
stat: statMock
}
})
vi.mock('@parcel/watcher', () => ({
subscribe: subscribeParcelWatcherMock
}))
vi.mock('../ipc/filesystem-auth', async () => {
const actual = await vi.importActual<typeof FilesystemAuth>('../ipc/filesystem-auth')
return {
...actual,
resolveAuthorizedPath: resolveAuthorizedPathMock
}
})
import { awaitRuntimeFileWatcherUnsubscribes, RuntimeFileCommands } from './orca-runtime-files'
function createRuntimeFileCommands(rootPath: string) {
const store = { getRepo: vi.fn(() => undefined) }
const commands = new RuntimeFileCommands({
getRuntimeId: () => 'runtime-1',
requireStore: () => store,
resolveWorktreeSelector: vi.fn(async () => ({
id: 'wt-1',
repoId: 'repo-1',
path: rootPath
})),
resolveRuntimeGitTarget: vi.fn(),
openFile: vi.fn()
} as never)
return { commands, store }
}
describe('RuntimeFileCommands file watching', () => {
const originalPlatform = process.platform
beforeEach(() => {
vi.useFakeTimers()
resolveAuthorizedPathMock.mockReset()
statMock.mockReset()
subscribeParcelWatcherMock.mockReset()
watchMock.mockReset()
Object.defineProperty(process, 'platform', {
configurable: true,
value: originalPlatform
})
})
afterEach(async () => {
await awaitRuntimeFileWatcherUnsubscribes()
Object.defineProperty(process, 'platform', {
configurable: true,
value: originalPlatform
})
vi.useRealTimers()
})
it('uses a conservative Node watcher for Windows runtime file watches', async () => {
Object.defineProperty(process, 'platform', {
configurable: true,
value: 'win32'
})
const close = vi.fn()
const on = vi.fn()
let listener: (() => void) | null = null
watchMock.mockImplementation((_rootPath, _options, callback) => {
listener = callback
return { close, on }
})
resolveAuthorizedPathMock.mockResolvedValue('C:\\repo')
statMock.mockResolvedValue({ isDirectory: () => true })
const { commands } = createRuntimeFileCommands('C:\\repo')
const onEvents = vi.fn()
const unsubscribe = await commands.watchFileExplorer('id:wt-1', onEvents)
expect(watchMock).toHaveBeenCalledWith('C:\\repo', { recursive: true }, expect.any(Function))
const emit = listener as (() => void) | null
expect(emit).not.toBeNull()
emit?.()
emit?.()
await vi.advanceTimersByTimeAsync(149)
expect(onEvents).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(1)
expect(onEvents).toHaveBeenCalledTimes(1)
expect(onEvents).toHaveBeenCalledWith([{ kind: 'overflow', absolutePath: 'C:\\repo' }])
unsubscribe()
expect(close).toHaveBeenCalledTimes(1)
})
it('tracks native Parcel watcher unsubscribe work so shutdown can await it', async () => {
resolveAuthorizedPathMock.mockResolvedValue('/repo')
statMock.mockResolvedValue({ isDirectory: () => true })
let resolveUnsubscribe: () => void = () => {}
const unsubscribeMock = vi.fn(
() =>
new Promise<void>((resolve) => {
resolveUnsubscribe = resolve
})
)
subscribeParcelWatcherMock.mockResolvedValue({ unsubscribe: unsubscribeMock })
const { commands } = createRuntimeFileCommands('/repo')
const unsubscribe = await commands.watchFileExplorer('id:wt-1', vi.fn())
unsubscribe()
let drained = false
const drainPromise = awaitRuntimeFileWatcherUnsubscribes().then(() => {
drained = true
})
await Promise.resolve()
expect(unsubscribeMock).toHaveBeenCalledTimes(1)
expect(drained).toBe(false)
resolveUnsubscribe()
await drainPromise
expect(drained).toBe(true)
})
})
@@ -105,6 +105,11 @@ const METHODS = [
params: z.object({}),
handler: () => ({ opened: true })
}),
defineMethod({
name: 'computer.permissionsStatus',
params: z.object({}),
handler: () => ({ permissions: [] })
}),
defineMethod({
name: 'computer.click',
params: z.object({}),
@@ -143,6 +148,7 @@ describe('RpcDispatcher feature interactions', () => {
const dispatcher = new RpcDispatcher({ runtime, methods: METHODS })
await dispatcher.dispatch(makeRequest('computer.permissions'))
await dispatcher.dispatch(makeRequest('computer.permissionsStatus'))
await dispatcher.dispatch(makeRequest('browser.profileImportFromBrowser'))
await dispatcher.dispatch(makeRequest('browser.profileList'))
await dispatcher.dispatch(makeRequest('browser.profileClearDefaultCookies'))
+5 -1
View File
@@ -245,7 +245,11 @@ function getRuntimeFeatureInteractionId(
if (method === 'computer.permissions') {
return 'computer-use-setup'
}
if (method.startsWith('computer.') && method !== 'computer.capabilities') {
if (
method.startsWith('computer.') &&
method !== 'computer.capabilities' &&
method !== 'computer.permissionsStatus'
) {
return 'computer-use'
}
if (method.startsWith('orchestration.')) {
@@ -168,7 +168,9 @@ describe('client UI RPC methods', () => {
featureTipsSeenIds: ['voice-dictation'],
featureInteractions: {
tasks: { firstInteractedAt: 100, interactionCount: 2 }
}
},
contextualToursSeenIds: ['tasks'],
contextualToursAutoEligible: true
}
const runtime = {
getRuntimeId: () => 'test-runtime',
@@ -199,7 +201,9 @@ describe('client UI RPC methods', () => {
featureTipsSeenIds: ['voice-dictation'],
featureInteractions: {
tasks: { firstInteractedAt: 100, interactionCount: 2 }
}
},
contextualToursSeenIds: ['tasks'],
contextualToursAutoEligible: true
}
const response = await dispatcher.dispatch(makeRequest('ui.set', payload))
+3 -1
View File
@@ -195,7 +195,9 @@ const UiUpdate = z
taskResumeState: TaskResumeState.optional(),
workspaceCleanup: WorkspaceCleanup.optional(),
featureTipsSeenIds: FeatureTipIds.optional(),
featureInteractions: FeatureInteractions.optional()
featureInteractions: FeatureInteractions.optional(),
contextualToursSeenIds: StringArray.optional(),
contextualToursAutoEligible: z.boolean().optional()
})
.strict()
.default({})
+21 -4
View File
@@ -9,7 +9,8 @@ const computerMocks = vi.hoisted(() => ({
callComputerSidecarListWindows: vi.fn(),
callComputerSidecarSnapshot: vi.fn(),
resetComputerSidecarForTest: vi.fn(),
openComputerUsePermissions: vi.fn()
openComputerUsePermissions: vi.fn(),
getComputerUsePermissionStatus: vi.fn()
}))
vi.mock('../../../computer/sidecar-client', () => ({
@@ -22,7 +23,8 @@ vi.mock('../../../computer/sidecar-client', () => ({
}))
vi.mock('../../../computer/macos-computer-use-permissions', () => ({
openComputerUsePermissions: computerMocks.openComputerUsePermissions
openComputerUsePermissions: computerMocks.openComputerUsePermissions,
getComputerUsePermissionStatus: computerMocks.getComputerUsePermissionStatus
}))
import { COMPUTER_METHODS, resetComputerSessionsForTest } from './computer'
@@ -36,6 +38,7 @@ describe('computer RPC methods', () => {
computerMocks.callComputerSidecarSnapshot.mockReset()
computerMocks.resetComputerSidecarForTest.mockReset()
computerMocks.openComputerUsePermissions.mockReset()
computerMocks.getComputerUsePermissionStatus.mockReset()
resetComputerSessionsForTest()
computerMocks.resetComputerSidecarForTest.mockClear()
})
@@ -54,6 +57,7 @@ describe('computer RPC methods', () => {
'computer.pasteText',
'computer.performSecondaryAction',
'computer.permissions',
'computer.permissionsStatus',
'computer.pressKey',
'computer.scroll',
'computer.setValue',
@@ -94,8 +98,21 @@ describe('computer RPC methods', () => {
}
computerMocks.openComputerUsePermissions.mockReturnValue(result)
await expect(call('computer.permissions', {})).resolves.toBe(result)
expect(computerMocks.openComputerUsePermissions).toHaveBeenCalledWith()
await expect(call('computer.permissions', { id: 'accessibility' })).resolves.toBe(result)
expect(computerMocks.openComputerUsePermissions).toHaveBeenCalledWith('accessibility')
})
it('returns computer-use permission status', async () => {
const result = {
platform: 'darwin',
helperAppPath: '/Applications/Orca Computer Use.app',
helperUnavailableReason: null,
permissions: [{ id: 'accessibility', status: 'granted' }]
}
computerMocks.getComputerUsePermissionStatus.mockReturnValue(result)
await expect(call('computer.permissionsStatus', {})).resolves.toBe(result)
expect(computerMocks.getComputerUsePermissionStatus).toHaveBeenCalledWith()
})
it('lists windows through the sidecar', async () => {
+16 -3
View File
@@ -179,6 +179,10 @@ const Hotkey = ComputerObserveTargetBase.extend({
key: requiredString('Missing key')
}).superRefine(validateWindowTarget)
const ComputerPermissions = z.object({
id: z.enum(['accessibility', 'screenshots']).optional()
})
const PasteText = ComputerObserveTargetBase.extend({
text: requiredString('Missing text')
}).superRefine(validateWindowTarget)
@@ -214,11 +218,20 @@ export const COMPUTER_METHODS: RpcMethod[] = [
}),
defineMethod({
name: 'computer.permissions',
params: z.object({}),
handler: async () => {
params: ComputerPermissions,
handler: async (params) => {
const { openComputerUsePermissions } =
await import('../../../computer/macos-computer-use-permissions')
return openComputerUsePermissions()
return openComputerUsePermissions(params.id)
}
}),
defineMethod({
name: 'computer.permissionsStatus',
params: z.object({}),
handler: async () => {
const { getComputerUsePermissionStatus } =
await import('../../../computer/macos-computer-use-permissions')
return getComputerUsePermissionStatus()
}
}),
defineMethod({
+2
View File
@@ -26,6 +26,7 @@ import { SSH_METHODS } from './ssh'
import { SPEECH_METHODS } from './speech'
import { CLIENT_UI_METHODS } from './client-ui'
import { WORKSPACE_PORT_METHODS } from './workspace-ports'
import { SKILL_METHODS } from './skills'
import { CLIPBOARD_METHODS } from './clipboard'
import { HOST_CAPABILITY_METHODS } from './host-capabilities'
@@ -59,6 +60,7 @@ export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [
...SSH_METHODS,
...SPEECH_METHODS,
...WORKSPACE_PORT_METHODS,
...SKILL_METHODS,
...CLIPBOARD_METHODS,
...HOST_CAPABILITY_METHODS,
...CLIENT_UI_METHODS
+10
View File
@@ -0,0 +1,10 @@
import { defineMethod, type RpcMethod } from '../core'
import { discoverSkills } from '../../../skills/discovery'
export const SKILL_METHODS: RpcMethod[] = [
defineMethod({
name: 'skills.discover',
params: null,
handler: async (_params, { runtime }) => discoverSkills({ repos: runtime.listRepos() })
})
]
+1
View File
@@ -1994,6 +1994,7 @@ export type PreloadApi = {
set: (args: Partial<PersistedUIState>) => Promise<void>
recordFeatureInteraction: (id: FeatureInteractionId) => Promise<PersistedUIState>
onOpenSettings: (callback: () => void) => () => void
onOpenSetupGuide: (callback: () => void) => () => void
onOpenFeatureTour: (callback: () => void) => () => void
onOpenCrashReport: (callback: () => void) => () => void
onToggleLeftSidebar: (callback: () => void) => () => void
+5
View File
@@ -2438,6 +2438,11 @@ const api = {
ipcRenderer.on('ui:openSettings', listener)
return () => ipcRenderer.removeListener('ui:openSettings', listener)
},
onOpenSetupGuide: (callback: () => void): (() => void) => {
const listener = (_event: Electron.IpcRendererEvent) => callback()
ipcRenderer.on('ui:openSetupGuide', listener)
return () => ipcRenderer.removeListener('ui:openSetupGuide', listener)
},
onOpenFeatureTour: (callback: () => void): (() => void) => {
const listener = (_event: Electron.IpcRendererEvent) => callback()
ipcRenderer.on('ui:openFeatureTour', listener)
+36
View File
@@ -117,6 +117,7 @@ import type { VirtualizedScrollAnchor } from './hooks/useVirtualizedScrollAnchor
import type { RemoteWorkspacePatchResult } from '../../shared/remote-workspace-types'
import type { OnboardingState } from '../../shared/types'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants'
import { ContextualTourOverlay } from './components/contextual-tours/ContextualTourOverlay'
import {
getFeatureTipsAppOpenDecision,
isCliFeatureTipCompleted
@@ -221,6 +222,7 @@ const NewWorkspaceComposerModal = lazy(() => import('./components/NewWorkspaceCo
const WorkspaceCleanupDialog = lazy(
() => import('./components/workspace-cleanup/WorkspaceCleanupDialog')
)
const SetupGuideModal = lazy(() => import('./components/setup-guide/SetupGuideModal'))
const FeatureWallModal = lazy(() => import('./components/feature-wall/FeatureWallModal'))
const FeatureTipsModal = lazy(() => import('./components/feature-tips/FeatureTipsModal'))
// Why: lazy-loaded so the WebP asset + overlay module aren't fetched unless
@@ -297,6 +299,9 @@ function App(): React.JSX.Element {
openModal: s.openModal,
closeModal: s.closeModal,
markFeatureTipsSeen: s.markFeatureTipsSeen,
setContextualToursAutoEligible: s.setContextualToursAutoEligible,
setContextualToursOnboardingVisible: s.setContextualToursOnboardingVisible,
cancelContextualTour: s.cancelContextualTour,
toggleRightSidebar: s.toggleRightSidebar,
setRightSidebarOpen: s.setRightSidebarOpen,
setRightSidebarTab: s.setRightSidebarTab,
@@ -313,6 +318,7 @@ function App(): React.JSX.Element {
const activeModal = useAppStore((s) => s.activeModal)
const featureTipsSeenIds = useAppStore((s) => s.featureTipsSeenIds)
const featureInteractions = useAppStore((s) => s.featureInteractions)
const contextualToursAutoEligible = useAppStore((s) => s.contextualToursAutoEligible)
const activeWorktreeId = useAppStore((s) => s.activeWorktreeId)
// Why: App swaps the sidebar between workspace and landing layouts when the
// active workspace is slept/deleted. Keep virtualized scroll memory above
@@ -478,6 +484,7 @@ function App(): React.JSX.Element {
const [collapsedSidebarHeaderWidth, setCollapsedSidebarHeaderWidth] = useState(0)
const [mountedLazyModalIds, setMountedLazyModalIds] = useState<Set<LazyModalId>>(() => new Set())
const [onboarding, setOnboarding] = useState<OnboardingState | null>(null)
const [onboardingLoaded, setOnboardingLoaded] = useState(false)
const featureTipsPromptedThisSessionRef = useRef(false)
const featureTipsSuppressedByOnboardingThisSessionRef = useRef(false)
const [featureTipCliInstalled, setFeatureTipCliInstalled] = useState<boolean | null>(null)
@@ -521,6 +528,23 @@ function App(): React.JSX.Element {
return onOnboardingReopened(setOnboarding)
}, [])
useEffect(() => {
// Why: `onboarding === null` is the startup loading state. Suppress
// contextual tours until the persisted onboarding state is known so a
// first-run user cannot have a tour marked seen before onboarding appears.
const suppressTours = !onboardingLoaded || shouldShowOnboarding(onboarding)
actions.setContextualToursOnboardingVisible(suppressTours)
}, [actions, onboarding, onboardingLoaded])
useEffect(() => {
if (!persistedUIReady || !onboardingLoaded || contextualToursAutoEligible !== null) {
return
}
// Why: this rollout is for users who are still in first-run onboarding.
// Existing profiles are locally classified once and never auto-toured.
actions.setContextualToursAutoEligible(shouldShowOnboarding(onboarding))
}, [actions, contextualToursAutoEligible, onboarding, onboardingLoaded, persistedUIReady])
useEffect(() => {
if (!persistedUIReady) {
return
@@ -665,6 +689,7 @@ function App(): React.JSX.Element {
const onboardingState = await window.api.onboarding.get()
if (!cancelled) {
setOnboarding(onboardingState)
setOnboardingLoaded(true)
}
// Why: SSH connections must be re-established BEFORE terminal
@@ -1880,6 +1905,16 @@ function App(): React.JSX.Element {
<WorktreeJumpPalette />
</RecoverableRenderErrorBoundary>
) : null}
{resolvedMountedLazyModalIds.has('setup-guide') ? (
<RecoverableRenderErrorBoundary
boundaryId="modal.setup-guide"
surface="modal"
resetKey={activeModal === 'setup-guide'}
compact
>
<SetupGuideModal />
</RecoverableRenderErrorBoundary>
) : null}
{resolvedMountedLazyModalIds.has('feature-wall') ? (
<RecoverableRenderErrorBoundary
boundaryId="modal.feature-wall"
@@ -1901,6 +1936,7 @@ function App(): React.JSX.Element {
</RecoverableRenderErrorBoundary>
) : null}
</Suspense>
<ContextualTourOverlay />
{/* Why: mount PetOverlay only after persisted UI hydration, with
both independent pet toggles allowing it; otherwise a hidden pet
flashes while the store still has default visibility. */}
+62
View File
@@ -1999,6 +1999,43 @@ html.onboarding-tour-start-transition::view-transition-new(root) {
}
}
.orca-contextual-tour-target-rings {
border-radius: 9999px;
pointer-events: none;
}
.orca-contextual-tour-target-rings::before {
content: '';
position: absolute;
inset: -2px;
border: 1px solid color-mix(in srgb, var(--ring) 72%, transparent);
border-radius: inherit;
box-shadow: 0 0 0 1px color-mix(in srgb, var(--ring) 18%, transparent);
opacity: 0;
transform-origin: center;
animation: contextual-tour-target-ring 1.8s ease-out infinite;
}
@keyframes contextual-tour-target-ring {
0% {
opacity: 0.72;
transform: scale(0.68);
}
72%,
100% {
opacity: 0;
transform: scale(2.4);
}
}
@media (prefers-reduced-motion: reduce) {
.orca-contextual-tour-target-rings::before {
animation: none;
opacity: 0.72;
transform: scale(1.28);
}
}
.feature-tour-copy-slide {
position: absolute;
inset: 0;
@@ -2866,3 +2903,28 @@ html.onboarding-tour-start-transition::view-transition-new(root) {
gap: 8px;
margin-top: 4px;
}
/* Why: a tour panel must read as elevated above the chrome it is teaching about
without resorting to color. A 1px inner top highlight plus the documented
floating shadow keeps it above the surface in both light and dark modes. */
.orca-contextual-tour-panel {
background: linear-gradient(
180deg,
color-mix(in srgb, var(--foreground) 4%, var(--popover)) 0%,
var(--popover) 12%
);
box-shadow:
inset 0 1px 0 0 color-mix(in srgb, var(--foreground) 10%, transparent),
0 10px 24px rgba(0, 0, 0, 0.18);
}
.dark .orca-contextual-tour-panel {
background: linear-gradient(
180deg,
color-mix(in srgb, var(--foreground) 4%, var(--popover)) 0%,
var(--popover) 14%
);
box-shadow:
inset 0 1px 0 0 color-mix(in srgb, var(--foreground) 5%, transparent),
0 10px 24px rgba(0, 0, 0, 0.18);
}
@@ -21,6 +21,7 @@ import { useAppStore } from '@/store'
import { cn } from '@/lib/utils'
import { WORKSPACE_FILE_PATH_MIME } from '@/lib/workspace-file-drag'
import { getScreenSubmitModifierLabel } from '@/lib/screen-submit-shortcut'
import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour'
import { filterEnabledTuiAgents } from '../../../shared/tui-agent-selection'
import type {
GitHubWorkItem,
@@ -41,6 +42,7 @@ import type { SshConnectionStatus } from '../../../shared/ssh-types'
type RepoOption = React.ComponentProps<typeof RepoCombobox>['repos'][number]
type NewWorkspaceComposerCardProps = {
contextualTourSource?: string
containerClassName?: string
composerRef?: React.RefObject<HTMLDivElement | null>
onComposerNodeChange?: (node: HTMLDivElement | null) => void
@@ -206,6 +208,7 @@ function useComposerFileDragOver(): {
}
export default function NewWorkspaceComposerCard({
contextualTourSource,
containerClassName,
composerRef,
onComposerNodeChange,
@@ -253,6 +256,7 @@ export default function NewWorkspaceComposerCard({
}: NewWorkspaceComposerCardProps): React.JSX.Element {
const { isFileDragOver, dragHandlers } = useComposerFileDragOver()
const openModal = useAppStore((s) => s.openModal)
const activeModal = useAppStore((s) => s.activeModal)
const defaultTuiAgent = useAppStore((s) => s.settings?.defaultTuiAgent ?? null)
const disabledTuiAgents = useAppStore((s) => s.settings?.disabledTuiAgents ?? [])
const updateSettings = useAppStore((s) => s.updateSettings)
@@ -352,6 +356,14 @@ export default function NewWorkspaceComposerCard({
const handleAddRepo = React.useCallback((): void => {
openModal('add-repo')
}, [openModal])
useContextualTour(
'workspace-creation',
eligibleRepos.length > 0 && Boolean(repoId),
contextualTourSource ??
(activeModal === 'new-workspace-composer'
? 'workspace_creation_modal'
: 'workspace_creation_visible')
)
return (
<div
@@ -371,7 +383,7 @@ export default function NewWorkspaceComposerCard({
)}
>
<div className="min-w-0 space-y-4 pt-3">
<div className="space-y-1">
<div className="space-y-1" data-contextual-tour-target="workspace-creation-project">
<div className="flex items-center justify-between gap-2">
<label className="text-xs font-medium text-muted-foreground">Project</label>
<Tooltip>
@@ -438,7 +450,7 @@ export default function NewWorkspaceComposerCard({
) : null}
</div>
<div className="min-w-0 space-y-1">
<div className="min-w-0 space-y-1" data-contextual-tour-target="workspace-creation-name">
<div className="flex items-center justify-between gap-2">
<label className="min-w-0 truncate text-xs font-medium text-muted-foreground">
{selectedRepoIsGit ? "Name or 'Create From'" : 'Workspace name'}{' '}
@@ -485,7 +497,7 @@ export default function NewWorkspaceComposerCard({
/>
</div>
<div className="space-y-1">
<div className="space-y-1" data-contextual-tour-target="workspace-creation-agent">
<div className="flex items-center justify-between gap-2">
<label className="text-xs font-medium text-muted-foreground">Agent</label>
<Tooltip>
@@ -28,6 +28,8 @@ type ComposerModalData = {
* `workspace_created.source` carries the right value. Falls back to
* `unknown` when omitted. */
telemetrySource?: WorkspaceCreateTelemetrySource
contextualTourSource?: string
setupGuideTourRequestId?: string
}
export default function NewWorkspaceComposerModal(): React.JSX.Element | null {
@@ -221,6 +223,7 @@ function QuickTabBody({
<DialogTitle className="text-base font-semibold">{primaryActionLabel}</DialogTitle>
</DialogHeader>
<NewWorkspaceComposerCard
contextualTourSource={modalData.contextualTourSource}
composerRef={composerRef}
onComposerNodeChange={onComposerNodeChange}
nameInputRef={nameInputRef}
+45 -7
View File
@@ -187,6 +187,7 @@ import type {
TaskViewPresetId
} from '../../../shared/types'
import { shouldSuppressEnterSubmit } from '@/lib/new-workspace-enter-guard'
import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour'
import { getScreenSubmitShortcutLabel, isScreenSubmitShortcut } from '@/lib/screen-submit-shortcut'
import {
useRepoAssignees,
@@ -4019,6 +4020,17 @@ export default function TaskPage(): React.JSX.Element {
}, [newLinearStates.data, newLinearIssueStateId])
const [linearConnectOpen, setLinearConnectOpen] = useState(false)
useContextualTour(
'tasks',
!dialogWorkItem &&
!gitlabDialogItem &&
!selectedLinearIssue &&
!newIssueOpen &&
!newLinearIssueOpen &&
!linearConnectOpen &&
activeModal === 'none',
'tasks_open'
)
const activeGithubTaskKind = getGitHubTaskKind(activeTaskPreset, appliedTaskSearch)
const selectedGitHubRepoExternalLink = useMemo(() => {
@@ -5898,7 +5910,10 @@ export default function TaskPage(): React.JSX.Element {
<section className="flex flex-col gap-3">
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<div
className="flex min-w-0 flex-wrap items-center gap-2"
data-contextual-tour-target="tasks-source-filters"
>
{/* Why: Close is anchored left in the same row as the
source icons so the top chrome is one compact band.
Left-aligned keeps it clear of the app sidebar on the
@@ -6128,7 +6143,10 @@ export default function TaskPage(): React.JSX.Element {
) : null}
{taskSource === 'github' && githubMode === 'items' ? (
<div className="min-w-0 rounded-md rounded-b-none border border-border/50 bg-muted/50 p-3 shadow-sm">
<div
className="min-w-0 rounded-md rounded-b-none border border-border/50 bg-muted/50 p-3 shadow-sm"
data-contextual-tour-target="tasks-search-presets"
>
<div className="mb-3 flex flex-wrap gap-2">
{getGitHubTaskKindPresets(activeGithubTaskKind).map((option) => {
const active = activeTaskPreset === option.id
@@ -6198,7 +6216,10 @@ export default function TaskPage(): React.JSX.Element {
</button>
) : null}
</div>
<div className="flex shrink-0 items-center gap-2">
<div
className="flex shrink-0 items-center gap-2"
data-contextual-tour-target="tasks-actions"
>
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -6323,7 +6344,10 @@ export default function TaskPage(): React.JSX.Element {
})()}
</div>
) : taskSource === 'linear' && linearStatus.connected ? (
<div className="min-w-0 rounded-md rounded-b-none border border-border/50 bg-muted/50 p-3 shadow-sm">
<div
className="min-w-0 rounded-md rounded-b-none border border-border/50 bg-muted/50 p-3 shadow-sm"
data-contextual-tour-target="tasks-search-presets"
>
<div className="flex min-w-0 flex-wrap items-center justify-between gap-3">
<div
className="flex items-center gap-1 text-xs"
@@ -6350,7 +6374,10 @@ export default function TaskPage(): React.JSX.Element {
)
})}
</div>
<div className="flex shrink-0 items-center gap-2">
<div
className="flex shrink-0 items-center gap-2"
data-contextual-tour-target="tasks-actions"
>
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -6737,7 +6764,10 @@ export default function TaskPage(): React.JSX.Element {
/>
</div>
</div>
<div className="min-w-0 rounded-md rounded-b-none border border-border/50 bg-muted/50 p-3 shadow-sm">
<div
className="min-w-0 rounded-md rounded-b-none border border-border/50 bg-muted/50 p-3 shadow-sm"
data-contextual-tour-target="tasks-search-presets"
>
<div className="flex min-w-0 flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<div className="flex flex-wrap gap-2">
@@ -6769,7 +6799,10 @@ export default function TaskPage(): React.JSX.Element {
: null}
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
<div
className="flex shrink-0 items-center gap-2"
data-contextual-tour-target="tasks-actions"
>
<Tooltip>
<TooltipTrigger asChild>
<Button
@@ -7162,6 +7195,7 @@ export default function TaskPage(): React.JSX.Element {
type="button"
variant={attachedWorkspace ? 'default' : 'outline'}
size="xs"
data-contextual-tour-target="tasks-start-workspace"
onClick={(event) => {
event.stopPropagation()
handleOpenOrUseGitHubWorkItem(item)
@@ -7215,6 +7249,7 @@ export default function TaskPage(): React.JSX.Element {
) : (
<button
type="button"
data-contextual-tour-target="tasks-start-workspace"
onClick={(event) => {
event.stopPropagation()
handleOpenOrUseGitHubWorkItem(item)
@@ -7460,6 +7495,7 @@ export default function TaskPage(): React.JSX.Element {
<Button
variant="ghost"
size="icon-xs"
data-contextual-tour-target="tasks-start-workspace"
onClick={(event) => {
event.stopPropagation()
handleUseGitLabItem(item)
@@ -8260,6 +8296,7 @@ export default function TaskPage(): React.JSX.Element {
<Button
variant="ghost"
size="icon-xs"
data-contextual-tour-target="tasks-start-workspace"
onClick={(event) => {
event.stopPropagation()
handleUseLinearItem(issue)
@@ -8483,6 +8520,7 @@ export default function TaskPage(): React.JSX.Element {
<Button
variant="ghost"
size="icon-xs"
data-contextual-tour-target="tasks-start-workspace"
onClick={(event) => {
event.stopPropagation()
handleUseLinearItem(issue)
+18
View File
@@ -88,6 +88,7 @@ import {
} from '../../../shared/keybindings'
import { matchesRecentTabSwitcherChord } from '../../../shared/window-shortcut-policy'
import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut-capture-notification'
import { useContextualTour } from './contextual-tours/use-contextual-tour'
import { openTabBarEntry, type TabCreateEntryArgs } from './tab-bar/tab-create-entry-action'
const EditorPanel = lazy(() => import('./editor/EditorPanel'))
@@ -280,6 +281,23 @@ function Terminal(): React.JSX.Element | null {
const activeWorktreeBrowserTabIdsKey = renderedActiveWorktreeId
? (browserTabsByWorktree[renderedActiveWorktreeId] ?? []).map((tab) => tab.id).join(',')
: ''
const activeContextualTourId = useAppStore((s) => s.activeContextualTourId)
const hasSplitTerminalPane = useAppStore((s) =>
Boolean(s.featureInteractions['terminal-pane-split']?.interactionCount)
)
useContextualTour(
'workspace-agent-sessions',
Boolean(
activeWorktreeId &&
activeView === 'terminal' &&
workspaceSessionReady &&
activeTabType === 'terminal' &&
Boolean(activeTabId) &&
(!hasSplitTerminalPane || activeContextualTourId === 'workspace-agent-sessions')
),
'workspace_agent_sessions_visible'
)
// Save confirmation dialog state
const [saveDialogFileId, setSaveDialogFileId] = useState<string | null>(null)
@@ -92,6 +92,7 @@ import { AUTOMATION_TEMPLATES, type AutomationTemplate } from './automation-temp
import { getExternalAutomationScheduleDisplay } from './external-automation-schedule-display'
import { ExternalAutomationManagers } from './ExternalAutomationManagers'
import type { FetchExternalAutomationRuns } from './ExternalAutomationRunTable'
import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour'
const AGENTS = AGENT_CATALOG.map((agent) => agent.id)
const DEFAULT_TIME = '09:00'
@@ -324,6 +325,11 @@ export default function AutomationsPage(): React.JSX.Element {
manager: ExternalAutomationManager
job: ExternalAutomationJob
} | null>(null)
useContextualTour(
'automations',
!createOpen && !deleteTarget && !externalDeleteTarget,
'automations_open'
)
const [editingExternalTarget, setEditingExternalTarget] = useState<{
manager: ExternalAutomationManager
job: ExternalAutomationJob
@@ -1047,6 +1053,9 @@ export default function AutomationsPage(): React.JSX.Element {
await refresh()
selectAutomationId(automation.id)
setCreateOpen(false)
if (!editingAutomationId) {
useAppStore.getState().recordFeatureInteraction('automation-created')
}
toast.success(editingAutomationId ? 'Automation updated.' : 'Automation saved.')
} catch (error) {
if (isHermesSave) {
@@ -1117,6 +1126,7 @@ export default function AutomationsPage(): React.JSX.Element {
const runNow = async (automation: Automation): Promise<void> => {
await window.api.automations.runNow({ id: automation.id })
useAppStore.getState().recordFeatureInteraction('automation-run')
await hydratePersistedUIState()
await refresh()
toast.message('Automation run queued.')
@@ -1374,6 +1384,7 @@ export default function AutomationsPage(): React.JSX.Element {
aria-label="Add automation"
onClick={() => openCreateDialog()}
className="border border-border/50 bg-transparent hover:bg-muted/50"
data-contextual-tour-target="automations-create"
>
<Plus className="size-4" />
</Button>
@@ -1560,7 +1571,10 @@ export default function AutomationsPage(): React.JSX.Element {
</Dialog>
<div className="grid min-h-0 flex-1 grid-cols-[minmax(280px,360px)_1fr] overflow-hidden border-t border-border/50">
<section className="flex min-h-0 flex-col border-r border-border/50 bg-muted/20">
<section
className="flex min-h-0 flex-col border-r border-border/50 bg-muted/20"
data-contextual-tour-target="automations-list"
>
<div className="scrollbar-sleek min-h-0 flex-1 overflow-auto p-2">
{automations.length + externalAutomationEntries.length > 0 ? (
<div className="grid grid-cols-[1fr_auto] gap-2 px-2 pb-2 text-[11px] font-medium uppercase text-muted-foreground">
@@ -1932,7 +1946,10 @@ export default function AutomationsPage(): React.JSX.Element {
onValueChange={(value) => setActivePaneTab(value as AutomationPaneTab)}
className="min-h-0 flex-1 gap-0"
>
<div className="flex shrink-0 items-center justify-between border-b border-border/50 px-5 py-2">
<div
className="flex shrink-0 items-center justify-between border-b border-border/50 px-5 py-2"
data-contextual-tour-target="automations-runs"
>
<TabsList variant="line" className="h-8">
<TabsTrigger value="overview">Overview</TabsTrigger>
<TabsTrigger value="runs" disabled={!selected}>
@@ -157,6 +157,7 @@ import {
type BrowserDriverState
} from '@/lib/pane-manager/browser-mobile-driver-state'
import { shouldPollChromiumErrorPage } from './chromium-error-page-polling'
import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour'
type BrowserTabPageState = Partial<
Pick<
@@ -744,6 +745,9 @@ export default function BrowserPane({
const setBrowserPageUrl = useAppStore((s) => s.setBrowserPageUrl)
const runtimeEnvironmentActive = Boolean(activeRuntimeEnvironmentId?.trim())
const activeBrowserPageId = activeBrowserPage?.id ?? null
const activeBrowserPageIsBlank =
!runtimeEnvironmentActive &&
(activeBrowserPage?.url === 'about:blank' || activeBrowserPage?.url === ORCA_BROWSER_BLANK_URL)
const browserPageIds = useMemo(() => browserPages.map((page) => page.id), [browserPages])
const automationVisiblePageIds = useBrowserAutomationVisiblePageIds(browserPageIds)
const renderedBrowserPages = useMemo(() => {
@@ -784,6 +788,15 @@ export default function BrowserPane({
})
}, [activeBrowserPageId, runtimeEnvironmentActive])
useContextualTour(
'browser',
isActive &&
activeBrowserPage !== null &&
!runtimeEnvironmentActive &&
!activeBrowserPageIsBlank,
'browser_visible'
)
const reclaimActiveBrowserForDesktop = useCallback(async (): Promise<void> => {
if (!activeBrowserPageId) {
return
@@ -2378,7 +2391,10 @@ function RemoteBrowserPagePane({
document.body
)
: null}
<div className="relative z-10 flex items-center gap-2 border-b border-border/70 bg-background/95 px-3 py-1.5">
<div
className="relative z-10 flex items-center gap-2 border-b border-border/70 bg-background/95 px-3 py-1.5"
data-contextual-tour-target="browser-toolbar"
>
<Button
size="icon"
variant="ghost"
@@ -2739,9 +2755,17 @@ function BrowserPagePane({
if (!grab.contextMenu) {
const text = formatGrabPayloadAsText(grab.payload)
void window.api.ui.writeClipboardText(text)
recordFeatureInteraction('browser-grab')
showGrabToast('Copied', 'success', grab.payload)
}
}, [grab.state, grab.payload, grab.contextMenu, grabIntent, showGrabToast])
}, [
grab.state,
grab.payload,
grab.contextMenu,
grabIntent,
recordFeatureInteraction,
showGrabToast
])
useEffect(() => {
if (grab.state === 'idle' || grab.state === 'error') {
@@ -3720,6 +3744,7 @@ function BrowserPagePane({
recordFeatureInteraction('browser-annotations')
}
setGrabIntent(nextIntent)
recordFeatureInteraction(nextIntent === 'annotate' ? 'browser-annotations' : 'browser-grab')
if (nextIntent === 'copy') {
setPendingAnnotationPayload(null)
} else {
@@ -3960,6 +3985,7 @@ function BrowserPagePane({
createdAt: new Date().toISOString(),
payload: createBrowserAnnotationPayload(payload)
})
recordFeatureInteraction('browser-annotations')
setPendingAnnotationPayload(null)
setBrowserAnnotationTrayOpen(true)
recordFeatureInteraction('browser-annotations')
@@ -4073,8 +4099,8 @@ function BrowserPagePane({
}
clearTimeout(annotationCopyTimerRef.current)
setBrowserAnnotationsCopied(false)
clearBrowserPageAnnotations(browserTab.id)
recordFeatureInteraction('browser-annotations')
clearBrowserPageAnnotations(browserTab.id)
}, [browserTab.id, clearBrowserPageAnnotations, recordFeatureInteraction])
const handleDeleteBrowserAnnotation = useCallback(
@@ -4420,7 +4446,10 @@ function BrowserPagePane({
)
: null}
<div className="relative z-10 flex items-center gap-2 border-b border-border/70 bg-background/95 px-3 py-1.5">
<div
className="relative z-10 flex items-center gap-2 border-b border-border/70 bg-background/95 px-3 py-1.5"
data-contextual-tour-target="browser-toolbar"
>
<Button
size="icon"
variant="ghost"
@@ -4487,6 +4516,7 @@ function BrowserPagePane({
onClick={() => startGrabIntent('copy')}
disabled={isBlankTab}
aria-label="Grab page element"
data-contextual-tour-target="browser-grab-control"
>
<Crosshair className="size-4" />
</Button>
@@ -4516,6 +4546,7 @@ function BrowserPagePane({
onClick={() => startGrabIntent('annotate')}
disabled={isBlankTab}
aria-label="Annotate page element"
data-contextual-tour-target="browser-annotation-control"
>
<MessageSquarePlus className="size-4" />
{browserAnnotations.length > 0 ? (
@@ -1,4 +1,4 @@
import React, { createContext, useCallback, useContext, useRef, useState } from 'react'
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'
import { Button } from '@/components/ui/button'
import {
@@ -9,6 +9,7 @@ import {
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import { useAppStore } from '@/store'
type ConfirmationDialogOptions = {
title: string
@@ -37,6 +38,9 @@ export function ConfirmationDialogProvider({
const [queue, setQueue] = useState<ConfirmationDialogRequest[]>([])
const activeRequest = queue[0] ?? null
const activeRequestRef = useRef<ConfirmationDialogRequest | null>(activeRequest)
const setContextualToursBlockingSurfaceVisible = useAppStore(
(s) => s.setContextualToursBlockingSurfaceVisible
)
const lastDisplayedRequestRef = useRef<ConfirmationDialogRequest | null>(activeRequest)
activeRequestRef.current = activeRequest
if (activeRequest) {
@@ -45,6 +49,13 @@ export function ConfirmationDialogProvider({
// Why: Radix keeps dialog content mounted while closing; keep labels stable without a post-render Effect.
const displayedRequest = activeRequest ?? lastDisplayedRequestRef.current
useEffect(() => {
// Why: this provider's dialog is not represented by activeModal. Block
// contextual tours so they cannot appear behind confirmation prompts.
setContextualToursBlockingSurfaceVisible(activeRequest !== null)
return () => setContextualToursBlockingSurfaceVisible(false)
}, [activeRequest, setContextualToursBlockingSurfaceVisible])
const confirm = useCallback<ConfirmationDialogContextValue>((options) => {
return new Promise((resolve) => {
const request: ConfirmationDialogRequest = {
@@ -0,0 +1,66 @@
import type { CSSProperties, JSX } from 'react'
import type { ContextualTourPanelPlacement } from './contextual-tour-panel-position'
export function ContextualTourArrow({
placement
}: {
placement: ContextualTourPanelPlacement
}): JSX.Element {
// Why: a small triangle pointing at the target makes the panel/target
// relationship readable when the user's eye starts on the panel.
const offsetCss = 'var(--contextual-tour-arrow-offset, 50%)'
const horizontal = placement === 'top' || placement === 'bottom'
const longSide = 12
const shortSide = 6
const wrapperStyle: CSSProperties = horizontal
? {
width: longSide,
height: shortSide,
left: offsetCss,
transform: 'translateX(-50%)',
...(placement === 'top' ? { top: '100%' } : { bottom: '100%' })
}
: {
width: shortSide,
height: longSide,
top: offsetCss,
transform: 'translateY(-50%)',
...(placement === 'left' ? { left: '100%' } : { right: '100%' })
}
const path =
placement === 'top'
? 'M0 0 L6 6 L12 0'
: placement === 'bottom'
? 'M0 6 L6 0 L12 6'
: placement === 'left'
? 'M0 0 L6 6 L0 12'
: 'M6 0 L0 6 L6 12'
const maskPath =
placement === 'top'
? 'M0 0 L12 0'
: placement === 'bottom'
? 'M0 6 L12 6'
: placement === 'left'
? 'M0 0 L0 12'
: 'M6 0 L6 12'
return (
<span aria-hidden="true" className="absolute block" style={wrapperStyle}>
<svg
viewBox={horizontal ? '0 0 12 6' : '0 0 6 12'}
width={horizontal ? longSide : shortSide}
height={horizontal ? shortSide : longSide}
className="overflow-visible"
preserveAspectRatio="none"
>
<path
d={path}
className="fill-popover stroke-border"
strokeWidth={1}
strokeLinejoin="round"
/>
{/* Why: hide the join with the panel border so the panel edge reads as continuous. */}
<path d={maskPath} className="stroke-popover" strokeWidth={1.5} fill="none" />
</svg>
</span>
)
}
@@ -0,0 +1,36 @@
import { describe, expect, it, vi } from 'vitest'
import { toggleAutoRenameBranchFromWork } from './ContextualTourControl'
import { CONTEXTUAL_TOUR_ENABLE_AUTO_WORKSPACE_NAME_EVENT } from './contextual-tour-composer-events'
describe('toggleAutoRenameBranchFromWork', () => {
it('clears the generated workspace name when enabling first-message auto-name', () => {
const updateSettings = vi.fn()
const dispatchEvent = vi.fn()
toggleAutoRenameBranchFromWork({
enabled: false,
updateSettings,
dispatchEvent
})
expect(updateSettings).toHaveBeenCalledWith({ autoRenameBranchFromWork: true })
expect(dispatchEvent).toHaveBeenCalledTimes(1)
expect(dispatchEvent.mock.calls[0]?.[0]).toMatchObject({
type: CONTEXTUAL_TOUR_ENABLE_AUTO_WORKSPACE_NAME_EVENT
})
})
it('does not clear the workspace name when disabling first-message auto-name', () => {
const updateSettings = vi.fn()
const dispatchEvent = vi.fn()
toggleAutoRenameBranchFromWork({
enabled: true,
updateSettings,
dispatchEvent
})
expect(updateSettings).toHaveBeenCalledWith({ autoRenameBranchFromWork: false })
expect(dispatchEvent).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,70 @@
import type { JSX } from 'react'
import { cn } from '@/lib/utils'
import { useAppStore } from '@/store'
import type { ContextualTourStepControl } from '../../../../shared/contextual-tours'
import { CONTEXTUAL_TOUR_ENABLE_AUTO_WORKSPACE_NAME_EVENT } from './contextual-tour-composer-events'
export function ContextualTourControl({
control
}: {
control: ContextualTourStepControl
}): JSX.Element | null {
switch (control.kind) {
case 'auto-rename-branch-from-work':
return <AutoRenameBranchFromWorkControl />
}
}
export function toggleAutoRenameBranchFromWork(args: {
enabled: boolean
updateSettings: (settings: { autoRenameBranchFromWork: boolean }) => void | Promise<unknown>
dispatchEvent: (event: Event) => void
}): void {
const nextEnabled = !args.enabled
void args.updateSettings({ autoRenameBranchFromWork: nextEnabled })
if (nextEnabled) {
args.dispatchEvent(new Event(CONTEXTUAL_TOUR_ENABLE_AUTO_WORKSPACE_NAME_EVENT))
}
}
function AutoRenameBranchFromWorkControl(): JSX.Element {
const enabled = useAppStore((s) => s.settings?.autoRenameBranchFromWork === true)
const updateSettings = useAppStore((s) => s.updateSettings)
return (
<div className="mt-3 rounded-md border border-border/70 bg-muted/35 px-3 py-2.5">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<div className="text-xs font-medium text-foreground">Auto-name from first message</div>
<div className="mt-0.5 text-[11px] leading-4 text-muted-foreground">
Auto-generates a new name when you leave this text box empty.
</div>
</div>
<button
type="button"
role="switch"
aria-checked={enabled}
aria-label="Auto-name workspace from first agent message"
onClick={() => {
toggleAutoRenameBranchFromWork({
enabled,
updateSettings,
dispatchEvent: (event) => window.dispatchEvent(event)
})
}}
className={cn(
'relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-colors',
enabled ? 'bg-foreground' : 'bg-muted-foreground/30'
)}
>
<span
className={cn(
'pointer-events-none block size-3.5 rounded-full bg-background shadow-sm transition-transform',
enabled ? 'translate-x-4' : 'translate-x-0.5'
)}
/>
</button>
</div>
</div>
)
}
@@ -0,0 +1,384 @@
import { Children, isValidElement, type ReactElement, type ReactNode, type RefObject } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { ContextualTourId } from '../../../../shared/contextual-tours'
import { getContextualTourCleanupOutcome } from './ContextualTourOverlay'
import {
ContextualTourOverlaySurface,
handleContextualTourGlobalKeyDown,
handleContextualTourOverlayKeyDown,
type ActiveTourRenderState
} from './ContextualTourOverlaySurface'
import { getContextualTourPanelHost } from './contextual-tour-gate'
import { useAppStore } from '@/store'
type ClickableElementProps = {
children?: ReactNode
onClick?: () => void
'aria-label'?: string
}
const baseRenderState: ActiveTourRenderState = {
rect: {
left: 10,
top: 20,
right: 110,
bottom: 80,
width: 100,
height: 60
} as DOMRect,
targetElement: {
closest: () => null
} as unknown as Element,
progress: { current: 1, total: 3 },
title: 'Choose the work source',
body: 'Switch between connected providers and project filters without changing pages.',
isLastStep: false,
isFirstStep: true,
panelHost: null
}
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
function renderSurface(
overrides: Partial<ActiveTourRenderState> = {},
callbacks: {
onSkip?: (id: ContextualTourId) => void
onNext?: () => void
onBack?: () => void
onStepAction?: Parameters<typeof ContextualTourOverlaySurface>[0]['onStepAction']
} = {}
): ReactElement {
const renderState = { ...baseRenderState, ...overrides }
return ContextualTourOverlaySurface({
activeTourId: 'tasks',
renderState,
panelRef: { current: null } as RefObject<HTMLElement | null>,
panelPosition: { left: 130, top: 20, '--contextual-tour-arrow-offset': '40px' },
panelPlacement: 'right',
panelHost: renderState.panelHost,
onSkip: callbacks.onSkip ?? vi.fn(),
onBack: callbacks.onBack ?? vi.fn(),
onNext: callbacks.onNext ?? vi.fn(),
onStepAction: callbacks.onStepAction ?? vi.fn(),
onOverlayKeyDownCapture: handleContextualTourOverlayKeyDown
})
}
function findElementByText(
node: ReactNode,
text: string
): ReactElement<ClickableElementProps> | null {
if (Array.isArray(node)) {
for (const child of node) {
const match = findElementByText(child, text)
if (match) {
return match
}
}
return null
}
if (!isValidElement(node)) {
return null
}
const props = node.props as ClickableElementProps
const childrenArray = Children.toArray(props.children)
if (childrenArray.some((child) => child === text)) {
return node as ReactElement<ClickableElementProps>
}
for (const child of childrenArray) {
const match = findElementByText(child, text)
if (match) {
return match
}
}
return null
}
function findElementByAriaLabel(
node: ReactNode,
label: string
): ReactElement<ClickableElementProps> | null {
if (Array.isArray(node)) {
for (const child of node) {
const match = findElementByAriaLabel(child, label)
if (match) {
return match
}
}
return null
}
if (!isValidElement(node)) {
return null
}
const props = node.props as ClickableElementProps
if (props['aria-label'] === label) {
return node as ReactElement<ClickableElementProps>
}
for (const child of Children.toArray(props.children)) {
const match = findElementByAriaLabel(child, label)
if (match) {
return match
}
}
return null
}
describe('ContextualTourOverlaySurface', () => {
it('renders visible progress and step copy', () => {
const markup = renderToStaticMarkup(renderSurface())
expect(markup).toContain('aria-valuenow="1"')
expect(markup).toContain('aria-valuemax="3"')
expect(markup).toContain('Step 1 of 3')
expect(markup).toContain('1 of 3')
expect(markup).toContain('Choose the work source')
expect(markup).toContain('Switch between connected providers')
expect(markup).toContain('aria-label="Skip tour"')
expect(markup).toContain('Next')
})
it('treats externally completed tours as completed during cleanup', () => {
useAppStore.setState({ lastCompletedContextualTourId: 'workspace-agent-sessions' })
expect(getContextualTourCleanupOutcome('workspace-agent-sessions')).toBe('completed')
expect(getContextualTourCleanupOutcome('tasks')).toBe('cancelled')
})
it('renders later progress and Done on the final visible step', () => {
const markup = renderToStaticMarkup(
renderSurface({
progress: { current: 2, total: 2 },
title: 'Start from work items',
isLastStep: true,
isFirstStep: false
})
)
expect(markup).toContain('aria-valuenow="2"')
expect(markup).toContain('aria-valuemax="2"')
expect(markup).toContain('2 of 2')
expect(markup).toContain('Start from work items')
expect(markup).toContain('Done')
})
it('does not render a step label for single-step tours', () => {
const markup = renderToStaticMarkup(
renderSurface({
progress: { current: 1, total: 1 },
title: 'Split panes for agents',
isLastStep: true,
isFirstStep: true
})
)
expect(markup).not.toContain('Step 1')
expect(markup).toContain('Split panes for agents')
})
it('renders configured step controls inside the tour panel', () => {
const markup = renderToStaticMarkup(
renderSurface({
control: { kind: 'auto-rename-branch-from-work' },
title: 'Name it, or start from existing work',
body: 'Start a workspace from a task source to inherit the title.'
})
)
expect(markup).toContain('Auto-name from first message')
expect(markup).toContain('role="switch"')
expect(markup).toContain('Auto-name workspace from first agent message')
})
it('hides the Back button on the first visible step', () => {
const markup = renderToStaticMarkup(renderSurface({ isFirstStep: true }))
expect(markup).not.toContain('>Back<')
})
it('shows the Back button on later steps and wires the callback', () => {
const onBack = vi.fn()
const element = renderSurface(
{ progress: { current: 2, total: 3 }, isFirstStep: false },
{ onBack }
)
const backNode = findElementByText(element, 'Back')
expect(backNode).not.toBeNull()
backNode?.props.onClick?.()
expect(onBack).toHaveBeenCalledTimes(1)
})
it('wires Skip and Next callbacks', () => {
const onSkip = vi.fn()
const onNext = vi.fn()
const element = renderSurface({}, { onSkip, onNext })
findElementByAriaLabel(element, 'Skip tour')?.props.onClick?.()
findElementByText(element, 'Next')?.props.onClick?.()
expect(onSkip).toHaveBeenCalledWith('tasks')
expect(onNext).toHaveBeenCalledTimes(1)
})
it('renders configured step action labels and wires them through the action callback', () => {
const onStepAction = vi.fn()
const primaryAction = { kind: 'split-terminal-pane' as const, label: 'Split terminal' }
const secondaryAction = { kind: 'next' as const, label: 'Skip' }
const element = renderSurface(
{
primaryAction,
secondaryAction
},
{ onStepAction }
)
findElementByText(element, 'Split terminal')?.props.onClick?.()
findElementByText(element, 'Skip')?.props.onClick?.()
expect(onStepAction).toHaveBeenCalledWith(primaryAction)
expect(onStepAction).toHaveBeenCalledWith(secondaryAction)
})
it('renders target rings only for steps that request a target pulse', () => {
const pulsedMarkup = renderToStaticMarkup(
renderSurface({
targetPulse: true,
title: 'Start another task in parallel'
})
)
const defaultMarkup = renderToStaticMarkup(renderSurface())
expect(pulsedMarkup).toContain('data-contextual-tour-target-rings')
expect(defaultMarkup).not.toContain('data-contextual-tour-target-rings')
})
it('can hide the primary action when the real target is the CTA', () => {
const markup = renderToStaticMarkup(
renderSurface({
hidePrimaryAction: true,
isLastStep: true,
title: 'Start another task in parallel'
})
)
expect(markup).not.toContain('Done')
expect(markup).not.toContain('Next')
})
it('handles Escape by clicking Skip before page-level handlers see it', () => {
const click = vi.fn()
const preventDefault = vi.fn()
const stopPropagation = vi.fn()
handleContextualTourOverlayKeyDown({
key: 'Escape',
preventDefault,
stopPropagation,
currentTarget: {
querySelector: () => ({ click })
}
} as unknown as Parameters<typeof handleContextualTourOverlayKeyDown>[0])
expect(preventDefault).toHaveBeenCalledTimes(1)
expect(stopPropagation).toHaveBeenCalledTimes(1)
expect(click).toHaveBeenCalledTimes(1)
})
it('handles global Escape through the panel button so telemetry callbacks run', () => {
const click = vi.fn()
const dismissContextualTour = vi.fn()
const preventDefault = vi.fn()
const stopImmediatePropagation = vi.fn()
const panel = {
querySelector: vi.fn(() => ({ click }))
}
const overlay = {}
vi.spyOn(useAppStore, 'getState').mockReturnValue({
activeContextualTourId: 'tasks',
dismissContextualTour
} as unknown as ReturnType<typeof useAppStore.getState>)
vi.stubGlobal('document', {
querySelector: vi.fn((selector: string) =>
selector === '[data-contextual-tour-overlay]'
? overlay
: selector === '[data-contextual-tour-panel]'
? panel
: null
)
})
handleContextualTourGlobalKeyDown({
key: 'Escape',
preventDefault,
stopImmediatePropagation
} as unknown as KeyboardEvent)
expect(preventDefault).toHaveBeenCalledTimes(1)
expect(stopImmediatePropagation).toHaveBeenCalledTimes(1)
expect(panel.querySelector).toHaveBeenCalledWith(
'button[aria-label^="Skip"], button[aria-label="Dismiss tour"]'
)
expect(click).toHaveBeenCalledTimes(1)
expect(dismissContextualTour).not.toHaveBeenCalled()
})
it('does not dismiss directly on global Escape when the panel button is missing', () => {
const dismissContextualTour = vi.fn()
const preventDefault = vi.fn()
const stopImmediatePropagation = vi.fn()
const panel = {
querySelector: vi.fn(() => null)
}
const overlay = {}
vi.spyOn(useAppStore, 'getState').mockReturnValue({
activeContextualTourId: 'tasks',
dismissContextualTour
} as unknown as ReturnType<typeof useAppStore.getState>)
vi.stubGlobal('document', {
querySelector: vi.fn((selector: string) =>
selector === '[data-contextual-tour-overlay]'
? overlay
: selector === '[data-contextual-tour-panel]'
? panel
: null
)
})
handleContextualTourGlobalKeyDown({
key: 'Escape',
preventDefault,
stopImmediatePropagation
} as unknown as KeyboardEvent)
expect(preventDefault).toHaveBeenCalledTimes(1)
expect(stopImmediatePropagation).toHaveBeenCalledTimes(1)
expect(dismissContextualTour).not.toHaveBeenCalled()
})
})
describe('getContextualTourPanelHost', () => {
it('hosts controls inside Radix dialog and sheet content', () => {
const dialogHost = {} as HTMLElement
const sheetHost = {} as HTMLElement
const dialogTarget = { closest: vi.fn(() => dialogHost) } as unknown as Element
const sheetTarget = { closest: vi.fn(() => sheetHost) } as unknown as Element
const pageTarget = { closest: vi.fn(() => null) } as unknown as Element
expect(getContextualTourPanelHost(dialogTarget)).toBe(dialogHost)
expect(getContextualTourPanelHost(sheetTarget)).toBe(sheetHost)
expect(getContextualTourPanelHost(pageTarget)).toBeNull()
expect(dialogTarget.closest).toHaveBeenCalledWith(
'[data-slot="dialog-content"], [data-slot="sheet-content"]'
)
})
})
@@ -0,0 +1,407 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type JSX } from 'react'
import { useAppStore } from '@/store'
import {
getContextualTour,
type ContextualTourId,
type ContextualTourStepAction
} from '../../../../shared/contextual-tours'
import type { ContextualTourOutcome } from '../../../../shared/feature-education-telemetry'
import {
trackContextualTourOutcome,
trackContextualTourShown
} from '@/lib/feature-education-telemetry'
import { formatShortcutLabel } from '@/hooks/useShortcutLabel'
import {
getContextualTourStepCopy,
getContextualTourStepProgress,
getContextualTourOutcomeStepTotal,
getMeasurableContextualTourTarget,
getContextualTourPanelHost,
getVisibleContextualTourStepIndexes,
isContextualTourAllowedForModal
} from './contextual-tour-gate'
import { getContextualTourOverlayPanelPosition } from './contextual-tour-overlay-position'
import {
ContextualTourOverlaySurface,
getContextualTourFocusableElements,
handleContextualTourOverlayKeyDown,
type ActiveTourRenderState
} from './ContextualTourOverlaySurface'
import {
REQUEST_ACTIVE_TERMINAL_PANE_SPLIT_EVENT,
type RequestActiveTerminalPaneSplitDetail
} from '@/constants/terminal'
import { performContextualTourStepAction } from './contextual-tour-step-actions'
import { openWorkspaceCreationComposerWithTourHandoff } from './workspace-creation-tour-handoff'
export function ContextualTourOverlay(): JSX.Element | null {
const activeTourId = useAppStore((s) => s.activeContextualTourId)
const activeStepIndex = useAppStore((s) => s.activeContextualTourStepIndex)
const activeTourSource = useAppStore((s) => s.activeContextualTourSource)
const wasFeaturePreviouslyInteracted = useAppStore(
(s) => s.activeContextualTourWasFeaturePreviouslyInteracted
)
const activeModal = useAppStore((s) => s.activeModal)
const onboardingVisible = useAppStore((s) => s.contextualToursOnboardingVisible)
const blockingSurfaceVisible = useAppStore((s) => s.contextualToursBlockingSurfaceVisible)
const activeTourSuppressed = useAppStore((s) => s.activeContextualTourSuppressed)
const keybindings = useAppStore((s) => s.keybindings)
const activeTabId = useAppStore((s) => s.activeTabId)
const sidebarOpen = useAppStore((s) => s.sidebarOpen)
const canCreateWorkspace = useAppStore((s) => s.repos.length > 0)
const markContextualToursSeen = useAppStore((s) => s.markContextualToursSeen)
const advanceContextualTour = useAppStore((s) => s.advanceContextualTour)
const regressContextualTour = useAppStore((s) => s.regressContextualTour)
const dismissContextualTour = useAppStore((s) => s.dismissContextualTour)
const completeContextualTour = useAppStore((s) => s.completeContextualTour)
const cancelContextualTour = useAppStore((s) => s.cancelContextualTour)
const detachContextualTourSource = useAppStore((s) => s.detachContextualTourSource)
const setSidebarOpen = useAppStore((s) => s.setSidebarOpen)
const openTaskPage = useAppStore((s) => s.openTaskPage)
const openModal = useAppStore((s) => s.openModal)
const [renderState, setRenderState] = useState<ActiveTourRenderState | null>(null)
const [measureVersion, setMeasureVersion] = useState(0)
const panelRef = useRef<HTMLElement | null>(null)
const markedTourIdRef = useRef<string | null>(null)
const previousFocusRef = useRef<HTMLElement | null>(null)
const focusedStepRef = useRef<string | null>(null)
const telemetryTourIdRef = useRef<ContextualTourId | null>(null)
const telemetryOutcomeSentRef = useRef(false)
const telemetryStepsSeenRef = useRef<Set<number>>(new Set())
const telemetryTotalStepsRef = useRef(1)
const activeTour = useMemo(
() => (activeTourId ? getContextualTour(activeTourId) : null),
[activeTourId]
)
const emitContextualTourOutcome = useCallback(
(outcome: ContextualTourOutcome): void => {
if (
!activeTourId ||
telemetryOutcomeSentRef.current ||
telemetryTourIdRef.current !== activeTourId
) {
return
}
telemetryOutcomeSentRef.current = true
trackContextualTourOutcome({
tourId: activeTourId,
source: activeTourSource,
outcome,
stepsSeen: telemetryStepsSeenRef.current.size,
totalSteps: telemetryTotalStepsRef.current
})
},
[activeTourId, activeTourSource]
)
useLayoutEffect(() => {
if (!activeTourId) {
setRenderState(null)
return
}
// Why: reset before the measurement layout effect below, otherwise the
// first passive effect can hide a freshly measured tour until the next tick.
markedTourIdRef.current = null
telemetryTourIdRef.current = null
telemetryOutcomeSentRef.current = false
telemetryStepsSeenRef.current = new Set()
telemetryTotalStepsRef.current = 1
setRenderState(null)
}, [activeTourId])
useEffect(() => {
if (!activeTour || !activeTourId) {
return
}
if (
onboardingVisible ||
blockingSurfaceVisible ||
activeTourSuppressed ||
!isContextualTourAllowedForModal(activeTour, activeModal)
) {
emitContextualTourOutcome('cancelled')
cancelContextualTour(activeTourId)
}
}, [
activeModal,
activeTourSuppressed,
activeTour,
activeTourId,
blockingSurfaceVisible,
cancelContextualTour,
emitContextualTourOutcome,
onboardingVisible
])
useEffect(() => {
if (!activeTourId) {
return
}
const scheduleMeasure = (): void => setMeasureVersion((version) => version + 1)
window.addEventListener('resize', scheduleMeasure)
window.addEventListener('scroll', scheduleMeasure, true)
const interval = window.setInterval(scheduleMeasure, 500)
return () => {
window.removeEventListener('resize', scheduleMeasure)
window.removeEventListener('scroll', scheduleMeasure, true)
window.clearInterval(interval)
}
}, [activeTourId])
useLayoutEffect(() => {
if (!activeTour || activeTourId === null) {
setRenderState(null)
return
}
const targetExists = (selector: string): boolean =>
getMeasurableContextualTourTarget(selector) !== null
const visibleStepIndexes = getVisibleContextualTourStepIndexes(activeTour, targetExists)
telemetryTotalStepsRef.current = Math.max(
telemetryTotalStepsRef.current,
getContextualTourOutcomeStepTotal(visibleStepIndexes)
)
const activeStep = activeTour.steps[activeStepIndex]
const target = activeStep ? getMeasurableContextualTourTarget(activeStep.targetSelector) : null
const progress = getContextualTourStepProgress({
visibleStepIndexes,
stepIndex: activeStepIndex
})
if (visibleStepIndexes.length === 0) {
emitContextualTourOutcome('cancelled')
cancelContextualTour(activeTourId)
return
}
if (!activeStep || !target || !progress) {
const hasLaterStep = visibleStepIndexes.some((index) => index > activeStepIndex)
if (hasLaterStep) {
advanceContextualTour()
} else {
emitContextualTourOutcome('cancelled')
cancelContextualTour(activeTourId)
}
return
}
// Why: the "Show worktrees" CTA only opens the sidebar; when it's already
// open the button is a no-op, so fall back to a plain Next and drop the Skip.
const sidebarAlreadyVisible = activeStep.primaryAction?.kind === 'show-worktrees' && sidebarOpen
const primaryAction = sidebarAlreadyVisible
? ({ kind: 'next', label: 'Next' } as const)
: activeStep.primaryAction
const secondaryAction = sidebarAlreadyVisible ? undefined : activeStep.secondaryAction
setRenderState({
rect: target.rect,
targetElement: target.element,
progress,
title: activeStep.title,
body: formatContextualTourStepCopy(getContextualTourStepCopy(activeStep), keybindings),
control: activeStep.control,
primaryAction,
secondaryAction,
preferredPlacement: activeStep.preferredPlacement,
targetPulse: activeStep.targetPulse,
hidePrimaryAction: activeStep.hidePrimaryAction,
isLastStep: progress.current === progress.total,
isFirstStep: progress.current === 1,
panelHost: getContextualTourPanelHost(target.element)
})
}, [
activeStepIndex,
activeTour,
activeTourId,
advanceContextualTour,
cancelContextualTour,
emitContextualTourOutcome,
keybindings,
measureVersion,
sidebarOpen
])
useEffect(() => {
if (!activeTourId || !renderState || markedTourIdRef.current === activeTourId) {
return
}
// Why: a tour is considered seen only after its first measured target
// paints, so missing or removed surfaces can retry on a later visit.
markedTourIdRef.current = activeTourId
markContextualToursSeen([activeTourId])
}, [activeTourId, markContextualToursSeen, renderState])
useEffect(() => {
if (!activeTourId || !renderState || telemetryTourIdRef.current === activeTourId) {
return
}
telemetryTourIdRef.current = activeTourId
telemetryStepsSeenRef.current.add(activeStepIndex)
trackContextualTourShown({
tourId: activeTourId,
source: activeTourSource,
wasFeaturePreviouslyInteracted
})
}, [activeStepIndex, activeTourId, activeTourSource, renderState, wasFeaturePreviouslyInteracted])
useEffect(() => {
if (!activeTourId || !renderState) {
return
}
telemetryStepsSeenRef.current.add(activeStepIndex)
}, [activeStepIndex, activeTourId, renderState])
useEffect(() => {
if (!activeTourId) {
return
}
const emitPendingCancellation = (): void => {
emitContextualTourOutcome(getContextualTourCleanupOutcome(activeTourId))
}
window.addEventListener('beforeunload', emitPendingCancellation)
return () => {
window.removeEventListener('beforeunload', emitPendingCancellation)
// Why: analytics expects every shown tour to have an outcome, even when
// the renderer closes or unmounts before the user presses Skip/Done.
emitPendingCancellation()
}
}, [activeTourId, emitContextualTourOutcome])
useEffect(() => {
if (!activeTourId || !renderState) {
return
}
const focusKey = `${activeTourId}:${activeStepIndex}`
if (focusedStepRef.current === focusKey) {
return
}
focusedStepRef.current = focusKey
const currentFocus = document.activeElement
if (
!previousFocusRef.current &&
currentFocus instanceof HTMLElement &&
!panelRef.current?.contains(currentFocus)
) {
previousFocusRef.current = currentFocus
}
const timeout = window.setTimeout(() => {
const panel = panelRef.current
const firstFocusable = panel ? getContextualTourFocusableElements(panel)[0] : null
;(firstFocusable ?? panel)?.focus({ preventScroll: true })
}, 0)
return () => window.clearTimeout(timeout)
}, [activeStepIndex, activeTourId, renderState])
useEffect(() => {
if (activeTourId) {
return
}
focusedStepRef.current = null
const previousFocus = previousFocusRef.current
previousFocusRef.current = null
if (previousFocus?.isConnected) {
previousFocus.focus({ preventScroll: true })
}
}, [activeTourId])
if (!activeTourId || !renderState) {
return null
}
const finishTour = (): void => {
emitContextualTourOutcome('completed')
completeContextualTour(activeTourId)
}
const handleStepAction = (action: ContextualTourStepAction): void => {
performContextualTourStepAction({
action,
activeTabId,
isLastStep: renderState.isLastStep,
finishTour,
advanceContextualTour,
detachContextualTourSource: () => {
if (activeTourSource) {
detachContextualTourSource(activeTourId, activeTourSource)
}
},
setSidebarOpen,
openTaskPage,
openModal,
canCreateWorkspace,
openWorkspaceComposer: openWorkspaceCreationComposerWithTourHandoff,
dispatchTerminalPaneSplit: (detail) => {
window.dispatchEvent(
new CustomEvent<RequestActiveTerminalPaneSplitDetail>(
REQUEST_ACTIVE_TERMINAL_PANE_SPLIT_EVENT,
{ detail }
)
)
},
schedule: (callback) => {
window.setTimeout(callback, 0)
}
})
}
const viewport = {
width: typeof window === 'undefined' ? 1024 : window.innerWidth,
height: typeof window === 'undefined' ? 768 : window.innerHeight
}
const { panelPosition, panelPlacement } = getContextualTourOverlayPanelPosition({
targetRect: renderState.rect,
panelElement: panelRef.current,
panelHost: renderState.panelHost,
preferredPlacement: renderState.preferredPlacement,
viewport
})
return (
<ContextualTourOverlaySurface
activeTourId={activeTourId}
renderState={renderState}
panelRef={panelRef}
panelPosition={panelPosition}
panelPlacement={panelPlacement}
panelHost={renderState.panelHost}
onSkip={(id) => {
emitContextualTourOutcome('skipped')
dismissContextualTour(id)
}}
onBack={regressContextualTour}
onNext={() => {
if (renderState.isLastStep) {
finishTour()
} else {
advanceContextualTour()
}
}}
onStepAction={handleStepAction}
onOverlayKeyDownCapture={handleContextualTourOverlayKeyDown}
/>
)
}
export function getContextualTourCleanupOutcome(
activeTourId: ContextualTourId
): ContextualTourOutcome {
return useAppStore.getState().lastCompletedContextualTourId === activeTourId
? 'completed'
: 'cancelled'
}
function formatContextualTourStepCopy(
copy: string,
keybindings: Parameters<typeof formatShortcutLabel>[1]
): string {
return copy.replace(
'{terminal.splitRight}',
formatShortcutLabel('terminal.splitRight', keybindings)
)
}
@@ -0,0 +1,250 @@
import { createPortal } from 'react-dom'
import { type CSSProperties, type JSX, type KeyboardEvent, type RefObject } from 'react'
import { ArrowLeft, ArrowRight, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useAppStore } from '@/store'
import type {
ContextualTourId,
ContextualTourStepPlacement,
ContextualTourStepControl,
ContextualTourStepAction
} from '../../../../shared/contextual-tours'
import { ContextualTourArrow } from './ContextualTourArrow'
import { ContextualTourControl } from './ContextualTourControl'
import { ContextualTourProgressDots } from './ContextualTourProgressDots'
import type { ContextualTourPanelPlacement } from './contextual-tour-panel-position'
const FOCUSABLE_SELECTOR =
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
const SKIP_BUTTON_SELECTOR = 'button[aria-label^="Skip"], button[aria-label="Dismiss tour"]'
export type ActiveTourRenderState = {
rect: DOMRect
targetElement: Element
progress: { current: number; total: number }
title: string
body: string
control?: ContextualTourStepControl
primaryAction?: ContextualTourStepAction
secondaryAction?: ContextualTourStepAction
preferredPlacement?: ContextualTourStepPlacement
targetPulse?: boolean
hidePrimaryAction?: boolean
isLastStep: boolean
isFirstStep: boolean
panelHost: HTMLElement | null
}
type PanelPositionStyle = CSSProperties & {
'--contextual-tour-arrow-offset'?: string
}
type ContextualTourOverlaySurfaceProps = {
activeTourId: ContextualTourId
renderState: ActiveTourRenderState
panelRef: RefObject<HTMLElement | null>
panelPosition: PanelPositionStyle
panelPlacement: ContextualTourPanelPlacement | null
panelHost: HTMLElement | null
onSkip: (id: ContextualTourId) => void
onBack: () => void
onNext: () => void
onStepAction: (action: ContextualTourStepAction) => void
onOverlayKeyDownCapture: (event: KeyboardEvent<HTMLDivElement>) => void
}
if (typeof window !== 'undefined') {
const guardedWindow = window as Window & {
__orcaContextualTourGlobalKeyGuardInstalled?: boolean
}
if (!guardedWindow.__orcaContextualTourGlobalKeyGuardInstalled) {
guardedWindow.__orcaContextualTourGlobalKeyGuardInstalled = true
window.addEventListener('keydown', handleContextualTourGlobalKeyDown, true)
}
}
const PANEL_BASE_CLASSES =
'orca-contextual-tour-panel rounded-lg border border-border text-popover-foreground backdrop-blur-[2px]'
const PANEL_ANIMATION_CLASSES = 'animate-in fade-in-0 zoom-in-95 duration-200 ease-out'
export function ContextualTourOverlaySurface({
activeTourId,
renderState,
panelRef,
panelPosition,
panelPlacement,
panelHost,
onSkip,
onBack,
onNext,
onStepAction,
onOverlayKeyDownCapture
}: ContextualTourOverlaySurfaceProps): JSX.Element {
const panelHostSlot = panelHost?.getAttribute('data-slot')
const hostedPanelClass = cn(
PANEL_BASE_CLASSES,
PANEL_ANIMATION_CLASSES,
panelHostSlot === 'sheet-content'
? 'absolute z-[80] w-[min(20rem,calc(100%-1.5rem))]'
: 'absolute z-[80] w-[min(20rem,calc(100%-2rem))]'
)
const floatingPanelClass = cn(
PANEL_BASE_CLASSES,
PANEL_ANIMATION_CLASSES,
'fixed w-[min(20rem,calc(100vw-1.5rem))]'
)
const stepKey = `${activeTourId}-${renderState.progress.current}`
const defaultPrimaryAction = {
kind: renderState.isLastStep ? 'complete' : 'next',
label: renderState.isLastStep ? 'Done' : 'Next'
} satisfies ContextualTourStepAction
const primaryAction =
renderState.primaryAction ?? (renderState.hidePrimaryAction ? null : defaultPrimaryAction)
const showTargetRings = renderState.targetPulse === true
const targetRingStyle = showTargetRings
? ({
left: renderState.rect.left,
top: renderState.rect.top,
width: renderState.rect.width,
height: renderState.rect.height
} satisfies CSSProperties)
: undefined
const panel = (
<section
ref={panelRef}
aria-live="polite"
aria-label={renderState.title}
data-contextual-tour-panel=""
data-placement={panelPlacement ?? undefined}
role="dialog"
tabIndex={-1}
className={panelHost ? hostedPanelClass : floatingPanelClass}
style={panelPosition}
>
{panelPlacement ? <ContextualTourArrow placement={panelPlacement} /> : null}
<div key={stepKey} className="animate-in fade-in-0 duration-150 ease-out p-4">
<Button
type="button"
variant="ghost"
size="icon-xs"
aria-label={renderState.isLastStep ? 'Dismiss tour' : 'Skip tour'}
onClick={() => onSkip(activeTourId)}
className="absolute right-2 top-2 text-muted-foreground hover:text-foreground"
>
<X />
</Button>
<h2 className="pr-6 text-sm font-semibold tracking-tight text-foreground">
{renderState.title}
</h2>
<p className="mt-1.5 text-xs leading-5 text-muted-foreground">{renderState.body}</p>
{renderState.control ? <ContextualTourControl control={renderState.control} /> : null}
<div className="mt-3.5 flex items-center justify-between gap-3">
<ContextualTourProgressDots
current={renderState.progress.current}
total={renderState.progress.total}
/>
<div className="flex items-center gap-1.5">
{!renderState.isFirstStep ? (
<Button type="button" variant="ghost" size="xs" aria-label="Back" onClick={onBack}>
<ArrowLeft />
Back
</Button>
) : null}
{renderState.secondaryAction ? (
<Button
type="button"
variant="ghost"
size="xs"
onClick={() => onStepAction(renderState.secondaryAction!)}
>
{renderState.secondaryAction.label}
</Button>
) : null}
{primaryAction ? (
<Button
type="button"
size="xs"
onClick={
primaryAction.kind === defaultPrimaryAction.kind &&
primaryAction.label === defaultPrimaryAction.label
? onNext
: () => onStepAction(primaryAction)
}
>
{primaryAction.label}
{primaryAction.kind === 'next' && !renderState.isLastStep ? <ArrowRight /> : null}
</Button>
) : null}
</div>
</div>
</div>
</section>
)
return (
<div
className={cn(
// Why: tours are callouts, not modality. Let pointer events reach the
// underlying surface; only the panel itself captures interaction.
'fixed inset-0 z-[70] pointer-events-none'
)}
data-contextual-tour-overlay=""
role="presentation"
onKeyDownCapture={onOverlayKeyDownCapture}
>
{showTargetRings ? (
<div
aria-hidden="true"
className="orca-contextual-tour-target-rings fixed z-[75]"
data-contextual-tour-target-rings=""
style={targetRingStyle}
/>
) : null}
<div className="pointer-events-auto">
{panelHost ? createPortal(panel, panelHost) : panel}
</div>
</div>
)
}
export function handleContextualTourOverlayKeyDown(event: KeyboardEvent<HTMLDivElement>): void {
if (event.key === 'Escape') {
event.preventDefault()
event.stopPropagation()
const skipButton = event.currentTarget.querySelector<HTMLButtonElement>(SKIP_BUTTON_SELECTOR)
skipButton?.click()
}
// Why: tours are non-modal callouts over live UI. Keyboard users must be able
// to tab into the highlighted surface just as pointer users can click it.
}
export function handleContextualTourGlobalKeyDown(event: globalThis.KeyboardEvent): void {
const activeTourId = useAppStore.getState().activeContextualTourId
if (!activeTourId || event.key !== 'Escape') {
return
}
const overlay = document.querySelector<HTMLElement>('[data-contextual-tour-overlay]')
const focusRoot = document.querySelector<HTMLElement>('[data-contextual-tour-panel]') ?? overlay
if (!overlay || !focusRoot) {
return
}
event.preventDefault()
event.stopImmediatePropagation()
const skipButton = focusRoot.querySelector<HTMLButtonElement>(SKIP_BUTTON_SELECTOR)
if (skipButton) {
skipButton.click()
}
}
export function getContextualTourFocusableElements(root: HTMLElement): HTMLElement[] {
return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(
(element) => element.getClientRects().length > 0 || element === document.activeElement
)
}
@@ -0,0 +1,47 @@
import type { JSX } from 'react'
import { cn } from '@/lib/utils'
export function ContextualTourProgressDots({
current,
total
}: {
current: number
total: number
}): JSX.Element {
if (total <= 1) {
return <span aria-hidden="true" className="h-1.5 w-4" />
}
return (
<div
className="flex items-center gap-2"
role="progressbar"
aria-valuemin={1}
aria-valuemax={total}
aria-valuenow={current}
aria-label={`Step ${current} of ${total}`}
>
<span className="flex items-center gap-1.5" aria-hidden="true">
{Array.from({ length: total }).map((_, index) => {
const isActive = index + 1 === current
const isComplete = index + 1 < current
return (
<span
key={index}
className={cn(
'block h-1.5 rounded-full transition-all duration-200 ease-out',
isActive
? 'w-4 bg-foreground'
: isComplete
? 'w-1.5 bg-foreground/55'
: 'w-1.5 bg-foreground/20'
)}
/>
)
})}
</span>
<span className="whitespace-nowrap text-[11px] font-medium leading-none text-muted-foreground">
{current} of {total}
</span>
</div>
)
}
@@ -0,0 +1,2 @@
export const CONTEXTUAL_TOUR_ENABLE_AUTO_WORKSPACE_NAME_EVENT =
'orca:contextual-tour-enable-auto-workspace-name'
@@ -0,0 +1,285 @@
import { describe, expect, it } from 'vitest'
import { getContextualTour } from '../../../../shared/contextual-tours'
import {
getContextualTourRequestDecision,
getContextualTourStepProgress,
getContextualTourOutcomeStepTotal,
getMeasurableContextualTourTarget,
getNextVisibleContextualTourStepIndex,
getPreviousVisibleContextualTourStepIndex,
getVisibleContextualTourStepIndexes,
isContextualTourAllowedForModal
} from './contextual-tour-gate'
describe('contextual tour gate', () => {
it('allows only workspace creation over its workspace composer modal', () => {
const workspaceCreation = getContextualTour('workspace-creation')
const tasks = getContextualTour('tasks')
expect(isContextualTourAllowedForModal(workspaceCreation, 'new-workspace-composer')).toBe(true)
expect(isContextualTourAllowedForModal(workspaceCreation, 'add-repo')).toBe(false)
expect(isContextualTourAllowedForModal(tasks, 'none')).toBe(true)
expect(isContextualTourAllowedForModal(tasks, 'new-workspace-composer')).toBe(false)
expect(isContextualTourAllowedForModal(tasks, 'add-repo')).toBe(false)
})
it('does not start when the required first target is missing', () => {
const decision = getContextualTourRequestDecision({
tour: getContextualTour('tasks'),
persistedUIReady: true,
autoEligible: true,
onboardingVisible: false,
seenIds: [],
sessionConsumed: false,
activeTourId: null,
activeModal: 'none',
blockingSurfaceVisible: false,
targetExists: () => false
})
expect(decision).toEqual({ kind: 'blocked', reason: 'missing-start-target' })
})
it('returns null when selector lookup or measurement throws', () => {
expect(
getMeasurableContextualTourTarget('[', {
querySelector: () => {
throw new Error('bad selector')
}
} as unknown as ParentNode)
).toBeNull()
expect(
getMeasurableContextualTourTarget('[data-contextual-tour-target="tasks-source-filters"]', {
querySelector: () => ({
getBoundingClientRect: () => {
throw new Error('detached element')
}
})
} as unknown as ParentNode)
).toBeNull()
})
it('returns null when the target is inside a hidden subtree', () => {
expect(
getMeasurableContextualTourTarget('[data-contextual-tour-target="browser-address"]', {
querySelector: () => ({
closest: (selector: string) => (selector.includes('aria-hidden') ? {} : null),
getBoundingClientRect: () => ({
left: 0,
top: 0,
right: 120,
bottom: 32,
width: 120,
height: 32
})
})
} as unknown as ParentNode)
).toBeNull()
})
it('uses the first visible measurable target when hidden mounted copies exist first', () => {
const hiddenElement = {
closest: (selector: string) => (selector.includes('aria-hidden') ? {} : null),
getBoundingClientRect: () => ({
left: 0,
top: 0,
right: 120,
bottom: 32,
width: 120,
height: 32
})
}
const visibleElement = {
closest: () => null,
getBoundingClientRect: () => ({
left: 10,
top: 20,
right: 210,
bottom: 64,
width: 200,
height: 44
})
}
const target = getMeasurableContextualTourTarget(
'[data-contextual-tour-target="browser-address"]',
{
querySelectorAll: () => [hiddenElement, visibleElement]
} as unknown as ParentNode
)
expect(target?.element).toBe(visibleElement)
expect(target?.rect.width).toBe(200)
})
it('starts an unseen tour only when global gates pass', () => {
const tour = getContextualTour('tasks')
const hasFirstTarget = (selector: string): boolean => selector === tour.steps[0]?.targetSelector
expect(
getContextualTourRequestDecision({
tour,
persistedUIReady: true,
autoEligible: true,
onboardingVisible: false,
seenIds: [],
sessionConsumed: false,
activeTourId: null,
activeModal: 'none',
blockingSurfaceVisible: false,
targetExists: hasFirstTarget
})
).toEqual({ kind: 'start', stepIndex: 0 })
expect(
getContextualTourRequestDecision({
tour,
persistedUIReady: false,
autoEligible: true,
onboardingVisible: false,
seenIds: [],
sessionConsumed: false,
activeTourId: null,
activeModal: 'none',
blockingSurfaceVisible: false,
targetExists: hasFirstTarget
})
).toEqual({ kind: 'blocked', reason: 'persisted-ui-not-ready' })
expect(
getContextualTourRequestDecision({
tour,
persistedUIReady: true,
autoEligible: false,
onboardingVisible: false,
seenIds: [],
sessionConsumed: false,
activeTourId: null,
activeModal: 'none',
blockingSurfaceVisible: false,
targetExists: hasFirstTarget
})
).toEqual({ kind: 'blocked', reason: 'auto-disabled' })
expect(
getContextualTourRequestDecision({
tour,
persistedUIReady: true,
autoEligible: true,
onboardingVisible: true,
seenIds: [],
sessionConsumed: false,
activeTourId: null,
activeModal: 'none',
blockingSurfaceVisible: false,
targetExists: hasFirstTarget
})
).toEqual({ kind: 'blocked', reason: 'onboarding' })
expect(
getContextualTourRequestDecision({
tour,
persistedUIReady: true,
autoEligible: true,
onboardingVisible: false,
seenIds: ['tasks'],
sessionConsumed: false,
activeTourId: null,
activeModal: 'none',
blockingSurfaceVisible: false,
targetExists: hasFirstTarget
})
).toEqual({ kind: 'blocked', reason: 'seen' })
expect(
getContextualTourRequestDecision({
tour,
persistedUIReady: true,
autoEligible: true,
onboardingVisible: false,
seenIds: [],
sessionConsumed: false,
activeTourId: null,
activeModal: 'none',
blockingSurfaceVisible: true,
targetExists: hasFirstTarget
})
).toEqual({ kind: 'blocked', reason: 'blocking-surface' })
})
it('skips missing later steps and keeps progress relative to visible steps', () => {
const tour = getContextualTour('tasks')
const visibleSelectors = new Set([tour.steps[0]!.targetSelector, tour.steps[2]!.targetSelector])
const targetExists = (selector: string): boolean => visibleSelectors.has(selector)
const visibleStepIndexes = getVisibleContextualTourStepIndexes(tour, targetExists)
expect(visibleStepIndexes).toEqual([0, 2])
expect(
getNextVisibleContextualTourStepIndex({
tour,
currentStepIndex: 0,
targetExists
})
).toBe(2)
expect(
getPreviousVisibleContextualTourStepIndex({
tour,
currentStepIndex: 2,
targetExists
})
).toBe(0)
expect(
getPreviousVisibleContextualTourStepIndex({
tour,
currentStepIndex: 0,
targetExists
})
).toBeNull()
expect(getContextualTourStepProgress({ visibleStepIndexes, stepIndex: 2 })).toEqual({
current: 2,
total: 2
})
expect(getContextualTourOutcomeStepTotal(visibleStepIndexes)).toBe(2)
expect(getContextualTourOutcomeStepTotal([])).toBe(1)
})
it('advances the workspace-agent-sessions tour from split to the create-worktree step', () => {
const tour = getContextualTour('workspace-agent-sessions')
const targetExists = (): boolean => true
const visibleStepIndexes = getVisibleContextualTourStepIndexes(tour, targetExists)
expect(tour.steps.map((step) => step.title)).toEqual([
'Split a terminal pane',
'Start another task in parallel'
])
expect(visibleStepIndexes).toEqual([0, 1])
expect(
getNextVisibleContextualTourStepIndex({
tour,
currentStepIndex: 0,
targetExists
})
).toBe(1)
expect(getContextualTourStepProgress({ visibleStepIndexes, stepIndex: 1 })).toEqual({
current: 2,
total: 2
})
})
it('cancels the workspace-agent-sessions tour when the new-worktree button is absent', () => {
const tour = getContextualTour('workspace-agent-sessions')
// Only the split step's target is present; the create-worktree button is not.
const targetExists = (selector: string): boolean => selector === tour.steps[0]!.targetSelector
const visibleStepIndexes = getVisibleContextualTourStepIndexes(tour, targetExists)
expect(visibleStepIndexes).toEqual([0])
expect(
getNextVisibleContextualTourStepIndex({
tour,
currentStepIndex: 0,
targetExists
})
).toBeNull()
})
})
@@ -0,0 +1,241 @@
import type { ContextualTour, ContextualTourStep } from '../../../../shared/contextual-tours'
export type ContextualTourTarget = {
element: Element
rect: DOMRect
}
export type ContextualTourRequestDecision =
| { kind: 'start'; stepIndex: number }
| {
kind: 'blocked'
reason:
| 'persisted-ui-not-ready'
| 'auto-disabled'
| 'onboarding'
| 'seen'
| 'session-consumed'
| 'active-tour'
| 'modal'
| 'blocking-surface'
| 'missing-start-target'
}
const PANEL_HOST_SELECTOR = '[data-slot="dialog-content"], [data-slot="sheet-content"]'
export function getContextualTourPanelHost(targetElement: Element): HTMLElement | null {
return targetElement.closest<HTMLElement>(PANEL_HOST_SELECTOR)
}
export function isContextualTourAllowedForModal(
tour: ContextualTour,
activeModal: string
): boolean {
if (activeModal === 'none') {
return true
}
return tour.allowedActiveModals?.includes(activeModal) === true
}
export function getMeasurableContextualTourTarget(
selector: string,
root?: ParentNode
): ContextualTourTarget | null {
const queryRoot = root ?? (typeof document !== 'undefined' ? document : null)
const elements = getContextualTourTargetCandidates(selector, queryRoot)
if (!elements) {
return null
}
for (const element of elements) {
if (!element || typeof element.getBoundingClientRect !== 'function') {
continue
}
if (!isContextualTourTargetVisible(element)) {
continue
}
let rect: DOMRect
try {
rect = element.getBoundingClientRect()
} catch {
continue
}
if (isMeasurableRect(rect)) {
return { element, rect }
}
}
return null
}
export function hasContextualTourTarget(selector: string, root?: ParentNode): boolean {
return getMeasurableContextualTourTarget(selector, root) !== null
}
export function getContextualTourStartStepIndex(
tour: ContextualTour,
targetExists: (selector: string) => boolean
): number | null {
const requiredStepIndex = tour.steps.findIndex((step) => step.requiredForStart === true)
const startIndex = Math.max(requiredStepIndex, 0)
const step = tour.steps[startIndex]
if (!step || !targetExists(step.targetSelector)) {
return null
}
return startIndex
}
export function getVisibleContextualTourStepIndexes(
tour: ContextualTour,
targetExists: (selector: string) => boolean
): number[] {
const indexes: number[] = []
tour.steps.forEach((step, index) => {
if (targetExists(step.targetSelector)) {
indexes.push(index)
}
})
return indexes
}
export function getNextVisibleContextualTourStepIndex(args: {
tour: ContextualTour
currentStepIndex: number
targetExists: (selector: string) => boolean
}): number | null {
return (
getVisibleContextualTourStepIndexes(args.tour, args.targetExists).find(
(index) => index > args.currentStepIndex
) ?? null
)
}
export function getPreviousVisibleContextualTourStepIndex(args: {
tour: ContextualTour
currentStepIndex: number
targetExists: (selector: string) => boolean
}): number | null {
const visible = getVisibleContextualTourStepIndexes(args.tour, args.targetExists)
let prev: number | null = null
for (const index of visible) {
if (index >= args.currentStepIndex) {
break
}
prev = index
}
return prev
}
export function getContextualTourRequestDecision(args: {
tour: ContextualTour
persistedUIReady: boolean
autoEligible: boolean
onboardingVisible: boolean
seenIds: readonly string[]
sessionConsumed: boolean
activeTourId: string | null
activeModal: string
blockingSurfaceVisible: boolean
targetExists: (selector: string) => boolean
}): ContextualTourRequestDecision {
if (!args.persistedUIReady) {
return { kind: 'blocked', reason: 'persisted-ui-not-ready' }
}
if (!args.autoEligible) {
return { kind: 'blocked', reason: 'auto-disabled' }
}
if (args.onboardingVisible) {
return { kind: 'blocked', reason: 'onboarding' }
}
if (args.seenIds.includes(args.tour.id)) {
return { kind: 'blocked', reason: 'seen' }
}
if (args.sessionConsumed) {
return { kind: 'blocked', reason: 'session-consumed' }
}
if (args.activeTourId !== null) {
return { kind: 'blocked', reason: 'active-tour' }
}
if (!isContextualTourAllowedForModal(args.tour, args.activeModal)) {
return { kind: 'blocked', reason: 'modal' }
}
if (args.blockingSurfaceVisible) {
return { kind: 'blocked', reason: 'blocking-surface' }
}
const stepIndex = getContextualTourStartStepIndex(args.tour, args.targetExists)
if (stepIndex === null) {
return { kind: 'blocked', reason: 'missing-start-target' }
}
return { kind: 'start', stepIndex }
}
export function getContextualTourStepProgress(args: {
visibleStepIndexes: readonly number[]
stepIndex: number
}): { current: number; total: number } | null {
const visibleIndex = args.visibleStepIndexes.indexOf(args.stepIndex)
if (visibleIndex < 0) {
return null
}
return { current: visibleIndex + 1, total: args.visibleStepIndexes.length }
}
export function getContextualTourOutcomeStepTotal(
visibleStepIndexes: readonly number[],
fallback = 1
): number {
return visibleStepIndexes.length > 0 ? visibleStepIndexes.length : fallback
}
export function getContextualTourStepCopy(step: ContextualTourStep): string {
return step.body || step.fallbackCopy || ''
}
function isMeasurableRect(rect: DOMRect): boolean {
return (
Number.isFinite(rect.width) && Number.isFinite(rect.height) && rect.width > 0 && rect.height > 0
)
}
function getContextualTourTargetCandidates(
selector: string,
queryRoot: ParentNode | null
): Element[] | null {
if (!queryRoot) {
return []
}
try {
if (typeof queryRoot.querySelectorAll === 'function') {
return Array.from(queryRoot.querySelectorAll(selector))
}
return queryRoot.querySelector(selector) ? [queryRoot.querySelector(selector)!] : []
} catch {
return null
}
}
function isContextualTourTargetVisible(element: Element): boolean {
if (
typeof element.closest === 'function' &&
element.closest('[hidden],[inert],[aria-hidden="true"]')
) {
return false
}
if (typeof window === 'undefined' || typeof HTMLElement === 'undefined') {
return true
}
let current: Element | null = element
while (current instanceof HTMLElement) {
const style = window.getComputedStyle(current)
if (
style.display === 'none' ||
style.visibility === 'hidden' ||
style.visibility === 'collapse'
) {
return false
}
current = current.parentElement
}
return true
}
@@ -0,0 +1,45 @@
import type { CSSProperties } from 'react'
import type { ContextualTourStepPlacement } from '../../../../shared/contextual-tours'
import type { ContextualTourPanelPlacement } from './contextual-tour-panel-position'
import {
clampContextualTourPanelPosition,
getContextualTourPanelCssPosition
} from './contextual-tour-panel-position'
const PANEL_FALLBACK_SIZE = { width: 304, height: 172 }
export type ContextualTourOverlayPanelPosition = {
panelPosition: CSSProperties & { '--contextual-tour-arrow-offset'?: string }
panelPlacement: ContextualTourPanelPlacement
}
export function getContextualTourOverlayPanelPosition(args: {
targetRect: DOMRect
panelElement: HTMLElement | null
panelHost: HTMLElement | null
preferredPlacement?: ContextualTourStepPlacement
viewport: { width: number; height: number }
}): ContextualTourOverlayPanelPosition {
const panelRect = args.panelElement?.getBoundingClientRect()
const panel = panelRect
? { width: panelRect.width, height: panelRect.height }
: PANEL_FALLBACK_SIZE
const clamped = clampContextualTourPanelPosition({
targetRect: args.targetRect,
viewport: args.viewport,
panel,
preferredPlacement: args.preferredPlacement
})
const cssPosition = getContextualTourPanelCssPosition({
position: clamped,
panelHostRect: args.panelHost?.getBoundingClientRect()
})
return {
panelPlacement: clamped.placement,
panelPosition: {
left: cssPosition.left,
top: cssPosition.top,
'--contextual-tour-arrow-offset': `${cssPosition.arrowOffset}px`
}
}
}
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest'
import {
clampContextualTourPanelPosition,
getContextualTourPanelCssPosition
} from './contextual-tour-panel-position'
describe('contextual tour panel position', () => {
it('clamps the panel inside narrow viewports', () => {
const position = clampContextualTourPanelPosition({
targetRect: {
left: 20,
right: 140,
top: 40,
bottom: 100,
width: 120,
height: 60
},
viewport: { width: 320, height: 220 },
panel: { width: 304, height: 160 }
})
expect(position.left).toBeGreaterThanOrEqual(12)
expect(position.top).toBeGreaterThanOrEqual(12)
expect(position.left).toBeLessThanOrEqual(12)
expect(position.top).toBeLessThanOrEqual(48)
})
it('places the panel to the right when room allows and aims the arrow at target center', () => {
const position = clampContextualTourPanelPosition({
targetRect: { left: 100, right: 200, top: 200, bottom: 240, width: 100, height: 40 },
viewport: { width: 1024, height: 768 },
panel: { width: 320, height: 180 }
})
expect(position.placement).toBe('right')
// panel is positioned to the right of the target, vertically centered;
// arrow should sit near the panel's vertical center pointing at the target's center
expect(position.left).toBe(212)
expect(position.arrowOffset).toBeGreaterThan(60)
expect(position.arrowOffset).toBeLessThan(120)
})
it('converts viewport panel coordinates into hosted dialog coordinates', () => {
const position = {
left: 838,
top: 168,
placement: 'right' as const,
arrowOffset: 64
}
expect(
getContextualTourPanelCssPosition({
position,
panelHostRect: { left: 500, top: 80 }
})
).toEqual({ left: 338, top: 88, arrowOffset: 64 })
expect(getContextualTourPanelCssPosition({ position })).toEqual({
left: 838,
top: 168,
arrowOffset: 64
})
})
it('flips below the target when neither side has horizontal room', () => {
const position = clampContextualTourPanelPosition({
targetRect: { left: 60, right: 260, top: 40, bottom: 80, width: 200, height: 40 },
viewport: { width: 320, height: 600 },
panel: { width: 304, height: 160 }
})
expect(position.placement).toBe('bottom')
expect(position.top).toBeGreaterThanOrEqual(80 + 12)
})
it('honors a preferred placement for anchored tip-style tours', () => {
const position = clampContextualTourPanelPosition({
targetRect: { left: 280, right: 1160, top: 452, bottom: 453, width: 880, height: 1 },
viewport: { width: 1512, height: 900 },
panel: { width: 320, height: 140 },
preferredPlacement: 'bottom'
})
expect(position.placement).toBe('bottom')
expect(position.top).toBe(465)
expect(position.left).toBe(560)
})
})
@@ -0,0 +1,136 @@
export type ContextualTourPanelPlacement = 'top' | 'right' | 'bottom' | 'left'
export type ContextualTourPanelPosition = {
left: number
top: number
placement: ContextualTourPanelPlacement
arrowOffset: number
}
type ViewportSize = {
width: number
height: number
}
type PanelSize = {
width: number
height: number
}
export function clampContextualTourPanelPosition(args: {
targetRect: Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom' | 'width' | 'height'>
viewport: ViewportSize
panel: PanelSize
preferredPlacement?: ContextualTourPanelPlacement
gap?: number
margin?: number
}): ContextualTourPanelPosition {
const gap = args.gap ?? 12
const margin = args.margin ?? 12
const { targetRect, viewport, panel } = args
const roomRight = viewport.width - targetRect.right
const roomLeft = targetRect.left
const roomBelow = viewport.height - targetRect.bottom
const roomAbove = targetRect.top
let placement: ContextualTourPanelPlacement
let left: number
let top: number
if (args.preferredPlacement) {
placement = args.preferredPlacement
const preferredPosition = getUnclampedPanelPosition({
placement,
targetRect,
panel,
gap
})
left = preferredPosition.left
top = preferredPosition.top
} else if (roomRight >= panel.width + gap || roomRight >= roomLeft) {
placement = 'right'
left = targetRect.right + gap
top = targetRect.top + targetRect.height / 2 - panel.height / 2
} else {
placement = 'left'
left = targetRect.left - panel.width - gap
top = targetRect.top + targetRect.height / 2 - panel.height / 2
}
if (roomRight < panel.width + gap && roomLeft < panel.width + gap) {
left = targetRect.left + targetRect.width / 2 - panel.width / 2
if (roomBelow >= panel.height + gap || roomBelow >= roomAbove) {
placement = 'bottom'
top = targetRect.bottom + gap
} else {
placement = 'top'
top = targetRect.top - panel.height - gap
}
}
const clampedLeft = clampNumber(
left,
margin,
Math.max(margin, viewport.width - panel.width - margin)
)
const clampedTop = clampNumber(
top,
margin,
Math.max(margin, viewport.height - panel.height - margin)
)
// Arrow offset along the panel edge, pointed at the target's center.
const targetCenterX = targetRect.left + targetRect.width / 2
const targetCenterY = targetRect.top + targetRect.height / 2
const arrowMargin = 16
const arrowOffset =
placement === 'top' || placement === 'bottom'
? clampNumber(targetCenterX - clampedLeft, arrowMargin, panel.width - arrowMargin)
: clampNumber(targetCenterY - clampedTop, arrowMargin, panel.height - arrowMargin)
return { left: clampedLeft, top: clampedTop, placement, arrowOffset }
}
function getUnclampedPanelPosition(args: {
placement: ContextualTourPanelPlacement
targetRect: Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom' | 'width' | 'height'>
panel: PanelSize
gap: number
}): Pick<ContextualTourPanelPosition, 'left' | 'top'> {
const { placement, targetRect, panel, gap } = args
if (placement === 'top') {
return {
left: targetRect.left + targetRect.width / 2 - panel.width / 2,
top: targetRect.top - panel.height - gap
}
}
if (placement === 'bottom') {
return {
left: targetRect.left + targetRect.width / 2 - panel.width / 2,
top: targetRect.bottom + gap
}
}
if (placement === 'left') {
return {
left: targetRect.left - panel.width - gap,
top: targetRect.top + targetRect.height / 2 - panel.height / 2
}
}
return {
left: targetRect.right + gap,
top: targetRect.top + targetRect.height / 2 - panel.height / 2
}
}
export function getContextualTourPanelCssPosition(args: {
position: ContextualTourPanelPosition
panelHostRect?: Pick<DOMRect, 'left' | 'top'> | null
}): Pick<ContextualTourPanelPosition, 'left' | 'top' | 'arrowOffset'> {
const { position, panelHostRect } = args
const left = panelHostRect ? position.left - panelHostRect.left : position.left
const top = panelHostRect ? position.top - panelHostRect.top : position.top
return { left, top, arrowOffset: position.arrowOffset }
}
function clampNumber(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max)
}
@@ -0,0 +1,111 @@
import { describe, expect, it, vi } from 'vitest'
import { performContextualTourStepAction } from './contextual-tour-step-actions'
describe('performContextualTourStepAction', () => {
it('opens Tasks after detaching the terminal-owned tour source', () => {
const finishTour = vi.fn()
const advanceContextualTour = vi.fn()
const detachContextualTourSource = vi.fn()
const openTaskPage = vi.fn()
performContextualTourStepAction({
action: { kind: 'open-tasks', label: 'Show tasks' },
activeTabId: 'tab-1',
isLastStep: false,
finishTour,
advanceContextualTour,
detachContextualTourSource,
setSidebarOpen: vi.fn(),
openTaskPage,
openModal: vi.fn(),
canCreateWorkspace: true,
openWorkspaceComposer: vi.fn(),
dispatchTerminalPaneSplit: vi.fn(),
schedule: vi.fn()
})
expect(detachContextualTourSource).toHaveBeenCalledTimes(1)
expect(openTaskPage).toHaveBeenCalledTimes(1)
expect(advanceContextualTour).toHaveBeenCalledTimes(1)
expect(finishTour).not.toHaveBeenCalled()
})
it('dispatches the terminal-pane split action against the active tab', () => {
const dispatchTerminalPaneSplit = vi.fn()
performContextualTourStepAction({
action: { kind: 'split-terminal-pane', label: 'Split terminal' },
activeTabId: 'tab-1',
isLastStep: false,
finishTour: vi.fn(),
advanceContextualTour: vi.fn(),
detachContextualTourSource: vi.fn(),
setSidebarOpen: vi.fn(),
openTaskPage: vi.fn(),
openModal: vi.fn(),
canCreateWorkspace: true,
openWorkspaceComposer: vi.fn(),
dispatchTerminalPaneSplit,
schedule: vi.fn()
})
expect(dispatchTerminalPaneSplit).toHaveBeenCalledWith({
tabId: 'tab-1',
direction: 'vertical'
})
})
it('opens the workspace composer after detaching, without advancing the tour itself', () => {
const detachContextualTourSource = vi.fn()
const openWorkspaceComposer = vi.fn()
const advanceContextualTour = vi.fn()
const finishTour = vi.fn()
performContextualTourStepAction({
action: { kind: 'create-worktree', label: 'Create worktree' },
activeTabId: 'tab-1',
isLastStep: true,
finishTour,
advanceContextualTour,
detachContextualTourSource,
setSidebarOpen: vi.fn(),
openTaskPage: vi.fn(),
openModal: vi.fn(),
canCreateWorkspace: true,
openWorkspaceComposer,
dispatchTerminalPaneSplit: vi.fn(),
schedule: vi.fn()
})
// Opening the composer cancels this tour and hands off, so we neither
// advance nor finish it here.
expect(detachContextualTourSource).toHaveBeenCalledTimes(1)
expect(openWorkspaceComposer).toHaveBeenCalledTimes(1)
expect(advanceContextualTour).not.toHaveBeenCalled()
expect(finishTour).not.toHaveBeenCalled()
})
it('does not open the workspace composer when workspace creation is unavailable', () => {
const detachContextualTourSource = vi.fn()
const openWorkspaceComposer = vi.fn()
performContextualTourStepAction({
action: { kind: 'create-worktree', label: 'Create worktree' },
activeTabId: 'tab-1',
isLastStep: true,
finishTour: vi.fn(),
advanceContextualTour: vi.fn(),
detachContextualTourSource,
setSidebarOpen: vi.fn(),
openTaskPage: vi.fn(),
openModal: vi.fn(),
canCreateWorkspace: false,
openWorkspaceComposer,
dispatchTerminalPaneSplit: vi.fn(),
schedule: vi.fn()
})
expect(detachContextualTourSource).not.toHaveBeenCalled()
expect(openWorkspaceComposer).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,66 @@
import type { ContextualTourStepAction } from '../../../../shared/contextual-tours'
import type { RequestActiveTerminalPaneSplitDetail } from '@/constants/terminal'
export function performContextualTourStepAction(args: {
action: ContextualTourStepAction
activeTabId: string | null
isLastStep: boolean
finishTour: () => void
advanceContextualTour: () => void
detachContextualTourSource: () => void
setSidebarOpen: (open: boolean) => void
openTaskPage: () => void
openModal: (modal: 'setup-guide') => void
canCreateWorkspace: boolean
openWorkspaceComposer: () => void
dispatchTerminalPaneSplit: (detail: RequestActiveTerminalPaneSplitDetail) => void
schedule: (callback: () => void) => void
}): void {
const advanceOrFinish = (): void => {
if (args.isLastStep) {
args.finishTour()
} else {
args.advanceContextualTour()
}
}
switch (args.action.kind) {
case 'next':
advanceOrFinish()
return
case 'complete':
args.finishTour()
return
case 'split-terminal-pane':
if (args.activeTabId) {
args.dispatchTerminalPaneSplit({ tabId: args.activeTabId, direction: 'vertical' })
}
return
case 'create-worktree':
if (args.canCreateWorkspace) {
// Why: opening the composer cancels this tour (it isn't allowed over the
// modal) and hands off to the workspace-creation tour. Detach first so the
// terminal source's unmount cleanup can't record a stray suppression.
args.detachContextualTourSource()
args.setSidebarOpen(true)
args.openWorkspaceComposer()
}
return
case 'show-worktrees':
args.setSidebarOpen(true)
advanceOrFinish()
return
case 'open-tasks':
// Why: the auto tour starts from the terminal, but this CTA intentionally
// navigates to Tasks before the final setup-guide step.
args.detachContextualTourSource()
args.openTaskPage()
advanceOrFinish()
return
case 'open-getting-started':
args.finishTour()
args.schedule(() => {
args.openModal('setup-guide')
})
}
}
@@ -0,0 +1,162 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
import { requestContextualTourWhenReady } from './request-contextual-tour-when-ready'
describe('requestContextualTourWhenReady', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
})
it('retries a forced tour request until the target starts', () => {
vi.useFakeTimers()
let activeContextualTourId: string | null = null
const requestContextualTour = vi.fn(() => {
if (requestContextualTour.mock.calls.length === 3) {
activeContextualTourId = 'workspace-agent-sessions'
}
})
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId,
requestContextualTour
}) as unknown as ReturnType<typeof useAppStore.getState>
)
requestContextualTourWhenReady({
id: 'workspace-agent-sessions',
source: 'setup_guide_parallel_work',
retryDelayMs: 10,
maxAttempts: 5
})
vi.advanceTimersByTime(0)
vi.advanceTimersByTime(10)
vi.advanceTimersByTime(10)
vi.advanceTimersByTime(20)
expect(requestContextualTour).toHaveBeenCalledTimes(3)
expect(requestContextualTour).toHaveBeenLastCalledWith(
'workspace-agent-sessions',
'setup_guide_parallel_work',
undefined,
{ force: true }
)
})
it('stops when another tour becomes active before the target starts', () => {
vi.useFakeTimers()
let activeContextualTourId: string | null = null
const requestContextualTour = vi.fn(() => {
activeContextualTourId = 'tasks'
})
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId,
requestContextualTour
}) as unknown as ReturnType<typeof useAppStore.getState>
)
requestContextualTourWhenReady({
id: 'workspace-agent-sessions',
source: 'setup_guide_parallel_work',
retryDelayMs: 10,
maxAttempts: 5
})
vi.advanceTimersByTime(0)
vi.advanceTimersByTime(50)
expect(requestContextualTour).toHaveBeenCalledTimes(1)
})
it('can wait for another tour to clear before requesting the target tour', () => {
vi.useFakeTimers()
let activeContextualTourId: string | null = 'workspace-agent-sessions'
const requestContextualTour = vi.fn(() => {
activeContextualTourId = 'workspace-creation'
})
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId,
requestContextualTour
}) as unknown as ReturnType<typeof useAppStore.getState>
)
requestContextualTourWhenReady({
id: 'workspace-creation',
source: 'workspace_creation_modal',
retryDelayMs: 10,
maxAttempts: 5,
waitForActiveTourToClear: true
})
vi.advanceTimersByTime(0)
expect(requestContextualTour).not.toHaveBeenCalled()
activeContextualTourId = null
vi.advanceTimersByTime(10)
expect(requestContextualTour).toHaveBeenCalledTimes(1)
expect(requestContextualTour).toHaveBeenLastCalledWith(
'workspace-creation',
'workspace_creation_modal',
undefined,
{ force: true }
)
})
it('cancels pending retries when the caller unmounts or starts another action', () => {
vi.useFakeTimers()
const requestContextualTour = vi.fn()
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId: null,
requestContextualTour
}) as unknown as ReturnType<typeof useAppStore.getState>
)
const cancel = requestContextualTourWhenReady({
id: 'workspace-agent-sessions',
source: 'setup_guide_parallel_work',
retryDelayMs: 10,
maxAttempts: 5
})
vi.advanceTimersByTime(0)
cancel()
vi.advanceTimersByTime(50)
expect(requestContextualTour).toHaveBeenCalledTimes(1)
})
it('stops before requesting when the destination surface is no longer current', () => {
vi.useFakeTimers()
const requestContextualTour = vi.fn()
const shouldContinue = vi.fn(() => false)
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId: null,
requestContextualTour
}) as unknown as ReturnType<typeof useAppStore.getState>
)
requestContextualTourWhenReady({
id: 'workspace-creation',
source: 'setup_guide_parallel_work',
shouldContinue,
retryDelayMs: 10,
maxAttempts: 5
})
vi.advanceTimersByTime(50)
expect(shouldContinue).toHaveBeenCalledTimes(1)
expect(requestContextualTour).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,64 @@
import type { ContextualTourId } from '../../../../shared/contextual-tours'
import { useAppStore } from '@/store'
type RequestContextualTourWhenReadyArgs = {
id: ContextualTourId
source: string
wasFeaturePreviouslyInteracted?: boolean
maxAttempts?: number
retryDelayMs?: number
waitForActiveTourToClear?: boolean
shouldContinue?: () => boolean
}
export type { RequestContextualTourWhenReadyArgs }
export function requestContextualTourWhenReady(
args: RequestContextualTourWhenReadyArgs
): () => void {
const maxAttempts = args.maxAttempts ?? 20
const retryDelayMs = args.retryDelayMs ?? 100
let attempts = 0
let timeoutId: ReturnType<typeof setTimeout> | null = null
let cancelled = false
const attempt = (): void => {
if (cancelled) {
return
}
if (args.shouldContinue && !args.shouldContinue()) {
cancelled = true
return
}
attempts += 1
const before = useAppStore.getState()
if (before.activeContextualTourId && before.activeContextualTourId !== args.id) {
if (args.waitForActiveTourToClear && attempts < maxAttempts) {
timeoutId = setTimeout(attempt, retryDelayMs)
}
return
}
before.requestContextualTour(args.id, args.source, args.wasFeaturePreviouslyInteracted, {
force: true
})
const after = useAppStore.getState()
if (after.activeContextualTourId === args.id || attempts >= maxAttempts) {
return
}
timeoutId = setTimeout(attempt, retryDelayMs)
}
// Why: setup-guide actions often reveal lazy surfaces first; retrying keeps
// explicit user-triggered education from depending on renderer mount timing.
timeoutId = setTimeout(attempt, 0)
return () => {
cancelled = true
if (timeoutId !== null) {
clearTimeout(timeoutId)
}
}
}
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { shouldRequestContextualTourAfterInteraction } from './use-contextual-tour'
import type { ContextualTourId } from '../../../../shared/contextual-tours'
describe('shouldRequestContextualTourAfterInteraction', () => {
it('waits for persisted seen ids before allowing a tour request', async () => {
let resolvePersisted!: () => void
const persisted = new Promise<void>((resolve) => {
resolvePersisted = resolve
})
const seenIds: ContextualTourId[] = []
const requestReady = shouldRequestContextualTourAfterInteraction({
id: 'tasks',
persisted,
isCancelled: () => false,
getContextualToursSeenIds: () => seenIds
})
let settled = false
void requestReady.then(() => {
settled = true
})
await Promise.resolve()
expect(settled).toBe(false)
seenIds.push('tasks')
resolvePersisted()
await expect(requestReady).resolves.toBe(false)
})
it('allows the request when the tour remains unseen after persistence settles', async () => {
await expect(
shouldRequestContextualTourAfterInteraction({
id: 'tasks',
persisted: Promise.resolve(),
isCancelled: () => false,
getContextualToursSeenIds: () => []
})
).resolves.toBe(true)
})
})
@@ -0,0 +1,216 @@
import { useEffect, useRef } from 'react'
import type { ContextualTourId } from '../../../../shared/contextual-tours'
import { hasFeatureInteraction } from '../../../../shared/feature-interactions'
import { useAppStore } from '@/store'
const TOUR_SOURCES = {
'workspace-board': 'workspace_board_visible',
'workspace-agent-sessions': 'workspace_agent_sessions_visible',
browser: 'browser_visible',
tasks: 'tasks_open',
automations: 'automations_open',
'workspace-creation': 'workspace_creation_visible'
} satisfies Record<ContextualTourId, string>
export async function shouldRequestContextualTourAfterInteraction(args: {
id: ContextualTourId
persisted: Promise<void>
isCancelled: () => boolean
getContextualToursSeenIds: () => ContextualTourId[]
}): Promise<boolean> {
await args.persisted
return !args.isCancelled() && !args.getContextualToursSeenIds().includes(args.id)
}
export function useContextualTour(
id: ContextualTourId,
enabled: boolean,
source: string = TOUR_SOURCES[id]
): void {
const requestContextualTour = useAppStore((s) => s.requestContextualTour)
const suppressContextualTour = useAppStore((s) => s.suppressContextualTour)
const recordFeatureInteraction = useAppStore((s) => s.recordFeatureInteraction)
const persistedUIReady = useAppStore((s) => s.persistedUIReady)
const activeModal = useAppStore((s) => s.activeModal)
const activeContextualTourId = useAppStore((s) => s.activeContextualTourId)
const activeContextualTourSource = useAppStore((s) => s.activeContextualTourSource)
const activeContextualTourSourceDetached = useAppStore(
(s) => s.activeContextualTourSourceDetached
)
const contextualToursSeenIds = useAppStore((s) => s.contextualToursSeenIds)
const contextualToursAutoEligible = useAppStore((s) => s.contextualToursAutoEligible)
const contextualTourShownThisSession = useAppStore((s) => s.contextualTourShownThisSession)
const contextualToursOnboardingVisible = useAppStore((s) => s.contextualToursOnboardingVisible)
const contextualToursBlockingSurfaceVisible = useAppStore(
(s) => s.contextualToursBlockingSurfaceVisible
)
const enabledInteractionSnapshotRef = useRef<{
id: ContextualTourId
source: string
wasPreviouslyInteracted: boolean
persisted: Promise<void>
} | null>(null)
useEffect(() => {
if (!enabled || !persistedUIReady) {
enabledInteractionSnapshotRef.current = null
return
}
if (
enabledInteractionSnapshotRef.current?.id === id &&
enabledInteractionSnapshotRef.current.source === source
) {
return
}
const wasPreviouslyInteracted = hasFeatureInteraction(
useAppStore.getState().featureInteractions,
id
)
enabledInteractionSnapshotRef.current = {
id,
source,
// Why: recording writes featureInteractions; subscribing here would retrigger
// this effect and repeatedly persist the same enabled source.
wasPreviouslyInteracted,
persisted: recordFeatureInteraction(id)
}
}, [enabled, id, persistedUIReady, recordFeatureInteraction, source])
useEffect(() => {
// Why: source disable should end through the overlay so a shown tour gets
// a cancellation outcome; the store flag also lets pre-render attempts retry.
if (
!enabled &&
activeContextualTourId === id &&
activeContextualTourSource === source &&
!activeContextualTourSourceDetached
) {
suppressContextualTour(id, source)
}
}, [
activeContextualTourId,
activeContextualTourSource,
activeContextualTourSourceDetached,
enabled,
id,
source,
suppressContextualTour
])
useEffect(() => {
return () => {
const state = useAppStore.getState()
// Why: surfaces like sheets can unmount without rendering an `enabled=false`
// pass, so suppress their active tour during cleanup too.
if (
state.activeContextualTourId === id &&
state.activeContextualTourSource === source &&
!state.activeContextualTourSourceDetached
) {
state.suppressContextualTour(id, source)
}
}
}, [id, source])
useEffect(() => {
if (
!enabled ||
typeof window === 'undefined' ||
typeof document === 'undefined' ||
!persistedUIReady ||
contextualToursAutoEligible !== true ||
contextualToursOnboardingVisible ||
contextualToursBlockingSurfaceVisible ||
activeContextualTourId !== null ||
contextualTourShownThisSession ||
contextualToursSeenIds.includes(id)
) {
return
}
let frame: number | null = null
let attempts = 0
let requestPending = false
let cancelled = false
const request = (): void => {
if (frame !== null || requestPending) {
return
}
requestPending = true
const snapshot = enabledInteractionSnapshotRef.current
const persisted =
snapshot?.id === id && snapshot.source === source ? snapshot.persisted : Promise.resolve()
void shouldRequestContextualTourAfterInteraction({
id,
persisted,
isCancelled: () => cancelled,
getContextualToursSeenIds: () => useAppStore.getState().contextualToursSeenIds
}).then((shouldRequest) => {
requestPending = false
if (!shouldRequest) {
return
}
attempts += 1
frame = window.requestAnimationFrame(() => {
frame = null
const latestSnapshot = enabledInteractionSnapshotRef.current
if (useAppStore.getState().contextualToursSeenIds.includes(id)) {
return
}
requestContextualTour(
id,
source,
latestSnapshot?.id === id && latestSnapshot.source === source
? latestSnapshot.wasPreviouslyInteracted
: hasFeatureInteraction(useAppStore.getState().featureInteractions, id)
)
})
})
}
request()
const timeout = window.setTimeout(request, 250)
const observer =
typeof MutationObserver === 'undefined' || !document.body
? null
: new MutationObserver(request)
observer?.observe(document.body, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['aria-hidden', 'class', 'data-contextual-tour-target', 'hidden', 'style']
})
// Why: native prompts and async surface hydration can pause or miss the
// first target measurement; retry briefly without long-lived polling.
const interval = window.setInterval(() => {
if (attempts >= 20) {
window.clearInterval(interval)
return
}
request()
}, 500)
return () => {
cancelled = true
if (frame !== null) {
window.cancelAnimationFrame(frame)
}
window.clearTimeout(timeout)
window.clearInterval(interval)
observer?.disconnect()
}
}, [
activeContextualTourId,
contextualToursBlockingSurfaceVisible,
activeModal,
contextualToursAutoEligible,
contextualTourShownThisSession,
contextualToursOnboardingVisible,
contextualToursSeenIds,
enabled,
id,
persistedUIReady,
requestContextualTour,
source
])
}
@@ -0,0 +1,144 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
import { openWorkspaceCreationComposerWithTourHandoff } from './workspace-creation-tour-handoff'
import { requestContextualTourWhenReady } from './request-contextual-tour-when-ready'
vi.mock('./request-contextual-tour-when-ready', () => ({
requestContextualTourWhenReady: vi.fn()
}))
describe('openWorkspaceCreationComposerWithTourHandoff', () => {
afterEach(() => {
vi.clearAllMocks()
vi.restoreAllMocks()
})
it('opens the workspace composer without a tour handoff outside the agent sessions tour', () => {
const openModal = vi.fn()
const detachContextualTourSource = vi.fn()
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId: null,
activeContextualTourStepIndex: 0,
activeContextualTourSource: null,
activeModal: 'none',
contextualToursSeenIds: [],
repos: [{ id: 'repo-1' }],
detachContextualTourSource,
openModal
}) as unknown as ReturnType<typeof useAppStore.getState>
)
openWorkspaceCreationComposerWithTourHandoff()
expect(openModal).toHaveBeenCalledWith('new-workspace-composer', {
telemetrySource: 'sidebar'
})
expect(detachContextualTourSource).not.toHaveBeenCalled()
expect(requestContextualTourWhenReady).not.toHaveBeenCalled()
})
it('hands off from the agent sessions create-worktree step to the workspace-creation tour', () => {
const openModal = vi.fn()
const detachContextualTourSource = vi.fn()
const completeContextualTour = vi.fn()
let activeModal: ReturnType<typeof useAppStore.getState>['activeModal'] = 'none'
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId: 'workspace-agent-sessions',
activeContextualTourStepIndex: 1,
activeContextualTourSource: 'setup_guide_parallel_work',
activeModal,
contextualToursSeenIds: [],
repos: [{ id: 'repo-1' }],
detachContextualTourSource,
completeContextualTour,
openModal
}) as unknown as ReturnType<typeof useAppStore.getState>
)
openWorkspaceCreationComposerWithTourHandoff()
expect(detachContextualTourSource).toHaveBeenCalledWith(
'workspace-agent-sessions',
'setup_guide_parallel_work'
)
expect(completeContextualTour).toHaveBeenCalledWith('workspace-agent-sessions')
expect(openModal).toHaveBeenCalledWith('new-workspace-composer', {
telemetrySource: 'sidebar',
contextualTourSource: 'workspace_creation_modal'
})
expect(requestContextualTourWhenReady).toHaveBeenCalledWith({
id: 'workspace-creation',
source: 'workspace_creation_modal',
wasFeaturePreviouslyInteracted: false,
waitForActiveTourToClear: true,
shouldContinue: expect.any(Function)
})
const [{ shouldContinue }] = vi.mocked(requestContextualTourWhenReady).mock.calls[0]
activeModal = 'new-workspace-composer'
expect(shouldContinue?.()).toBe(true)
activeModal = 'none'
expect(shouldContinue?.()).toBe(false)
})
it('opens the composer without re-showing workspace creation when that tour was already seen', () => {
const openModal = vi.fn()
const detachContextualTourSource = vi.fn()
const completeContextualTour = vi.fn()
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId: 'workspace-agent-sessions',
activeContextualTourStepIndex: 1,
activeContextualTourSource: 'setup_guide_parallel_work',
activeModal: 'none',
contextualToursSeenIds: ['workspace-creation'],
repos: [{ id: 'repo-1' }],
detachContextualTourSource,
completeContextualTour,
openModal
}) as unknown as ReturnType<typeof useAppStore.getState>
)
openWorkspaceCreationComposerWithTourHandoff()
expect(detachContextualTourSource).toHaveBeenCalledWith(
'workspace-agent-sessions',
'setup_guide_parallel_work'
)
expect(completeContextualTour).toHaveBeenCalledWith('workspace-agent-sessions')
expect(openModal).toHaveBeenCalledWith('new-workspace-composer', {
telemetrySource: 'sidebar',
contextualTourSource: 'workspace_creation_modal'
})
expect(requestContextualTourWhenReady).not.toHaveBeenCalled()
})
it('does not open the composer when no project is available for workspace creation', () => {
const openModal = vi.fn()
const detachContextualTourSource = vi.fn()
vi.spyOn(useAppStore, 'getState').mockImplementation(
() =>
({
activeContextualTourId: 'workspace-agent-sessions',
activeContextualTourStepIndex: 1,
activeContextualTourSource: 'setup_guide_parallel_work',
activeModal: 'none',
contextualToursSeenIds: [],
repos: [],
detachContextualTourSource,
openModal
}) as unknown as ReturnType<typeof useAppStore.getState>
)
openWorkspaceCreationComposerWithTourHandoff()
expect(detachContextualTourSource).not.toHaveBeenCalled()
expect(openModal).not.toHaveBeenCalled()
expect(requestContextualTourWhenReady).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,44 @@
import { useAppStore } from '@/store'
import { requestContextualTourWhenReady } from './request-contextual-tour-when-ready'
export function openWorkspaceCreationComposerWithTourHandoff(): void {
const state = useAppStore.getState()
if (state.repos.length === 0) {
return
}
const shouldHandoffFromAgentSessionsTour =
state.activeContextualTourId === 'workspace-agent-sessions' &&
state.activeContextualTourStepIndex === 1
if (shouldHandoffFromAgentSessionsTour && state.activeContextualTourSource) {
// Why: clicking the highlighted create button is the final tour action.
// Clear it synchronously so the composer tour request is not blocked by
// a modal-cancellation effect that may run after the handoff retry window.
state.detachContextualTourSource('workspace-agent-sessions', state.activeContextualTourSource)
state.completeContextualTour('workspace-agent-sessions')
}
state.openModal('new-workspace-composer', {
telemetrySource: 'sidebar',
...(shouldHandoffFromAgentSessionsTour
? { contextualTourSource: 'workspace_creation_modal' }
: {})
})
if (!shouldHandoffFromAgentSessionsTour) {
return
}
if (state.contextualToursSeenIds.includes('workspace-creation')) {
return
}
requestContextualTourWhenReady({
id: 'workspace-creation',
source: 'workspace_creation_modal',
wasFeaturePreviouslyInteracted: false,
waitForActiveTourToClear: true,
shouldContinue: () => useAppStore.getState().activeModal === 'new-workspace-composer'
})
}
@@ -0,0 +1,201 @@
import { useEffect, useState } from 'react'
import type { JSX, ReactNode } from 'react'
import { FolderGit2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { ClaudeIcon } from '../status-bar/icons'
import { CodexInlineIcon, WorkingSpinner } from './feature-tour-preview-glyphs'
type RepoFocus = 'personal' | 'work' | 'both'
type RepoVisual = {
id: Exclude<RepoFocus, 'both'>
name: string
worktree: string
prompt: string
action: string
agent: 'Claude Code' | 'Codex'
agentIcon: ReactNode
}
const REPOS: readonly RepoVisual[] = [
{
id: 'personal',
name: 'recipe-box',
worktree: 'weekend polish',
prompt: 'refine recipe search',
action: 'Editing search filters',
agent: 'Claude Code',
agentIcon: <ClaudeIcon size={12} />
},
{
id: 'work',
name: 'billing-app',
worktree: 'checkout fix',
prompt: 'fix checkout bug',
action: 'Updating checkout tests',
agent: 'Codex',
agentIcon: <CodexInlineIcon />
}
]
const FOCUS_SEQUENCE: readonly RepoFocus[] = ['personal', 'both', 'work', 'both', 'both']
export function AddReposAnimatedVisual(props: { reducedMotion: boolean }): JSX.Element {
const focus = useRepoFocus(props.reducedMotion)
return (
<div className="grid min-h-[282px] gap-3 rounded-xl border border-border bg-card p-3 text-foreground shadow-xs md:grid-cols-2">
{REPOS.map((repo) => (
<RepoProjectCard
key={repo.id}
repo={repo}
active={focus === repo.id || focus === 'both'}
reducedMotion={props.reducedMotion}
/>
))}
</div>
)
}
function RepoProjectCard(props: {
repo: RepoVisual
active: boolean
reducedMotion: boolean
}): JSX.Element {
return (
<section
className={cn(
'flex min-w-0 flex-col gap-2 rounded-lg border border-sidebar-border bg-sidebar p-2 text-sidebar-foreground transition-[border-color,box-shadow] duration-500',
props.active ? 'shadow-xs' : null
)}
>
<ProjectSidebarRow name={props.repo.name} />
<ProjectWorktreeRow
repo={props.repo}
active={props.active}
reducedMotion={props.reducedMotion}
/>
<div className="min-w-0 overflow-hidden rounded-lg border border-border bg-background text-foreground">
<VisualTitlebar title={`${props.repo.worktree} - ${props.repo.agent}`} />
<div className="space-y-1.5 p-2.5 font-mono text-[11px]">
<TerminalLine>
<Prompt>&gt;</Prompt>
{props.repo.prompt}
</TerminalLine>
<TerminalLine muted>
{props.repo.agentIcon}
{props.repo.agent} session ready
</TerminalLine>
<TerminalLine muted>
<WorkingSpinner size="xs" reducedMotion={props.reducedMotion} />
{props.repo.action}
</TerminalLine>
</div>
</div>
</section>
)
}
function ProjectSidebarRow(props: { name: string }): JSX.Element {
return (
<div
aria-hidden
className="relative flex h-8 min-w-0 items-center gap-1.5 rounded-md px-1.5 text-sidebar-foreground"
>
<span className="flex size-4 shrink-0 items-center justify-center text-muted-foreground">
<FolderGit2 className="size-3.5" />
</span>
<span className="min-w-0 flex-1 truncate text-[13px] font-semibold leading-none">
{props.name}
</span>
<span className="min-w-[3.75rem] rounded-full bg-sidebar-accent px-1.5 py-0.5 text-center text-[9px] font-medium leading-none text-muted-foreground">
1 worktree
</span>
</div>
)
}
function ProjectWorktreeRow(props: {
repo: RepoVisual
active: boolean
reducedMotion: boolean
}): JSX.Element {
return (
<div
className={cn(
'rounded-md border border-sidebar-border px-2.5 py-2 transition-colors',
props.active ? 'bg-sidebar-accent' : 'bg-sidebar'
)}
>
<div className="flex items-center gap-2">
<span
className={cn(
'size-1.5 shrink-0 rounded-full',
props.active ? 'bg-emerald-500' : 'bg-muted-foreground/35'
)}
/>
<span className="truncate text-xs font-medium text-sidebar-foreground">
{props.repo.worktree}
</span>
</div>
<div className="mt-2 grid grid-cols-[8px_14px_minmax(0,1fr)] items-center gap-1.5">
<WorkingSpinner size="xs" reducedMotion={props.reducedMotion} />
<span className="flex size-3.5 items-center justify-center text-sidebar-foreground/65">
{props.repo.agentIcon}
</span>
<span className="truncate font-mono text-[11px] text-sidebar-foreground/65">
{props.repo.prompt}
</span>
</div>
</div>
)
}
function VisualTitlebar(props: { title: string }): JSX.Element {
return (
<div className="flex h-6 items-center gap-1.5 border-b border-border bg-muted/40 px-2">
<span className="size-2 rounded-full bg-foreground/15" />
<span className="size-2 rounded-full bg-foreground/15" />
<span className="size-2 rounded-full bg-foreground/15" />
<span className="ml-1 truncate font-mono text-[11px] text-muted-foreground">
{props.title}
</span>
</div>
)
}
function TerminalLine(props: { children: ReactNode; muted?: boolean }): JSX.Element {
return (
<div
className={cn(
'flex min-w-0 items-center gap-1.5 truncate leading-[1.45]',
props.muted ? 'text-muted-foreground' : 'text-foreground'
)}
>
{props.children}
</div>
)
}
function Prompt(props: { children: ReactNode }): JSX.Element {
return <span className="shrink-0 text-primary">{props.children}</span>
}
function useRepoFocus(reducedMotion: boolean): RepoFocus {
const [idx, setIdx] = useState(() => (reducedMotion ? FOCUS_SEQUENCE.indexOf('both') : 0))
useEffect(() => {
if (reducedMotion) {
setIdx(FOCUS_SEQUENCE.indexOf('both'))
return
}
const id = window.setInterval(() => {
setIdx((current) => (current + 1) % FOCUS_SEQUENCE.length)
}, 1700)
return () => window.clearInterval(id)
}, [reducedMotion])
return FOCUS_SEQUENCE[idx] ?? 'both'
}
@@ -0,0 +1,65 @@
import { describe, expect, it } from 'vitest'
import { getDefaultAgentCapabilitySetupSelection } from './agent-capability-setup-status'
const READY_INPUT = {
browserUseSkillInstalled: true,
browserUseSkillLoading: false,
computerUseSkillInstalled: true,
computerUseSkillLoading: false,
computerUseReady: true,
computerUseChecking: false,
computerUseUnavailable: false,
orchestrationSkillInstalled: true,
orchestrationSkillLoading: false
}
describe('getDefaultAgentCapabilitySetupSelection', () => {
it('leaves already-ready capabilities unchecked by default', () => {
expect(getDefaultAgentCapabilitySetupSelection(READY_INPUT)).toEqual({
browserUse: false,
computerUse: false,
orchestration: false
})
})
it('keeps missing skills selected by default', () => {
expect(
getDefaultAgentCapabilitySetupSelection({
...READY_INPUT,
browserUseSkillInstalled: false,
orchestrationSkillInstalled: false
})
).toEqual({
browserUse: true,
computerUse: false,
orchestration: true
})
})
it('keeps Computer Use selected when permissions still need setup', () => {
expect(
getDefaultAgentCapabilitySetupSelection({
...READY_INPUT,
computerUseReady: false
})
).toEqual({
browserUse: false,
computerUse: true,
orchestration: false
})
})
it('leaves Computer Use unchecked when this build cannot enable it', () => {
expect(
getDefaultAgentCapabilitySetupSelection({
...READY_INPUT,
computerUseReady: false,
computerUseUnavailable: true
})
).toEqual({
browserUse: false,
computerUse: false,
orchestration: false
})
})
})
@@ -0,0 +1,388 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { Check, Globe2, Loader2, MonitorCog, Terminal, Workflow } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useAppStore } from '@/store'
import { FeatureSetupInlineTerminal } from '../onboarding/FeatureSetupInlineTerminal'
import {
DEFAULT_ONBOARDING_FEATURE_SETUP_SELECTION,
hasSelectedOnboardingFeatureSetup,
runOnboardingFeatureSetup,
type OnboardingFeatureSetupId,
type OnboardingFeatureSetupSelection
} from '../onboarding/onboarding-feature-setup'
import {
getAgentCapabilityStatusClassName,
getDefaultAgentCapabilitySetupSelection,
isAgentCapabilityReadinessChecking,
useAgentCapabilitySetupStatus,
type AgentCapabilityInstallStatus
} from './agent-capability-setup-status'
import { AgentsOrchestrationVisual } from './AgentsOrchestrationVisual'
import { BrowserAnimatedVisual } from './BrowserAnimatedVisual'
import { ComputerUseAnimatedVisual } from './ComputerUseAnimatedVisual'
export function AgentCapabilitiesSetupAction(props: {
reducedMotion: boolean
onOrchestrationSkillInstalledChange: (installed: boolean) => void
onBrowserUseSkillInstalledChange: (installed: boolean) => void
}): React.JSX.Element {
const { reducedMotion, onBrowserUseSkillInstalledChange, onOrchestrationSkillInstalledChange } =
props
const capabilitySetupStatus = useAgentCapabilitySetupStatus()
const { readiness } = capabilitySetupStatus
const featureSetupDefaultsAppliedRef = useRef(false)
const featureSetupChangedByUserRef = useRef(false)
const [featureSetup, setFeatureSetup] = useState<OnboardingFeatureSetupSelection>(
DEFAULT_ONBOARDING_FEATURE_SETUP_SELECTION
)
const [featureSetupCommand, setFeatureSetupCommand] = useState<string | null>(null)
const [featureSetupCommandSelection, setFeatureSetupCommandSelection] =
useState<OnboardingFeatureSetupSelection | null>(null)
const [setupBusyLabel, setSetupBusyLabel] = useState<string | null>(null)
const recordFeatureInteraction = useAppStore((s) => s.recordFeatureInteraction)
useEffect(() => {
onBrowserUseSkillInstalledChange(readiness.browserUseSkillInstalled)
}, [onBrowserUseSkillInstalledChange, readiness.browserUseSkillInstalled])
useEffect(() => {
onOrchestrationSkillInstalledChange(readiness.orchestrationSkillInstalled)
}, [onOrchestrationSkillInstalledChange, readiness.orchestrationSkillInstalled])
useEffect(() => {
if (featureSetupDefaultsAppliedRef.current || featureSetupChangedByUserRef.current) {
return
}
if (isAgentCapabilityReadinessChecking(readiness)) {
return
}
featureSetupDefaultsAppliedRef.current = true
setFeatureSetup(getDefaultAgentCapabilitySetupSelection(readiness))
}, [readiness])
const handleFeatureSetupChange = useCallback((value: OnboardingFeatureSetupSelection): void => {
featureSetupChangedByUserRef.current = true
setFeatureSetup(value)
}, [])
const handleStartFeatureSetup = useCallback(async (): Promise<void> => {
if (setupBusyLabel !== null || featureSetupCommand !== null) {
return
}
setSetupBusyLabel('Setting up capabilities...')
try {
const result = await runOnboardingFeatureSetup(featureSetup)
if (featureSetup.browserUse) {
recordFeatureInteraction('agent-browser-setup')
}
if (featureSetup.computerUse) {
recordFeatureInteraction('computer-use-setup')
}
if (featureSetup.orchestration) {
recordFeatureInteraction('agent-orchestration-setup')
}
const firstWarning = result.warnings[0]
if (firstWarning) {
toast.warning('Some capability setup needs attention', {
description: firstWarning.message
})
}
if (result.skillCommandsCopied) {
toast.success('Capability setup ready', {
description: 'Skill command copied and inserted below for review.'
})
}
if (result.computerUsePermissionsOpened) {
toast.message('Opened Computer Use permissions')
}
if (result.skillInstallCommand) {
setFeatureSetupCommandSelection(featureSetup)
setFeatureSetupCommand(result.skillInstallCommand)
}
} finally {
setSetupBusyLabel(null)
}
}, [featureSetup, featureSetupCommand, recordFeatureInteraction, setupBusyLabel])
return (
<div className="space-y-5">
<AgentCapabilitySetupControls
featureSetup={featureSetup}
onFeatureSetupChange={handleFeatureSetupChange}
featureSetupCommand={featureSetupCommand}
featureSetupCommandSelection={featureSetupCommandSelection}
setupBusyLabel={setupBusyLabel}
onStartFeatureSetup={() => void handleStartFeatureSetup()}
installStatus={capabilitySetupStatus.installStatus}
/>
<AgentCapabilityAnimationCarousel reducedMotion={reducedMotion} />
</div>
)
}
type AgentCapabilitySetupRow = {
id: OnboardingFeatureSetupId
title: string
icon: ReactNode
}
type AgentCapabilitySlide = {
id: string
title: string
icon: ReactNode
widthClassName: string
node: ReactNode
}
const AGENT_CAPABILITY_SETUP_ROWS: readonly AgentCapabilitySetupRow[] = [
{
id: 'orchestration',
title: 'Agent Orchestration',
icon: <Workflow className="size-4" />
},
{
id: 'browserUse',
title: 'Agent Browser Use',
icon: <Globe2 className="size-4" />
},
{
id: 'computerUse',
title: 'Computer Use',
icon: <MonitorCog className="size-4" />
}
]
function AgentCapabilitySetupControls(props: {
featureSetup: OnboardingFeatureSetupSelection
onFeatureSetupChange: (value: OnboardingFeatureSetupSelection) => void
featureSetupCommand: string | null
featureSetupCommandSelection: OnboardingFeatureSetupSelection | null
setupBusyLabel: string | null
onStartFeatureSetup: () => void
installStatus: Record<OnboardingFeatureSetupId, AgentCapabilityInstallStatus>
}): React.JSX.Element {
const hasSelectedFeatures = hasSelectedOnboardingFeatureSetup(props.featureSetup)
const showSetupAction = !props.featureSetupCommand
return (
<>
<AgentCapabilitySetupChecklist
value={props.featureSetup}
onChange={props.onFeatureSetupChange}
installStatus={props.installStatus}
/>
{showSetupAction ? (
<div className="mt-4 flex items-center">
<Button
type="button"
variant="default"
className="shrink-0"
disabled={!hasSelectedFeatures || Boolean(props.setupBusyLabel)}
onClick={props.onStartFeatureSetup}
>
{props.setupBusyLabel ? (
<Loader2 className="size-4 animate-spin" />
) : (
<Terminal className="size-4" />
)}
{props.setupBusyLabel ?? 'Install CLI & Skills'}
</Button>
</div>
) : null}
{props.featureSetupCommand ? (
<FeatureSetupInlineTerminal
command={props.featureSetupCommand}
selection={props.featureSetupCommandSelection ?? props.featureSetup}
/>
) : null}
</>
)
}
function AgentCapabilitySetupChecklist(props: {
value: OnboardingFeatureSetupSelection
onChange: (value: OnboardingFeatureSetupSelection) => void
installStatus: Record<OnboardingFeatureSetupId, AgentCapabilityInstallStatus>
}): React.JSX.Element {
return (
<section className="mt-6">
<div className="grid gap-3 md:grid-cols-3">
{AGENT_CAPABILITY_SETUP_ROWS.map((row) => {
const selected = props.value[row.id]
const installStatus = props.installStatus[row.id]
return (
<button
key={row.id}
type="button"
role="checkbox"
aria-checked={selected}
aria-label={`${selected ? 'Disable' : 'Enable'} ${row.title}`}
className={cn(
'flex min-h-24 flex-col rounded-lg border px-4 py-3 text-left transition-colors',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
selected
? 'border-ring bg-accent text-foreground ring-2 ring-ring/25'
: 'border-border bg-muted/20 text-muted-foreground hover:bg-muted/40'
)}
onClick={() => props.onChange({ ...props.value, [row.id]: !selected })}
>
<span className="flex items-start justify-between gap-3">
<span
className={cn(
'flex size-8 items-center justify-center rounded-lg border',
selected
? 'border-border bg-background text-foreground'
: 'border-border bg-muted/40'
)}
>
{row.icon}
</span>
<span
aria-hidden
className={cn(
'flex size-5 items-center justify-center rounded-full border transition-colors',
selected
? 'border-primary bg-primary text-primary-foreground'
: 'border-border bg-background'
)}
>
{selected ? <Check className="size-3" strokeWidth={3} /> : null}
</span>
</span>
<span className="mt-3 text-sm font-medium text-foreground">{row.title}</span>
<AgentCapabilityStatusNote status={installStatus} />
</button>
)
})}
</div>
</section>
)
}
function AgentCapabilityStatusNote(props: {
status: AgentCapabilityInstallStatus
}): React.JSX.Element {
if (props.status.installed) {
return (
<span className="mt-2 flex flex-wrap items-center gap-1.5">
<span className="rounded-full border border-green-500/45 bg-green-500/10 px-2 py-0.5 text-[11px] font-semibold leading-none text-green-700 dark:text-green-300">
Installed
</span>
{props.status.label !== 'Installed' ? (
<span
className={cn(
'text-xs font-medium',
getAgentCapabilityStatusClassName(props.status.tone)
)}
>
{props.status.label}
</span>
) : null}
</span>
)
}
return (
<span
className={cn(
'mt-1 text-xs font-medium',
getAgentCapabilityStatusClassName(props.status.tone)
)}
>
{props.status.label}
</span>
)
}
const AGENT_CAPABILITY_SLIDE_COUNT = 3
function AgentCapabilityAnimationCarousel(props: { reducedMotion: boolean }): React.JSX.Element {
const [activeIndex, setActiveIndex] = useState(() => (props.reducedMotion ? 1 : 0))
const advanceSlide = useCallback(() => {
if (props.reducedMotion) {
return
}
setActiveIndex((current) => (current + 1) % AGENT_CAPABILITY_SLIDE_COUNT)
}, [props.reducedMotion])
const slides = useMemo<readonly AgentCapabilitySlide[]>(
() => [
{
id: 'browser-use',
title: 'Browser use',
icon: <Globe2 className="size-3.5" />,
widthClassName: 'w-[460px]',
node: (
<BrowserAnimatedVisual
reducedMotion={props.reducedMotion}
onCycleComplete={advanceSlide}
/>
)
},
{
id: 'computer-use',
title: 'Computer Use',
icon: <MonitorCog className="size-3.5" />,
widthClassName: 'w-[520px]',
node: (
<ComputerUseAnimatedVisual
reducedMotion={props.reducedMotion}
onCycleComplete={advanceSlide}
/>
)
},
{
id: 'orchestration',
title: 'Agent orchestration',
icon: <Workflow className="size-3.5" />,
widthClassName: 'w-[520px]',
node: (
<AgentsOrchestrationVisual
reducedMotion={props.reducedMotion}
activeStepId="orchestration"
widthPx={400}
heightPx={300}
onCycleComplete={advanceSlide}
/>
)
}
],
[advanceSlide, props.reducedMotion]
)
useEffect(() => {
if (props.reducedMotion) {
setActiveIndex(1)
}
}, [props.reducedMotion])
const activeSlide = slides[activeIndex] ?? slides[0]
return (
<div className="rounded-xl border border-border bg-muted/20 p-3">
<div className="mb-3 flex items-center justify-between gap-3">
<div className="text-xs font-semibold leading-none text-muted-foreground">Preview</div>
<div className="flex items-center gap-1">
{slides.map((slide, index) => (
<button
key={slide.id}
type="button"
aria-label={`Show ${slide.title}`}
aria-pressed={index === activeIndex}
className={cn(
'inline-flex h-7 items-center gap-1.5 rounded-md border px-2 text-[11px] font-medium transition-colors',
index === activeIndex
? 'border-border bg-card text-foreground shadow-xs'
: 'border-transparent text-muted-foreground hover:bg-muted/50 hover:text-foreground'
)}
onClick={() => setActiveIndex(index)}
>
{slide.icon}
<span className="max-w-28 truncate">{slide.title}</span>
</button>
))}
</div>
</div>
<div className="mx-auto flex min-h-[300px] max-w-[560px] items-start justify-center overflow-visible">
<div className={cn('max-w-full', activeSlide.widthClassName)}>{activeSlide.node}</div>
</div>
</div>
)
}
@@ -13,6 +13,7 @@ export function AgentsOrchestrationVisual(props: {
activeStepId: AgentsStepId
widthPx?: number
heightPx?: number
onCycleComplete?: () => void
orchestrationCreatedChildCount?: number
orchestrationLoopMs?: number
orchestrationShowResponseBeats?: boolean
@@ -22,6 +23,7 @@ export function AgentsOrchestrationVisual(props: {
activeStepId,
widthPx,
heightPx,
onCycleComplete,
orchestrationCreatedChildCount,
orchestrationLoopMs,
orchestrationShowResponseBeats
@@ -41,6 +43,7 @@ export function AgentsOrchestrationVisual(props: {
<OrchestrationPage
active={activeStepId === 'orchestration'}
reducedMotion={reducedMotion}
onCycleComplete={onCycleComplete}
controlledCreatedChildCount={orchestrationCreatedChildCount}
loopMs={orchestrationLoopMs}
showResponseBeats={orchestrationShowResponseBeats}
@@ -151,8 +151,11 @@ const TERM_ENTRIES: readonly { entry: TermEntry; minPhase: Phase }[] = [
}
]
export function BrowserAnimatedVisual(props: { reducedMotion: boolean }): JSX.Element {
const { reducedMotion } = props
export function BrowserAnimatedVisual(props: {
reducedMotion: boolean
onCycleComplete?: () => void
}): JSX.Element {
const { reducedMotion, onCycleComplete } = props
const newBrowserShortcutLabel = useShortcutLabel('tab.newBrowser')
const [phase, setPhase] = useState<Phase>('idle')
@@ -413,6 +416,7 @@ export function BrowserAnimatedVisual(props: { reducedMotion: boolean }): JSX.El
if (cancelled) {
return
}
onCycleComplete?.()
await wait(RESET_HOLD_MS)
}
@@ -423,7 +427,7 @@ export function BrowserAnimatedVisual(props: { reducedMotion: boolean }): JSX.El
cancelled = true
timeouts.forEach((id) => window.clearTimeout(id))
}
}, [reducedMotion])
}, [onCycleComplete, reducedMotion])
const isIntroPhase =
phase === 'idle' ||
@@ -520,7 +524,7 @@ export function BrowserAnimatedVisual(props: { reducedMotion: boolean }): JSX.El
'grid items-center gap-2 rounded-md px-2 py-[5px]',
newtabRowActive ? 'bg-foreground/[0.06]' : null
)}
style={{ gridTemplateColumns: '18px 1fr auto' }}
style={{ gridTemplateColumns: '18px 1fr' }}
>
<span className="inline-flex size-[13px] items-center justify-center text-foreground">
<GlobeGlyph />
@@ -7,6 +7,7 @@ import {
import { BROWSER_USE_ENABLED_STORAGE_KEY } from '@/lib/browser-use-setup-state'
import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills'
import { AgentSkillSetupPanel } from '@/components/settings/AgentSkillSetupPanel'
import { useAppStore } from '@/store'
export function BrowserUseSkillSetupCard(props: {
compact?: boolean
@@ -16,6 +17,7 @@ export function BrowserUseSkillSetupCard(props: {
const { compact, terminalHeightPx, skill } = props
const handleBeforeOpenTerminal = async (): Promise<void> => {
useAppStore.getState().recordFeatureInteraction('agent-browser-setup')
await ensureOrcaCliAvailableForAgentSkillTerminal()
localStorage.setItem(BROWSER_USE_ENABLED_STORAGE_KEY, '1')
}
@@ -0,0 +1,328 @@
import { useEffect, useLayoutEffect, useRef, useState, type JSX, type ReactNode } from 'react'
import { GitBranch } from 'lucide-react'
import { cn } from '@/lib/utils'
import { ClaudeIcon } from '../status-bar/icons'
import { FeatureWallClickRing } from './FeatureWallClickRing'
import { CursorIcon } from './feature-tour-preview-glyphs'
type ComputerUsePhase = 'inspect' | 'target' | 'click' | 'verified'
const PHASES: readonly ComputerUsePhase[] = ['inspect', 'target', 'click', 'verified', 'verified']
const PHASE_MS = 1350
// Why: the visual must read as "an agent in an Orca worktree drives the
// local app via the `orca computer` CLI" — each command on the left causes
// the visible effect on the right, in lockstep.
const WORKTREE_LABEL = 'checkout fix'
export function ComputerUseAnimatedVisual(props: {
reducedMotion: boolean
onCycleComplete?: () => void
}): JSX.Element {
const phase = useComputerUsePhase(props.reducedMotion, props.onCycleComplete)
const containerRef = useRef<HTMLDivElement>(null)
const buttonRef = useRef<HTMLDivElement>(null)
const [cursorCoords, setCursorCoords] = useState({ x: 0, y: 0, visible: false })
const targetVisible = phase === 'target' || phase === 'click' || phase === 'verified'
const clicked = phase === 'click' || phase === 'verified'
const verified = phase === 'verified'
// Why: cursor coordinates are computed against the app body so they survive
// any reflow when the carousel sizes the slide.
useLayoutEffect(() => {
if (props.reducedMotion) {
setCursorCoords({ x: 0, y: 0, visible: false })
return
}
function updateCoords(): void {
const container = containerRef.current
const button = buttonRef.current
if (!container || !button) {
return
}
const containerRect = container.getBoundingClientRect()
const buttonRect = button.getBoundingClientRect()
const buttonX = buttonRect.left - containerRect.left + buttonRect.width * 0.78
const buttonY = buttonRect.top - containerRect.top + buttonRect.height / 2
const startX = containerRect.width * 0.35
const startY = containerRect.height * 0.35
if (phase === 'inspect' || phase === 'verified') {
setCursorCoords({ x: startX, y: startY, visible: false })
} else {
setCursorCoords({ x: buttonX, y: buttonY, visible: true })
}
}
updateCoords()
window.addEventListener('resize', updateCoords)
return () => window.removeEventListener('resize', updateCoords)
}, [phase, props.reducedMotion])
return (
<div className="relative grid min-h-[282px] gap-3 rounded-xl border border-border bg-card p-3 text-foreground shadow-xs md:h-[282px] md:grid-cols-[230px_minmax(0,1fr)]">
<AgentWorktreeTerminal
phase={phase}
targetVisible={targetVisible}
clicked={clicked}
verified={verified}
/>
<div className="relative min-w-0 overflow-hidden rounded-lg border border-border bg-background">
<div className="flex h-7 items-center gap-1.5 border-b border-border bg-muted/40 px-2.5">
<span className="size-2 rounded-full bg-rose-400/70" />
<span className="size-2 rounded-full bg-amber-400/70" />
<span className="size-2 rounded-full bg-emerald-400/70" />
<span className="ml-1 truncate text-[11px] font-medium text-muted-foreground">
Local app
</span>
</div>
<div className="grid h-[253px] grid-rows-[58px_minmax(0,1fr)] bg-muted/10">
<div className="border-b border-border bg-card px-4 py-2.5">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0 flex-1 overflow-hidden">
<div className="h-2.5 w-24 max-w-full rounded-full bg-foreground/20" />
<div className="mt-2 h-2 w-36 max-w-full rounded-full bg-muted-foreground/25" />
</div>
<span
className={cn(
'shrink-0 rounded-full border px-2 py-1 text-[11px] font-medium transition-colors',
verified
? 'border-primary/30 bg-primary/10 text-primary'
: 'border-border bg-muted/40 text-muted-foreground'
)}
>
{verified ? 'Approved' : 'Pending'}
</span>
</div>
</div>
<div ref={containerRef} className="relative p-3">
<div className="space-y-2">
<AppRow width="78%" />
<div
className={cn(
'flex items-center gap-2 rounded-lg border bg-card px-3 py-2.5 transition-[background-color,border-color,box-shadow]',
targetVisible
? 'border-ring bg-accent/50 ring-2 ring-ring/30 shadow-xs'
: 'border-border'
)}
>
<div className="min-w-0 flex-1 overflow-hidden pr-1">
<div className="h-2.5 w-1/2 max-w-16 rounded-full bg-foreground/20" />
<div className="mt-2 h-2 w-3/5 max-w-20 rounded-full bg-muted-foreground/25" />
</div>
<div
ref={buttonRef}
aria-hidden
className={cn(
'flex h-8 w-[72px] shrink-0 items-center justify-center rounded-md border px-2 text-xs font-medium transition-[background-color,color,transform]',
clicked
? 'border-primary/30 bg-primary/10 text-primary'
: 'border-border bg-secondary text-secondary-foreground',
phase === 'click' ? 'scale-[0.97]' : null
)}
>
{clicked ? 'Done' : 'Approve'}
</div>
</div>
</div>
<ComputerUseCursor
visible={cursorCoords.visible}
x={cursorCoords.x}
y={cursorCoords.y}
isClick={phase === 'click'}
/>
</div>
</div>
</div>
</div>
)
}
function AgentWorktreeTerminal(props: {
phase: ComputerUsePhase
targetVisible: boolean
clicked: boolean
verified: boolean
}): JSX.Element {
return (
<div className="min-w-0 overflow-hidden rounded-lg border border-border bg-background">
<div className="flex h-7 items-center gap-1.5 border-b border-border bg-muted/40 px-2.5">
<ClaudeIcon size={13} />
<span className="truncate text-[11px] font-medium text-muted-foreground">Claude Code</span>
<span className="ml-auto inline-flex min-w-0 items-center gap-1 text-[10px] text-muted-foreground">
<GitBranch className="size-3" />
<span className="truncate">{WORKTREE_LABEL}</span>
</span>
</div>
<div className="space-y-1.5 p-3 font-mono text-[10.5px] leading-snug">
<TerminalLine muted>
<span className="mr-1.5 text-foreground">●</span>
Claude Code session started
</TerminalLine>
<TerminalLine wrap>
<span className="mr-1.5 text-amber-600">&gt;</span>
approve the note in my app
</TerminalLine>
<ComputerActionLine
action="Computer"
target="inspect Notes"
active={props.phase === 'inspect'}
done={props.targetVisible}
/>
<TerminalLine visible={props.targetVisible} indent muted>
found &ldquo;Approve&rdquo; <span>[#7]</span>
</TerminalLine>
<ComputerActionLine
action="Computer"
target="click Approve"
active={props.phase === 'target' || props.phase === 'click'}
done={props.clicked}
/>
<TerminalLine visible={props.clicked} indent muted>
click sent
</TerminalLine>
<ComputerActionLine
action="Computer"
target="verify Notes"
active={props.phase === 'click'}
done={props.verified}
/>
<TerminalLine visible={props.verified} indent muted>
status: <span className="text-foreground">approved</span>
</TerminalLine>
</div>
</div>
)
}
function ComputerActionLine(props: {
action: string
target: string
active: boolean
done: boolean
}): JSX.Element {
return (
<TerminalLine visible={props.active || props.done}>
{props.done ? <span className="mr-1.5 font-bold text-emerald-600">✓</span> : <RunSpinner />}
<span className="text-foreground">{props.action}</span>
<span className="ml-1.5 truncate text-muted-foreground">{props.target}</span>
</TerminalLine>
)
}
function TerminalLine(props: {
children: ReactNode
muted?: boolean
wrap?: boolean
indent?: boolean
visible?: boolean
}): JSX.Element {
const visible = props.visible ?? true
return (
<div
className={cn(
'min-h-[15px] transition-opacity duration-200',
props.muted ? 'text-muted-foreground' : null,
props.indent ? 'pl-4' : null,
props.wrap ? 'whitespace-pre-wrap break-words' : 'truncate whitespace-pre',
visible ? 'opacity-100' : 'opacity-0'
)}
>
{props.children}
</div>
)
}
function RunSpinner(): JSX.Element {
return (
<span
className="mr-1.5 inline-block size-2 animate-spin rounded-full border-[1.5px] border-foreground/20 border-t-foreground align-[-1px]"
aria-hidden
/>
)
}
function useComputerUsePhase(
reducedMotion: boolean,
onCycleComplete?: () => void
): ComputerUsePhase {
const [idx, setIdx] = useState(() => (reducedMotion ? PHASES.indexOf('verified') : 0))
useEffect(() => {
if (reducedMotion) {
setIdx(PHASES.indexOf('verified'))
return
}
let cancelled = false
const timeouts: number[] = []
const wait = (ms: number): Promise<void> =>
new Promise((resolve) => {
const id = window.setTimeout(() => resolve(), ms)
timeouts.push(id)
})
setIdx(0)
async function loop(): Promise<void> {
while (!cancelled) {
for (let nextIdx = 0; nextIdx < PHASES.length; nextIdx += 1) {
setIdx(nextIdx)
await wait(PHASE_MS)
if (cancelled) {
return
}
}
onCycleComplete?.()
}
}
loop()
return () => {
cancelled = true
timeouts.forEach((id) => window.clearTimeout(id))
}
}, [onCycleComplete, reducedMotion])
return PHASES[idx] ?? 'verified'
}
function AppRow(props: { width: string }): JSX.Element {
return (
<div className="rounded-lg border border-border bg-card px-3 py-2">
<div className="h-2.5 rounded-full bg-foreground/15" style={{ width: props.width }} />
<div className="mt-2 h-2 w-1/2 rounded-full bg-muted-foreground/20" />
</div>
)
}
function ComputerUseCursor(props: {
visible: boolean
x: number
y: number
isClick: boolean
}): JSX.Element {
return (
<div
aria-hidden
className={cn(
'pointer-events-none absolute left-0 top-0 z-20 size-4 transition-[opacity,transform] duration-700 ease-[cubic-bezier(.45,.05,.2,1)]',
props.visible ? 'opacity-100' : 'opacity-0'
)}
style={{
transform: `translate(${props.x - 4}px, ${props.y - 4}px)`
}}
>
<CursorIcon />
{props.isClick ? <FeatureWallClickRing /> : null}
</div>
)
}
@@ -0,0 +1,274 @@
import { useCallback, useEffect, useMemo } from 'react'
import { ArrowUpRight, Check } from 'lucide-react'
import type {
FeatureWallSetupStep,
FeatureWallSetupStepId
} from '../../../../shared/feature-wall-setup-steps'
import { getFeatureWallSetupStepsForSection } from '../../../../shared/feature-wall-setup-steps'
import { cn } from '@/lib/utils'
import type { FeatureWallSetupProgress } from './feature-wall-setup-progress'
import { usePrefersReducedMotion } from './feature-wall-modal-helpers'
import { TasksAnimatedVisual } from './TasksAnimatedVisual'
import { AgentCapabilitiesSetupAction } from './AgentCapabilitiesSetupAction'
import {
AddReposAction,
SetupScriptAction,
TwoAgentsAction,
WorkspacesAction
} from './FeatureWallSetupWorkflowActions'
import { SetupStepPreview } from './SetupStepPreview'
import { Button } from '@/components/ui/button'
import { GitHubRow, LinearRow } from '../onboarding/IntegrationsStep'
import { AgentStep } from '../onboarding/AgentStep'
import { NotificationStep } from '../onboarding/NotificationStep'
import { useAppStore } from '@/store'
import type { TuiAgent } from '../../../../shared/types'
type FeatureWallSetupChecklistProps = {
activeStep: FeatureWallSetupStep | null
progress: FeatureWallSetupProgress
onSelectStep: (id: FeatureWallSetupStepId) => void
onOrchestrationSkillInstalledChange: (installed: boolean) => void
onBrowserUseSkillInstalledChange: (installed: boolean) => void
}
function SetupStepRow(props: {
step: FeatureWallSetupStep
done: boolean
active: boolean
onSelect: () => void
}): React.JSX.Element {
const { step, done, active, onSelect } = props
return (
<button
type="button"
onClick={onSelect}
aria-current={active ? 'step' : undefined}
className={cn(
'flex w-full items-center gap-3 rounded-md border px-3 py-2.5 text-left transition-colors',
active
? 'border-border bg-accent text-accent-foreground'
: 'border-border bg-card hover:bg-accent'
)}
>
<span
className={cn(
'flex size-5 shrink-0 items-center justify-center rounded-full border',
done
? 'border-green-500/45 bg-green-500/10 text-green-600 dark:text-green-300'
: 'border-border text-muted-foreground'
)}
>
{done ? <Check className="size-3" /> : null}
</span>
<span className="min-w-0">
<span className="block text-[15px] font-medium leading-tight text-foreground">
{step.name}
</span>
</span>
</button>
)
}
function SetupSection(props: {
title: string
steps: readonly FeatureWallSetupStep[]
activeStepId: FeatureWallSetupStepId | null
progress: FeatureWallSetupProgress
onSelectStep: (id: FeatureWallSetupStepId) => void
}): React.JSX.Element {
const doneCount = props.steps.filter((step) => props.progress.stepDone[step.id]).length
return (
<section className="space-y-2">
<div className="flex items-center justify-between gap-3">
<h4 className="text-xs font-semibold uppercase tracking-[0.08em] text-muted-foreground">
{props.title}
</h4>
<span className="font-mono text-xs text-muted-foreground">
{doneCount}/{props.steps.length}
</span>
</div>
<div className="space-y-1.5">
{props.steps.map((step) => (
<SetupStepRow
key={step.id}
step={step}
done={props.progress.stepDone[step.id]}
active={props.activeStepId === step.id}
onSelect={() => props.onSelectStep(step.id)}
/>
))}
</div>
</section>
)
}
function SelectedStepAction(props: FeatureWallSetupChecklistProps): React.JSX.Element | null {
const { activeStep } = props
const reducedMotion = usePrefersReducedMotion()
if (!activeStep) {
return null
}
const activeDone = props.progress.stepDone[activeStep.id]
if (activeStep.id === 'default-agent') {
return <DefaultAgentAction />
}
if (activeStep.id === 'add-two-repos') {
return <AddReposAction reducedMotion={reducedMotion} />
}
if (activeStep.id === 'notifications') {
return <NotificationAction />
}
if (activeStep.id === 'split-terminal') {
return <TwoAgentsAction reducedMotion={reducedMotion} done={activeDone} />
}
if (activeStep.id === 'two-worktrees') {
return <WorkspacesAction reducedMotion={reducedMotion} done={activeDone} />
}
if (activeStep.id === 'task-sources') {
return <TaskSourcesAction reducedMotion={reducedMotion} />
}
if (activeStep.id === 'agent-capabilities') {
return (
<AgentCapabilitiesSetupAction
reducedMotion={reducedMotion}
onOrchestrationSkillInstalledChange={props.onOrchestrationSkillInstalledChange}
onBrowserUseSkillInstalledChange={props.onBrowserUseSkillInstalledChange}
/>
)
}
if (activeStep.id === 'setup-script') {
return <SetupScriptAction reducedMotion={reducedMotion} />
}
return null
}
function DefaultAgentAction(): React.JSX.Element {
const settings = useAppStore((s) => s.settings)
const updateSettings = useAppStore((s) => s.updateSettings)
const refreshDetectedAgents = useAppStore((s) => s.refreshDetectedAgents)
const detectedAgentIds = useAppStore((s) => s.detectedAgentIds)
const isDetectingAgents = useAppStore((s) => s.isDetectingAgents || s.isRefreshingAgents)
const selectedAgent =
settings?.defaultTuiAgent && settings.defaultTuiAgent !== 'blank'
? settings.defaultTuiAgent
: null
const detectedSet = useMemo(() => new Set(detectedAgentIds ?? []), [detectedAgentIds])
const handleSelectAgent = useCallback(
(agent: TuiAgent) => {
void updateSettings({ defaultTuiAgent: agent })
},
[updateSettings]
)
useEffect(() => {
void refreshDetectedAgents()
}, [refreshDetectedAgents])
return (
<div className="rounded-xl border border-border bg-muted/20 p-4">
<AgentStep
selectedAgent={selectedAgent}
onSelect={handleSelectAgent}
detectedSet={detectedSet}
isDetecting={isDetectingAgents}
/>
</div>
)
}
function NotificationAction(): React.JSX.Element {
const settings = useAppStore((s) => s.settings)
const updateSettings = useAppStore((s) => s.updateSettings)
return (
<div className="rounded-xl border border-border bg-muted/20 p-4">
<NotificationStep settings={settings} updateSettings={updateSettings} />
</div>
)
}
function TaskSourcesAction(props: { reducedMotion: boolean }): React.JSX.Element {
const closeModal = useAppStore((s) => s.closeModal)
const openTaskPage = useAppStore((s) => s.openTaskPage)
return (
<div className="space-y-5">
<div className="grid gap-3 xl:grid-cols-2">
<GitHubRow compact />
<LinearRow compact />
</div>
<Button
type="button"
size="sm"
className="w-fit gap-2"
onClick={() => {
closeModal()
openTaskPage()
}}
>
<ArrowUpRight className="size-3.5" />
See tasks
</Button>
<SetupStepPreview className="mx-auto h-[220px] w-full max-w-[480px]">
<TasksAnimatedVisual reducedMotion={props.reducedMotion} />
</SetupStepPreview>
</div>
)
}
export function FeatureWallSetupChecklist(
props: FeatureWallSetupChecklistProps
): React.JSX.Element {
const { activeStep, progress, onSelectStep } = props
const activeDone = activeStep ? progress.stepDone[activeStep.id] : false
const parallelWorkSteps = getFeatureWallSetupStepsForSection('parallel-work')
const setupSteps = getFeatureWallSetupStepsForSection('setup')
return (
<div className="grid gap-5 lg:grid-cols-[minmax(280px,360px)_minmax(0,1fr)]">
<div className="space-y-5">
<SetupSection
title="Start here"
steps={parallelWorkSteps}
activeStepId={activeStep?.id ?? null}
progress={progress}
onSelectStep={onSelectStep}
/>
<SetupSection
title="Setup"
steps={setupSteps}
activeStepId={activeStep?.id ?? null}
progress={progress}
onSelectStep={onSelectStep}
/>
</div>
<section className="min-h-[420px] rounded-xl border border-border bg-card p-5">
{activeStep ? (
<div className="flex h-full flex-col gap-4">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 space-y-1">
<div className="text-2xl font-semibold leading-tight tracking-tight text-foreground">
{activeStep.name}
</div>
<p className="max-w-[58ch] text-base leading-normal text-muted-foreground">
{activeStep.description}
</p>
</div>
<span
className={cn(
'shrink-0 rounded-full border px-2.5 py-1 text-xs font-medium',
activeDone
? 'border-green-500/45 bg-green-500/10 text-green-600 dark:text-green-300'
: 'border-border bg-muted/30 text-muted-foreground'
)}
>
{activeDone ? 'Done' : 'Not done yet'}
</span>
</div>
<SelectedStepAction {...props} />
</div>
) : null}
</section>
</div>
)
}
@@ -0,0 +1,574 @@
/* eslint-disable max-lines -- Why: these setup visuals are self-contained storyboards; splitting the phase markup from timing and measured cursor logic would make the animation harder to verify. */
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { JSX, MutableRefObject, ReactNode, RefObject } from 'react'
import { FolderGit2, Plus } from 'lucide-react'
import { cn } from '@/lib/utils'
import { ClaudeIcon } from '../status-bar/icons'
import { useShortcutLabel } from '@/hooks/useShortcutLabel'
import { CodexInlineIcon, CursorIcon, WorkingSpinner } from './feature-tour-preview-glyphs'
import { WorkbenchAnimatedVisual } from './WorkbenchAnimatedVisual'
import { FeatureWallClickRing } from './FeatureWallClickRing'
type WorktreePhase =
| 'claude-active'
| 'plus-hover'
| 'plus-click'
| 'modal'
| 'modal-name-start'
| 'modal-name-complete'
| 'modal-hover'
| 'create-click'
| 'modal-closing'
| 'codex-starting'
| 'codex-typing-start'
| 'codex-typing-mid'
| 'codex-submitted'
| 'both-working'
const WORKTREE_PHASES: readonly WorktreePhase[] = [
'claude-active',
'claude-active',
'plus-hover',
'plus-hover',
'plus-click',
'modal',
'modal-name-start',
'modal-name-complete',
// Why: allow the cursor to slide onto and highlight the "Create" button before click.
'modal-hover',
'modal-hover',
'create-click',
// Why: the new worktree should not appear until the create dialog has cleared.
'modal-closing',
'codex-starting',
'codex-typing-start',
'codex-typing-mid',
'codex-submitted',
'both-working',
'both-working',
'both-working'
]
const CODEX_WORKTREE_NAME = 'checkout fix'
const CODEX_WORKTREE_PROMPT = 'fix checkout timeout'
const WORKTREE_NAME_TYPE_PER_CHAR_MS = 70
const WORKTREE_PROMPT_TYPE_PER_CHAR_MS = 55
export function SetupTwoAgentsVisual(props: { reducedMotion: boolean }): JSX.Element {
return (
<WorkbenchAnimatedVisual reducedMotion={props.reducedMotion} variant="two-agents-checklist" />
)
}
export function SetupWorkspacesVisual(props: { reducedMotion: boolean }): JSX.Element {
const { reducedMotion } = props
const rootRef = useRef<HTMLDivElement | null>(null)
const plusRef = useRef<HTMLSpanElement | null>(null)
const createButtonRef = useRef<HTMLDivElement | null>(null)
const modalNameTimeoutsRef = useRef<number[]>([])
const codexPromptTimeoutsRef = useRef<number[]>([])
const newWorktreeShortcut = useShortcutLabel('workspace.create')
const phase = useLoopedPhase(WORKTREE_PHASES, 900, reducedMotion, 'both-working')
const [modalNameValue, setModalNameValue] = useState(() =>
reducedMotion ? CODEX_WORKTREE_NAME : ''
)
const [codexPromptText, setCodexPromptText] = useState(() =>
reducedMotion ? CODEX_WORKTREE_PROMPT : ''
)
const plusHovered = phase === 'plus-hover'
const plusClicked = phase === 'plus-click'
const modalVisible =
phase === 'modal' ||
phase === 'modal-name-start' ||
phase === 'modal-name-complete' ||
phase === 'modal-hover' ||
phase === 'create-click'
const createHovered = phase === 'modal-hover' || phase === 'create-click'
const createClicked = phase === 'create-click'
const codexStarting = phase === 'codex-starting'
const codexTyping = phase === 'codex-typing-start' || phase === 'codex-typing-mid'
const codexSubmitted = phase === 'codex-submitted'
const codexWorking = phase === 'both-working'
const codexWorktreeVisible = codexStarting || codexTyping || codexSubmitted || codexWorking
const modalNameTyping = phase === 'modal-name-start'
const cursorTarget =
phase === 'claude-active'
? 'start'
: phase === 'plus-hover' ||
phase === 'plus-click' ||
phase === 'modal' ||
phase === 'modal-name-start' ||
phase === 'modal-name-complete'
? 'plus'
: phase === 'modal-hover' || phase === 'create-click'
? 'create'
: 'hidden'
const cursor = useMeasuredCursor(rootRef, plusRef, createButtonRef, cursorTarget, reducedMotion)
useEffect(() => {
return () => {
clearTypedTimeouts(modalNameTimeoutsRef)
clearTypedTimeouts(codexPromptTimeoutsRef)
}
}, [])
useEffect(() => {
if (reducedMotion) {
clearTypedTimeouts(modalNameTimeoutsRef)
setModalNameValue(CODEX_WORKTREE_NAME)
return
}
if (phase === 'modal') {
clearTypedTimeouts(modalNameTimeoutsRef)
setModalNameValue('')
return
}
if (phase === 'modal-name-start') {
scheduleTypedText(
modalNameTimeoutsRef,
CODEX_WORKTREE_NAME,
WORKTREE_NAME_TYPE_PER_CHAR_MS,
setModalNameValue
)
return
}
if (modalVisible || codexWorktreeVisible) {
clearTypedTimeouts(modalNameTimeoutsRef)
setModalNameValue(CODEX_WORKTREE_NAME)
return
}
clearTypedTimeouts(modalNameTimeoutsRef)
setModalNameValue('')
}, [codexWorktreeVisible, modalVisible, phase, reducedMotion])
useEffect(() => {
if (reducedMotion) {
clearTypedTimeouts(codexPromptTimeoutsRef)
setCodexPromptText(CODEX_WORKTREE_PROMPT)
return
}
if (phase === 'codex-typing-start') {
scheduleTypedText(
codexPromptTimeoutsRef,
CODEX_WORKTREE_PROMPT,
WORKTREE_PROMPT_TYPE_PER_CHAR_MS,
setCodexPromptText
)
return
}
// Why: the prompt is long enough to keep typing across the second typing beat.
if (phase === 'codex-typing-mid') {
return
}
if (codexSubmitted || codexWorking) {
clearTypedTimeouts(codexPromptTimeoutsRef)
setCodexPromptText(CODEX_WORKTREE_PROMPT)
return
}
clearTypedTimeouts(codexPromptTimeoutsRef)
setCodexPromptText('')
}, [codexSubmitted, codexWorking, phase, reducedMotion])
return (
<div
ref={rootRef}
className="relative grid min-h-[320px] gap-3 overflow-hidden rounded-xl border border-border bg-card p-3 text-foreground shadow-xs md:grid-cols-[220px_minmax(0,1fr)]"
>
<div className="flex min-w-0 flex-col gap-1.5 rounded-lg border border-sidebar-border bg-sidebar p-2 text-sidebar-foreground">
<ProjectSidebarRow
plusRef={plusRef}
plusActive={plusHovered || plusClicked}
plusHovered={plusHovered}
shortcut={newWorktreeShortcut}
worktreeCount={codexWorktreeVisible ? 2 : 1}
/>
<div className="relative flex min-w-0 flex-col gap-1.5">
<WorkspaceListCard
title="release notes"
active
prompt="draft release notes"
icon={<ClaudeIcon size={12} />}
state="working"
reducedMotion={reducedMotion}
/>
<WorkspaceListCard
title="checkout fix"
active={codexWorktreeVisible}
prompt="fix checkout timeout"
icon={<CodexInlineIcon />}
state={
codexSubmitted || codexWorking
? 'working'
: codexWorktreeVisible
? 'starting'
: 'idle'
}
reducedMotion={reducedMotion}
className={cn(
'transition-[opacity,transform]',
codexWorktreeVisible
? 'translate-y-0 opacity-100 duration-500'
: '-translate-y-1 opacity-0 duration-0'
)}
/>
</div>
</div>
<div className="relative grid min-w-0 gap-3 md:grid-rows-[88px_minmax(0,1fr)]">
<div className="min-w-0 overflow-hidden rounded-lg border border-border bg-background">
<VisualTitlebar title="release notes - Claude Code" compact />
<div className="space-y-1.5 p-2.5 font-mono text-[11px]">
<TerminalLine>
<Prompt>&gt;</Prompt> draft release notes
</TerminalLine>
<TerminalLine muted>
<WorkingSpinner size="xs" reducedMotion={reducedMotion} />
Edit release-notes.md
</TerminalLine>
</div>
</div>
<div
className={cn(
'min-w-0 overflow-hidden rounded-lg border border-border bg-background transition-[opacity,transform]',
codexWorktreeVisible
? 'translate-y-0 opacity-100 duration-500'
: 'translate-y-2 opacity-0 duration-0'
)}
>
<VisualTitlebar title="checkout fix - Codex" compact />
<div className="space-y-1.5 p-2.5 font-mono text-[11px]">
{codexStarting ? (
<TerminalLine muted>
<CodexInlineIcon />
Codex session ready
</TerminalLine>
) : (
<TerminalLine>
<Prompt>&gt;</Prompt>
{codexPromptText}
{codexTyping ? (
<span className="ml-px inline-block h-[10px] w-[5px] -translate-y-px animate-pulse bg-foreground align-[-1px]" />
) : null}
</TerminalLine>
)}
<TerminalLine muted>
<CodexInlineIcon />
{codexWorking
? 'Read checkout.test.ts'
: codexSubmitted
? 'Reading checkout.test.ts'
: 'Waiting'}
</TerminalLine>
{codexWorking ? (
<TerminalLine muted>
<WorkingSpinner size="xs" reducedMotion={reducedMotion} />
Edit src/checkout.ts
</TerminalLine>
) : null}
</div>
</div>
<NewWorkspaceModal
visible={modalVisible}
createHovered={createHovered}
createClicked={createClicked}
createButtonRef={createButtonRef}
nameValue={modalNameValue}
nameTyping={modalNameTyping}
/>
</div>
<div
aria-hidden
className={cn(
'pointer-events-none absolute left-0 top-0 z-50 size-5 drop-shadow-sm transition-[opacity,transform] duration-700 ease-[cubic-bezier(.45,.05,.2,1)] [&_svg]:size-5',
cursor.visible ? 'opacity-100' : 'opacity-0'
)}
style={{ transform: `translate(${cursor.x}px, ${cursor.y}px)` }}
>
<div className="relative">
<CursorIcon />
{plusClicked || createClicked ? <FeatureWallClickRing /> : null}
</div>
</div>
</div>
)
}
function ProjectSidebarRow(props: {
plusRef: RefObject<HTMLSpanElement | null>
plusActive: boolean
plusHovered: boolean
shortcut: string
worktreeCount: number
}): JSX.Element {
return (
<div
aria-hidden
className="relative flex h-8 min-w-0 items-center gap-1.5 rounded-md px-1.5 text-sidebar-foreground"
>
<span className="flex size-4 shrink-0 items-center justify-center text-muted-foreground">
<FolderGit2 className="size-3.5" />
</span>
<span className="min-w-0 flex-1 truncate text-[13px] font-semibold leading-none">orca</span>
<span className="min-w-[3.75rem] rounded-full bg-sidebar-accent px-1.5 py-0.5 text-center text-[9px] font-medium leading-none text-muted-foreground">
{props.worktreeCount} worktree{props.worktreeCount === 1 ? '' : 's'}
</span>
<span
ref={props.plusRef}
className={cn(
'relative flex size-5 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors',
props.plusActive ? 'bg-sidebar-accent text-sidebar-accent-foreground' : null
)}
>
<Plus className="size-3.5" />
</span>
<div
className={cn(
'pointer-events-none absolute left-[calc(100%+0.375rem)] top-0 z-10 flex h-7 w-max items-center gap-2 whitespace-nowrap rounded-md border border-border bg-popover px-2.5 text-[11px] font-medium text-popover-foreground shadow-xs transition-[opacity,transform] duration-200',
props.plusHovered ? 'translate-y-0 opacity-100' : '-translate-y-1 opacity-0'
)}
>
<span className="whitespace-nowrap">New worktree</span>
<kbd className="rounded border border-border bg-background px-1.5 py-0.5 font-mono text-[10px] font-medium text-muted-foreground">
{props.shortcut}
</kbd>
</div>
</div>
)
}
function NewWorkspaceModal(props: {
visible: boolean
createHovered: boolean
createClicked: boolean
createButtonRef: RefObject<HTMLDivElement | null>
nameValue: string
nameTyping: boolean
}): JSX.Element {
return (
<div
className={cn(
'pointer-events-none absolute inset-0 flex items-center justify-center rounded-lg bg-background/55 transition-opacity duration-300',
props.visible ? 'opacity-100' : 'opacity-0'
)}
aria-hidden
>
<div
className={cn(
'relative w-[min(250px,88%)] rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-xs transition-[opacity,transform] duration-300',
props.visible
? 'translate-y-0 scale-100 opacity-100'
: 'translate-y-2 scale-[0.98] opacity-0'
)}
>
<div className="text-sm font-semibold leading-none text-foreground">Create Worktree</div>
<div className="mt-3 space-y-2">
<ModalField label="Project" value="orca" />
<ModalField label="Name" value={props.nameValue} typing={props.nameTyping} />
<ModalField label="Agent" value="Codex" icon={<CodexInlineIcon />} />
</div>
<div
ref={props.createButtonRef}
aria-hidden
className={cn(
'relative mt-3 flex h-8 w-full items-center justify-center rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground transition-all duration-200',
props.createHovered ? 'opacity-90' : null,
props.createClicked ? 'scale-[0.98]' : null
)}
>
Create worktree
</div>
</div>
</div>
)
}
function clearTypedTimeouts(ref: MutableRefObject<number[]>): void {
for (const timeoutId of ref.current) {
window.clearTimeout(timeoutId)
}
ref.current = []
}
function scheduleTypedText(
ref: MutableRefObject<number[]>,
text: string,
perCharMs: number,
setValue: (value: string) => void
): void {
clearTypedTimeouts(ref)
setValue('')
for (let i = 1; i <= text.length; i += 1) {
ref.current.push(window.setTimeout(() => setValue(text.slice(0, i)), i * perCharMs))
}
}
function useMeasuredCursor(
rootRef: RefObject<HTMLDivElement | null>,
plusRef: RefObject<HTMLElement | null>,
createButtonRef: RefObject<HTMLElement | null>,
target: 'hidden' | 'start' | 'plus' | 'create',
reducedMotion: boolean
): { x: number; y: number; visible: boolean } {
const [pos, setPos] = useState({ x: 0, y: 0, visible: false })
// Why: measuring targets keeps the cursor aligned as the setup card resizes.
useLayoutEffect(() => {
if (reducedMotion || target === 'hidden') {
setPos((current) => ({ ...current, visible: false }))
return
}
const root = rootRef.current
if (target === 'start') {
setPos({ x: 34, y: 218, visible: true })
return
}
const targetNode = target === 'plus' ? plusRef.current : createButtonRef.current
if (!root || !targetNode) {
return
}
const rootRect = root.getBoundingClientRect()
const targetRect = targetNode.getBoundingClientRect()
setPos({
x: targetRect.left - rootRect.left + targetRect.width * 0.58,
y: targetRect.top - rootRect.top + targetRect.height * 0.58,
visible: true
})
}, [createButtonRef, plusRef, reducedMotion, rootRef, target])
return pos
}
function ModalField(props: {
label: string
value: string
icon?: ReactNode
typing?: boolean
}): JSX.Element {
return (
<div>
<div className="text-[11px] font-medium text-muted-foreground">{props.label}</div>
<div className="mt-1 flex h-7 items-center gap-1.5 rounded-md border border-border bg-background px-2 text-xs font-medium text-foreground">
{props.icon ? <span className="flex size-3.5 shrink-0 items-center">{props.icon}</span> : null}
<span className="truncate">{props.value}</span>
{props.typing ? (
<span className="ml-px inline-block h-[10px] w-[5px] animate-pulse bg-foreground" />
) : null}
</div>
</div>
)
}
function useLoopedPhase<T extends string>(
phases: readonly T[],
intervalMs: number,
reducedMotion: boolean,
reducedMotionPhase: T
): T {
const [idx, setIdx] = useState(() => {
const reducedIdx = phases.indexOf(reducedMotionPhase)
return reducedMotion && reducedIdx >= 0 ? reducedIdx : 0
})
useEffect(() => {
if (reducedMotion) {
const reducedIdx = phases.indexOf(reducedMotionPhase)
setIdx(Math.max(reducedIdx, 0))
return
}
setIdx(0)
const id = window.setInterval(() => {
setIdx((current) => (current + 1) % phases.length)
}, intervalMs)
return () => window.clearInterval(id)
}, [intervalMs, phases, reducedMotion, reducedMotionPhase])
return phases[idx] ?? phases[0]
}
function VisualTitlebar(props: { title: string; compact?: boolean }): JSX.Element {
return (
<div
className={cn(
'flex items-center gap-1.5 border-b border-border bg-muted/40',
props.compact ? 'h-6 px-2' : 'h-8 px-3'
)}
>
<span className="size-2 rounded-full bg-foreground/15" />
<span className="size-2 rounded-full bg-foreground/15" />
<span className="size-2 rounded-full bg-foreground/15" />
<span className="ml-1 truncate font-mono text-[11px] text-muted-foreground">
{props.title}
</span>
</div>
)
}
function WorkspaceListCard(props: {
title: string
active: boolean
prompt: string
icon: ReactNode
state: 'idle' | 'starting' | 'working'
reducedMotion: boolean
className?: string
}): JSX.Element {
return (
<div
className={cn(
'rounded-md border border-sidebar-border px-2.5 py-2 transition-colors',
props.active ? 'bg-sidebar-accent' : 'bg-sidebar',
props.className
)}
>
<div className="flex items-center gap-2">
<span
className={cn(
'size-1.5 shrink-0 rounded-full',
props.active ? 'bg-emerald-500' : 'bg-muted-foreground/35'
)}
/>
<span className="truncate text-xs font-medium text-sidebar-foreground">{props.title}</span>
</div>
<div className="mt-2 grid grid-cols-[8px_14px_minmax(0,1fr)] items-center gap-1.5">
{props.state === 'working' || props.state === 'starting' ? (
<WorkingSpinner size="xs" reducedMotion={props.reducedMotion} />
) : (
<span className="size-1.5 rounded-full bg-muted-foreground/35" />
)}
<span className="flex size-3.5 items-center justify-center text-sidebar-foreground/65">
{props.icon}
</span>
<span className="truncate font-mono text-[11px] text-sidebar-foreground/65">
{props.state === 'idle' ? 'ready' : props.prompt}
</span>
</div>
</div>
)
}
function TerminalLine(props: { children: ReactNode; muted?: boolean }): JSX.Element {
return (
<div
className={cn(
'flex min-w-0 items-center gap-1.5 truncate leading-[1.45]',
props.muted ? 'text-muted-foreground' : 'text-foreground'
)}
>
{props.children}
</div>
)
}
function Prompt(props: { children: ReactNode }): JSX.Element {
return <span className="shrink-0 text-primary">{props.children}</span>
}
@@ -0,0 +1,211 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
SETUP_GUIDE_PROJECT_PROMPT,
activateWorktreeTerminalForSetupTour,
cancelPendingSetupGuideTourRequest,
getSetupGuideGitRepo,
isSetupGuideWorkspaceComposerRequestCurrent,
promptForSetupGuideProject,
requestSetupGuideTourAfterFrame,
requestSetupGuideTourWhenReady
} from './FeatureWallSetupWorkflowActions'
import { useAppStore } from '@/store'
import * as worktreeActivation from '@/lib/worktree-activation'
import * as webRuntimeSession from '@/runtime/web-runtime-session'
import { toast } from 'sonner'
import type { Repo } from '../../../../shared/types'
vi.mock('sonner', () => ({
toast: {
message: vi.fn(),
success: vi.fn(),
error: vi.fn()
}
}))
vi.mock('@/lib/worktree-activation', () => ({
activateAndRevealWorktree: vi.fn()
}))
vi.mock('@/lib/focus-terminal-tab-surface', () => ({
focusTerminalTabSurface: vi.fn()
}))
vi.mock('@/runtime/web-runtime-session', () => ({
isWebRuntimeSessionActive: vi.fn(() => false)
}))
vi.mock('./FeatureWallSetupStepVisuals', () => ({
SetupTwoAgentsVisual: () => <div />,
SetupWorkspacesVisual: () => <div />
}))
vi.mock('./AddReposAnimatedVisual', () => ({
AddReposAnimatedVisual: () => <div />
}))
vi.mock('./SetupScriptAnimatedVisual', () => ({
SetupScriptAnimatedVisual: () => <div />
}))
function makeRepo(id: string, overrides: Partial<Repo> = {}): Repo {
return {
id,
path: `/tmp/${id}`,
displayName: id,
badgeColor: '#000000',
addedAt: 1,
kind: 'git',
...overrides
}
}
describe('TwoAgentsAction', () => {
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
useAppStore.setState({
activeWorktreeId: null,
worktreesByRepo: {},
tabsByWorktree: {},
activeTabId: null,
activeGroupIdByWorktree: {},
terminalLayoutsByTabId: {}
})
})
it('prompts for a project before setup-guide actions that need one', () => {
const openModal = vi.fn()
promptForSetupGuideProject(openModal)
expect(openModal).toHaveBeenCalledWith('add-repo')
expect(toast.message).toHaveBeenCalledWith(SETUP_GUIDE_PROJECT_PROMPT)
})
it('chooses the active git repo for setup-guide workspace creation', () => {
const active = makeRepo('active')
expect(getSetupGuideGitRepo([makeRepo('first'), active], 'active')).toBe(active)
})
it('falls back to the first git repo when the active project is a folder', () => {
const gitRepo = makeRepo('git')
expect(getSetupGuideGitRepo([makeRepo('folder', { kind: 'folder' }), gitRepo], 'folder')).toBe(
gitRepo
)
})
it('returns no setup-guide repo when only folders exist', () => {
expect(getSetupGuideGitRepo([makeRepo('folder', { kind: 'folder' })], 'folder')).toBeNull()
})
it('creates a terminal tab before requesting the split tour when a worktree has only editor/browser tabs', () => {
const createTab = vi.fn(() => ({ id: 'terminal-tab-1' }))
const setActiveTab = vi.fn()
const setActiveTabType = vi.fn()
vi.mocked(worktreeActivation.activateAndRevealWorktree).mockReturnValue({ primaryTabId: null })
useAppStore.setState({
activeWorktreeId: 'worktree-1',
worktreesByRepo: {
'repo-1': [{ id: 'worktree-1', repoId: 'repo-1' }]
} as never,
tabsByWorktree: { 'worktree-1': [] },
activeTabId: 'editor-tab-1',
activeGroupIdByWorktree: { 'worktree-1': 'group-1' },
terminalLayoutsByTabId: {},
closeModal: vi.fn(),
createTab: createTab as never,
setActiveTabType: setActiveTabType as never,
setActiveTab: setActiveTab as never
})
const tabId = activateWorktreeTerminalForSetupTour('worktree-1')
expect(tabId).toBe('terminal-tab-1')
expect(createTab).toHaveBeenCalledWith('worktree-1', 'group-1')
expect(setActiveTabType).toHaveBeenCalledWith('terminal')
expect(setActiveTab).toHaveBeenCalledWith('terminal-tab-1')
})
it('does not create a local fallback terminal for paired web runtime sessions', () => {
const createTab = vi.fn(() => ({ id: 'terminal-tab-1' }))
const setActiveTab = vi.fn()
vi.mocked(webRuntimeSession.isWebRuntimeSessionActive).mockReturnValue(true)
vi.mocked(worktreeActivation.activateAndRevealWorktree).mockReturnValue({ primaryTabId: null })
useAppStore.setState({
settings: { activeRuntimeEnvironmentId: 'runtime-1' } as never,
activeWorktreeId: 'worktree-1',
worktreesByRepo: {
'repo-1': [{ id: 'worktree-1', repoId: 'repo-1' }]
} as never,
tabsByWorktree: { 'worktree-1': [] },
activeTabId: 'editor-tab-1',
activeGroupIdByWorktree: { 'worktree-1': 'group-1' },
terminalLayoutsByTabId: {},
createTab: createTab as never,
setActiveTab: setActiveTab as never
})
const tabId = activateWorktreeTerminalForSetupTour('worktree-1')
expect(tabId).toBeNull()
expect(createTab).not.toHaveBeenCalled()
expect(setActiveTab).not.toHaveBeenCalled()
})
it('keeps setup-guide tour work alive across the modal transition that unmounts the action', () => {
const callbacks: FrameRequestCallback[] = []
const callback = vi.fn()
vi.stubGlobal('window', {
requestAnimationFrame: vi.fn((frameCallback: FrameRequestCallback) => {
callbacks.push(frameCallback)
return callbacks.length
}),
cancelAnimationFrame: vi.fn()
})
requestSetupGuideTourAfterFrame(callback)
callbacks[0]?.(1)
expect(callback).toHaveBeenCalledTimes(1)
cancelPendingSetupGuideTourRequest()
})
it('gates setup-guide tour retries on the expected destination surface', () => {
vi.useFakeTimers()
const requestContextualTour = vi.fn()
useAppStore.setState({
activeModal: 'none',
activeContextualTourId: null,
requestContextualTour: requestContextualTour as never
})
requestSetupGuideTourWhenReady({
id: 'workspace-creation',
source: 'setup_guide_parallel_work',
shouldContinue: () => useAppStore.getState().activeModal === 'new-workspace-composer',
retryDelayMs: 10,
maxAttempts: 5
})
vi.advanceTimersByTime(50)
expect(requestContextualTour).not.toHaveBeenCalled()
cancelPendingSetupGuideTourRequest()
vi.useRealTimers()
})
it('rejects a stale setup-guide composer request after close and reopen', () => {
useAppStore.setState({
activeModal: 'new-workspace-composer',
modalData: { setupGuideTourRequestId: 'new-request' }
})
expect(isSetupGuideWorkspaceComposerRequestCurrent('old-request')).toBe(false)
expect(isSetupGuideWorkspaceComposerRequestCurrent('new-request')).toBe(true)
})
})
@@ -0,0 +1,381 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { ArrowUpRight, Plus, Save, Settings } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface'
import { useAppStore } from '@/store'
import { useAllWorktrees } from '@/store/selectors'
import { getDefaultRepoHookSettings } from '../../../../shared/constants'
import { isGitRepoKind } from '../../../../shared/repo-kind'
import type {
Repo,
RepoHookSettings,
TerminalPaneLayoutNode,
Worktree
} from '../../../../shared/types'
import { getRepositoryLocalCommandsSectionId } from '../settings/repository-settings-targets'
import { AddReposAnimatedVisual } from './AddReposAnimatedVisual'
import { SetupTwoAgentsVisual, SetupWorkspacesVisual } from './FeatureWallSetupStepVisuals'
import { SetupScriptAnimatedVisual } from './SetupScriptAnimatedVisual'
import { SetupStepPreview } from './SetupStepPreview'
import {
requestContextualTourWhenReady,
type RequestContextualTourWhenReadyArgs
} from '../contextual-tours/request-contextual-tour-when-ready'
import { isWebRuntimeSessionActive } from '@/runtime/web-runtime-session'
export const SETUP_GUIDE_PROJECT_PROMPT = "First add a project you'd like to work on."
export function promptForSetupGuideProject(openModal: (modal: 'add-repo') => void): void {
openModal('add-repo')
toast.message(SETUP_GUIDE_PROJECT_PROMPT)
}
export function getSetupGuideGitRepo(
repos: readonly Repo[],
activeRepoId: string | null
): Repo | null {
const activeRepo = activeRepoId
? repos.find((entry) => entry.id === activeRepoId && isGitRepoKind(entry))
: undefined
return activeRepo ?? repos.find((entry) => isGitRepoKind(entry)) ?? null
}
export function AddReposAction(props: { reducedMotion: boolean }): React.JSX.Element {
const openModal = useAppStore((s) => s.openModal)
return (
<div className="space-y-4">
<Button type="button" size="sm" className="w-fit gap-2" onClick={() => openModal('add-repo')}>
<Plus className="size-3.5" />
Add project
</Button>
<SetupStepPreview>
<AddReposAnimatedVisual reducedMotion={props.reducedMotion} />
</SetupStepPreview>
</div>
)
}
export function TwoAgentsAction(props: {
reducedMotion: boolean
done: boolean
}): React.JSX.Element {
const targetWorktree = useSetupTargetWorktree()
const openModal = useAppStore((s) => s.openModal)
const closeModal = useAppStore((s) => s.closeModal)
const paneTarget = useSecondPaneTarget(targetWorktree?.id ?? null)
const handlePrimaryAction = useCallback(() => {
cancelPendingSetupGuideTourRequest()
if (!targetWorktree) {
promptForSetupGuideProject(openModal)
return
}
closeModal()
requestSetupGuideTourAfterFrame(() => {
activateWorktreeTerminalForSetupTour(targetWorktree.id)
requestSetupGuideTourWhenReady({
id: 'workspace-agent-sessions',
source: 'setup_guide_parallel_work',
wasFeaturePreviouslyInteracted: false,
shouldContinue: () => isWorktreeTerminalStillCurrent(targetWorktree.id)
})
})
}, [closeModal, openModal, targetWorktree])
return (
<div className="space-y-4">
{!props.done && !paneTarget ? (
<div>
<div className="flex flex-wrap gap-2">
<Button type="button" size="sm" className="w-fit gap-2" onClick={handlePrimaryAction}>
<ArrowUpRight className="size-3.5" />
Try it out
</Button>
</div>
</div>
) : null}
<SetupStepPreview>
<SetupTwoAgentsVisual reducedMotion={props.reducedMotion} />
</SetupStepPreview>
</div>
)
}
export function WorkspacesAction(props: {
reducedMotion: boolean
done: boolean
}): React.JSX.Element {
const openModal = useAppStore((s) => s.openModal)
const activeRepoId = useAppStore((s) => s.activeRepoId)
const repos = useAppStore((s) => s.repos)
const repo = getSetupGuideGitRepo(repos, activeRepoId)
return (
<div className="space-y-4">
{!props.done ? (
<Button
type="button"
size="sm"
className="w-fit gap-2"
onClick={() => {
cancelPendingSetupGuideTourRequest()
if (!repo) {
promptForSetupGuideProject(openModal)
return
}
const tourRequestId = createSetupGuideTourRequestId()
openModal('new-workspace-composer', {
initialRepoId: repo.id,
telemetrySource: 'unknown',
contextualTourSource: 'setup_guide_parallel_work',
setupGuideTourRequestId: tourRequestId
})
requestSetupGuideTourWhenReady({
id: 'workspace-creation',
source: 'setup_guide_parallel_work',
wasFeaturePreviouslyInteracted: false,
shouldContinue: () => isSetupGuideWorkspaceComposerRequestCurrent(tourRequestId)
})
}}
>
<ArrowUpRight className="size-3.5" />
Try it out
</Button>
) : null}
<SetupStepPreview>
<SetupWorkspacesVisual reducedMotion={props.reducedMotion} />
</SetupStepPreview>
</div>
)
}
export function SetupScriptAction(props: { reducedMotion: boolean }): React.JSX.Element {
const repos = useAppStore((s) => s.repos)
const activeRepoId = useAppStore((s) => s.activeRepoId)
const closeModal = useAppStore((s) => s.closeModal)
const openSettingsPage = useAppStore((s) => s.openSettingsPage)
const openSettingsTarget = useAppStore((s) => s.openSettingsTarget)
const setSettingsSearchQuery = useAppStore((s) => s.setSettingsSearchQuery)
const updateRepo = useAppStore((s) => s.updateRepo)
const repo = getSetupGuideGitRepo(repos, activeRepoId)
const canConfigure = repo !== null
const [setupScript, setSetupScript] = useState('pnpm install')
useEffect(() => {
if (!canConfigure) {
setSetupScript('pnpm install')
return
}
setSetupScript(repo.hookSettings?.scripts?.setup?.trim() || 'pnpm install')
}, [canConfigure, repo])
const openLocalCommandSettings = useCallback(() => {
if (!repo || !isGitRepoKind(repo)) {
return
}
setSettingsSearchQuery('')
openSettingsTarget({
pane: 'repo',
repoId: repo.id,
sectionId: getRepositoryLocalCommandsSectionId(repo.id)
})
closeModal()
openSettingsPage()
}, [closeModal, openSettingsPage, openSettingsTarget, repo, setSettingsSearchQuery])
const handleSaveSetupScript = useCallback(async () => {
if (!repo || !isGitRepoKind(repo)) {
return
}
const current = repo.hookSettings
const defaults = getDefaultRepoHookSettings()
const nextHookSettings: RepoHookSettings = {
...defaults,
...current,
setupRunPolicy: current?.setupRunPolicy ?? defaults.setupRunPolicy,
// Why: setup guide edits are local repo commands and must run after save.
commandSourcePolicy: current?.commandSourcePolicy ?? 'local-only',
scripts: {
...defaults.scripts,
...current?.scripts,
setup: setupScript.trim()
}
}
const updated = await updateRepo(repo.id, { hookSettings: nextHookSettings })
if (updated) {
toast.success('Setup script saved')
} else {
toast.error('Failed to save setup script')
}
}, [repo, setupScript, updateRepo])
return (
<div className="space-y-4">
<div className="rounded-lg border border-border bg-muted/20 p-3">
<div className="grid gap-2 sm:grid-cols-[minmax(0,1fr)_auto]">
<Input
value={setupScript}
disabled={!canConfigure}
onChange={(event) => setSetupScript(event.target.value)}
placeholder="pnpm install"
aria-label="Setup script"
className="font-mono text-sm"
/>
<Button
type="button"
size="sm"
className="gap-2"
disabled={!canConfigure || setupScript.trim().length === 0}
onClick={() => void handleSaveSetupScript()}
>
<Save className="size-3.5" />
Save
</Button>
</div>
<Button
type="button"
variant="ghost"
size="sm"
className="mt-2 w-fit gap-2 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground"
disabled={!canConfigure}
onClick={openLocalCommandSettings}
>
<Settings className="size-3.5" />
View in settings
</Button>
</div>
{!canConfigure ? (
<p className="text-xs text-muted-foreground">
Add a git project first, then configure the setup script for that repository.
</p>
) : null}
<SetupStepPreview>
<SetupScriptAnimatedVisual reducedMotion={props.reducedMotion} />
</SetupStepPreview>
</div>
)
}
function useSetupTargetWorktree(): Worktree | null {
const allWorktrees = useAllWorktrees()
const activeWorktreeId = useAppStore((s) => s.activeWorktreeId)
return useMemo(
() =>
allWorktrees.find((worktree) => worktree.id === activeWorktreeId) ?? allWorktrees[0] ?? null,
[activeWorktreeId, allWorktrees]
)
}
export function activateWorktreeTerminalForSetupTour(worktreeId: string): string | null {
const activation = activateAndRevealWorktree(worktreeId)
if (!activation) {
return null
}
const state = useAppStore.getState()
const activeRuntimeEnvironmentId = state.settings?.activeRuntimeEnvironmentId ?? null
const webRuntimeActive = isWebRuntimeSessionActive(activeRuntimeEnvironmentId)
const activeGroupId = state.activeGroupIdByWorktree[worktreeId]
const tabs = state.tabsByWorktree[worktreeId] ?? []
const activeTerminalTabId =
state.activeTabId && tabs.some((tab) => tab.id === state.activeTabId) ? state.activeTabId : null
const tabId =
activeTerminalTabId ??
activation.primaryTabId ??
tabs[0]?.id ??
(webRuntimeActive ? null : state.createTab(worktreeId, activeGroupId).id)
if (!tabId) {
return null
}
// Why: the forced tour's split action targets the visible terminal tab.
// Worktree activation can restore an editor/browser as the active surface.
state.setActiveTabType('terminal')
state.setActiveTab(tabId)
focusTerminalTabSurface(tabId)
return tabId
}
function useSecondPaneTarget(worktreeId: string | null): { tabId: string; leafId: string } | null {
const activeTabId = useAppStore((s) => s.activeTabId)
const tabsByWorktree = useAppStore((s) => s.tabsByWorktree)
const terminalLayoutsByTabId = useAppStore((s) => s.terminalLayoutsByTabId)
return useMemo(() => {
if (!worktreeId) {
return null
}
const tabIds = (tabsByWorktree[worktreeId] ?? []).map((tab) => tab.id)
const orderedTabIds =
activeTabId && tabIds.includes(activeTabId)
? [activeTabId, ...tabIds.filter((tabId) => tabId !== activeTabId)]
: tabIds
for (const tabId of orderedTabIds) {
const root = terminalLayoutsByTabId[tabId]?.root
const secondLeafId = getSecondSplitLeafId(root)
if (secondLeafId) {
return { tabId, leafId: secondLeafId }
}
}
return null
}, [activeTabId, tabsByWorktree, terminalLayoutsByTabId, worktreeId])
}
function getSecondSplitLeafId(node: TerminalPaneLayoutNode | null | undefined): string | null {
if (!node || node.type === 'leaf') {
return null
}
return getLeftmostLeafId(node.second)
}
function getLeftmostLeafId(node: TerminalPaneLayoutNode): string {
return node.type === 'leaf' ? node.leafId : getLeftmostLeafId(node.first)
}
let pendingSetupGuideTourCancel: (() => void) | null = null
let pendingSetupGuideFrame: number | null = null
let setupGuideTourRequestSequence = 0
function createSetupGuideTourRequestId(): string {
setupGuideTourRequestSequence += 1
return `setup-guide-tour-${setupGuideTourRequestSequence}`
}
export function cancelPendingSetupGuideTourRequest(): void {
pendingSetupGuideTourCancel?.()
pendingSetupGuideTourCancel = null
if (pendingSetupGuideFrame !== null) {
window.cancelAnimationFrame(pendingSetupGuideFrame)
pendingSetupGuideFrame = null
}
}
export function requestSetupGuideTourWhenReady(args: RequestContextualTourWhenReadyArgs): void {
cancelPendingSetupGuideTourRequest()
pendingSetupGuideTourCancel = requestContextualTourWhenReady(args)
}
export function requestSetupGuideTourAfterFrame(callback: () => void): void {
cancelPendingSetupGuideTourRequest()
pendingSetupGuideFrame = window.requestAnimationFrame(() => {
pendingSetupGuideFrame = null
callback()
})
}
export function isSetupGuideWorkspaceComposerRequestCurrent(requestId: string): boolean {
const state = useAppStore.getState()
const modalData = state.modalData as { setupGuideTourRequestId?: unknown }
return (
state.activeModal === 'new-workspace-composer' &&
modalData.setupGuideTourRequestId === requestId
)
}
function isWorktreeTerminalStillCurrent(worktreeId: string): boolean {
const state = useAppStore.getState()
return (
state.activeModal === 'none' &&
state.activeWorktreeId === worktreeId &&
state.activeView === 'terminal' &&
state.activeTabType === 'terminal'
)
}
@@ -0,0 +1,512 @@
/* eslint-disable max-lines -- Why: this is a single storyboarded setup-script animation; splitting the phase markup from target measurement makes the visual harder to verify. */
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { JSX, ReactNode, RefObject } from 'react'
import { FolderGit2, Plus, TerminalSquare } from 'lucide-react'
import { cn } from '@/lib/utils'
import { ClaudeIcon } from '../status-bar/icons'
import { CodexInlineIcon, CursorIcon, WorkingSpinner } from './feature-tour-preview-glyphs'
import { FeatureWallClickRing } from './FeatureWallClickRing'
const PHASES = [
{ name: 'create-init', duration: 1200 },
{ name: 'plus-hover', duration: 600 },
{ name: 'plus-click', duration: 400 },
{ name: 'modal-visible', duration: 600 },
{ name: 'modal-typing', duration: 1500 },
{ name: 'modal-complete', duration: 600 },
{ name: 'create-click', duration: 400 },
{ name: 'modal-closing', duration: 400 },
{ name: 'worktree-opening', duration: 1000 },
{ name: 'pane-splitting', duration: 1000 },
{ name: 'setup-running', duration: 2500 },
{ name: 'setup-complete', duration: 800 },
{ name: 'agent-running', duration: 3000 },
{ name: 'dwell', duration: 2000 }
] as const
export function SetupScriptAnimatedVisual(props: { reducedMotion: boolean }): JSX.Element {
const { reducedMotion } = props
const rootRef = useRef<HTMLDivElement | null>(null)
const plusRef = useRef<HTMLSpanElement | null>(null)
const createButtonRef = useRef<HTMLDivElement | null>(null)
const [phaseIdx, setPhaseIdx] = useState(0)
const [modalNameValue, setModalNameValue] = useState('')
// Why: variable-length timeout loop to perfectly sync animation story beats.
useEffect(() => {
if (reducedMotion) {
setPhaseIdx(PHASES.findIndex((p) => p.name === 'agent-running'))
return
}
let timer: number
const tick = (idx: number) => {
const currentPhase = PHASES[idx]
timer = window.setTimeout(() => {
const nextIdx = (idx + 1) % PHASES.length
setPhaseIdx(nextIdx)
tick(nextIdx)
}, currentPhase.duration)
}
tick(0)
return () => {
window.clearTimeout(timer)
}
}, [reducedMotion])
const phase = PHASES[phaseIdx]?.name ?? 'agent-running'
// Why: type out the worktree name character-by-character to simulate user input.
useEffect(() => {
if (reducedMotion) {
setModalNameValue('checkout fix')
return
}
if (
phase === 'create-init' ||
phase === 'plus-hover' ||
phase === 'plus-click' ||
phase === 'modal-visible'
) {
setModalNameValue('')
return
}
if (phase === 'modal-typing') {
const text = 'checkout fix'
let current = ''
let idx = 0
const timer = window.setInterval(() => {
if (idx < text.length) {
current += text[idx]
setModalNameValue(current)
idx++
} else {
window.clearInterval(timer)
}
}, 75)
return () => window.clearInterval(timer)
}
setModalNameValue('checkout fix')
return undefined
}, [phase, reducedMotion])
const isWorkspaceActive = !(
phase === 'create-init' ||
phase === 'plus-hover' ||
phase === 'plus-click' ||
phase === 'modal-visible' ||
phase === 'modal-typing' ||
phase === 'modal-complete' ||
phase === 'create-click' ||
phase === 'modal-closing'
)
const modalVisible =
phase === 'modal-visible' ||
phase === 'modal-typing' ||
phase === 'modal-complete' ||
phase === 'create-click'
const plusHovered = phase === 'plus-hover'
const plusClicked = phase === 'plus-click'
const createHovered = phase === 'modal-complete'
const createClicked = phase === 'create-click'
const cursorTarget =
phase === 'plus-hover' || phase === 'plus-click'
? 'plus'
: phase === 'modal-complete' || phase === 'create-click'
? 'create'
: phase === 'create-init'
? 'start'
: 'hidden'
const cursor = useMeasuredCursor(rootRef, plusRef, createButtonRef, cursorTarget, reducedMotion)
return (
<div
ref={rootRef}
className="relative grid min-h-[240px] gap-3 rounded-xl border border-border bg-card p-3 text-foreground shadow-xs md:grid-cols-[180px_minmax(0,1fr)] overflow-hidden"
>
{/* Sidebar */}
<div className="flex min-w-0 flex-col rounded-lg border border-sidebar-border bg-sidebar p-2 text-sidebar-foreground h-full">
<div className="flex h-8 items-center justify-between gap-2 px-1.5">
<div className="flex items-center gap-2 min-w-0">
<FolderGit2 className="size-3.5 text-muted-foreground" />
<span className="truncate text-[13px] font-semibold">orca</span>
</div>
<span
ref={plusRef}
className={cn(
'relative flex size-5 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-all duration-300 z-10',
plusHovered ? 'bg-sidebar-accent text-sidebar-accent-foreground' : null,
plusClicked
? 'scale-90 bg-sidebar-accent text-sidebar-accent-foreground animate-pulse'
: null
)}
>
<Plus className="size-3.5" />
{plusClicked && <FeatureWallClickRing />}
</span>
</div>
<div className="mt-1 flex flex-col gap-1.5 min-w-0 flex-1">
<WorkspaceListCard
title="release notes"
active={!isWorkspaceActive}
prompt="draft release notes"
icon={<ClaudeIcon size={12} />}
state={!isWorkspaceActive ? 'working' : 'idle'}
reducedMotion={reducedMotion}
/>
<WorkspaceListCard
title="checkout fix"
active={isWorkspaceActive}
prompt="fix checkout timeout"
icon={<CodexInlineIcon />}
state={
phase === 'worktree-opening' || phase === 'pane-splitting'
? 'starting'
: phase === 'setup-running'
? 'setup'
: isWorkspaceActive
? 'working'
: 'idle'
}
reducedMotion={reducedMotion}
className={cn(
'transition-all duration-500 ease-in-out',
isWorkspaceActive
? 'opacity-100 translate-y-0 scale-100'
: 'opacity-0 -translate-y-1 scale-95 h-0 overflow-hidden border-none p-0 m-0'
)}
/>
</div>
</div>
{/* Terminal Pane / Screen */}
<div className="relative min-w-0 overflow-hidden rounded-lg border border-border bg-background h-full flex-1">
{/* Inactive Terminal (Visible when no active worktree) */}
<div
className={cn(
'absolute inset-0 flex flex-col bg-background transition-opacity duration-300 z-10',
isWorkspaceActive ? 'opacity-0 pointer-events-none' : 'opacity-100'
)}
>
<div className="flex h-7 items-center gap-1.5 border-b border-border bg-muted/40 px-2.5">
<TerminalSquare className="size-3.5 text-muted-foreground/60" />
<span className="truncate text-[11px] font-medium text-muted-foreground/60">
Terminal
</span>
</div>
<div className="flex-1 p-3 font-mono text-[11px] text-muted-foreground/30">
<div className="flex items-center gap-1.5">
<span>$</span>
<span className="h-[10px] w-[5px] bg-muted-foreground/30 animate-pulse" />
</div>
</div>
</div>
{/* Active Split Terminal Pane (Visible when worktree opens) */}
<div
className={cn(
'absolute inset-0 flex h-full w-full gap-2 p-2 bg-background transition-opacity duration-300 z-20',
isWorkspaceActive ? 'opacity-100' : 'opacity-0 pointer-events-none'
)}
>
{/* Agent Pane (Left) */}
<div
className={cn(
'flex flex-col rounded-md border border-border bg-card/40 overflow-hidden h-full transition-all duration-700 ease-in-out min-w-0',
phase === 'worktree-opening' ? 'w-full' : 'w-1/2'
)}
>
<div className="flex h-6 items-center gap-1.5 border-b border-border bg-muted/40 px-2 shrink-0">
<CodexInlineIcon />
<span className="truncate text-[10px] font-semibold text-muted-foreground">
Agent: Codex
</span>
</div>
<div className="flex-1 p-2 font-mono text-[10px] space-y-1.5 overflow-hidden">
<TerminalLine>
<Prompt>$</Prompt> orca agent start
</TerminalLine>
{phase === 'worktree-opening' ||
phase === 'pane-splitting' ||
phase === 'setup-running' ? (
<TerminalLine muted>
<WorkingSpinner size="xs" reducedMotion={reducedMotion} />
Waiting for setup script...
</TerminalLine>
) : phase === 'setup-complete' ? (
<TerminalLine muted>
<span>Initializing agent...</span>
</TerminalLine>
) : (
<>
<TerminalLine muted>
<span className="text-emerald-500 font-semibold">✓ Setup complete</span>
</TerminalLine>
<TerminalLine className="text-foreground">
<WorkingSpinner size="xs" reducedMotion={reducedMotion} />
<span>Running: checkout timeout</span>
</TerminalLine>
<TerminalLine muted className="pl-3 text-[9px] text-muted-foreground/75">
<span>Reading checkout.test.ts</span>
</TerminalLine>
<TerminalLine muted className="pl-3 text-[9px] text-muted-foreground/75">
<span>Modifying checkout.ts</span>
</TerminalLine>
</>
)}
</div>
</div>
{/* Setup Script Pane (Right - Splits and slides/fades in) */}
<div
className={cn(
'flex flex-col rounded-md border border-border bg-card/40 overflow-hidden h-full transition-all duration-700 ease-in-out min-w-0',
phase === 'worktree-opening' ? 'w-0 opacity-0 border-none p-0' : 'w-1/2 opacity-100'
)}
>
<div className="flex h-6 items-center gap-1.5 border-b border-border bg-muted/40 px-2 shrink-0">
<TerminalSquare className="size-3 text-muted-foreground" />
<span className="truncate text-[10px] font-semibold text-muted-foreground">
Setup Script
</span>
</div>
<div className="flex-1 p-2 font-mono text-[10px] space-y-1.5 overflow-hidden">
<TerminalLine>
<Prompt>$</Prompt> pnpm install
</TerminalLine>
{phase === 'pane-splitting' ? (
<TerminalLine muted>
<span className="h-2.5 w-1 bg-muted-foreground/40 animate-pulse" />
</TerminalLine>
) : phase === 'setup-running' ? (
<>
<TerminalLine muted>
<WorkingSpinner size="xs" reducedMotion={reducedMotion} />
<span>Installing dependencies</span>
</TerminalLine>
<TerminalLine muted className="text-[9px] text-muted-foreground/75 pl-3">
<span>pnpm-lock.yaml found</span>
</TerminalLine>
<TerminalLine muted className="text-[9px] text-muted-foreground/75 pl-3">
<span>Resolving package tree...</span>
</TerminalLine>
</>
) : (
<>
<TerminalLine muted className="text-emerald-500">
<span className="size-1.5 rounded-full bg-emerald-500 shrink-0" />
<span className="font-semibold text-emerald-500">Dependencies ready</span>
</TerminalLine>
<TerminalLine muted className="text-[9px] text-muted-foreground/75 pl-3">
<span>Done in 1.4s</span>
</TerminalLine>
</>
)}
</div>
</div>
</div>
{/* Create Worktree Modal Overlay */}
<NewWorkspaceModal
visible={modalVisible}
nameValue={modalNameValue}
nameTyping={phase === 'modal-typing'}
createHovered={createHovered}
createClicked={createClicked}
createButtonRef={createButtonRef}
/>
</div>
{/* Floating Animated Cursor */}
<div
aria-hidden
className={cn(
'pointer-events-none absolute left-0 top-0 z-50 size-5 drop-shadow-sm transition-[opacity,transform] duration-700 ease-[cubic-bezier(.45,.05,.2,1)] [&_svg]:size-5',
cursor.visible ? 'opacity-100' : 'opacity-0'
)}
style={{ transform: `translate(${cursor.x}px, ${cursor.y}px)` }}
>
<div className="relative">
<CursorIcon />
{createClicked && <FeatureWallClickRing />}
</div>
</div>
</div>
)
}
// Why: measuring targets keeps the cursor aligned as the setup card resizes.
function useMeasuredCursor(
rootRef: RefObject<HTMLDivElement | null>,
plusRef: RefObject<HTMLElement | null>,
createButtonRef: RefObject<HTMLDivElement | null>,
target: 'hidden' | 'start' | 'plus' | 'create',
reducedMotion: boolean
): { x: number; y: number; visible: boolean } {
const [pos, setPos] = useState({ x: 0, y: 0, visible: false })
useLayoutEffect(() => {
if (reducedMotion || target === 'hidden') {
setPos((current) => ({ ...current, visible: false }))
return
}
const root = rootRef.current
if (target === 'start') {
setPos({ x: 30, y: 150, visible: true })
return
}
const targetNode = target === 'plus' ? plusRef.current : createButtonRef.current
if (!root || !targetNode) {
return
}
const rootRect = root.getBoundingClientRect()
const targetRect = targetNode.getBoundingClientRect()
setPos({
x: targetRect.left - rootRect.left + targetRect.width * 0.58,
y: targetRect.top - rootRect.top + targetRect.height * 0.58,
visible: true
})
}, [createButtonRef, plusRef, reducedMotion, rootRef, target])
return pos
}
function WorkspaceListCard(props: {
title: string
active: boolean
prompt?: string
icon?: ReactNode
state: 'idle' | 'starting' | 'setup' | 'working'
reducedMotion: boolean
className?: string
}): JSX.Element {
return (
<div
className={cn(
'rounded-md border border-sidebar-border px-2 py-1.5 transition-colors duration-300',
props.active ? 'bg-sidebar-accent' : 'bg-sidebar',
props.className
)}
>
<div className="flex items-center gap-1.5">
<span
className={cn(
'size-1.5 shrink-0 rounded-full transition-colors duration-300',
props.active ? 'bg-emerald-500' : 'bg-muted-foreground/35'
)}
/>
<span className="truncate text-xs font-semibold text-sidebar-foreground">
{props.title}
</span>
</div>
{props.prompt && (
<div className="mt-1.5 grid grid-cols-[8px_14px_minmax(0,1fr)] items-center gap-1.5">
{props.state === 'working' || props.state === 'starting' || props.state === 'setup' ? (
<WorkingSpinner size="xs" reducedMotion={props.reducedMotion} />
) : (
<span className="size-1.5 rounded-full bg-muted-foreground/35" />
)}
<span className="flex size-3.5 items-center justify-center text-sidebar-foreground/65">
{props.icon}
</span>
<span className="truncate font-mono text-[10px] text-sidebar-foreground/65">
{props.state === 'setup' ? 'running setup' : props.prompt}
</span>
</div>
)}
</div>
)
}
function NewWorkspaceModal(props: {
visible: boolean
nameValue: string
nameTyping: boolean
createHovered: boolean
createClicked: boolean
createButtonRef: RefObject<HTMLDivElement | null>
}): JSX.Element {
return (
<div
className={cn(
'pointer-events-none absolute inset-0 flex items-center justify-center rounded-lg bg-background/55 backdrop-blur-[1px] transition-opacity duration-300 z-40',
props.visible ? 'opacity-100' : 'opacity-0'
)}
aria-hidden
>
<div
className={cn(
'relative w-[min(240px,92%)] rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg transition-[opacity,transform] duration-300',
props.visible
? 'translate-y-0 scale-100 opacity-100'
: 'translate-y-2 scale-[0.98] opacity-0'
)}
>
<div className="text-xs font-semibold leading-none text-foreground">Create Worktree</div>
<div className="mt-2.5 space-y-1.5">
<ModalField label="Project" value="orca" />
<ModalField label="Name" value={props.nameValue} typing={props.nameTyping} />
<ModalField label="Agent" value="Codex" />
</div>
<div
ref={props.createButtonRef}
className={cn(
'mt-3 flex h-7 w-full items-center justify-center rounded-md bg-primary px-3 text-[11px] font-medium text-primary-foreground transition-all duration-200',
props.createHovered ? 'opacity-90' : null,
props.createClicked ? 'scale-[0.98]' : null
)}
>
Create worktree
</div>
</div>
</div>
)
}
function ModalField(props: { label: string; value: string; typing?: boolean }): JSX.Element {
return (
<div className="flex items-center justify-between gap-2 rounded-md border border-border bg-muted/30 px-2 py-1 text-[11px]">
<span className="text-muted-foreground">{props.label}</span>
<div className="flex items-center font-mono font-medium text-foreground min-w-0">
<span className="truncate">{props.value}</span>
{props.typing ? (
<span className="ml-px inline-block h-2.5 w-[5px] animate-pulse bg-foreground" />
) : null}
</div>
</div>
)
}
function TerminalLine(props: {
children: ReactNode
muted?: boolean
className?: string
}): JSX.Element {
return (
<div
className={cn(
'flex min-w-0 items-center gap-1.5 truncate leading-[1.45]',
props.muted ? 'text-muted-foreground' : 'text-foreground',
props.className
)}
>
{props.children}
</div>
)
}
function Prompt(props: { children: ReactNode }): JSX.Element {
return <span className="shrink-0 text-primary">{props.children}</span>
}
@@ -0,0 +1,18 @@
import type { ReactNode } from 'react'
import { cn } from '@/lib/utils'
type SetupStepPreviewProps = {
children: ReactNode
className?: string
}
export function SetupStepPreview(props: SetupStepPreviewProps): React.JSX.Element {
return (
<div className={cn('relative', props.className)}>
<div className="pointer-events-none absolute left-3 top-3 z-20 rounded-md bg-card/85 px-1.5 py-0.5 text-xs font-semibold leading-none text-muted-foreground shadow-xs backdrop-blur-sm">
Preview
</div>
<div className="h-full [&>*]:h-full [&>*]:pt-8">{props.children}</div>
</div>
)
}
@@ -11,9 +11,7 @@ type Issue = {
}
const ISSUES: readonly Issue[] = [
{ number: 1842, title: 'Worktree picker truncates names' },
{ number: 1799, title: 'Sleep workspace keeps scrollback' },
{ number: 1721, title: 'Bulk archive in source control' }
{ number: 1842, title: 'Worktree picker truncates names' }
]
type Phase =
@@ -141,7 +139,8 @@ export function TasksAnimatedVisual(props: { reducedMotion: boolean }): JSX.Elem
timeouts.push(id)
}
function runCycle(issueIdx: number): void {
function runCycle(): void {
const issueIdx = 0
// 1. Cursor enters and travels toward the row.
setPhase({ kind: 'idle' })
setCursorTarget({ kind: 'row', issueIdx, settle: false })
@@ -186,10 +185,10 @@ export function TasksAnimatedVisual(props: { reducedMotion: boolean }): JSX.Elem
setPhase({ kind: 'idle' })
}, teardown)
schedule(() => {
runCycle((issueIdx + 1) % ISSUES.length)
runCycle()
}, teardown + RESET_MS)
}
runCycle(0)
runCycle()
return () => {
cancelled = true
timeouts.forEach((id) => window.clearTimeout(id))
@@ -2,8 +2,10 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import type { JSX } from 'react'
import { cn } from '@/lib/utils'
import { ClaudeIcon } from '../status-bar/icons'
import { useShortcutLabel } from '@/hooks/useShortcutLabel'
import { FeatureWallClickRing } from './FeatureWallClickRing'
import { CodexInlineIcon } from './feature-tour-preview-glyphs'
// Why: the right-click menu needs the same icons as the real Orca menu so the
// visual reads as the actual product, not a generic terminal mockup.
@@ -88,9 +90,11 @@ type Phase =
| { kind: 'split-active' }
type RightLine =
| { kind: 'submitted-command'; text: string }
| { kind: 'session-started' }
| { kind: 'submitted-prompt'; text: string }
| { kind: 'thinking' }
| { kind: 'agent-action'; action: string; target: string; working?: boolean }
| { kind: 'response-skeleton'; widthPct: number; withGlyph: boolean }
type CursorTarget = { kind: 'hidden' } | { kind: 'pane' } | { kind: 'split-row' }
@@ -118,27 +122,52 @@ const THINKING_MS = 1100
const RESPONSE_GAP_MS = 500
const RESPONSE_GAP_LATER_MS = 550
const FINAL_HOLD_MS = 1800
// Why: the success state of side-by-side agents needs a longer dwell time so the user can easily see both active.
const CHECKLIST_FINAL_HOLD_MS = 3800
const RUN_TICK_MS = 2400
const CLAUDE_CMD = 'claude'
const REVIEW_PROMPT = 'review src/auth for missing error handling'
const CODEX_CMD = 'codex'
const CODEX_PROMPT = 'fix failing checkout test'
const RESPONSE_WIDTHS = [72, 88, 64, 78] as const
export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.Element {
const { reducedMotion } = props
function getTwoAgentsReducedMotionLines(): readonly RightLine[] {
return [
{ kind: 'submitted-command', text: CODEX_CMD },
{ kind: 'session-started' },
{ kind: 'submitted-prompt', text: CODEX_PROMPT },
{ kind: 'agent-action', action: 'Read', target: 'checkout.test.ts' },
{ kind: 'agent-action', action: 'Grep', target: 'timeout checkout' },
{ kind: 'agent-action', action: 'Edit', target: 'src/checkout.ts', working: true }
]
}
type WorkbenchAnimatedVisualVariant = 'tour' | 'two-agents-checklist'
export function WorkbenchAnimatedVisual(props: {
reducedMotion: boolean
variant?: WorkbenchAnimatedVisualVariant
}): JSX.Element {
const { reducedMotion, variant = 'tour' } = props
const isTwoAgentsChecklist = variant === 'two-agents-checklist'
const splitRightShortcutLabel = useShortcutLabel('terminal.splitRight')
const splitDownShortcutLabel = useShortcutLabel('terminal.splitDown')
const panelRef = useRef<HTMLDivElement | null>(null)
const leftPaneRef = useRef<HTMLDivElement | null>(null)
const splitRowRef = useRef<HTMLDivElement | null>(null)
const [phase, setPhase] = useState<Phase>({ kind: 'idle' })
const [phase, setPhase] = useState<Phase>(() =>
reducedMotion && isTwoAgentsChecklist ? { kind: 'split-active' } : { kind: 'idle' }
)
const [runIdx, setRunIdx] = useState(0)
const [cursorTarget, setCursorTarget] = useState<CursorTarget>({ kind: 'hidden' })
const [rightTyped, setRightTyped] = useState('')
const [rightLines, setRightLines] = useState<readonly RightLine[]>([])
const [showInputLine, setShowInputLine] = useState(true)
const [rightLines, setRightLines] = useState<readonly RightLine[]>(() =>
reducedMotion && isTwoAgentsChecklist ? getTwoAgentsReducedMotionLines() : []
)
const [showInputLine, setShowInputLine] = useState(!(reducedMotion && isTwoAgentsChecklist))
const [promptGlyph, setPromptGlyph] = useState<'$' | '>'>('$')
const [showCaret, setShowCaret] = useState(true)
const [rippleKey, setRippleKey] = useState(0)
@@ -146,21 +175,26 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
// Cycle the running test on the left, independent of the loop, so the
// playwright run keeps moving while the user works on the right.
useEffect(() => {
if (reducedMotion) {
if (reducedMotion || isTwoAgentsChecklist) {
return
}
const id = window.setInterval(() => {
setRunIdx((i) => (i + 1) % RUN_QUEUE.length)
}, RUN_TICK_MS)
return () => window.clearInterval(id)
}, [reducedMotion])
}, [isTwoAgentsChecklist, reducedMotion])
// Main animation loop — async-ish using setTimeout chains so reduced-motion
// can short-circuit the entire effect cleanly.
useEffect(() => {
if (reducedMotion) {
setPhase({ kind: 'idle' })
setPhase(isTwoAgentsChecklist ? { kind: 'split-active' } : { kind: 'idle' })
setCursorTarget({ kind: 'hidden' })
setRightTyped('')
setRightLines(isTwoAgentsChecklist ? getTwoAgentsReducedMotionLines() : [])
setShowInputLine(!isTwoAgentsChecklist)
setPromptGlyph('$')
setShowCaret(!isTwoAgentsChecklist)
return
}
let cancelled = false
@@ -233,13 +267,14 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
return
}
// 6. User types `claude` into the new pane.
// 6. User types an agent command into the new pane.
setPhase({ kind: 'split-active' })
for (let i = 1; i <= CLAUDE_CMD.length; i += 1) {
const agentCommand = isTwoAgentsChecklist ? CODEX_CMD : CLAUDE_CMD
for (let i = 1; i <= agentCommand.length; i += 1) {
if (cancelled) {
return
}
setRightTyped(CLAUDE_CMD.slice(0, i))
setRightTyped(agentCommand.slice(0, i))
await wait(TYPE_PER_CHAR_MS)
}
await wait(POST_CLAUDE_TYPE_MS)
@@ -248,9 +283,13 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
}
// 7. Hide input line, show "session started", then bring input back
// with the Claude `>` prompt glyph.
// with the agent `>` prompt glyph.
setShowInputLine(false)
setRightLines((lines) => [...lines, { kind: 'session-started' }])
setRightLines((lines) => [
...lines,
{ kind: 'submitted-command', text: agentCommand },
{ kind: 'session-started' }
])
await wait(SESSION_HEADER_MS)
if (cancelled) {
return
@@ -263,12 +302,13 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
return
}
// 8. Type the review prompt.
for (let i = 1; i <= REVIEW_PROMPT.length; i += 1) {
// 8. Type the task prompt.
const taskPrompt = isTwoAgentsChecklist ? CODEX_PROMPT : REVIEW_PROMPT
for (let i = 1; i <= taskPrompt.length; i += 1) {
if (cancelled) {
return
}
setRightTyped(REVIEW_PROMPT.slice(0, i))
setRightTyped(taskPrompt.slice(0, i))
await wait(PROMPT_PER_CHAR_MS)
}
await wait(POST_PROMPT_TYPE_MS)
@@ -278,7 +318,7 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
// 9. Submit: collapse input into scrollback, swap to thinking spinner.
setShowCaret(false)
setRightLines((lines) => [...lines, { kind: 'submitted-prompt', text: REVIEW_PROMPT }])
setRightLines((lines) => [...lines, { kind: 'submitted-prompt', text: taskPrompt }])
setShowInputLine(false)
await wait(POST_SUBMIT_MS)
if (cancelled) {
@@ -290,6 +330,39 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
return
}
// 10. Stream concrete work for the checklist visual; keep the generic
// tour abstract so it stays about the split gesture.
if (isTwoAgentsChecklist) {
setRightLines((lines) => {
const withoutThinking = lines.filter((l) => l.kind !== 'thinking')
return [
...withoutThinking,
{ kind: 'agent-action', action: 'Read', target: 'checkout.test.ts' }
]
})
await wait(RESPONSE_GAP_MS)
if (cancelled) {
return
}
setRightLines((lines) => [
...lines,
{ kind: 'agent-action', action: 'Grep', target: 'timeout checkout' }
])
await wait(RESPONSE_GAP_LATER_MS)
if (cancelled) {
return
}
setRightLines((lines) => [
...lines,
{ kind: 'agent-action', action: 'Edit', target: 'src/checkout.ts', working: true }
])
await wait(CHECKLIST_FINAL_HOLD_MS)
if (cancelled) {
return
}
continue
}
// 10. Stream skeleton response bars — actual answer doesn't matter.
setRightLines((lines) => {
const withoutThinking = lines.filter((l) => l.kind !== 'thinking')
@@ -322,7 +395,7 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
...lines,
{ kind: 'response-skeleton', widthPct: RESPONSE_WIDTHS[3], withGlyph: false }
])
await wait(FINAL_HOLD_MS)
await wait(isTwoAgentsChecklist ? CHECKLIST_FINAL_HOLD_MS : FINAL_HOLD_MS)
if (cancelled) {
return
}
@@ -334,7 +407,7 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
cancelled = true
timeouts.forEach((id) => window.clearTimeout(id))
}
}, [reducedMotion])
}, [isTwoAgentsChecklist, reducedMotion])
const cursor = useFakeCursor(panelRef, leftPaneRef, splitRowRef, cursorTarget, reducedMotion)
@@ -345,6 +418,7 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
const splitRowActive = phase.kind === 'menu-active' || phase.kind === 'menu-click'
const showRipple = phase.kind === 'right-click' || phase.kind === 'menu-click'
const running = RUN_QUEUE[runIdx] ?? RUN_QUEUE[0]
const promptAccentClass = isTwoAgentsChecklist ? 'text-foreground' : 'text-amber-600'
return (
<div
@@ -362,34 +436,21 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
token-backed terminal chrome follows explicit and system theme changes. */}
<div
className={cn(
'grid bg-[var(--editor-surface)] font-mono text-[11px] transition-[grid-template-columns] duration-[600ms] ease-[cubic-bezier(.2,.8,.2,1)]',
'grid bg-[var(--editor-surface)] font-mono text-[11px]',
reducedMotion
? 'transition-none'
: 'transition-[grid-template-columns] duration-[600ms] ease-[cubic-bezier(.2,.8,.2,1)]',
splitOpen ? 'grid-cols-[1fr_1fr]' : 'grid-cols-[1fr_0fr]'
)}
style={{ minHeight: 230 }}
>
{/* Left pane: playwright list reporter. */}
{/* Left pane: source work that remains visible after the split. */}
<div ref={leftPaneRef} className="relative flex min-w-0 flex-col gap-1.5 px-3 py-2.5">
<TermLine>
<Prompt>$</Prompt>
<span className="text-foreground">pnpm playwright test</span>
</TermLine>
<TermLine muted>Running 12 tests using 4 workers</TermLine>
<TermLine>
<PwCheck />
<PwIdx>1</PwIdx>login.spec.ts<PwName> › can sign in</PwName>
<PwDur>(1.2s)</PwDur>
</TermLine>
<TermLine>
<PwCheck />
<PwIdx>2</PwIdx>checkout.spec.ts<PwName> › cart total updates</PwName>
<PwDur>(0.8s)</PwDur>
</TermLine>
<TermLine>
<RunSpinner />
<PwIdx>3</PwIdx>
{running.name}
<PwName> {running.desc}</PwName>
</TermLine>
{isTwoAgentsChecklist ? (
<ClaudeChecklistPane reducedMotion={reducedMotion} />
) : (
<PlaywrightPane running={running} reducedMotion={reducedMotion} />
)}
{/* Right-click context menu — theme card, skeleton bars for the
other items, real labels only for the two split actions. */}
@@ -402,15 +463,20 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
/>
</div>
{/* Right pane: empty until the split lands, then a Claude session. */}
{/* Right pane: empty until the split lands, then an agent session. */}
<div
className={cn(
'flex min-w-0 flex-col gap-1.5 overflow-hidden border-l border-border px-3 py-2.5 transition-[opacity,transform] duration-[480ms] ease-[cubic-bezier(.2,.8,.2,1)]',
reducedMotion ? 'transition-none' : null,
splitOpen ? 'opacity-100' : 'translate-x-2 opacity-0'
)}
style={{ transitionDelay: splitOpen ? '200ms' : '0ms' }}
>
<RightPaneScrollback lines={rightLines} />
<RightPaneScrollback
lines={rightLines}
isCodex={isTwoAgentsChecklist}
promptAccentClass={promptAccentClass}
/>
{showInputLine ? (
<TermLine wrap>
<Prompt claude={promptGlyph === '>'}>{promptGlyph}</Prompt>
@@ -439,16 +505,85 @@ export function WorkbenchAnimatedVisual(props: { reducedMotion: boolean }): JSX.
</div>
</div>
{/* Standalone keyboard hint stays inside the visual so the tour copy can
remain a single subheader line. */}
<div className="border-t border-border bg-card px-3 py-2 text-[11px] text-muted-foreground">
Same pane: <kbd className={KBD_CLASS}>{splitRightShortcutLabel}</kbd> splits right ·{' '}
<kbd className={KBD_CLASS}>{splitDownShortcutLabel}</kbd> splits down
</div>
{isTwoAgentsChecklist ? null : (
/* Standalone keyboard hint stays inside the visual so the tour copy can
remain a single subheader line. */
<div className="border-t border-border bg-card px-3 py-2 text-[11px] text-muted-foreground">
Same pane: <kbd className={KBD_CLASS}>{splitRightShortcutLabel}</kbd> splits right ·{' '}
<kbd className={KBD_CLASS}>{splitDownShortcutLabel}</kbd> splits down
</div>
)}
</div>
)
}
function PlaywrightPane(props: {
running: (typeof RUN_QUEUE)[number]
reducedMotion: boolean
}): JSX.Element {
return (
<>
<TermLine>
<Prompt>$</Prompt>
<span className="text-foreground">pnpm playwright test</span>
</TermLine>
<TermLine muted>Running 12 tests using 4 workers</TermLine>
<TermLine>
<PwCheck />
<PwIdx>1</PwIdx>login.spec.ts<PwName> › can sign in</PwName>
<PwDur>(1.2s)</PwDur>
</TermLine>
<TermLine>
<PwCheck />
<PwIdx>2</PwIdx>checkout.spec.ts<PwName> › cart total updates</PwName>
<PwDur>(0.8s)</PwDur>
</TermLine>
<TermLine>
<RunSpinner reducedMotion={props.reducedMotion} />
<PwIdx>3</PwIdx>
{props.running.name}
<PwName> {props.running.desc}</PwName>
</TermLine>
</>
)
}
function ClaudeChecklistPane(props: { reducedMotion: boolean }): JSX.Element {
return (
<>
<TermLine>
<Prompt>$</Prompt>
<span className="text-foreground">claude</span>
</TermLine>
<TermLine muted>
<span className="mr-1.5 inline-flex align-[-2px]">
<ClaudeIcon size={12} />
</span>
Claude Code session started
</TermLine>
<TermLine wrap>
<span className="mr-1.5 text-amber-600">&gt;</span>
review auth edge cases
</TermLine>
<TermLine>
<span className="mr-1.5 font-bold text-emerald-600">✓</span>
<span className="text-foreground">Read</span>
<span className="ml-1.5 truncate text-muted-foreground">src/auth/session.ts</span>
</TermLine>
<TermLine>
<span className="mr-1.5 font-bold text-emerald-600">✓</span>
<span className="text-foreground">Grep</span>
<span className="ml-1.5 truncate text-muted-foreground">throw src/auth</span>
</TermLine>
<TermLine>
<RunSpinner reducedMotion={props.reducedMotion} />
<span className="text-foreground">Edit</span>
<span className="ml-1.5 truncate text-muted-foreground">src/auth/session.ts</span>
</TermLine>
</>
)
}
function TermLine(props: {
children: React.ReactNode
muted?: boolean
@@ -491,9 +626,14 @@ function PwDur(props: { children: React.ReactNode }): JSX.Element {
return <span className="ml-2 text-muted-foreground">{props.children}</span>
}
function RunSpinner(): JSX.Element {
function RunSpinner(props: { reducedMotion?: boolean }): JSX.Element {
return (
<span className="mr-1.5 inline-block size-2 animate-spin rounded-full border-[1.5px] border-foreground/20 border-t-foreground align-[-1px]" />
<span
className={cn(
'mr-1.5 inline-block size-2 rounded-full border-[1.5px] border-foreground/20 align-[-1px]',
props.reducedMotion ? 'border-t-foreground/20' : 'animate-spin border-t-foreground'
)}
/>
)
}
@@ -563,21 +703,43 @@ function CtxSeparator(): JSX.Element {
return <div className="my-1 h-px bg-foreground/[0.08]" />
}
function RightPaneScrollback(props: { lines: readonly RightLine[] }): JSX.Element {
function RightPaneScrollback(props: {
lines: readonly RightLine[]
isCodex?: boolean
promptAccentClass?: string
}): JSX.Element {
return (
<>
{props.lines.map((line, i) => {
// Why: preserving the submitted command keeps the terminal view realistic after submitting.
if (line.kind === 'submitted-command') {
return (
<TermLine key={i}>
<Prompt>$</Prompt>
<span className="text-foreground">{line.text}</span>
</TermLine>
)
}
if (line.kind === 'session-started') {
return (
<TermLine key={i} muted>
<span className="mr-1.5 text-foreground">●</span>Claude Code session started
{props.isCodex ? (
<span className="mr-1.5 inline-flex align-[-2px]">
<CodexInlineIcon />
</span>
) : (
<span className="mr-1.5 text-foreground">●</span>
)}
{props.isCodex ? 'Codex session started' : 'Claude Code session started'}
</TermLine>
)
}
if (line.kind === 'submitted-prompt') {
return (
<TermLine key={i} wrap>
<span className="mr-1.5 text-amber-600">&gt;</span>
<span className={cn('mr-1.5', props.promptAccentClass ?? 'text-amber-600')}>
&gt;
</span>
{line.text}
</TermLine>
)
@@ -590,9 +752,30 @@ function RightPaneScrollback(props: { lines: readonly RightLine[] }): JSX.Elemen
</TermLine>
)
}
if (line.kind === 'agent-action') {
return (
<TermLine key={i}>
{line.working ? (
<RunSpinner />
) : (
<span className="mr-1.5 font-bold text-emerald-600">✓</span>
)}
<span className="text-foreground">{line.action}</span>
<span className="ml-1.5 truncate text-muted-foreground">{line.target}</span>
</TermLine>
)
}
return (
<TermLine key={i}>
{line.withGlyph ? <span className="mr-1.5 text-amber-600">●</span> : null}
{line.withGlyph ? (
props.isCodex ? (
<span className="mr-1.5 inline-flex align-[-2px]">
<CodexInlineIcon />
</span>
) : (
<span className="mr-1.5 text-amber-600">●</span>
)
) : null}
<span
className="inline-block h-[7px] rounded-[3px] bg-foreground/[0.18] align-[1px]"
style={{ width: `${line.widthPct}%` }}
@@ -0,0 +1,235 @@
import { useEffect, useMemo, useState } from 'react'
import type {
OnboardingFeatureSetupId,
OnboardingFeatureSetupSelection
} from '../onboarding/onboarding-feature-setup'
import {
COMPUTER_USE_SKILL_NAME,
ORCA_CLI_SKILL_NAME,
ORCHESTRATION_SKILL_NAME
} from '@/lib/agent-feature-install-commands'
import {
GLOBAL_AGENT_SKILL_SOURCE_KINDS,
useInstalledAgentSkill
} from '@/hooks/useInstalledAgentSkills'
export type AgentCapabilityInstallStatusTone = 'ready' | 'pending' | 'checking' | 'error'
export type AgentCapabilityInstallStatus = {
label: string
tone: AgentCapabilityInstallStatusTone
installed?: boolean
}
export type AgentCapabilityReadiness = {
browserUseSkillInstalled: boolean
browserUseSkillLoading: boolean
computerUseSkillInstalled: boolean
computerUseSkillLoading: boolean
computerUseReady: boolean
computerUseChecking: boolean
computerUseUnavailable: boolean
orchestrationSkillInstalled: boolean
orchestrationSkillLoading: boolean
}
export type AgentCapabilitySetupStatus = {
readiness: AgentCapabilityReadiness
installStatus: Record<OnboardingFeatureSetupId, AgentCapabilityInstallStatus>
}
export function useAgentCapabilitySetupStatus(): AgentCapabilitySetupStatus {
const browserUseSkill = useInstalledAgentSkill(ORCA_CLI_SKILL_NAME, {
sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS
})
const computerUseSkill = useInstalledAgentSkill(COMPUTER_USE_SKILL_NAME, {
sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS
})
const orchestrationSkill = useInstalledAgentSkill(ORCHESTRATION_SKILL_NAME, {
sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS
})
const computerUsePermissionStatus = useComputerUsePermissionStatus(computerUseSkill.installed)
const readiness: AgentCapabilityReadiness = useMemo(
() => ({
browserUseSkillInstalled: browserUseSkill.installed,
browserUseSkillLoading: browserUseSkill.loading,
computerUseSkillInstalled: computerUseSkill.installed,
computerUseSkillLoading: computerUseSkill.loading,
computerUseReady: computerUsePermissionStatus.ready,
computerUseChecking: computerUsePermissionStatus.checking,
computerUseUnavailable: computerUsePermissionStatus.unavailableReason !== null,
orchestrationSkillInstalled: orchestrationSkill.installed,
orchestrationSkillLoading: orchestrationSkill.loading
}),
[
browserUseSkill.installed,
browserUseSkill.loading,
computerUsePermissionStatus.checking,
computerUsePermissionStatus.ready,
computerUsePermissionStatus.unavailableReason,
computerUseSkill.installed,
computerUseSkill.loading,
orchestrationSkill.installed,
orchestrationSkill.loading
]
)
const installStatus = useMemo(
() => ({
browserUse: getSkillInstallStatus(browserUseSkill),
computerUse: getComputerUseInstallStatus(computerUseSkill, computerUsePermissionStatus),
orchestration: getSkillInstallStatus(orchestrationSkill)
}),
[browserUseSkill, computerUsePermissionStatus, computerUseSkill, orchestrationSkill]
)
return { readiness, installStatus }
}
export function getDefaultAgentCapabilitySetupSelection(
readiness: AgentCapabilityReadiness
): OnboardingFeatureSetupSelection {
return {
browserUse: !readiness.browserUseSkillInstalled,
// Why: Computer Use has OS permission setup in addition to the skill install.
// Keep it selected when permissions still need action, even if the skill exists.
computerUse:
!readiness.computerUseSkillInstalled ||
(!readiness.computerUseReady && !readiness.computerUseUnavailable),
orchestration: !readiness.orchestrationSkillInstalled
}
}
export function isAgentCapabilityReadinessChecking(readiness: AgentCapabilityReadiness): boolean {
return (
readiness.browserUseSkillLoading ||
readiness.computerUseSkillLoading ||
(readiness.computerUseSkillInstalled && readiness.computerUseChecking) ||
readiness.orchestrationSkillLoading
)
}
export function getAgentCapabilityStatusClassName(tone: AgentCapabilityInstallStatusTone): string {
switch (tone) {
case 'ready':
return 'text-green-600 dark:text-green-300'
case 'error':
return 'text-destructive'
case 'checking':
case 'pending':
return 'text-muted-foreground'
}
}
function getSkillInstallStatus(skill: {
installed: boolean
loading: boolean
error: string | null
}): AgentCapabilityInstallStatus {
if (skill.loading) {
return { label: 'Checking install', tone: 'checking' }
}
if (skill.error) {
return { label: 'Could not check install', tone: 'error' }
}
if (skill.installed) {
return { label: 'Installed', tone: 'ready', installed: true }
}
return { label: 'Click Install CLI & Skills', tone: 'pending' }
}
function getComputerUseInstallStatus(
skill: {
installed: boolean
loading: boolean
error: string | null
},
permissions: {
ready: boolean
checking: boolean
unavailableReason: string | null
}
): AgentCapabilityInstallStatus {
const skillStatus = getSkillInstallStatus(skill)
if (skillStatus.tone !== 'ready') {
return skillStatus
}
if (permissions.checking) {
return { label: 'checking app access', tone: 'checking', installed: true }
}
if (permissions.unavailableReason) {
return {
label:
permissions.unavailableReason === 'web_client'
? 'open Orca Desktop on this Mac'
: 'Unavailable in this build',
tone: 'pending',
installed: true
}
}
if (!permissions.ready) {
return {
label: 'click Install CLI & Skills to open macOS access settings',
tone: 'pending',
installed: true
}
}
return { label: 'Installed', tone: 'ready', installed: true }
}
function useComputerUsePermissionStatus(enabled: boolean): {
ready: boolean
checking: boolean
unavailableReason: string | null
} {
const [status, setStatus] = useState<{
ready: boolean
checking: boolean
unavailableReason: string | null
}>({
ready: false,
checking: enabled,
unavailableReason: null
})
useEffect(() => {
if (!enabled) {
setStatus({ ready: false, checking: false, unavailableReason: null })
return
}
let stale = false
const refresh = (): void => {
setStatus((current) => ({ ...current, checking: true }))
window.api.computerUsePermissions
.getStatus()
.then((next) => {
if (stale) {
return
}
setStatus({
ready:
next.helperUnavailableReason === null &&
next.permissions.every((permission) => permission.status !== 'not-granted'),
checking: false,
unavailableReason: next.helperUnavailableReason
})
})
.catch(() => {
if (stale) {
return
}
setStatus({ ready: false, checking: false, unavailableReason: null })
})
}
refresh()
window.addEventListener('focus', refresh)
return () => {
stale = true
window.removeEventListener('focus', refresh)
}
}, [enabled])
return status
}
@@ -35,6 +35,7 @@ const FIRST_DISPATCH_MS = ORCHESTRATION_CLI_COMMAND_TIMINGS_MS[2]
export function OrchestrationPage(props: {
active: boolean
reducedMotion: boolean
onCycleComplete?: () => void
controlledCreatedChildCount?: number
loopMs?: number
showResponseBeats?: boolean
@@ -42,6 +43,7 @@ export function OrchestrationPage(props: {
const {
active,
reducedMotion,
onCycleComplete,
controlledCreatedChildCount,
loopMs,
showResponseBeats = true
@@ -244,13 +246,14 @@ export function OrchestrationPage(props: {
later(next, FIRST_DISPATCH_MS)
}
const loop = (): void => {
runOnce(() => {
const beatCount = showResponseBeats ? PHASE1_BEATS.length : 2
const elapsedMs = FIRST_DISPATCH_MS + beatCount * BUBBLE_GAP_MS + 800
later(loop, loopMs ? Math.max(0, loopMs - elapsedMs) : 1400)
})
}
const loop = (): void => {
runOnce(() => {
onCycleComplete?.()
const beatCount = showResponseBeats ? PHASE1_BEATS.length : 2
const elapsedMs = FIRST_DISPATCH_MS + beatCount * BUBBLE_GAP_MS + 800
later(loop, loopMs ? Math.max(0, loopMs - elapsedMs) : 1400)
})
}
loop()
@@ -268,7 +271,7 @@ export function OrchestrationPage(props: {
cleanupLayer.innerHTML = ''
}
}
}, [active, reducedMotion, drawArrow, loopMs, showResponseBeats])
}, [active, onCycleComplete, reducedMotion, drawArrow, loopMs, showResponseBeats])
return (
<div
@@ -19,14 +19,21 @@ export function CodexInlineIcon(): JSX.Element {
)
}
export function WorkingSpinner({ size = 'sm' }: { size?: 'sm' | 'xs' }): JSX.Element {
export function WorkingSpinner({
size = 'sm',
reducedMotion = false
}: {
size?: 'sm' | 'xs'
reducedMotion?: boolean
}): JSX.Element {
// Why: matches AgentStateDot's working indicator so the preview teaches
// the same state language users see in the real app.
const ring = size === 'xs' ? 'size-1.5 border' : 'size-2 border-2'
return (
<span
className={cn(
'inline-block shrink-0 rounded-full border-yellow-500 border-t-transparent animate-spin',
'inline-block shrink-0 rounded-full border-yellow-500',
reducedMotion ? 'border-t-yellow-500' : 'animate-spin border-t-transparent',
ring
)}
aria-hidden
@@ -0,0 +1,282 @@
import { describe, expect, it } from 'vitest'
import type { FeatureWallSetupProgressInput } from './feature-wall-setup-progress'
import { getFeatureWallSetupProgress } from './feature-wall-setup-progress'
import {
getFeatureWallSetupSteps,
getFeatureWallSetupStepsForSection,
getFirstIncompleteFeatureWallSetupStepId
} from '../../../../shared/feature-wall-setup-steps'
import type { Worktree } from '../../../../shared/types'
function makeInput(
overrides: Partial<FeatureWallSetupProgressInput> = {}
): FeatureWallSetupProgressInput {
return {
settings: null,
featureInteractions: {},
hasConnectedTaskSource: false,
browserUseSkillInstalled: false,
computerUseSkillInstalled: false,
computerUsePermissionsReady: false,
orchestrationSkillInstalled: false,
gitRepoCount: 0,
worktreesByRepo: {},
tabsByWorktree: {},
terminalLayoutsByTabId: {},
hasSetupScript: false,
...overrides
}
}
function makeWorktree(
id: string,
options: { createdAt?: number; isMainWorktree?: boolean; path?: string | null } = {}
): Worktree {
return {
id,
path: options.path === null ? undefined : (options.path ?? `/repo/${id}`),
createdAt: options.createdAt,
isMainWorktree: options.isMainWorktree ?? false
} as unknown as Worktree
}
function makeSplitLayout(): FeatureWallSetupProgressInput['terminalLayoutsByTabId'][string] {
return {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: 'leaf-1' },
second: { type: 'leaf', leafId: 'leaf-2' }
}
} as never
}
function makeLeafLayout(): FeatureWallSetupProgressInput['terminalLayoutsByTabId'][string] {
return { root: { type: 'leaf', leafId: 'leaf-1' } } as never
}
describe('getFeatureWallSetupProgress', () => {
it('tracks Add 2 projects from durable git repo count', () => {
expect(getFeatureWallSetupProgress(makeInput({ gitRepoCount: 1 })).stepDone).toMatchObject({
'add-two-repos': false
})
const progress = getFeatureWallSetupProgress(makeInput({ gitRepoCount: 2 }))
expect(progress.stepDone['add-two-repos']).toBe(true)
expect(progress.coreTotal).toBe(8)
})
it('orders visible parallel work before setup tasks', () => {
expect(getFeatureWallSetupSteps().map((step) => step.id)).toEqual([
'split-terminal',
'two-worktrees',
'notifications',
'default-agent',
'task-sources',
'setup-script',
'add-two-repos',
'agent-capabilities'
])
})
it('groups setup guide steps into Parallel work and Setup sections', () => {
expect(getFeatureWallSetupStepsForSection('parallel-work').map((step) => step.id)).toEqual([
'split-terminal',
'two-worktrees'
])
expect(getFeatureWallSetupStepsForSection('setup').map((step) => step.id)).toEqual([
'notifications',
'default-agent',
'task-sources',
'setup-script',
'add-two-repos',
'agent-capabilities'
])
})
it('auto-selects incomplete parallel work before setup steps', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
settings: {
defaultTuiAgent: 'claude',
notifications: { enabled: true, agentTaskComplete: true }
} as never,
hasConnectedTaskSource: true,
hasSetupScript: true,
gitRepoCount: 2,
browserUseSkillInstalled: true,
computerUseSkillInstalled: true,
computerUsePermissionsReady: true,
orchestrationSkillInstalled: true
})
)
expect(getFirstIncompleteFeatureWallSetupStepId(progress.stepDone)).toBe('split-terminal')
})
it('does not mark the step complete from split-pane interaction count alone', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
featureInteractions: {
'terminal-pane-split': { firstInteractedAt: 1_700_000_000_000, interactionCount: 1 }
}
})
)
expect(progress.stepDone['split-terminal']).toBe(false)
})
it('does not mark the step complete when a worktree tab has only a single pane', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
worktreesByRepo: { 'repo-1': [makeWorktree('worktree-1')] },
tabsByWorktree: {
'worktree-1': [{ id: 'tab-1', title: 'Terminal' }] as never
},
terminalLayoutsByTabId: { 'tab-1': makeLeafLayout() }
})
)
expect(progress.stepDone['split-terminal']).toBe(false)
})
it('marks the step complete once a worktree terminal is split into two panes', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
worktreesByRepo: { 'repo-1': [makeWorktree('worktree-1')] },
tabsByWorktree: {
'worktree-1': [{ id: 'tab-1', title: 'Terminal' }] as never
},
terminalLayoutsByTabId: { 'tab-1': makeSplitLayout() }
})
)
expect(progress.stepDone['split-terminal']).toBe(true)
})
it('ignores split layouts for tabs that do not belong to a known worktree', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
worktreesByRepo: { 'repo-1': [makeWorktree('worktree-1')] },
tabsByWorktree: {
'worktree-1': [{ id: 'tab-1', title: 'Terminal' }] as never
},
terminalLayoutsByTabId: { 'orphan-tab': makeSplitLayout() }
})
)
expect(progress.stepDone['split-terminal']).toBe(false)
})
it('does not mark the step complete from the main checkout alone', () => {
expect(
getFeatureWallSetupProgress(
makeInput({
worktreesByRepo: { 'repo-1': [makeWorktree('main', { isMainWorktree: true })] }
})
).stepDone['two-worktrees']
).toBe(false)
})
it('does not pre-complete the step when two repos contribute only main checkouts', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
worktreesByRepo: {
'repo-1': [makeWorktree('main-1', { isMainWorktree: true })],
'repo-2': [makeWorktree('main-2', { isMainWorktree: true })]
}
})
)
expect(progress.stepDone['two-worktrees']).toBe(false)
})
it('does not mark the step complete from an unconfirmed non-main worktree placeholder', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
worktreesByRepo: {
'repo-1': [
makeWorktree('main', { isMainWorktree: true }),
makeWorktree('ssh-restored-placeholder', { path: null })
]
}
})
)
expect(progress.stepDone['two-worktrees']).toBe(false)
})
it('marks the step complete once a non-main worktree exists beyond the main checkout', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
worktreesByRepo: {
'repo-1': [makeWorktree('main', { isMainWorktree: true }), makeWorktree('worktree-1')]
}
})
)
expect(progress.stepDone['two-worktrees']).toBe(true)
})
it('marks task sources complete for any supported connected provider', () => {
const progress = getFeatureWallSetupProgress(makeInput({ hasConnectedTaskSource: true }))
expect(progress.stepDone['task-sources']).toBe(true)
})
it('does not mark agent capabilities complete from setup-start interactions alone', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
featureInteractions: {
'agent-browser-setup': { firstInteractedAt: 1_700_000_000_000, interactionCount: 1 },
'computer-use-setup': { firstInteractedAt: 1_700_000_000_001, interactionCount: 1 },
'agent-orchestration-setup': {
firstInteractedAt: 1_700_000_000_002,
interactionCount: 1
}
}
})
)
expect(progress.stepDone['agent-capabilities']).toBe(false)
})
it('marks agent capabilities complete only when required skills and permissions are ready', () => {
expect(
getFeatureWallSetupProgress(
makeInput({
browserUseSkillInstalled: true,
computerUseSkillInstalled: true,
computerUsePermissionsReady: false,
orchestrationSkillInstalled: true
})
).stepDone['agent-capabilities']
).toBe(false)
const progress = getFeatureWallSetupProgress(
makeInput({
browserUseSkillInstalled: true,
computerUseSkillInstalled: true,
computerUsePermissionsReady: true,
orchestrationSkillInstalled: true
})
)
expect(progress.stepDone['agent-capabilities']).toBe(true)
})
it('does not block agent capabilities on unavailable Computer Use access', () => {
const progress = getFeatureWallSetupProgress(
makeInput({
browserUseSkillInstalled: true,
computerUseSkillInstalled: true,
computerUsePermissionsReady: false,
computerUseUnavailable: true,
orchestrationSkillInstalled: true
})
)
expect(progress.stepDone['agent-capabilities']).toBe(true)
})
})
@@ -0,0 +1,99 @@
import type { FeatureInteractionState } from '../../../../shared/feature-interactions'
import {
FEATURE_WALL_SETUP_STEPS,
type FeatureWallSetupStepId
} from '../../../../shared/feature-wall-setup-steps'
import type {
GlobalSettings,
TerminalLayoutSnapshot,
TerminalPaneLayoutNode,
TerminalTab,
Worktree
} from '../../../../shared/types'
export type FeatureWallSetupProgressInput = {
settings: GlobalSettings | null
featureInteractions: FeatureInteractionState
hasConnectedTaskSource: boolean
browserUseSkillInstalled: boolean
computerUseSkillInstalled: boolean
computerUsePermissionsReady: boolean
computerUseUnavailable?: boolean
orchestrationSkillInstalled: boolean
gitRepoCount: number
worktreesByRepo: Record<string, Worktree[]>
tabsByWorktree: Record<string, TerminalTab[]>
terminalLayoutsByTabId: Record<string, TerminalLayoutSnapshot>
hasSetupScript: boolean
}
export type FeatureWallSetupProgress = {
stepDone: Record<FeatureWallSetupStepId, boolean>
coreDoneCount: number
coreTotal: number
}
function isSplitLayout(node: TerminalPaneLayoutNode | null | undefined): boolean {
// A split node means the tab holds 2+ panes, regardless of what runs in them.
return Boolean(node) && node!.type === 'split'
}
function hasSplitTerminalInAnyWorktree(input: FeatureWallSetupProgressInput): boolean {
const validWorktreeIds = new Set(
Object.values(input.worktreesByRepo)
.flat()
.map((worktree) => worktree.id)
)
for (const [worktreeId, tabs] of Object.entries(input.tabsByWorktree)) {
if (!validWorktreeIds.has(worktreeId)) {
continue
}
for (const tab of tabs) {
if (isSplitLayout(input.terminalLayoutsByTabId[tab.id]?.root)) {
return true
}
}
}
return false
}
function countAvailableNonMainWorktrees(worktreesByRepo: Record<string, Worktree[]>): number {
// Why: imported git worktrees count as real parallel-work capacity, but
// partially hydrated placeholders can appear before a worktree path is known.
return Object.values(worktreesByRepo).reduce(
(sum, worktrees) =>
sum +
worktrees.filter(
(worktree) => !worktree.isMainWorktree && typeof worktree.path === 'string' && worktree.path
).length,
0
)
}
export function getFeatureWallSetupProgress(
input: FeatureWallSetupProgressInput
): FeatureWallSetupProgress {
const agentCapabilitiesDone =
input.browserUseSkillInstalled &&
input.computerUseSkillInstalled &&
(input.computerUsePermissionsReady || input.computerUseUnavailable === true) &&
input.orchestrationSkillInstalled
const stepDone: Record<FeatureWallSetupStepId, boolean> = {
'default-agent':
Boolean(input.settings?.defaultTuiAgent) && input.settings?.defaultTuiAgent !== 'blank',
'add-two-repos': input.gitRepoCount >= 2,
notifications:
input.settings?.notifications.enabled === true &&
input.settings.notifications.agentTaskComplete === true,
'split-terminal': hasSplitTerminalInAnyWorktree(input),
'two-worktrees': countAvailableNonMainWorktrees(input.worktreesByRepo) >= 1,
'task-sources': input.hasConnectedTaskSource,
'agent-capabilities': agentCapabilitiesDone,
'setup-script': input.hasSetupScript
}
return {
stepDone,
coreDoneCount: FEATURE_WALL_SETUP_STEPS.filter((step) => stepDone[step.id]).length,
coreTotal: FEATURE_WALL_SETUP_STEPS.length
}
}
@@ -45,6 +45,7 @@ export function useFeatureWallTaskSourcePresentation(
const hasConnectedTaskSource =
(preflightStatus?.gh.installed === true && preflightStatus.gh.authenticated === true) ||
(preflightStatus?.glab?.installed === true && preflightStatus.glab.authenticated === true) ||
linearStatus.connected === true
const isCheckingTaskSources =
preflightStatusLoading || !preflightStatusChecked || !linearStatusChecked
@@ -1,5 +1,6 @@
import { useCallback, useMemo, useRef, type KeyboardEvent } from 'react'
import { track } from '@/lib/telemetry'
import { notifyInstalledAgentSkillsChanged } from '@/hooks/useInstalledAgentSkills'
import { OnboardingInlineCommandTerminal } from './OnboardingInlineCommandTerminal'
import {
onboardingFeatureSetupTelemetrySelection,
@@ -63,6 +64,7 @@ export function FeatureSetupInlineTerminal({
autoScrollIntoView={false}
onOpened={trackTerminalOpened}
onInteracted={trackTerminalInteraction}
onTerminalExit={notifyInstalledAgentSkillsChanged}
/>
)
}
@@ -26,6 +26,7 @@ type OnboardingInlineCommandTerminalProps = {
shellOverride?: string
onOpened?: () => void
onInteracted?: (method: 'keyboard' | 'pointer', event?: KeyboardEvent<HTMLElement>) => void
onTerminalExit?: () => void
}
export function OnboardingInlineCommandTerminal({
@@ -40,7 +41,8 @@ export function OnboardingInlineCommandTerminal({
worktreeId = ONBOARDING_INLINE_TERMINAL_WORKTREE_ID,
shellOverride,
onOpened,
onInteracted
onInteracted,
onTerminalExit
}: OnboardingInlineCommandTerminalProps): React.JSX.Element {
const createTab = useAppStore((s) => s.createTab)
const closeTab = useAppStore((s) => s.closeTab)
@@ -280,7 +282,10 @@ export function OnboardingInlineCommandTerminal({
cwd={cwd}
isActive
isVisible
onPtyExit={() => closeTab(tabId, { recordInteraction: false })}
onPtyExit={() => {
onTerminalExit?.()
closeTab(tabId, { recordInteraction: false })
}}
onCloseTab={() => closeTab(tabId, { recordInteraction: false })}
/>
) : (
@@ -569,7 +569,7 @@ export function useOnboardingFlow(
})
if (isGit) {
openModal('project-added', {
projectId,
repoId: projectId,
defaultWorktreeName: 'orca-worktree-1',
telemetrySource: 'onboarding'
})
@@ -6,6 +6,7 @@ import {
import { ORCHESTRATION_SKILL_INSTALL_COMMAND } from '@/lib/orchestration-install-command'
import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills'
import { AgentSkillSetupPanel } from './AgentSkillSetupPanel'
import { useAppStore } from '@/store'
export function OrchestrationSetupCard(props: {
compact?: boolean
@@ -29,6 +30,7 @@ export function OrchestrationSetupCard(props: {
terminalHeightPx={terminalHeightPx}
preInstallNotice={AGENT_SKILL_CLI_PREREQUISITE_NOTICE}
onBeforeOpenTerminal={async () => {
useAppStore.getState().recordFeatureInteraction('agent-orchestration-setup')
await ensureOrcaCliAvailableForAgentSkillTerminal()
}}
showRecheckWhenInstalled={false}
@@ -45,6 +45,7 @@ import { MobileSettingsPane } from './MobileSettingsPane'
import { RuntimeEnvironmentsPane } from './RuntimeEnvironmentsPane'
import { PrivacyPane } from './PrivacyPane'
import { SettingsSidebar } from './SettingsSidebar'
import { SettingsSetupGuideCard } from './SettingsSetupGuideCard'
import { ActiveSettingsSectionProvider, SettingsSection } from './SettingsSection'
import { matchesSettingsSearch } from './settings-search'
import { cn } from '@/lib/utils'
@@ -806,6 +807,8 @@ function Settings(): React.JSX.Element {
</div>
) : (
<ActiveSettingsSectionProvider value={activeSectionId}>
{settingsSearchQuery.trim() === '' ? <SettingsSetupGuideCard /> : null}
<SettingsSection
id="agents"
title="Agents"
@@ -0,0 +1,87 @@
import { ArrowRight, ListChecks } from 'lucide-react'
import { useMemo } from 'react'
import {
getFeatureWallSetupSteps,
getFirstIncompleteFeatureWallSetupStepId
} from '../../../../shared/feature-wall-setup-steps'
import type { FeatureWallSetupStepId } from '../../../../shared/feature-wall-setup-steps'
import { useAppStore } from '@/store'
import { Button } from '../ui/button'
import { useSetupGuideProgress } from '../setup-guide/use-setup-guide-progress'
export function SettingsSetupGuideCard(): React.JSX.Element | null {
const openModal = useAppStore((s) => s.openModal)
const progress = useSetupGuideProgress(true, false, false)
const setupSteps = useMemo(() => getFeatureWallSetupSteps(), [])
const unfinishedSteps = useMemo(
() => setupSteps.filter((step) => !progress.stepDone[step.id]),
[progress.stepDone, setupSteps]
)
const completedStepCount = useMemo(
() => setupSteps.filter((step) => progress.stepDone[step.id]).length,
[progress.stepDone, setupSteps]
)
const firstUnfinishedStepId: FeatureWallSetupStepId = getFirstIncompleteFeatureWallSetupStepId(
progress.stepDone
)
const setupComplete = unfinishedSteps.length === 0
return (
<section className="rounded-xl border border-border/60 bg-card/50 px-5 py-4">
<div className="flex items-start justify-between gap-5">
<div className="flex min-w-0 items-start gap-3">
<span className="flex size-9 shrink-0 items-center justify-center rounded-md border border-border bg-background text-muted-foreground">
<ListChecks className="size-4" />
</span>
<div className="min-w-0 space-y-3">
<div className="space-y-1">
<h2 className="text-base font-semibold leading-tight text-foreground">
Getting started with Orca
</h2>
<p className="text-sm text-muted-foreground">
{completedStepCount}/{setupSteps.length} setup tasks complete
</p>
</div>
<div className="space-y-2">
<p className="text-[11px] font-medium uppercase tracking-[0.12em] text-muted-foreground">
{setupComplete ? 'Status' : 'To do'}
</p>
<div className="flex flex-wrap gap-2">
{setupComplete ? (
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-xs text-muted-foreground">
All core workflows complete
</span>
) : (
<>
{unfinishedSteps.slice(0, 3).map((step) => (
<span
key={step.id}
className="rounded-full border border-border bg-background px-2.5 py-1 text-xs text-muted-foreground"
>
{step.name}
</span>
))}
{unfinishedSteps.length > 3 ? (
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-xs text-muted-foreground">
+{unfinishedSteps.length - 3} more
</span>
) : null}
</>
)}
</div>
</div>
</div>
</div>
<Button
type="button"
size="sm"
className="w-fit shrink-0 whitespace-nowrap gap-1.5"
onClick={() => openModal('setup-guide', { setupStepId: firstUnfinishedStepId })}
>
{setupComplete ? 'Review setup' : 'Continue setup'}
<ArrowRight className="size-4" />
</Button>
</div>
</section>
)
}
@@ -0,0 +1,127 @@
import { useEffect, useMemo, useState, type JSX } from 'react'
import {
FEATURE_WALL_SETUP_STEP_IDS,
getFirstIncompleteFeatureWallSetupStepId,
getFeatureWallSetupSteps
} from '../../../../shared/feature-wall-setup-steps'
import type { FeatureWallSetupStepId } from '../../../../shared/feature-wall-setup-steps'
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import { useAppStore } from '@/store'
import { FeatureWallSetupChecklist } from '../feature-wall/FeatureWallSetupChecklist'
import { useSetupGuideProgress } from './use-setup-guide-progress'
export default function SetupGuideModal(): JSX.Element | null {
const activeModal = useAppStore((s) => s.activeModal)
const modalData = useAppStore((s) => s.modalData)
const closeModal = useAppStore((s) => s.closeModal)
const isOpen = activeModal === 'setup-guide'
const setupSteps = useMemo(() => getFeatureWallSetupSteps(), [])
const [activeStepId, setActiveStepId] = useState<FeatureWallSetupStepId>(
() => setupSteps[0]?.id ?? 'default-agent'
)
const [userSelectedStep, setUserSelectedStep] = useState(false)
const [orchestrationSkillInstalled, setOrchestrationSkillInstalled] = useState(false)
const [browserUseSkillInstalled, setBrowserUseSkillInstalled] = useState(false)
const progress = useSetupGuideProgress(
isOpen,
orchestrationSkillInstalled,
browserUseSkillInstalled
)
const requestedStepId = isFeatureWallSetupStepId(modalData.setupStepId)
? modalData.setupStepId
: null
const activeStep = setupSteps.find((step) => step.id === activeStepId) ?? setupSteps[0] ?? null
useEffect(() => {
if (!isOpen) {
setUserSelectedStep(false)
return
}
if (requestedStepId === null) {
return
}
setUserSelectedStep(false)
setActiveStepId(requestedStepId)
}, [isOpen, requestedStepId])
useEffect(() => {
if (!isOpen || userSelectedStep || requestedStepId !== null) {
return
}
setActiveStepId(getFirstIncompleteFeatureWallSetupStepId(progress.stepDone))
}, [isOpen, progress.stepDone, requestedStepId, userSelectedStep])
useEffect(() => {
if (
!isOpen ||
userSelectedStep ||
requestedStepId === null ||
activeStep?.id !== requestedStepId ||
!progress.stepDone[activeStep.id]
) {
return
}
const nextUnfinishedCoreStepId = getFirstIncompleteFeatureWallSetupStepId(progress.stepDone)
if (nextUnfinishedCoreStepId !== activeStep.id) {
setActiveStepId(nextUnfinishedCoreStepId)
}
}, [activeStep, isOpen, progress.stepDone, requestedStepId, userSelectedStep])
const handleSelectStep = (id: FeatureWallSetupStepId): void => {
setUserSelectedStep(true)
setActiveStepId(id)
}
const handleOpenChange = (open: boolean): void => {
if (!open) {
closeModal()
}
}
if (!isOpen) {
return null
}
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogContent
className="grid h-[min(780px,calc(100vh-2rem))] w-[min(1080px,calc(100vw-2rem))] max-w-none grid-rows-[auto_minmax(0,1fr)] gap-0 p-0 sm:max-w-none"
tabIndex={-1}
>
<DialogHeader className="gap-1 border-b border-border px-7 py-4">
<div className="flex items-center justify-between gap-4">
<DialogTitle className="text-lg">Getting started</DialogTitle>
<span className="mr-7 font-mono text-xs text-muted-foreground">
{progress.coreDoneCount}/{progress.coreTotal}
</span>
</div>
<DialogDescription className="text-sm text-muted-foreground">
Finish the core workflows that make Orca useful for parallel agent work.
</DialogDescription>
</DialogHeader>
<div className="scrollbar-sleek min-h-0 overflow-y-auto px-7 py-6">
<FeatureWallSetupChecklist
activeStep={activeStep}
progress={progress}
onSelectStep={handleSelectStep}
onOrchestrationSkillInstalledChange={setOrchestrationSkillInstalled}
onBrowserUseSkillInstalledChange={setBrowserUseSkillInstalled}
/>
</div>
</DialogContent>
</Dialog>
)
}
function isFeatureWallSetupStepId(value: unknown): value is FeatureWallSetupStepId {
return (
typeof value === 'string' &&
FEATURE_WALL_SETUP_STEP_IDS.includes(value as FeatureWallSetupStepId)
)
}
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest'
import { getComputerUsePermissionSetupState } from './use-setup-guide-progress'
describe('getComputerUsePermissionSetupState', () => {
it('does not treat a failed status read as unavailable setup completion', () => {
expect(getComputerUsePermissionSetupState(null)).toEqual({
ready: false,
unavailable: false
})
})
it('marks Computer Use ready only when permissions are granted and helper is available', () => {
expect(
getComputerUsePermissionSetupState({
platform: 'darwin',
helperAppPath: '/Applications/Orca Helper.app',
helperUnavailableReason: null,
permissions: [
{ id: 'accessibility', status: 'granted' },
{ id: 'screenshots', status: 'granted' }
]
})
).toEqual({ ready: true, unavailable: false })
})
it('marks Computer Use unavailable only for explicit helper unavailability', () => {
expect(
getComputerUsePermissionSetupState({
platform: 'linux',
helperAppPath: null,
helperUnavailableReason: 'unsupported-platform',
permissions: []
})
).toEqual({ ready: false, unavailable: true })
})
})
@@ -0,0 +1,206 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useAppStore } from '@/store'
import { isGitRepoKind } from '../../../../shared/repo-kind'
import { checkRuntimeHooks } from '@/runtime/runtime-hooks-client'
import { hasEffectiveSetupCommand } from '@/lib/setup-script-status'
import {
COMPUTER_USE_SKILL_NAME,
ORCA_CLI_SKILL_NAME,
ORCHESTRATION_SKILL_NAME
} from '@/lib/agent-feature-install-commands'
import {
GLOBAL_AGENT_SKILL_SOURCE_KINDS,
useInstalledAgentSkill
} from '@/hooks/useInstalledAgentSkills'
import {
getFeatureWallSetupProgress,
type FeatureWallSetupProgress
} from '../feature-wall/feature-wall-setup-progress'
import type { ComputerUsePermissionStatusResult } from '../../../../shared/computer-use-permissions-types'
export function getComputerUsePermissionSetupState(
status: ComputerUsePermissionStatusResult | null
): { ready: boolean; unavailable: boolean } {
return {
ready:
status !== null &&
status.helperUnavailableReason === null &&
status.permissions.every((permission) => permission.status !== 'not-granted'),
unavailable: status !== null && status.helperUnavailableReason !== null
}
}
export function useSetupGuideProgress(
shouldRefreshCoreState: boolean,
orchestrationSkillInstalled: boolean,
browserUseSkillInstalled: boolean
): FeatureWallSetupProgress {
const settings = useAppStore((s) => s.settings)
const featureInteractions = useAppStore((s) => s.featureInteractions)
const worktreesByRepo = useAppStore((s) => s.worktreesByRepo)
const tabsByWorktree = useAppStore((s) => s.tabsByWorktree)
const terminalLayoutsByTabId = useAppStore((s) => s.terminalLayoutsByTabId)
const preflightStatus = useAppStore((s) => s.preflightStatus)
const preflightStatusChecked = useAppStore((s) => s.preflightStatusChecked)
const refreshPreflightStatus = useAppStore((s) => s.refreshPreflightStatus)
const linearStatus = useAppStore((s) => s.linearStatus)
const linearStatusChecked = useAppStore((s) => s.linearStatusChecked)
const checkLinearConnection = useAppStore((s) => s.checkLinearConnection)
const repos = useAppStore((s) => s.repos)
const activeRepoId = useAppStore((s) => s.activeRepoId)
const [hasSetupScript, setHasSetupScript] = useState(false)
const [computerUsePermissionsReady, setComputerUsePermissionsReady] = useState(false)
const [computerUseUnavailable, setComputerUseUnavailable] = useState(false)
const { installed: detectedBrowserUseSkillInstalled } = useInstalledAgentSkill(
ORCA_CLI_SKILL_NAME,
{
enabled: shouldRefreshCoreState,
sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS
}
)
const { installed: computerUseSkillInstalled } = useInstalledAgentSkill(COMPUTER_USE_SKILL_NAME, {
enabled: shouldRefreshCoreState,
sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS
})
const { installed: detectedOrchestrationSkillInstalled } = useInstalledAgentSkill(
ORCHESTRATION_SKILL_NAME,
{
enabled: shouldRefreshCoreState,
sourceKinds: GLOBAL_AGENT_SKILL_SOURCE_KINDS
}
)
useEffect(() => {
if (!shouldRefreshCoreState) {
return
}
if (!preflightStatusChecked) {
void refreshPreflightStatus()
}
if (!linearStatusChecked) {
void checkLinearConnection()
}
}, [
checkLinearConnection,
linearStatusChecked,
preflightStatusChecked,
refreshPreflightStatus,
shouldRefreshCoreState
])
useEffect(() => {
if (!shouldRefreshCoreState || !settings) {
return
}
let stale = false
const gitRepos = repos.filter(isGitRepoKind)
const activeRepo = activeRepoId
? (gitRepos.find((repo) => repo.id === activeRepoId) ?? null)
: null
const orderedRepos = activeRepo
? [activeRepo, ...gitRepos.filter((repo) => repo.id !== activeRepo.id)]
: gitRepos
async function refreshSetupScriptState(): Promise<void> {
for (const repo of orderedRepos) {
const hooksResult = await checkRuntimeHooks(settings, repo.id).catch(() => null)
if (stale) {
return
}
if (hooksResult && hasEffectiveSetupCommand(repo, hooksResult)) {
setHasSetupScript(true)
return
}
}
setHasSetupScript(false)
}
void refreshSetupScriptState()
return () => {
stale = true
}
}, [activeRepoId, repos, settings, shouldRefreshCoreState])
const readComputerUsePermissions = useCallback(async (isStale: () => boolean): Promise<void> => {
const status = await window.api.computerUsePermissions.getStatus().catch(() => null)
if (isStale()) {
return
}
const permissionState = getComputerUsePermissionSetupState(status)
setComputerUsePermissionsReady(permissionState.ready)
setComputerUseUnavailable(permissionState.unavailable)
}, [])
useEffect(() => {
if (!shouldRefreshCoreState || !computerUseSkillInstalled) {
setComputerUsePermissionsReady(false)
setComputerUseUnavailable(false)
return
}
let stale = false
const refreshComputerUsePermissions = (): void => {
void readComputerUsePermissions(() => stale)
}
refreshComputerUsePermissions()
const handleFocus = (): void => {
void refreshComputerUsePermissions()
}
const handleVisibilityChange = (): void => {
if (document.visibilityState === 'visible') {
void refreshComputerUsePermissions()
}
}
// Why: users grant Computer Use permissions outside the setup guide. Refresh
// on return so the checklist updates without requiring a remount.
window.addEventListener('focus', handleFocus)
document.addEventListener('visibilitychange', handleVisibilityChange)
return () => {
stale = true
window.removeEventListener('focus', handleFocus)
document.removeEventListener('visibilitychange', handleVisibilityChange)
}
}, [computerUseSkillInstalled, readComputerUsePermissions, shouldRefreshCoreState])
const hasConnectedTaskSource =
(preflightStatus?.gh.installed === true && preflightStatus.gh.authenticated === true) ||
(preflightStatus?.glab?.installed === true && preflightStatus.glab.authenticated === true) ||
linearStatus.connected === true
const gitRepoCount = useMemo(() => repos.filter(isGitRepoKind).length, [repos])
return useMemo(
() =>
getFeatureWallSetupProgress({
settings,
featureInteractions,
hasConnectedTaskSource,
browserUseSkillInstalled: browserUseSkillInstalled || detectedBrowserUseSkillInstalled,
computerUseSkillInstalled,
computerUsePermissionsReady,
computerUseUnavailable,
orchestrationSkillInstalled:
orchestrationSkillInstalled || detectedOrchestrationSkillInstalled,
gitRepoCount,
worktreesByRepo,
tabsByWorktree,
terminalLayoutsByTabId,
hasSetupScript
}),
[
browserUseSkillInstalled,
computerUseUnavailable,
computerUsePermissionsReady,
computerUseSkillInstalled,
detectedBrowserUseSkillInstalled,
detectedOrchestrationSkillInstalled,
featureInteractions,
terminalLayoutsByTabId,
gitRepoCount,
hasConnectedTaskSource,
hasSetupScript,
orchestrationSkillInstalled,
settings,
tabsByWorktree,
worktreesByRepo
]
)
}
@@ -121,6 +121,16 @@ describe('ProjectAddedDialog', () => {
expect(markup).toContain('setup:orca:main')
})
it('renders when older onboarding modal data uses projectId', async () => {
mocks.state.modalData = { projectId: 'repo-1' }
const { default: ProjectAddedDialog } = await import('./ProjectAddedDialog')
const markup = renderToStaticMarkup(<ProjectAddedDialog />)
expect(markup).toContain('setup:orca')
expect(mocks.state.closeModal).not.toHaveBeenCalled()
})
it('closes without rendering Git setup for folder repos', async () => {
mocks.state.repos = [makeRepo({ kind: 'folder' })]
const { default: ProjectAddedDialog } = await import('./ProjectAddedDialog')
@@ -12,6 +12,7 @@ import {
type ProjectAddedModalData = {
repoId?: string
projectId?: string
defaultWorktreeName?: string
telemetrySource?: WorkspaceCreateTelemetrySource
}
@@ -30,7 +31,14 @@ export default function ProjectAddedDialog(): React.JSX.Element | null {
const worktreesByRepo = useAppStore((s) => s.worktreesByRepo)
const setHideDefaultBranchWorkspace = useAppStore((s) => s.setHideDefaultBranchWorkspace)
const repoId = typeof modalData?.repoId === 'string' ? modalData.repoId : ''
// Why: older onboarding builds wrote `projectId`; accepting both prevents an
// invisible project-added modal from blocking follow-up contextual tours.
const repoId =
typeof modalData?.repoId === 'string'
? modalData.repoId
: typeof modalData?.projectId === 'string'
? modalData.projectId
: ''
const repo = repos.find((candidate) => candidate.id === repoId) ?? null
const isFolder = repo ? isFolderRepo(repo) : false
const detected = repoId ? detectedWorktreesByRepo[repoId] : undefined
@@ -0,0 +1,89 @@
import React from 'react'
import { ListChecks, X } from 'lucide-react'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import { useAppStore } from '@/store'
import {
FEATURE_WALL_SETUP_PARALLEL_WORK_STEP_IDS,
getFirstIncompleteFeatureWallSetupStepId,
type FeatureWallSetupStepId
} from '../../../../shared/feature-wall-setup-steps'
import { useSetupGuideProgress } from '../setup-guide/use-setup-guide-progress'
export function shouldShowSetupGuideEntry(setupComplete: boolean, dismissed: boolean): boolean {
return !setupComplete && !dismissed
}
export function SetupGuideSidebarEntry(): React.JSX.Element | null {
const openModal = useAppStore((s) => s.openModal)
const activeModal = useAppStore((s) => s.activeModal)
const setupGuideSidebarDismissed = useAppStore((s) => s.setupGuideSidebarDismissed)
const setSetupGuideSidebarDismissed = useAppStore((s) => s.setSetupGuideSidebarDismissed)
// Why: the sidebar count must be warmed before click so it matches the modal
// count instead of changing while the lazy modal is mounting.
const setupProgress = useSetupGuideProgress(true, false, false)
const setupComplete = setupProgress.coreDoneCount >= setupProgress.coreTotal
const setupActive = activeModal === 'setup-guide'
const firstUnfinishedSetupStepId = React.useMemo<FeatureWallSetupStepId>(
() => getFirstIncompleteFeatureWallSetupStepId(setupProgress.stepDone),
[setupProgress.stepDone]
)
const hasIncompleteParallelWork = FEATURE_WALL_SETUP_PARALLEL_WORK_STEP_IDS.some(
(id) => !setupProgress.stepDone[id]
)
const showSetupGuideEntry = shouldShowSetupGuideEntry(setupComplete, setupGuideSidebarDismissed)
const handleHideSetupGuide = React.useCallback(() => {
setSetupGuideSidebarDismissed(true)
toast('see it anytime from the help menu')
}, [setSetupGuideSidebarDismissed])
if (!showSetupGuideEntry) {
return null
}
return (
<div
data-contextual-tour-target="setup-guide-entry"
className={cn(
'group/setup-guide relative rounded-md border border-sidebar-border transition-colors',
setupActive
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-ring'
: 'bg-sidebar-accent/60 text-sidebar-foreground hover:bg-sidebar-accent'
)}
>
<button
type="button"
onClick={() => openModal('setup-guide', { setupStepId: firstUnfinishedSetupStepId })}
aria-current={setupActive ? 'page' : undefined}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] font-medium tracking-tight"
>
<ListChecks
className={cn(
'size-4 shrink-0',
setupActive ? 'text-sidebar-accent-foreground' : 'text-sidebar-foreground/70'
)}
strokeWidth={setupActive ? 2.25 : 1.75}
/>
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">Getting started with Orca</span>
{hasIncompleteParallelWork ? (
<span className="truncate text-[11px] font-normal leading-3 text-muted-foreground">
See what Orca can do
</span>
) : null}
</span>
<span className="font-mono text-[11px] text-muted-foreground">
{setupProgress.coreDoneCount}/{setupProgress.coreTotal}
</span>
</button>
<button
type="button"
aria-label="Hide Getting started with Orca"
onClick={handleHideSetupGuide}
className="pointer-events-none absolute -right-1 -top-1 flex size-4 items-center justify-center rounded-full border border-sidebar-border bg-sidebar text-sidebar-foreground/60 opacity-0 shadow-xs transition-colors transition-opacity group-hover/setup-guide:pointer-events-auto group-hover/setup-guide:opacity-100 group-focus-within/setup-guide:pointer-events-auto group-focus-within/setup-guide:opacity-100 hover:bg-sidebar-accent hover:text-sidebar-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-sidebar-ring"
>
<X className="size-2.5" aria-hidden />
</button>
</div>
)
}
@@ -6,6 +6,7 @@ import type { Repo } from '../../../../shared/types'
type ButtonCapture = {
label: string
ariaLabel?: string
dataContextualTourTarget?: string
size?: string
onClick?: () => unknown
disabled?: boolean
@@ -13,6 +14,7 @@ type ButtonCapture = {
type MenuItemCapture = {
label: string
dataContextualTourTarget?: string
onSelect?: () => unknown
disabled?: boolean
}
@@ -70,16 +72,22 @@ vi.mock('@/components/ui/button', () => ({
disabled?: boolean
size?: string
'aria-label'?: string
'data-contextual-tour-target'?: string
}) => {
mocks.buttons.push({
label: textContent(children),
ariaLabel: props['aria-label'],
dataContextualTourTarget: props['data-contextual-tour-target'],
size,
onClick,
disabled
})
return (
<button disabled={disabled} onClick={onClick}>
<button
data-contextual-tour-target={props['data-contextual-tour-target']}
disabled={disabled}
onClick={onClick}
>
{children}
</button>
)
@@ -102,14 +110,17 @@ vi.mock('@/components/ui/dropdown-menu', () => ({
DropdownMenuItem: ({
children,
onSelect,
disabled
disabled,
...props
}: {
children: ReactModule.ReactNode
onSelect?: () => unknown
disabled?: boolean
'data-contextual-tour-target'?: string
}) => {
mocks.menuItems.push({
label: textContent(children),
dataContextualTourTarget: props['data-contextual-tour-target'],
onSelect,
disabled
})
@@ -182,6 +193,28 @@ describe('SidebarHeader', () => {
)
})
it('anchors the workspace creation tour to the visible Add trigger when a worktree can be created', async () => {
mocks.state.repos = [
{
id: 'repo-1',
path: '/repo',
displayName: 'Repo',
badgeColor: 'blue',
addedAt: 1
}
]
await render()
const addToOrca = findButton((b) => b.ariaLabel === 'Add to Orca')
expect(addToOrca?.dataContextualTourTarget).toBe('workspace-create-control')
const newWorkspace = findMenuItem((b) => b.label.includes('New worktree'))
// Why: closed dropdown items are not reliable tour anchors; the visible
// trigger stays measurable while the handoff remains on this menu action.
expect(newWorkspace?.dataContextualTourTarget).toBeUndefined()
})
it('shows the compact visible Add label under repo grouping', async () => {
mocks.state.groupBy = 'repo'
await render()
@@ -15,6 +15,7 @@ import {
import SidebarWorkspaceOptionsMenu from './SidebarWorkspaceOptionsMenu'
import WorkspaceKanbanDrawer from './WorkspaceKanbanDrawer'
import { useShortcutLabel } from '@/hooks/useShortcutLabel'
import { openWorkspaceCreationComposerWithTourHandoff } from '../contextual-tours/workspace-creation-tour-handoff'
const SidebarHeader = React.memo(function SidebarHeader() {
const newWorktreeShortcutLabel = useShortcutLabel('workspace.create')
@@ -150,6 +151,9 @@ const SidebarHeader = React.memo(function SidebarHeader() {
size={isRepoGrouping ? 'xs' : 'icon-xs'}
aria-label="Add to Orca"
className={isRepoGrouping ? 'gap-1 text-muted-foreground' : 'text-muted-foreground'}
data-contextual-tour-target={
canCreateWorkspace ? 'workspace-create-control' : undefined
}
>
<Plus className="size-3.5" strokeWidth={2.25} />
{isRepoGrouping ? <span className="text-[11px]">Add</span> : null}
@@ -159,13 +163,14 @@ const SidebarHeader = React.memo(function SidebarHeader() {
<DropdownMenuContent align="end" sideOffset={6} className="w-64">
<DropdownMenuLabel>Worktree</DropdownMenuLabel>
<DropdownMenuItem
disabled={!canCreateWorkspace}
onSelect={() => {
if (!canCreateWorkspace) {
return
}
openModal('new-workspace-composer', { telemetrySource: 'sidebar' })
openWorkspaceCreationComposerWithTourHandoff()
}}
aria-label="New workspace"
disabled={!canCreateWorkspace}
>
<Plus className="size-3.5" />
<span className="flex min-w-0 flex-col">
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest'
import { getDefaultSettings } from '../../../../shared/constants'
import { shouldShowAgentsButton, shouldShowMobileButton } from './SidebarNav'
import {
shouldShowAgentsButton,
shouldShowMobileButton,
shouldShowSetupGuideEntry
} from './SidebarNav'
describe('SidebarNav', () => {
it('hides the Agents entry while settings are loading', () => {
@@ -33,4 +37,10 @@ describe('SidebarNav', () => {
it('hides the Mobile entry when the sidebar setting is off', () => {
expect(shouldShowMobileButton({ showMobileButton: false })).toBe(false)
})
it('shows the setup guide entry only before completion and before explicit hide', () => {
expect(shouldShowSetupGuideEntry(false, false)).toBe(true)
expect(shouldShowSetupGuideEntry(true, false)).toBe(false)
expect(shouldShowSetupGuideEntry(false, true)).toBe(false)
})
})
@@ -22,6 +22,9 @@ import {
ContextMenuItem,
ContextMenuTrigger
} from '@/components/ui/context-menu'
import { SetupGuideSidebarEntry } from './SetupGuideSidebarEntry'
export { shouldShowSetupGuideEntry } from './SetupGuideSidebarEntry'
export function shouldShowAgentsButton(
settings: Pick<GlobalSettings, 'experimentalActivity'> | null | undefined
@@ -141,7 +144,11 @@ const SidebarNav = React.memo(function SidebarNav() {
}, [updateSettings])
return (
<div className="flex flex-col gap-0.5 px-2 pt-2 pb-1">
<div
className="flex flex-col gap-0.5 px-2 pt-2 pb-1"
data-contextual-tour-target="sidebar-navigation"
>
<SetupGuideSidebarEntry />
{showTasksButton ? (
<button
type="button"
@@ -155,6 +162,7 @@ const SidebarNav = React.memo(function SidebarNav() {
onFocus={handlePrefetch}
disabled={!canBrowseTasks}
aria-current={tasksActive ? 'page' : undefined}
data-contextual-tour-target="sidebar-tasks"
className={cn(
'flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] font-medium tracking-tight transition-colors',
tasksActive
@@ -6,6 +6,7 @@ import {
ExternalLink,
FolderPlus,
HardDrive,
ListChecks,
MessageSquareText,
RotateCw,
School,
@@ -163,13 +164,17 @@ const SidebarToolbar = React.memo(function SidebarToolbar() {
</TooltipContent>
</Tooltip>
<DropdownMenuContent side="top" align="start" sideOffset={8} className="w-48">
<DropdownMenuItem onSelect={() => openModal('setup-guide')}>
<ListChecks className="size-3.5" />
Getting started with Orca
</DropdownMenuItem>
<DropdownMenuItem
className="whitespace-nowrap"
onClick={handleShowOnboarding}
onSelect={handleShowOnboarding}
>
<School className="size-3.5" />
Show Onboarding
Explore Orca
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => setFeedbackOpen(true)}>
<MessageSquareText className="size-3.5" />
@@ -32,6 +32,7 @@ import {
} from './worktree-manual-order'
import type { WorkspaceStatus, WorktreeMeta } from '../../../../shared/types'
import { makeWorkspaceStatusId } from '../../../../shared/workspace-statuses'
import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour'
type WorkspaceKanbanDrawerProps = {
open: boolean
@@ -441,6 +442,7 @@ export default function WorkspaceKanbanDrawer({
useWorkspaceKanbanShiftWheelScroll(boardRef, laneScrollerRef, open, isPointerDragActiveRef)
useWorkspaceKanbanOutsideDismiss({ open, boardRef, preserveOpenForMenu, onOpenChange })
useContextualTour('workspace-board', open, 'workspace_board_visible')
useEffect(() => {
if (!open || selectedWorktreeIds.size === 0) {
@@ -487,6 +489,7 @@ export default function WorkspaceKanbanDrawer({
width: `min(calc(100vw - ${drawerLeftCss}), 1294px)`
} as React.CSSProperties
}
data-contextual-tour-target="workspace-board-surface"
onOpenAutoFocus={(event) => {
// Why: Radix focuses the first toolbar button on open, which opens
// its tooltip without hover and makes the drawer feel noisy.
@@ -562,6 +565,10 @@ export default function WorkspaceKanbanDrawer({
onPointerDown={handleAreaSelectionPointerDown}
>
<WorkspaceKanbanAreaSelectionOverlay ref={areaSelectionOverlayRef} />
<div
className="pointer-events-none absolute left-1/2 top-1/2 size-6 -translate-x-1/2 -translate-y-1/2"
data-contextual-tour-target="workspace-board-center"
/>
<WorkspaceKanbanPinDropTarget
isDragOver={pinDragOver}
onDragOver={handlePinDragOver}
@@ -56,6 +56,7 @@ export default function WorkspaceKanbanLaneGrid({
return (
<div
className="grid h-full min-h-0 min-w-full grid-rows-[minmax(0,1fr)] gap-3"
data-contextual-tour-target="workspace-board-lanes"
style={{
gridTemplateColumns: `repeat(${statuses.length}, minmax(${columnWidth}px, ${columnWidth}px))`
}}
@@ -41,6 +41,7 @@ export default function WorkspaceKanbanSettingsMenu({
variant="ghost"
size="icon-xs"
aria-label="Workspace board settings"
data-contextual-tour-target="workspace-board-settings"
className="text-muted-foreground"
>
<Settings className="size-3.5" />
@@ -81,6 +81,9 @@ export default function WorkspaceKanbanStatusLane({
<section
data-workspace-status-drop-target=""
data-workspace-status={status.id}
data-contextual-tour-target={
status.id === 'completed' ? 'workspace-board-done-lane' : undefined
}
className={cn(
'group/lane',
'relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden rounded-md border border-t-2 border-sidebar-border transition-colors',
@@ -2393,7 +2393,11 @@ const VirtualizedWorktreeViewport = React.memo(function VirtualizedWorktreeViewp
)
return (
<div data-worktree-sidebar-container className="relative min-h-0 flex-1">
<div
data-worktree-sidebar-container
data-contextual-tour-target="workspace-list"
className="relative min-h-0 flex-1"
>
<div
ref={setScrollRootRef}
data-worktree-sidebar
@@ -4266,7 +4270,11 @@ const WorktreeList = React.memo(function WorktreeList({
// active filters hide everything the Clear Filters empty state must win.
if (rows.length === 0 || filtersHideAllRows) {
return (
<div data-worktree-sidebar-container className="relative min-h-0 flex-1">
<div
data-worktree-sidebar-container
data-contextual-tour-target="workspace-list"
className="relative min-h-0 flex-1"
>
<div className="worktree-sidebar-scrollbar flex h-full flex-col overflow-y-scroll overflow-x-hidden pl-1 scrollbar-sleek pt-px">
<div className="flex flex-col items-center gap-2 px-4 py-6 text-center text-[11px] text-muted-foreground">
<span>No workspaces found</span>
@@ -46,6 +46,13 @@ describe('workspace kanban outside dismiss keep-open targets', () => {
expect(isWorkspaceBoardKeepOpenTarget(action as unknown as EventTarget)).toBe(true)
})
it('keeps the board open when the contextual tour panel is clicked', () => {
const panel = new FakeElement(['[data-contextual-tour-panel]'])
const nextButton = new FakeElement([], panel)
expect(isWorkspaceBoardKeepOpenTarget(nextButton as unknown as EventTarget)).toBe(true)
})
it('does not keep the board open for generic outside content', () => {
const target = new FakeElement()
@@ -5,6 +5,8 @@ const WORKSPACE_BOARD_KEEP_OPEN_SELECTOR = [
'[data-workspace-board-trigger]',
'[data-workspace-board-preserve-open]',
'[data-workspace-status-appearance-popover]',
'[data-contextual-tour-overlay]',
'[data-contextual-tour-panel]',
'[data-radix-popper-content-wrapper]',
'[data-slot="dropdown-menu-content"]',
'[data-slot="context-menu-content"]',
@@ -338,6 +338,14 @@ export default function TabGroupPanel({
className="relative flex-1 min-h-0 overflow-hidden"
style={bodyAnchorStyle}
>
{/* Why: this empty anchor lets the agent-sessions tour read as a
terminal-area tip instead of attaching to toolbar chrome. */}
{isFocused ? (
<div
className="pointer-events-none absolute inset-x-0 top-1/4 h-px"
data-contextual-tour-target="workspace-agent-terminal-tip"
/>
) : null}
{activeDropZone ? <TabGroupDropOverlay zone={activeDropZone} /> : null}
{activeTab &&
activeTab.contentType !== 'terminal' &&
@@ -388,6 +388,7 @@ export default function TerminalPane({
const clearWorktreeUnread = useAppStore((store) => store.clearWorktreeUnread)
const clearTerminalTabUnread = useAppStore((store) => store.clearTerminalTabUnread)
const clearTerminalPaneUnread = useAppStore((store) => store.clearTerminalPaneUnread)
const recordFeatureInteraction = useAppStore((store) => store.recordFeatureInteraction)
const openSpacePage = useAppStore((store) => store.openSpacePage)
const refreshWorkspaceSpace = useAppStore((store) => store.refreshWorkspaceSpace)
const settings = useAppStore((store) => store.settings)
@@ -407,6 +408,9 @@ export default function TerminalPane({
() => useAppStore.getState().pendingIssueCommandSplitByTabId[tabId]
)
const consumeTabIssueCommandSplit = useAppStore((store) => store.consumeTabIssueCommandSplit)
const handleSplitPaneCommand = useCallback(() => {
recordFeatureInteraction('terminal-pane-split')
}, [recordFeatureInteraction])
useEffect(() => {
if (startup) {
@@ -1059,6 +1063,7 @@ export default function TerminalPane({
setSearchOpen,
onSearchSelectedText: handleSearchSelectedText,
onRequestClosePane: handleRequestClosePane,
onSplitPaneCommand: handleSplitPaneCommand,
searchOpenRef,
searchStateRef,
macOptionAsAltRef,
@@ -1583,6 +1588,7 @@ export default function TerminalPane({
fallbackCwd: cwd ?? '',
toggleExpandPane,
onRequestClosePane: handleRequestClosePane,
onSplitPaneCommand: handleSplitPaneCommand,
onSetTitle: handleStartRename,
onPasteError: setTerminalError,
onAgentSessionForkReady: setAgentSessionFork,
@@ -1695,6 +1701,7 @@ export default function TerminalPane({
ref={setContainerRef}
className="absolute inset-0 min-h-0 min-w-0"
data-native-file-drop-target="terminal"
data-contextual-tour-target="terminal-pane-split-target"
data-terminal-tab-id={tabId}
data-pane-title-surface={titleUsesLightSurface ? 'light' : 'dark'}
style={terminalContainerStyle}
@@ -108,6 +108,7 @@ type KeyboardHandlersDeps = {
setSearchOpen: React.Dispatch<React.SetStateAction<boolean>>
onSearchSelectedText: (text: string) => void
onRequestClosePane: (paneId: number) => void
onSplitPaneCommand?: () => void
searchOpenRef: React.RefObject<boolean>
searchStateRef: React.RefObject<SearchState>
macOptionAsAltRef: React.RefObject<MacOptionAsAlt>
@@ -131,6 +132,7 @@ export function useTerminalKeyboardShortcuts({
setSearchOpen,
onSearchSelectedText,
onRequestClosePane,
onSplitPaneCommand,
searchOpenRef,
searchStateRef,
macOptionAsAltRef,
@@ -372,6 +374,7 @@ export function useTerminalKeyboardShortcuts({
if (!pane) {
return
}
onSplitPaneCommand?.()
const ptyId = paneTransportsRef.current.get(pane.id)?.getPtyId() ?? null
if (splitWebRuntimeTerminal(ptyId, action.direction)) {
return
@@ -423,6 +426,7 @@ export function useTerminalKeyboardShortcuts({
setSearchOpen,
onSearchSelectedText,
onRequestClosePane,
onSplitPaneCommand,
searchOpenRef,
searchStateRef,
macOptionAsAltRef,

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