YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix chat worktree startup and tab interactions (#6708)
Louis Beaumontb70072f32bac
diff --git a/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.test.tsx b/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.test.tsxindex 0689a7328..f39a40528 100644--- a/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.test.tsx+++ b/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.test.tsx@@ -156,4 +156,36 @@ describe("ChatTabStrip", () => {fireEvent(first.parentElement!, new MouseEvent("auxclick", { bubbles: true, button: 1 }));expect(useChatStore.getState().openChatIds).toEqual(["chat-b", "chat-c"]);});++ it("keeps a conversation-owned worktree visible after the chat becomes inactive", () => {+ const actions = useChatStore.getState().actions;+ actions.upsert(+ record({+ id: "chat-a",+ title: "isolated fix",+ codingWorkspace: {+ repoName: "screenpipe",+ branch: "screenpipe/chat-chat-a",+ worktreePath: "/worktrees/chat-a",+ },+ }),+ );+ actions.upsert(record({ id: "chat-b", title: "primary" }));+ actions.openChat("chat-a");+ actions.openChat("chat-b");++ render(+ <ChatTabStrip+ activeId="chat-b"+ onActivate={vi.fn()}+ onNewChat={vi.fn()}+ />,+ );++ expect(screen.getByTestId("chat-tab-worktree-chat-a")).toBeInTheDocument();+ expect(screen.getByRole("tab", { name: "isolated fix" })).toHaveAttribute(+ "title",+ "isolated fix · worktree · screenpipe",+ );+ });});diff --git a/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.tsx b/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.tsxindex 074569273..8fab5ab0b 100644--- a/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.tsx+++ b/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.tsx@@ -4,7 +4,7 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import { AlertCircle, Columns2, Plus, X } from "lucide-react";+import { AlertCircle, Columns2, GitBranch, Plus, X } from "lucide-react";import {ContextMenu,ContextMenuContent,@@ -136,7 +136,7 @@ export function ChatTabStrip({return (<div- className="flex min-w-0 flex-1 items-center gap-1"+ className="relative z-20 flex min-w-0 flex-1 items-center gap-1"data-testid="chat-tab-strip"><div@@ -150,6 +150,7 @@ export function ChatTabStrip({const split = session.id === splitChatId;const title = visibleTabTitle(session);const status = tabStatus(session);+ const codingWorkspace = session.codingWorkspace;const hasTabsToRight = index < tabs.length - 1;return (@@ -175,7 +176,15 @@ export function ChatTabStrip({role="tab"aria-selected={active}aria-label={title}- title={split ? `${title} · split pane` : title}+ title={[+ title,+ codingWorkspace+ ? `worktree · ${codingWorkspace.repoName}`+ : null,+ split ? "split pane" : null,+ ]+ .filter(Boolean)+ .join(" · ")}tabIndex={active ? 0 : -1}className="flex h-full min-w-0 flex-1 items-center gap-2 rounded-md py-1 pl-2.5 pr-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"onClick={() => void onActivate(session.id)}@@ -195,6 +204,13 @@ export function ChatTabStrip({}}}>+ {codingWorkspace ? (+ <GitBranch+ aria-hidden+ className="h-3 w-3 shrink-0"+ data-testid={`chat-tab-worktree-${session.id}`}+ />+ ) : null}{split ? (<Columns2aria-label="split pane"diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.tsxindex 6ef6e60ed..80c714824 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.tsx@@ -126,13 +126,13 @@ export function ChatTitleMenu({}}}onBlur={() => void commitRename()}- className="relative z-10 h-7 max-w-[260px] border border-border bg-background px-2 text-xs font-medium focus:outline-none focus:ring-1 focus:ring-foreground/30"+ className="relative z-20 h-7 max-w-[260px] border border-border bg-background px-2 text-xs font-medium focus:outline-none focus:ring-1 focus:ring-foreground/30"/>);}return (- <div className="relative z-10 flex min-w-0 max-w-[320px] items-center gap-1.5">+ <div className="relative z-20 flex min-w-0 max-w-[320px] items-center gap-1.5">{!compact ? (<span data-testid="chat-title" className="truncate text-xs font-medium text-foreground">{title}diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/composer-controls-row.test.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/composer-controls-row.test.tsxindex 5c3f362fa..005e991d3 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/composer-controls-row.test.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/composer-controls-row.test.tsx@@ -78,6 +78,50 @@ const idleCodingWorkspace = {};describe("ComposerControlsRow", () => {+ it("explains worktree preparation while the repository is being resolved", () => {+ render(+ <ComposerControlsRow+ canChat={false}+ filters={+ {+ activeFilterCount: 0,+ activeFilters: [],+ activeFilterLabels: [],+ hasActiveFilters: false,+ appFilterOpen: false,+ onFilterMenuOpenChange: vi.fn(),+ } as any+ }+ modelControls={{+ settings: { aiPresets: [] },+ activePreset: null,+ activePipeExecution: null,+ currentQueueSessionId: null,+ onSelectPreset: vi.fn(),+ onPresetSaved: vi.fn(),+ }}+ codingWorkspace={{+ ...idleCodingWorkspace,+ enabled: true,+ isLoading: true,+ }}+ isStreaming={false}+ sendButton={{+ isStopMode: false,+ hasPendingDocs: false,+ sendDisabled: true,+ onStop: vi.fn(),+ }}+ />,+ );++ expect(screen.getByText("preparing worktree")).toBeInTheDocument();+ expect(screen.getByLabelText("worktree")).toHaveAttribute(+ "title",+ "run this task in its own isolated Git worktree",+ );+ });+it("uses an upward arrow for the send action", () => {render(<ComposerControlsRowdiff --git a/apps/screenpipe-app-tauri/components/chat/standalone/composer-worktree-toggle.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/composer-worktree-toggle.tsxindex ca2870d32..382bfa50d 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/composer-worktree-toggle.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/composer-worktree-toggle.tsx@@ -25,6 +25,7 @@ export function ComposerWorktreeToggle({const repoName = workspace?.repoRoot.split(/[\\/]/).filter(Boolean).at(-1);const cannotUncheck = Boolean(workspace);const checkboxDisabled = disabled || isLoading || cannotUncheck;+ const label = isLoading ? "preparing worktree" : "worktree";return (<div@@ -40,7 +41,7 @@ export function ComposerWorktreeToggle({}}data-testid="coding-workspace-checkbox"aria-label="worktree"- title="let the AI choose a repository, then start the coding task in an isolated worktree"+ title="run this task in its own isolated Git worktree"className="h-3.5 w-3.5"/><Label@@ -50,7 +51,7 @@ export function ComposerWorktreeToggle({checkboxDisabled ? "cursor-not-allowed" : "cursor-pointer",)}>- worktree+ {label}</Label>{isLoading && (<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-coding-workspace.test.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-coding-workspace.test.tsxindex b63f51afc..345143ac0 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-coding-workspace.test.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-coding-workspace.test.tsx@@ -5,6 +5,7 @@import { act, renderHook, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { CodingWorkspace } from "@/lib/utils/tauri";+import { useChatStore } from "@/lib/stores/chat-store";import { useCodingWorkspace } from "./use-coding-workspace";const mocks = vi.hoisted(() => ({@@ -57,6 +58,13 @@ function workspace(conversationId: string): CodingWorkspace {beforeEach(() => {vi.stubEnv("NEXT_PUBLIC_SCREENPIPE_E2E", "true");+ useChatStore.setState({+ sessions: {},+ openChatIds: [],+ splitChatId: null,+ currentId: null,+ panelSessionId: null,+ });});afterEach(() => {@@ -67,6 +75,37 @@ afterEach(() => {});describe("useCodingWorkspace", () => {+ it("publishes a compact worktree identity for inactive chat tabs", async () => {+ useChatStore.getState().actions.upsert({+ id: "conversation-a",+ title: "isolated fix",+ preview: "",+ status: "idle",+ messageCount: 1,+ createdAt: 1,+ updatedAt: 1,+ pinned: false,+ unread: false,+ });+ mocks.get.mockResolvedValue({+ status: "ok",+ data: workspace("conversation-a"),+ });++ const hook = renderHook(() =>+ useCodingWorkspace({ conversationId: "conversation-a", locked: true }),+ );++ await waitFor(() => expect(hook.result.current.isLoading).toBe(false));+ expect(+ useChatStore.getState().sessions["conversation-a"].codingWorkspace,+ ).toEqual({+ repoName: "conversation-a",+ branch: "screenpipe/chat-conversation-a",+ worktreePath: "/worktrees/conversation-a",+ });+ });+it("does not leak an in-flight creation into a newly selected conversation", async () => {let resolveCreate:((value: { status: "ok"; data: CodingWorkspace }) => void) | undefined;diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-coding-workspace.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-coding-workspace.tsindex 5a18806bf..c91e7511c 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-coding-workspace.ts+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-coding-workspace.ts@@ -4,6 +4,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { toast } from "@/components/ui/use-toast";+import { useChatStore } from "@/lib/stores/chat-store";import {commands,type CodingWorkspace,@@ -16,6 +17,23 @@ export type WorktreeRouterContext = {userToken: string | null;};+function publishWorkspaceIdentity(+ conversationId: string,+ workspace: CodingWorkspace | null,+): void {+ const repoName = workspace?.repoRoot.split(/[\\/]/).filter(Boolean).at(-1);+ useChatStore.getState().actions.patch(conversationId, {+ codingWorkspace:+ workspace && repoName+ ? {+ repoName,+ branch: workspace.branch,+ worktreePath: workspace.worktreePath,+ }+ : undefined,+ });+}+declare global {interface Window {__e2eAttachCodingWorkspace?: (@@ -82,6 +100,7 @@ export function useCodingWorkspace({.then((result) => {if (generation !== requestGenerationRef.current) return;if (result.status === "error") throw new Error(result.error);+ publishWorkspaceIdentity(conversationId, result.data);setWorkspace(result.data);setEnabled(Boolean(result.data));setResolvedConversationId(conversationId);@@ -128,6 +147,7 @@ export function useCodingWorkspace({return result.data;}setWorkspace(result.data);+ publishWorkspaceIdentity(requestConversationId, result.data);setResolvedConversationId(requestConversationId);toast({title: "coding workspace ready",@@ -253,6 +273,7 @@ export function useCodingWorkspace({conversationIdRef.current === requestConversationId) {setWorkspace(preparedWorkspace);+ publishWorkspaceIdentity(requestConversationId, preparedWorkspace);setEnabled(true);setResolvedConversationId(requestConversationId);toast({diff --git a/apps/screenpipe-app-tauri/components/standalone-chat.tsx b/apps/screenpipe-app-tauri/components/standalone-chat.tsxindex 955f4910f..95591deae 100644--- a/apps/screenpipe-app-tauri/components/standalone-chat.tsx+++ b/apps/screenpipe-app-tauri/components/standalone-chat.tsx@@ -2061,7 +2061,14 @@ export function StandaloneChat({await startNewConversation();}}rightActions={- <div className="relative z-10 flex items-center gap-1">+ <div className="relative z-20 flex items-center gap-1">+ <ChatInspectorPopover+ open={inspectorOpen}+ onOpenChange={setInspectorOpen}+ outputs={inspectorOutputs}+ sources={inspectorSources}+ onOpenFile={openFilePreview}+ />{hideInlineHistory ? (<Buttonvariant="ghost"@@ -2098,15 +2105,6 @@ export function StandaloneChat({<div className="flex-1 flex min-h-0" data-browser-panel-host><div className="relative flex-1 flex flex-col min-w-0" data-firstrun-target="messages">- <div className="absolute -top-8 right-2 z-30">- <ChatInspectorPopover- open={inspectorOpen}- onOpenChange={setInspectorOpen}- outputs={inspectorOutputs}- sources={inspectorSources}- onOpenFile={openFilePreview}- />- </div><ChatMainPanefirstRunLearningEnabled={firstRunLearningEnabled}firstRunAiPreset={firstRunAiPreset}diff --git a/apps/screenpipe-app-tauri/e2e/COVERAGE.md b/apps/screenpipe-app-tauri/e2e/COVERAGE.mdindex 6985f70ab..b3511fc4a 100644--- a/apps/screenpipe-app-tauri/e2e/COVERAGE.md+++ b/apps/screenpipe-app-tauri/e2e/COVERAGE.md@@ -123,7 +123,7 @@ pass/fail/skip counts.| chat-agent-activity-sidebar.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e | chat, chat-sidebar-groups, chat-unread-state, chat-structured-output | high | strong | real-user-flow | 3 | Recent local Codex and Claude histories sync automatically into the same Recents stream as native Screenpipe chats. Isolated real JSONL files prove that a background provider update does not invent an unread dot when the transcript has no provider attention state, and that a later assistant message updates the already-open chat without a page reload for both providers. A large Claude JSON response stays compact by default and expands into readable, pretty-printed output. The primary sidebar has no import action; right-clicking View all filters by only the sources present, while a hover-only organizer exposes the same filters plus source grouping and priority or latest-update sorting. Captures sparse, crowded mixed-provider, Codex-heavy, and structured-output native UI states with one harness icon per row, expanded pinned rows, and the capped recent working set. || chat-ask-user-tool-card.spec.ts | windows, macos, linux | chat-ai, tauri-command, window-lifecycle | chat, chat-tools, pi-ask-user | medium | partial | mixed | 1 | Synthetic assistant tool block renders the Pi ask_user dropdown and sends the selected answer through the normal chat reply path. || chat-automation-card-duplicate.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e | chat, chat-home-card-placeholder-preview, chat-sidebar-dedupe, chat-session-activity | medium | partial | real-user-flow | 1 | The Day Recap automation card previews its user-facing prompt in the empty composer on hover, restores the default placeholder on leave, and creates exactly one persisted conversation and one sidebar row; status-only activity for an unknown session must not create an empty untitled sibling. |-| chat-coding-worktree.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e | chat, chat-coding-worktrees | high | strong | real-user-flow | 1 | Arms worktree mode without a folder picker, gives a vague ‘make the button blue’ task plus nearby repositories to a real local model, requires that model to call only start_worktree, then creates the conversation-owned worktree through the authenticated desktop broker. Also proves dirty-source preservation, conversation isolation and resume, launches Pi in the owned cwd while ignoring a hostile project-local extension, and verifies work survives Pi stop. Runs in the focused Windows CI list as well as the recursive macOS and Linux suites. |+| chat-coding-worktree.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e | chat, chat-coding-worktrees | high | strong | real-user-flow | 1 | Arms worktree mode without a folder picker, gives a vague ‘make the button blue’ task plus nearby repositories to a real local model, requires that model to call only start_worktree, then creates the conversation-owned worktree through the authenticated desktop broker. Also proves dirty-source preservation, conversation isolation and resume, keeps the worktree identity visible in the chat tab, launches Pi in the owned cwd while ignoring a hostile project-local extension, and verifies work survives Pi stop. Runs in the focused Windows CI list as well as the recursive macOS and Linux suites. || chat-composer-isolation.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e | chat, chat-drafts | medium | partial | mixed | 1 | Composer draft isolation across conversations. || chat-connections-context-duplicate.spec.ts | windows, macos | chat-ai | chat, chat-sidebar-dedupe | medium | partial | synthetic | 1 | QUARANTINED (#4689): connections-context wrapper stripping regression. The synthetic background-router event path never persists deterministically on Linux/macOS CI; re-enable once it drives a deterministic persisted session. || chat-context-usage-providers.spec.ts | macos | chat-ai, real-ui-e2e, tauri-command | chat, context-usage, acp-backend, agent-streaming | medium | strong | real-user-flow | 3 | The composer's context reading, once per harness class that can report one. Native Pi answers a real OpenAI-compatible turn whose stream carries usage, and the project-local context-usage extension publishes a per-category breakdown that must sum to the model's own total and must keep non-empty rules/skills buckets, which is what guards the classifier's coupling to pi's prompt section markers. A deterministic stdio ACP adapter reports only the protocol usage_update pair and must render one bar plus the line saying no breakdown is available. Also covers the pre-first-turn state, where the panel says nothing rather than estimating. |@@ -160,7 +160,7 @@ pass/fail/skip counts.| chat-turn-liveness.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e | chat, chat-streaming, offline-recovery | high | strong | real-user-flow | 1 | The real desktop chat turns off its active phosphor signal and explains that a message is saved when WebView connectivity drops, restores active state on reconnect, and exposes a silent harness after the bounded no-event deadline. || chat-window.spec.ts | windows, macos, linux | chat-ai, window-lifecycle, real-ui-e2e | chat, window-lifecycle | high | strong | real-user-flow | 1 | Opens Chat and focuses the composer for typing. || chat-within-session-context-loss.spec.ts | macos | chat-ai | chat, chat-context | medium | conditional | synthetic | 5 | macOS-only within-chat context retention regression. |-| chat-workspace-tabs.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e | chat, chat-tabs, chat-split-pane | high | strong | real-user-flow | 1 | Multiple chats remain in a non-destructive working set, a second live transcript stays visible, and promoting it swaps primary composer ownership. |+| chat-workspace-tabs.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e | chat, chat-tabs, chat-split-pane | high | strong | real-user-flow | 1 | Native pointer clicks reach tabs, close, and new-chat controls above the window drag region; unused mount placeholders do not create extra untitled tabs. Multiple real chats remain in a non-destructive working set, a second live transcript stays visible, and promoting it swaps primary composer ownership. || connected-share.spec.ts | windows, macos, linux | real-ui-e2e, local-api | meeting-notes, brain-overview, live-views, connections | high | strong | real-user-flow | 1 | Exercises the Send snapshot dialog from meeting notes and Live Views across disconnected setup, connected direct-send, receipt, and Chat-draft destinations, with mocked connection APIs and screenshot coverage. || db-hard-fault-fail-closed.spec.ts | windows, macos, linux | local-api, tauri-command, real-ui-e2e | database-hard-fault-containment, app-launch | high | strong | mixed | 1 | Opt-in packaged-desktop regression: causes real SQLITE_CORRUPT in the isolated E2E database, then proves the engine API and database owners stop while the desktop stays alive and does not respawn across the watchdog window. || first-run-agent-handoff.spec.ts | windows, macos, linux | onboarding, real-ui-e2e | onboarding, first-run-learning, mcp-registration | high | partial | real-user-flow | 4 | Agent handoff beside the first-run summary: the summary stays primary and clickable whether or not an agent is offered, an offered target is never nameless or unclickable, the filesystem probe cannot break the ready banner or the summary click-through, opening the result collapses into the compact setup dock, and the paste instruction appears only after the handoff runs. Waits for the async probe before concluding absence. Does not assert WHICH agent: detectAiTools resolves the real home in the webview (SCREENPIPE_E2E_AI_TOOLS_HOME is Rust-only), so selection is host-dependent and is covered in lib/first-run/agent-handoff.test.ts and use-agent-handoff.test.ts. |diff --git a/apps/screenpipe-app-tauri/e2e/coverage-map.json b/apps/screenpipe-app-tauri/e2e/coverage-map.jsonindex 0a224e89a..d2d31de2e 100644--- a/apps/screenpipe-app-tauri/e2e/coverage-map.json+++ b/apps/screenpipe-app-tauri/e2e/coverage-map.json@@ -713,7 +713,7 @@"criticality": "high","confidence": "strong","ux": "real-user-flow",- "notes": "Arms worktree mode without a folder picker, gives a vague ‘make the button blue’ task plus nearby repositories to a real local model, requires that model to call only start_worktree, then creates the conversation-owned worktree through the authenticated desktop broker. Also proves dirty-source preservation, conversation isolation and resume, launches Pi in the owned cwd while ignoring a hostile project-local extension, and verifies work survives Pi stop. Runs in the focused Windows CI list as well as the recursive macOS and Linux suites."+ "notes": "Arms worktree mode without a folder picker, gives a vague ‘make the button blue’ task plus nearby repositories to a real local model, requires that model to call only start_worktree, then creates the conversation-owned worktree through the authenticated desktop broker. Also proves dirty-source preservation, conversation isolation and resume, keeps the worktree identity visible in the chat tab, launches Pi in the owned cwd while ignoring a hostile project-local extension, and verifies work survives Pi stop. Runs in the focused Windows CI list as well as the recursive macOS and Linux suites."},{"spec": "chat-composer-isolation.spec.ts",@@ -1271,7 +1271,7 @@"criticality": "high","confidence": "strong","ux": "real-user-flow",- "notes": "Multiple chats remain in a non-destructive working set, a second live transcript stays visible, and promoting it swaps primary composer ownership."+ "notes": "Native pointer clicks reach tabs, close, and new-chat controls above the window drag region; unused mount placeholders do not create extra untitled tabs. Multiple real chats remain in a non-destructive working set, a second live transcript stays visible, and promoting it swaps primary composer ownership."},{"spec": "owned-browser-tabs.spec.ts",diff --git a/apps/screenpipe-app-tauri/e2e/specs/chat-coding-worktree.spec.ts b/apps/screenpipe-app-tauri/e2e/specs/chat-coding-worktree.spec.tsindex a3b133b06..a23d11370 100644--- a/apps/screenpipe-app-tauri/e2e/specs/chat-coding-worktree.spec.ts+++ b/apps/screenpipe-app-tauri/e2e/specs/chat-coding-worktree.spec.ts@@ -263,6 +263,8 @@ describe("Chat coding worktrees", function () {async () => (await checkbox.getAttribute("data-state")) === "checked",{ timeout: t(5_000), timeoutMsg: "worktree mode did not arm" },);+ const armedScreenshot = await saveScreenshot("chat-coding-worktree-armed");+ expect(existsSync(armedScreenshot)).toBe(true);const first = await prepareCurrentConversation("make the button blue",fixture.root,@@ -285,6 +287,8 @@ describe("Chat coding worktrees", function () {expect(await checkbox.getAttribute("data-state")).toBe("checked");const badge = await $('[data-testid="coding-workspace-badge"]');await badge.waitForDisplayed({ timeout: t(10_000) });+ const tabMarker = await $('[data-testid^="chat-tab-worktree-"]');+ await tabMarker.waitForDisplayed({ timeout: t(10_000) });await badge.click();const popover = await $('[data-testid="coding-workspace-popover"]');await popover.waitForDisplayed({ timeout: t(5_000) });diff --git a/apps/screenpipe-app-tauri/e2e/specs/chat-workspace-tabs.spec.ts b/apps/screenpipe-app-tauri/e2e/specs/chat-workspace-tabs.spec.tsindex c1b8f9168..1cdb98016 100644--- a/apps/screenpipe-app-tauri/e2e/specs/chat-workspace-tabs.spec.ts+++ b/apps/screenpipe-app-tauri/e2e/specs/chat-workspace-tabs.spec.ts@@ -155,7 +155,15 @@ describe("Chat workspace tabs and split", function () {it("keeps multiple chats open, swaps the split pane, and closes non-destructively", async () => {const initialTabs = await openTabIds();- expect(initialTabs.slice(-2)).toEqual([CHAT_A, CHAT_B]);+ expect(initialTabs).toEqual([CHAT_A, CHAT_B]);++ // Use native pointer clicks here. DOM element.click() bypasses hit testing+ // and previously let the transparent window-drag layer hide the fact that+ // every control in this header was physically unclickable.+ await $(`button[role="tab"][aria-label="${TITLES[CHAT_A]}"]`).click();+ await waitForForeground(CHAT_A);+ await $(`button[role="tab"][aria-label="${TITLES[CHAT_B]}"]`).click();+ await waitForForeground(CHAT_B);await openContextItem(CHAT_A, "Open in split");const split = await $('[data-testid="chat-split-pane"]');@@ -200,13 +208,8 @@ describe("Chat workspace tabs and split", function () {},);- await browser.execute((id: string) => {- document- .querySelector<HTMLButtonElement>(- `[data-testid="chat-tab-close-${id}"]`,- )- ?.click();- }, CHAT_B);+ await $(`[data-chat-tab-id="${CHAT_B}"]`).moveTo();+ await $(`[data-testid="chat-tab-close-${CHAT_B}"]`).click();await browser.waitUntil(async () => !(await openTabIds()).includes(CHAT_B),{@@ -218,5 +221,19 @@ describe("Chat workspace tabs and split", function () {expect(await $(`[data-testid="chat-row-${CHAT_B}"]`).isExisting()).toBe(true,);++ await $('button[aria-label="New chat tab"]').click();+ await browser.waitUntil(+ async () => {+ const ids = await openTabIds();+ return ids.length === 2 && ids[0] === CHAT_A && ids[1] !== CHAT_B;+ },+ {+ timeout: t(8_000),+ interval: 100,+ timeoutMsg: "new chat button did not create one interactive tab",+ },+ );+ await saveScreenshot("chat-workspace-tabs-recovery");});});diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.tsindex 178fd1d79..b3000840d 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts@@ -461,6 +461,57 @@ describe("chat-store: getOrCreateEmptyChatId (no spam on +new)", () => {describe("chat-store: visible selection follows the rendered panel", () => {beforeEach(reset);+ it("drops an unused mount placeholder after another chat reaches the panel", () => {+ const actions = useChatStore.getState().actions;+ actions.upsert(+ baseRecord({+ id: "placeholder",+ draft: true,+ messageCount: 0,+ messages: [],+ }),+ );+ actions.setCurrent("placeholder");+ actions.setPanelSession("placeholder");+ actions.upsert(baseRecord({ id: "real", messageCount: 2 }));+ actions.setCurrent("real");++ actions.setPanelSession("real");++ const state = useChatStore.getState();+ expect(state.panelSessionId).toBe("real");+ expect(state.openChatIds).toEqual(["real"]);+ expect(state.sessions.placeholder).toBeUndefined();+ });++ it("preserves an inactive blank tab when it owns a composer draft", () => {+ const actions = useChatStore.getState().actions;+ actions.upsert(+ baseRecord({+ id: "draft",+ draft: true,+ messageCount: 0,+ messages: [],+ }),+ );+ actions.setCurrent("draft");+ actions.setPanelSession("draft");+ actions.setComposerDraft("draft", {+ input: "unsent work",+ pastedImages: [],+ attachedDocs: [],+ pendingDocs: [],+ });+ actions.upsert(baseRecord({ id: "real", messageCount: 2 }));+ actions.setCurrent("real");++ actions.setPanelSession("real");++ const state = useChatStore.getState();+ expect(state.openChatIds).toEqual(["draft", "real"]);+ expect(state.sessions.draft.composerDraft?.input).toBe("unsent work");+ });+it("clears unread immediately without claiming the panel switched", () => {useChatStore.getState().actions.upsert(baseRecord({ id: "A", lastContentAt: 100 }));useChatStore.getState().actions.setCurrent("A");diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.tsindex ed300357c..fd01cfded 100644--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts@@ -63,6 +63,12 @@ export interface SessionDraft {pendingDocs: StoredPendingDoc[];}+export interface SessionCodingWorkspace {+ repoName: string;+ branch: string;+ worktreePath: string;+}+export interface SessionRecord {/** Pi `session_id` — also the uuid used by `commands.piStart`. */id: string;@@ -131,6 +137,10 @@ export interface SessionRecord {* the model selection when switching between chats. Persisted to disk* so the selection survives app restart. */presetId?: string;+ /** Compact, in-memory identity for a conversation-owned worktree. The+ * backend remains authoritative; this lets inactive tabs keep showing+ * which chats are isolated after the user switches away. */+ codingWorkspace?: SessionCodingWorkspace;// ── Live session content (Phase 3) ─────────────────────────────────// The chat panel reads these instead of holding its own per-render@@ -567,7 +577,42 @@ export const useChatStore = create<ChatStore>((set) => ({return { currentId: id, openChatIds };}),- setPanelSession: (id) => set({ panelSessionId: id }),+ setPanelSession: (id) =>+ set((s) => {+ if (!id) return { panelSessionId: id };++ // The panel creates one empty session on mount so first-send events have+ // an owner immediately. If another chat wins navigation before that+ // placeholder is used, keeping both ids in the tab set paints a second+ // unexplained "untitled" tab. Prune only disposable, inactive blanks+ // after the visual panel switch commits. Real chats, active turns, and+ // blanks with composer text or attachments remain untouched.+ const disposableIds = s.openChatIds.filter((openId) => {+ if (openId === id) return false;+ const session = s.sessions[openId];+ return Boolean(+ session &&+ !session.composerDraft &&+ isReusableBlankChatSession(session),+ );+ });+ if (disposableIds.length === 0) return { panelSessionId: id };++ const disposable = new Set(disposableIds);+ const sessions = { ...s.sessions };+ disposableIds.forEach((disposableId) => delete sessions[disposableId]);+ return {+ panelSessionId: id,+ sessions,+ openChatIds: s.openChatIds.filter(+ (openId) => !disposable.has(openId),+ ),+ splitChatId:+ s.splitChatId && disposable.has(s.splitChatId)+ ? null+ : s.splitChatId,+ };+ }),openChat: (id) =>set((s) =>diff --git a/apps/screenpipe-app-tauri/lib/utils/select-worktree-repository.test.ts b/apps/screenpipe-app-tauri/lib/utils/select-worktree-repository.test.tsindex 0690b4cab..dff016dc3 100644--- a/apps/screenpipe-app-tauri/lib/utils/select-worktree-repository.test.ts+++ b/apps/screenpipe-app-tauri/lib/utils/select-worktree-repository.test.ts@@ -4,10 +4,14 @@import { beforeEach, describe, expect, it, vi } from "vitest";import type { CodingWorkspace, PiProviderConfig } from "@/lib/utils/tauri";-import { selectWorktreeRepository } from "./select-worktree-repository";+import {+ deterministicRepositoryCandidate,+ selectWorktreeRepository,+} from "./select-worktree-repository";const mocks = vi.hoisted(() => ({startAndPrompt: vi.fn(),+ create: vi.fn(),get: vi.fn(),stop: vi.fn(),register: vi.fn(() => vi.fn()),@@ -26,6 +30,7 @@ vi.mock("@/lib/events/bus", () => ({vi.mock("@/lib/utils/tauri", () => ({commands: {piStartAndPrompt: mocks.startAndPrompt,+ codingWorkspaceCreate: mocks.create,codingWorkspaceGet: mocks.get,piStop: mocks.stop,},@@ -56,11 +61,58 @@ const workspace: CodingWorkspace = {beforeEach(() => {vi.clearAllMocks();mocks.startAndPrompt.mockResolvedValue({ status: "ok", data: "prompt-id" });+ mocks.create.mockResolvedValue({ status: "ok", data: workspace });mocks.get.mockResolvedValue({ status: "ok", data: workspace });mocks.stop.mockResolvedValue({ status: "ok", data: { running: false } });});describe("selectWorktreeRepository", () => {+ it("uses the repository containing the starting directory without starting a router agent", async () => {+ await expect(+ selectWorktreeRepository({+ routeSessionId: "__worktree-route:conversation-a:route-123",+ conversationId: "conversation-a",+ task: "make the button blue",+ candidates: [+ "/Users/test/Documents/screenpipe",+ "/Users/test/Documents/website-screenpipe",+ ],+ startingPath: "/Users/test/Documents/screenpipe/apps/desktop",+ providerConfig,+ userToken: "token",+ }),+ ).resolves.toEqual(workspace);++ expect(mocks.create).toHaveBeenCalledWith(+ "conversation-a",+ "/Users/test/Documents/screenpipe",+ );+ expect(mocks.startAndPrompt).not.toHaveBeenCalled();+ });++ it("uses one explicitly named repository without starting a router agent", async () => {+ await expect(+ selectWorktreeRepository({+ routeSessionId: "__worktree-route:conversation-a:route-123",+ conversationId: "conversation-a",+ task: "send a test PR to the screenpipe repo",+ candidates: [+ "/Users/test/Documents/screenpipe",+ "/Users/test/Documents/website-screenpipe",+ ],+ startingPath: "/Users/test/Documents/Codex/task",+ providerConfig,+ userToken: "token",+ }),+ ).resolves.toEqual(workspace);++ expect(mocks.create).toHaveBeenCalledWith(+ "conversation-a",+ "/Users/test/Documents/screenpipe",+ );+ expect(mocks.startAndPrompt).not.toHaveBeenCalled();+ });+it("asks the selected AI to call only start_worktree for a vague task", async () => {await expect(selectWorktreeRepository({@@ -96,6 +148,26 @@ describe("selectWorktreeRepository", () => {expect(mocks.stop).toHaveBeenCalledWith(sessionId);});+ it("does not guess when two candidates share the explicitly named repository", () => {+ expect(+ deterministicRepositoryCandidate({+ task: "fix the screenpipe repo",+ candidates: ["/repos/one/screenpipe", "/repos/two/screenpipe"],+ startingPath: "/tmp/task",+ }),+ ).toBeNull();+ });++ it("does not partially match a related repository name", () => {+ expect(+ deterministicRepositoryCandidate({+ task: "fix screenpipe",+ candidates: ["/repos/website-screenpipe"],+ startingPath: "/tmp/task",+ }),+ ).toBeNull();+ });+it("refuses to route without a discovered repository", async () => {await expect(selectWorktreeRepository({diff --git a/apps/screenpipe-app-tauri/lib/utils/select-worktree-repository.ts b/apps/screenpipe-app-tauri/lib/utils/select-worktree-repository.tsindex 49f11f56a..06efd00dd 100644--- a/apps/screenpipe-app-tauri/lib/utils/select-worktree-repository.ts+++ b/apps/screenpipe-app-tauri/lib/utils/select-worktree-repository.ts@@ -10,9 +10,78 @@ import {type PiProviderConfig,} from "@/lib/utils/tauri";-const ROUTE_TIMEOUT_MS = 60_000;+const ROUTE_TIMEOUT_MS = 15_000;const ROUTE_POLL_MS = 100;+function normalizedPath(value: string): string {+ return value.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();+}++function normalizedWords(value: string): string {+ return value+ .normalize("NFKD")+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, " ")+ .trim();+}++function repositoryName(repositoryPath: string): string {+ const path = normalizedPath(repositoryPath);+ return normalizedWords(+ path.slice(path.lastIndexOf("/") + 1).replace(/\.git$/, ""),+ );+}++/**+ * Skip a second agent process when the repository choice is already explicit.+ *+ * The starting directory owns the strongest signal: a coding task launched+ * from inside a repository belongs to that repository. Outside a repository,+ * accept only one exact, full repository-name mention. Partial keyword scoring+ * stays deliberately out of this path so "screenpipe" cannot silently choose+ * "website-screenpipe", and ambiguous requests still reach the constrained+ * router agent.+ */+export function deterministicRepositoryCandidate({+ task,+ candidates,+ startingPath,+}: {+ task: string;+ candidates: string[];+ startingPath: string | null;+}): string | null {+ if (startingPath) {+ const normalizedStart = normalizedPath(startingPath);+ const containing = candidates+ .filter((candidate) => {+ const normalizedCandidate = normalizedPath(candidate);+ return (+ normalizedStart === normalizedCandidate ||+ normalizedStart.startsWith(`${normalizedCandidate}/`)+ );+ })+ .sort(+ (left, right) =>+ normalizedPath(right).length - normalizedPath(left).length,+ );+ if (containing.length > 0) return containing[0];+ }++ const normalizedTask = ` ${normalizedWords(task)} `;+ const matches = candidates+ .map((candidate) => ({ candidate, name: repositoryName(candidate) }))+ .filter(+ ({ name }) => name.length >= 4 && normalizedTask.includes(` ${name} `),+ )+ .sort((left, right) => right.name.length - left.name.length);+ if (matches.length === 0) return null;++ const bestName = matches[0].name;+ const bestMatches = matches.filter(({ name }) => name === bestName);+ return bestMatches.length === 1 ? bestMatches[0].candidate : null;+}+function routerPrompt(task: string,candidates: string[],@@ -68,6 +137,20 @@ export async function selectWorktreeRepository({throw new Error("No nearby Git repository was found");}+ const deterministicCandidate = deterministicRepositoryCandidate({+ task,+ candidates,+ startingPath,+ });+ if (deterministicCandidate) {+ const created = await commands.codingWorkspaceCreate(+ conversationId,+ deterministicCandidate,+ );+ if (created.status === "error") throw new Error(created.error);+ return created.data;+ }+await mountAgentEventBus();const projectDir = await join(await homeDir(),@@ -75,12 +158,15 @@ export async function selectWorktreeRepository({"pi-worktree-router",);let routeError: string | null = null;+ let routeFinished = false;const unregister = registerForeground(routeSessionId, (envelope) => {const event = envelope.event;if (event?.type === "error") {routeError = String(event.error || event.message || "repository router failed",);+ } else if (event?.type === "agent_end") {+ routeFinished = true;}});@@ -100,6 +186,9 @@ export async function selectWorktreeRepository({if (workspace.status === "error") throw new Error(workspace.error);if (workspace.data) return workspace.data;if (routeError) throw new Error(routeError);+ if (routeFinished) {+ throw new Error("The AI did not choose a repository");+ }await new Promise((resolve) => setTimeout(resolve, ROUTE_POLL_MS));}throw new Error("The AI did not choose a repository in time");diff --git a/docs/pr-assets/chat-worktree-tabs/user-journey.png b/docs/pr-assets/chat-worktree-tabs/user-journey.pngnew file mode 100644index 000000000..24d043721Binary files /dev/null and b/docs/pr-assets/chat-worktree-tabs/user-journey.png differ