diff --git a/config/patches/@xterm__addon-webgl@0.20.0-beta.219.patch b/config/patches/@xterm__addon-webgl@0.20.0-beta.219.patch index c4d416626..2a77d4e90 100644 --- a/config/patches/@xterm__addon-webgl@0.20.0-beta.219.patch +++ b/config/patches/@xterm__addon-webgl@0.20.0-beta.219.patch @@ -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; } - diff --git a/docs/reference/README.md b/docs/reference/README.md index 1b5477dd7..0f33294e8 100644 --- a/docs/reference/README.md +++ b/docs/reference/README.md @@ -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. \ No newline at end of file diff --git a/docs/reference/feature-discovery-interaction-tracking.md b/docs/reference/feature-discovery-interaction-tracking.md index cdc2dafcc..2ed6cdcdc 100644 --- a/docs/reference/feature-discovery-interaction-tracking.md +++ b/docs/reference/feature-discovery-interaction-tracking.md @@ -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 diff --git a/docs/reference/feature-education-retention-analytics.md b/docs/reference/feature-education-retention-analytics.md new file mode 100644 index 000000000..df259f431 --- /dev/null +++ b/docs/reference/feature-education-retention-analytics.md @@ -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. diff --git a/docs/reference/feature-education-state.md b/docs/reference/feature-education-state.md new file mode 100644 index 000000000..950d4823d --- /dev/null +++ b/docs/reference/feature-education-state.md @@ -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`. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ff31d1a4d..723217055 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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 diff --git a/src/main/index.ts b/src/main/index.ts index bd427f31e..fa90ae9fb 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -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 diff --git a/src/main/menu/register-app-menu.test.ts b/src/main/menu/register-app-menu.test.ts index 510a47d3a..b28b7ed83 100644 --- a/src/main/menu/register-app-menu.test.ts +++ b/src/main/menu/register-app-menu.test.ts @@ -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', () => { diff --git a/src/main/menu/register-app-menu.ts b/src/main/menu/register-app-menu.ts index fb91ea6d5..f6a04cc78 100644 --- a/src/main/menu/register-app-menu.ts +++ b/src/main/menu/register-app-menu.ts @@ -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 ? [] : ([ diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index 4207b5d14..d73873b86 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -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 } diff --git a/src/main/persistence.ts b/src/main/persistence.ts index adf8f4f96..a50cbd90c 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -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. diff --git a/src/main/runtime/orca-runtime-files-watch.test.ts b/src/main/runtime/orca-runtime-files-watch.test.ts new file mode 100644 index 000000000..92994bd94 --- /dev/null +++ b/src/main/runtime/orca-runtime-files-watch.test.ts @@ -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('fs') + return { + ...actual, + watch: watchMock + } +}) + +vi.mock('fs/promises', async () => { + const actual = await vi.importActual('fs/promises') + return { + ...actual, + stat: statMock + } +}) + +vi.mock('@parcel/watcher', () => ({ + subscribe: subscribeParcelWatcherMock +})) + +vi.mock('../ipc/filesystem-auth', async () => { + const actual = await vi.importActual('../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((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) + }) +}) diff --git a/src/main/runtime/rpc/dispatcher-feature-interactions.test.ts b/src/main/runtime/rpc/dispatcher-feature-interactions.test.ts index 87c127bbb..6b4bcf345 100644 --- a/src/main/runtime/rpc/dispatcher-feature-interactions.test.ts +++ b/src/main/runtime/rpc/dispatcher-feature-interactions.test.ts @@ -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')) diff --git a/src/main/runtime/rpc/dispatcher.ts b/src/main/runtime/rpc/dispatcher.ts index add223a2d..77c2b442c 100644 --- a/src/main/runtime/rpc/dispatcher.ts +++ b/src/main/runtime/rpc/dispatcher.ts @@ -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.')) { diff --git a/src/main/runtime/rpc/methods/client-ui.test.ts b/src/main/runtime/rpc/methods/client-ui.test.ts index d2d89488d..842ae8e67 100644 --- a/src/main/runtime/rpc/methods/client-ui.test.ts +++ b/src/main/runtime/rpc/methods/client-ui.test.ts @@ -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)) diff --git a/src/main/runtime/rpc/methods/client-ui.ts b/src/main/runtime/rpc/methods/client-ui.ts index 900ae14a3..70289e3cd 100644 --- a/src/main/runtime/rpc/methods/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-ui.ts @@ -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({}) diff --git a/src/main/runtime/rpc/methods/computer.test.ts b/src/main/runtime/rpc/methods/computer.test.ts index 4791e5182..20ed5fcec 100644 --- a/src/main/runtime/rpc/methods/computer.test.ts +++ b/src/main/runtime/rpc/methods/computer.test.ts @@ -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 () => { diff --git a/src/main/runtime/rpc/methods/computer.ts b/src/main/runtime/rpc/methods/computer.ts index 88618daf6..01e50abb3 100644 --- a/src/main/runtime/rpc/methods/computer.ts +++ b/src/main/runtime/rpc/methods/computer.ts @@ -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({ diff --git a/src/main/runtime/rpc/methods/index.ts b/src/main/runtime/rpc/methods/index.ts index 10132edd8..4ec7a883d 100644 --- a/src/main/runtime/rpc/methods/index.ts +++ b/src/main/runtime/rpc/methods/index.ts @@ -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 diff --git a/src/main/runtime/rpc/methods/skills.ts b/src/main/runtime/rpc/methods/skills.ts new file mode 100644 index 000000000..0c1577790 --- /dev/null +++ b/src/main/runtime/rpc/methods/skills.ts @@ -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() }) + }) +] diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 7d6601aa6..30ec3c085 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1994,6 +1994,7 @@ export type PreloadApi = { set: (args: Partial) => Promise recordFeatureInteraction: (id: FeatureInteractionId) => Promise onOpenSettings: (callback: () => void) => () => void + onOpenSetupGuide: (callback: () => void) => () => void onOpenFeatureTour: (callback: () => void) => () => void onOpenCrashReport: (callback: () => void) => () => void onToggleLeftSidebar: (callback: () => void) => () => void diff --git a/src/preload/index.ts b/src/preload/index.ts index 94e292f13..5db787809 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -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) diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 1538a7212..8c194053b 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -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>(() => new Set()) const [onboarding, setOnboarding] = useState(null) + const [onboardingLoaded, setOnboardingLoaded] = useState(false) const featureTipsPromptedThisSessionRef = useRef(false) const featureTipsSuppressedByOnboardingThisSessionRef = useRef(false) const [featureTipCliInstalled, setFeatureTipCliInstalled] = useState(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 { ) : null} + {resolvedMountedLazyModalIds.has('setup-guide') ? ( + + + + ) : null} {resolvedMountedLazyModalIds.has('feature-wall') ? ( ) : null} + {/* 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. */} diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index f15491656..25c740adb 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -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); +} diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index 6eed73489..5fe493a11 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -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['repos'][number] type NewWorkspaceComposerCardProps = { + contextualTourSource?: string containerClassName?: string composerRef?: React.RefObject 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 (
-
+
@@ -438,7 +450,7 @@ export default function NewWorkspaceComposerCard({ ) : null}
-
+
-
+
diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.tsx index cae22aa3b..4e41117f6 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.tsx @@ -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({ {primaryActionLabel} { @@ -5898,7 +5910,10 @@ export default function TaskPage(): React.JSX.Element {
-
+
{/* 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' ? ( -
+
{getGitHubTaskKindPresets(activeGithubTaskKind).map((option) => { const active = activeTaskPreset === option.id @@ -6198,7 +6216,10 @@ export default function TaskPage(): React.JSX.Element { ) : null}
-
+
-
+
@@ -6769,7 +6799,10 @@ export default function TaskPage(): React.JSX.Element { : null}
-
+
@@ -1560,7 +1571,10 @@ export default function AutomationsPage(): React.JSX.Element {
-
+
{automations.length + externalAutomationEntries.length > 0 ? (
@@ -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" > -
+
Overview diff --git a/src/renderer/src/components/browser-pane/BrowserPane.tsx b/src/renderer/src/components/browser-pane/BrowserPane.tsx index c4f0aaea9..803962451 100644 --- a/src/renderer/src/components/browser-pane/BrowserPane.tsx +++ b/src/renderer/src/components/browser-pane/BrowserPane.tsx @@ -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 => { if (!activeBrowserPageId) { return @@ -2378,7 +2391,10 @@ function RemoteBrowserPagePane({ document.body ) : null} -
+
@@ -4516,6 +4546,7 @@ function BrowserPagePane({ onClick={() => startGrabIntent('annotate')} disabled={isBlankTab} aria-label="Annotate page element" + data-contextual-tour-target="browser-annotation-control" > {browserAnnotations.length > 0 ? ( diff --git a/src/renderer/src/components/confirmation-dialog.tsx b/src/renderer/src/components/confirmation-dialog.tsx index 8449708fc..f990c6c4e 100644 --- a/src/renderer/src/components/confirmation-dialog.tsx +++ b/src/renderer/src/components/confirmation-dialog.tsx @@ -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([]) const activeRequest = queue[0] ?? null const activeRequestRef = useRef(activeRequest) + const setContextualToursBlockingSurfaceVisible = useAppStore( + (s) => s.setContextualToursBlockingSurfaceVisible + ) const lastDisplayedRequestRef = useRef(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((options) => { return new Promise((resolve) => { const request: ConfirmationDialogRequest = { diff --git a/src/renderer/src/components/contextual-tours/ContextualTourArrow.tsx b/src/renderer/src/components/contextual-tours/ContextualTourArrow.tsx new file mode 100644 index 000000000..a0ff41729 --- /dev/null +++ b/src/renderer/src/components/contextual-tours/ContextualTourArrow.tsx @@ -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 ( + + ) +} diff --git a/src/renderer/src/components/contextual-tours/ContextualTourControl.test.ts b/src/renderer/src/components/contextual-tours/ContextualTourControl.test.ts new file mode 100644 index 000000000..8587138fd --- /dev/null +++ b/src/renderer/src/components/contextual-tours/ContextualTourControl.test.ts @@ -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() + }) +}) diff --git a/src/renderer/src/components/contextual-tours/ContextualTourControl.tsx b/src/renderer/src/components/contextual-tours/ContextualTourControl.tsx new file mode 100644 index 000000000..8b860a27d --- /dev/null +++ b/src/renderer/src/components/contextual-tours/ContextualTourControl.tsx @@ -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 + } +} + +export function toggleAutoRenameBranchFromWork(args: { + enabled: boolean + updateSettings: (settings: { autoRenameBranchFromWork: boolean }) => void | Promise + 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 ( +
+
+
+
Auto-name from first message
+
+ Auto-generates a new name when you leave this text box empty. +
+
+ +
+
+ ) +} diff --git a/src/renderer/src/components/contextual-tours/ContextualTourOverlay.test.tsx b/src/renderer/src/components/contextual-tours/ContextualTourOverlay.test.tsx new file mode 100644 index 000000000..5da45370b --- /dev/null +++ b/src/renderer/src/components/contextual-tours/ContextualTourOverlay.test.tsx @@ -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 = {}, + callbacks: { + onSkip?: (id: ContextualTourId) => void + onNext?: () => void + onBack?: () => void + onStepAction?: Parameters[0]['onStepAction'] + } = {} +): ReactElement { + const renderState = { ...baseRenderState, ...overrides } + return ContextualTourOverlaySurface({ + activeTourId: 'tasks', + renderState, + panelRef: { current: null } as RefObject, + 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 | 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 + } + + for (const child of childrenArray) { + const match = findElementByText(child, text) + if (match) { + return match + } + } + return null +} + +function findElementByAriaLabel( + node: ReactNode, + label: string +): ReactElement | 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 + } + + 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[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) + 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) + 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"]' + ) + }) +}) diff --git a/src/renderer/src/components/contextual-tours/ContextualTourOverlay.tsx b/src/renderer/src/components/contextual-tours/ContextualTourOverlay.tsx new file mode 100644 index 000000000..eeba04e1c --- /dev/null +++ b/src/renderer/src/components/contextual-tours/ContextualTourOverlay.tsx @@ -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(null) + const [measureVersion, setMeasureVersion] = useState(0) + const panelRef = useRef(null) + const markedTourIdRef = useRef(null) + const previousFocusRef = useRef(null) + const focusedStepRef = useRef(null) + const telemetryTourIdRef = useRef(null) + const telemetryOutcomeSentRef = useRef(false) + const telemetryStepsSeenRef = useRef>(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( + 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 ( + { + 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[1] +): string { + return copy.replace( + '{terminal.splitRight}', + formatShortcutLabel('terminal.splitRight', keybindings) + ) +} diff --git a/src/renderer/src/components/contextual-tours/ContextualTourOverlaySurface.tsx b/src/renderer/src/components/contextual-tours/ContextualTourOverlaySurface.tsx new file mode 100644 index 000000000..4ed72f769 --- /dev/null +++ b/src/renderer/src/components/contextual-tours/ContextualTourOverlaySurface.tsx @@ -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 + panelPosition: PanelPositionStyle + panelPlacement: ContextualTourPanelPlacement | null + panelHost: HTMLElement | null + onSkip: (id: ContextualTourId) => void + onBack: () => void + onNext: () => void + onStepAction: (action: ContextualTourStepAction) => void + onOverlayKeyDownCapture: (event: KeyboardEvent) => 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 = ( +
+ {panelPlacement ? : null} +
+ +

+ {renderState.title} +

+

{renderState.body}

+ {renderState.control ? : null} +
+ +
+ {!renderState.isFirstStep ? ( + + ) : null} + {renderState.secondaryAction ? ( + + ) : null} + {primaryAction ? ( + + ) : null} +
+
+
+
+ ) + + return ( +
+ {showTargetRings ? ( + + ) +} + +export function handleContextualTourOverlayKeyDown(event: KeyboardEvent): void { + if (event.key === 'Escape') { + event.preventDefault() + event.stopPropagation() + const skipButton = event.currentTarget.querySelector(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('[data-contextual-tour-overlay]') + const focusRoot = document.querySelector('[data-contextual-tour-panel]') ?? overlay + if (!overlay || !focusRoot) { + return + } + + event.preventDefault() + event.stopImmediatePropagation() + const skipButton = focusRoot.querySelector(SKIP_BUTTON_SELECTOR) + if (skipButton) { + skipButton.click() + } +} + +export function getContextualTourFocusableElements(root: HTMLElement): HTMLElement[] { + return Array.from(root.querySelectorAll(FOCUSABLE_SELECTOR)).filter( + (element) => element.getClientRects().length > 0 || element === document.activeElement + ) +} diff --git a/src/renderer/src/components/contextual-tours/ContextualTourProgressDots.tsx b/src/renderer/src/components/contextual-tours/ContextualTourProgressDots.tsx new file mode 100644 index 000000000..7d7b82838 --- /dev/null +++ b/src/renderer/src/components/contextual-tours/ContextualTourProgressDots.tsx @@ -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