Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): remove local-cloud run handoff (#89986)

Jonathan Mieloo64dec6fb6351
diff --git a/products/desktop/apps/code/src/main/di/bindings.ts b/products/desktop/apps/code/src/main/di/bindings.ts
index cece435150cd..5654d04a9960 100644
--- a/products/desktop/apps/code/src/main/di/bindings.ts
+++ b/products/desktop/apps/code/src/main/di/bindings.ts
@@ -39,7 +39,6 @@ import type {
GIT_DIFF_SOURCE,
GitDiffSource,
} from "@posthog/core/git-pr/identifiers";
-import type { HANDOFF_HOST } from "@posthog/core/handoff/identifiers";
import type { GitHubIntegrationService } from "@posthog/core/integrations/github";
import type {
GITHUB_INTEGRATION_SERVICE,
@@ -172,15 +171,6 @@ import type {
FsCapability,
} from "@posthog/workspace-server/services/fs/identifiers";
import type { GitService } from "@posthog/workspace-server/services/git/service";
-import type {
- HANDOFF_GIT_GATEWAY,
- HANDOFF_LOG_GATEWAY,
-} from "@posthog/workspace-server/services/handoff/identifiers";
-import type {
- HandoffGitGateway,
- HandoffLogGateway,
-} from "@posthog/workspace-server/services/handoff/ports";
-import type { HandoffHostService } from "@posthog/workspace-server/services/handoff/service";
import type {
ILogsService,
LOGS_SERVICE,
@@ -429,11 +419,6 @@ export interface MainBindings {
[GIT_WORKSPACE_LOOKUP]: GitWorkspaceLookup;
[GIT_PR_STATUS_PROVIDER]: IGitPrStatus;
- // Handoff
- [HANDOFF_HOST]: HandoffHostService;
- [HANDOFF_GIT_GATEWAY]: HandoffGitGateway;
- [HANDOFF_LOG_GATEWAY]: HandoffLogGateway;
-
// Notification / oauth
[NOTIFICATION_SERVICE]: NotificationService;
[OAUTH_HOST]: OAuthHost;
diff --git a/products/desktop/apps/code/src/main/di/container.ts b/products/desktop/apps/code/src/main/di/container.ts
index 6483efa8138d..327c09377100 100644
--- a/products/desktop/apps/code/src/main/di/container.ts
+++ b/products/desktop/apps/code/src/main/di/container.ts
@@ -43,8 +43,6 @@ import {
} from "@posthog/core/git/identifiers";
import { gitPrModule } from "@posthog/core/git-pr/git-pr.module";
import { GIT_DIFF_SOURCE } from "@posthog/core/git-pr/identifiers";
-import { handoffModule } from "@posthog/core/handoff/handoff.module";
-import { HANDOFF_HOST } from "@posthog/core/handoff/identifiers";
import { integrationsModule } from "@posthog/core/integrations/integrations.module";
import { CanvasLinkService } from "@posthog/core/links/canvas-link";
import { ChannelLinkService } from "@posthog/core/links/channel-link";
@@ -174,12 +172,6 @@ import type { ExternalAppsPreferences } from "@posthog/workspace-server/services
import { foldersModule } from "@posthog/workspace-server/services/folders/folders.module";
import { GitService } from "@posthog/workspace-server/services/git/service";
import { TaskPrStatusService } from "@posthog/workspace-server/services/git/task-pr-status";
-import {
- HANDOFF_GIT_GATEWAY,
- HANDOFF_LOG_GATEWAY,
-} from "@posthog/workspace-server/services/handoff/identifiers";
-import type { HandoffGitGateway } from "@posthog/workspace-server/services/handoff/ports";
-import { HandoffHostService } from "@posthog/workspace-server/services/handoff/service";
import { LOGS_SERVICE } from "@posthog/workspace-server/services/local-logs/identifiers";
import { localMcpModule } from "@posthog/workspace-server/services/local-mcp/local-mcp.module";
import { mcpCallbackModule } from "@posthog/workspace-server/services/mcp-callback/mcp-callback.module";
@@ -599,44 +591,6 @@ container
.bind<IGitPrStatus>(GIT_PR_STATUS_PROVIDER)
.to(TaskPrStatusService)
.inSingletonScope();
-container.load(handoffModule);
-container.bind(HANDOFF_HOST).to(HandoffHostService).inSingletonScope();
-container.bind(HANDOFF_GIT_GATEWAY).toDynamicValue((ctx): HandoffGitGateway => {
- const workspace = ctx.get<WorkspaceClient>(MAIN_WORKSPACE_CLIENT);
- return {
- async getChangedFiles(repoPath) {
- const files = await workspace.git.getChangedFilesHead.query({
- directoryPath: repoPath,
- });
- return files.map((f) => ({
- path: f.path,
- status: f.status,
- linesAdded: f.linesAdded,
- linesRemoved: f.linesRemoved,
- }));
- },
- getLocalGitState: (repoPath) =>
- workspace.git.readHandoffLocalGitState.query({
- directoryPath: repoPath,
- }),
- cleanupAfterCloudHandoff: (repoPath, branchName) =>
- workspace.git.cleanupAfterCloudHandoff.mutate({
- directoryPath: repoPath,
- branchName,
- }),
- };
-});
-container.bind(HANDOFF_LOG_GATEWAY).toDynamicValue((ctx) => {
- const ws = ctx.get<WorkspaceClient>(MAIN_WORKSPACE_CLIENT);
- return {
- seedLocalLogs: (taskRunId: string, content: string) =>
- ws.localLogs.seed.mutate({ taskRunId, content }),
- countLocalLogEntries: (taskRunId: string) =>
- ws.localLogs.count.query({ taskRunId }),
- deleteLocalLogCache: (taskRunId: string) =>
- ws.localLogs.delete.mutate({ taskRunId }),
- };
-});
container.load(mcpCallbackModule);
container.bind(NOTIFICATION_SERVICE).to(NotificationService);
container.load(oauthCallbackModule);
diff --git a/products/desktop/apps/code/src/main/trpc/router.ts b/products/desktop/apps/code/src/main/trpc/router.ts
index 9c63e8b37b78..27428905086a 100644
--- a/products/desktop/apps/code/src/main/trpc/router.ts
+++ b/products/desktop/apps/code/src/main/trpc/router.ts
@@ -24,7 +24,6 @@ import { foldersRouter } from "@posthog/host-router/routers/folders.router";
import { fsRouter } from "@posthog/host-router/routers/fs.router";
import { gitRouter } from "@posthog/host-router/routers/git.router";
import { githubIntegrationRouter } from "@posthog/host-router/routers/github-integration.router";
-import { handoffRouter } from "@posthog/host-router/routers/handoff.router";
import { integrationRouter } from "@posthog/host-router/routers/integration.router";
import { linearIntegrationRouter } from "@posthog/host-router/routers/linear-integration.router";
import { llmGatewayRouter } from "@posthog/host-router/routers/llm-gateway.router";
@@ -88,7 +87,6 @@ export const trpcRouter = router({
git: gitRouter,
githubIntegration: githubIntegrationRouter,
releaseFeed: releaseFeedRouter,
- handoff: handoffRouter,
integration: integrationRouter,
linearIntegration: linearIntegrationRouter,
llmGateway: llmGatewayRouter,
diff --git a/products/desktop/apps/code/src/renderer/di/bindings.ts b/products/desktop/apps/code/src/renderer/di/bindings.ts
index 2736d72bc835..f96aebe4b409 100644
--- a/products/desktop/apps/code/src/renderer/di/bindings.ts
+++ b/products/desktop/apps/code/src/renderer/di/bindings.ts
@@ -96,16 +96,6 @@ import {
CLOUD_ARTIFACT_RESOLVE_SKILL_DEPENDENCIES,
type ResolveSkillBundleDependencies,
} from "@posthog/core/sessions/cloudArtifactIdentifiers";
-import {
- LOCAL_HANDOFF_DIALOG,
- LOCAL_HANDOFF_HOST,
- LOCAL_HANDOFF_NOTIFIER,
- LOCAL_HANDOFF_SERVICE,
- type LocalHandoffDialog,
- type LocalHandoffHost,
- type LocalHandoffNotifier,
- type LocalHandoffService,
-} from "@posthog/core/sessions/localHandoffService";
import {
SESSION_SERVICE,
type SessionService,
@@ -328,10 +318,6 @@ export interface RendererBindings {
[TASK_SERVICE]: TaskService;
[WORKSPACE_SETUP_SAGA]: WorkspaceSetupSaga;
[SESSION_SERVICE]: SessionService;
- [LOCAL_HANDOFF_HOST]: LocalHandoffHost;
- [LOCAL_HANDOFF_DIALOG]: LocalHandoffDialog;
- [LOCAL_HANDOFF_NOTIFIER]: LocalHandoffNotifier;
- [LOCAL_HANDOFF_SERVICE]: LocalHandoffService;
[GIT_WRITE_CLIENT]: IGitWriteClient;
[GIT_INTERACTION_EFFECTS]: GitInteractionEffects;
[GIT_INTERACTION_SERVICE]: GitInteractionService;
diff --git a/products/desktop/apps/code/src/renderer/di/container.ts b/products/desktop/apps/code/src/renderer/di/container.ts
index 844c593723e6..0eaa700a3104 100644
--- a/products/desktop/apps/code/src/renderer/di/container.ts
+++ b/products/desktop/apps/code/src/renderer/di/container.ts
@@ -47,14 +47,6 @@ import {
CLOUD_ARTIFACT_READ_FILE_AS_BASE64,
CLOUD_ARTIFACT_RESOLVE_SKILL_DEPENDENCIES,
} from "@posthog/core/sessions/cloudArtifactIdentifiers";
-import {
- LOCAL_HANDOFF_DIALOG,
- LOCAL_HANDOFF_HOST,
- LOCAL_HANDOFF_NOTIFIER,
- LOCAL_HANDOFF_SERVICE,
- type LocalHandoffHost,
- LocalHandoffService,
-} from "@posthog/core/sessions/localHandoffService";
import {
SESSION_SERVICE,
type SessionService,
@@ -137,10 +129,6 @@ import {
} from "@posthog/ui/features/quick-ask/identifiers";
import { ARTIFACT_HTML_FRAME_COMPONENT } from "@posthog/ui/features/sessions/components/artifactHtmlFrameHost";
import { MCP_TOOL_BLOCK_COMPONENT } from "@posthog/ui/features/sessions/components/session-update/identifiers";
-import {
- localHandoffDialog,
- localHandoffNotifier,
-} from "@posthog/ui/features/sessions/localHandoffService";
import { getSessionService } from "@posthog/ui/features/sessions/sessionServiceHost";
import {
DEV_MODE_CLIENT,
@@ -367,24 +355,6 @@ container
.bind<SessionService>(SESSION_SERVICE)
.toDynamicValue(() => getSessionService())
.inSingletonScope();
-container.bind<LocalHandoffHost>(LOCAL_HANDOFF_HOST).toConstantValue({
- getRepositoryByRemoteUrl: (input) =>
- trpcClient.folders.getRepositoryByRemoteUrl.query(input),
- selectDirectory: () => trpcClient.os.selectDirectory.query(),
- addFolder: (input) => trpcClient.folders.addFolder.mutate(input),
- getWorktreeLocation: () => trpcClient.os.getWorktreeLocation.query(),
- cloneRepository: (input) => trpcClient.git.cloneRepository.mutate(input),
- addAdditionalDirectory: async (input) => {
- await trpcClient.additionalDirectories.addForTask.mutate(input);
- },
-});
-container.bind(LOCAL_HANDOFF_DIALOG).toConstantValue(localHandoffDialog);
-container.bind(LOCAL_HANDOFF_NOTIFIER).toConstantValue(localHandoffNotifier);
-container
- .bind<LocalHandoffService>(LOCAL_HANDOFF_SERVICE)
- .to(LocalHandoffService)
- .inSingletonScope();
-
// git-interaction
container.bind(GIT_WRITE_CLIENT).toConstantValue(gitWriteClient);
container.bind(GIT_INTERACTION_EFFECTS).toConstantValue(gitInteractionEffects);
diff --git a/products/desktop/apps/web/src/web-container.ts b/products/desktop/apps/web/src/web-container.ts
index 03ecd3983ac5..19bea98fd52d 100644
--- a/products/desktop/apps/web/src/web-container.ts
+++ b/products/desktop/apps/web/src/web-container.ts
@@ -115,16 +115,6 @@ import {
type ResolveSkillBundleDependencies,
} from "@posthog/core/sessions/cloudArtifactIdentifiers";
import type { CloudArtifactService } from "@posthog/core/sessions/cloudArtifactService";
-import {
- LOCAL_HANDOFF_DIALOG,
- LOCAL_HANDOFF_HOST,
- LOCAL_HANDOFF_NOTIFIER,
- LOCAL_HANDOFF_SERVICE,
- type LocalHandoffDialog,
- type LocalHandoffHost,
- type LocalHandoffNotifier,
- LocalHandoffService,
-} from "@posthog/core/sessions/localHandoffService";
import {
SESSION_SERVICE,
type SessionService,
@@ -262,10 +252,6 @@ import {
} from "@posthog/ui/features/notifications/identifiers";
import { notificationsUiModule } from "@posthog/ui/features/notifications/notifications.module";
import { OnboardingGithubConnectClient } from "@posthog/ui/features/onboarding/githubConnectClientImpl";
-import {
- localHandoffDialog,
- localHandoffNotifier,
-} from "@posthog/ui/features/sessions/localHandoffService";
import { getSessionService } from "@posthog/ui/features/sessions/sessionServiceHost";
import { setupUiModule } from "@posthog/ui/features/setup/setup.module";
import { taskCreationEffects } from "@posthog/ui/features/task-detail/taskCreationEffectsImpl";
@@ -408,10 +394,6 @@ interface WebBindings {
[TITLE_GENERATOR_LOGGER]: TitleGeneratorLogger;
[LLM_GATEWAY_SERVICE]: LlmGatewayService;
[LLM_GATEWAY_HOST]: LlmGatewayHost;
- [LOCAL_HANDOFF_SERVICE]: LocalHandoffService;
- [LOCAL_HANDOFF_HOST]: LocalHandoffHost;
- [LOCAL_HANDOFF_DIALOG]: LocalHandoffDialog;
- [LOCAL_HANDOFF_NOTIFIER]: LocalHandoffNotifier;
[FILE_WATCHER_CLIENT]: FileWatcherClient;
[GIT_INTERACTION_SERVICE]: GitInteractionService;
[GIT_WRITE_CLIENT]: IGitWriteClient;
@@ -775,28 +757,6 @@ container.bind(LLM_GATEWAY_HOST).toDynamicValue((ctx) => {
};
});
-// ── Local handoff (cloud git header's "hand off to local" affordance) ──
-// LocalHandoffService is resolved eagerly by CloudGitInteractionHeader. The
-// dialog + notifier are host-agnostic UI (reused from @posthog/ui); the host is
-// local-fs (pick a folder, add it) which can't run on the browser, so it's
-// stubbed — a cloud-only host can't hand a task off to a local checkout.
-container.bind(LOCAL_HANDOFF_HOST).toConstantValue({
- getRepositoryByRemoteUrl: () => Promise.resolve(null),
- selectDirectory: () => Promise.resolve(null),
- addFolder: () =>
- Promise.reject(new Error("Local handoff is not available on the web")),
- getWorktreeLocation: () => Promise.resolve(""),
- cloneRepository: () =>
- Promise.reject(new Error("Local handoff is not available on the web")),
- addAdditionalDirectory: () => Promise.resolve(),
-});
-container.bind(LOCAL_HANDOFF_DIALOG).toConstantValue(localHandoffDialog);
-container.bind(LOCAL_HANDOFF_NOTIFIER).toConstantValue(localHandoffNotifier);
-container
- .bind(LOCAL_HANDOFF_SERVICE)
- .to(LocalHandoffService)
- .inSingletonScope();
-
// ── File watcher (TaskDetail's useRepoFileWatcher) ──
// Watches a local repo for changes; there is none on web. The consumer gates
// start/stop on a repoPath (null for cloud tasks), so this no-op never runs.
diff --git a/products/desktop/packages/agent/README.md b/products/desktop/packages/agent/README.md
index 337d6e38fbc1..5ae4b50303a5 100644
--- a/products/desktop/packages/agent/README.md
+++ b/products/desktop/packages/agent/README.md
@@ -59,8 +59,6 @@ The same ACP agent runs in both contexts. The difference is how it's connected:
**Local (desktop):** The agent runs in-process. The desktop app calls `createAcpConnection()` directly — no HTTP server, no JWT. The bidirectional ACP streams connect client ↔ agent within the same process.
-**HandoffCheckpointTracker** handles the bridge between these contexts: it captures git checkpoint state plus the object pack/index needed to restore the worktree across cloud and local. This enables the "hand off" flow — start locally, continue in cloud, or vice versa.
-
### Permission modes
Four modes defined in `src/execution-mode.ts`:
@@ -110,7 +108,7 @@ start()
├─ Creates synthetic JwtPayload from CLI config
├─ configureEnvironment() — sets ANTHROPIC_BASE_URL, OPENAI_BASE_URL, etc.
│ pointing at the PostHog LLM gateway
- ├─ Creates HandoffCheckpointTracker, SessionLogWriter, PostHogAPIClient
+ ├─ Creates SessionLogWriter and PostHogAPIClient
├─ createAcpConnection() — sets up ACP streams with log tapping
│
├─ Wraps client streams with a SECOND tap layer (NdJsonTap)
@@ -148,10 +146,6 @@ When `POST /command` receives a `user_message`, it doesn't handle it directly
The `AgentServer` provides the `requestPermission` callback to the `ClientSideConnection`. Background mode selects an allow option automatically. Interactive mode relays approvals that need a person over SSE and parks them until a client responds; other requests follow the selected permission mode.
-### Checkpoint capture
-
-After file-mutating tool calls, the server captures a git checkpoint via `HandoffCheckpointTracker` and broadcasts it as a `_posthog/git_checkpoint` SSE event. A final checkpoint is captured during session cleanup. This is how the client restores repo state for cloud↔local handoff.
-
### CLI
```bash
@@ -215,7 +209,7 @@ For Codex adapters, `agent.run()` also fetches available models from the PostHog
## Log pipeline and session resume
-Logs serve two purposes: real-time observability and session resume. Every ACP message that flows through the tapped streams is persisted, creating a complete record of the conversation — user messages, agent responses, tool calls, tool results, git checkpoints, and metadata events. This record is the single source of truth for resuming a session from any point.
+Logs serve two purposes: real-time observability and session resume. Every ACP message that flows through the tapped streams is persisted, creating a complete record of the conversation, including user messages, agent responses, tool calls, tool results, and metadata events. This record is the source of truth for resuming a conversation.
### Writing logs
@@ -225,14 +219,12 @@ Independently of that flush cycle, the writer tees every parsed non-chunk entry
### Resuming from logs
-When a session needs to continue (e.g. cloud↔local handoff, or recovering from a crash), `resumeFromLog()` in `src/resume.ts` reconstructs the agent's state from the persisted log. This is implemented as a `ResumeSaga` (`src/sagas/resume-saga.ts`) with the following steps:
+When a session needs to recover from a crash, `resumeFromLog()` in `src/resume.ts` reconstructs the agent's state from the persisted log. This is implemented as a `ResumeSaga` (`src/sagas/resume-saga.ts`) with the following steps:
```text
-1. fetch_task_run → GET /api/.../runs/{runId}/ to find the log_url
-2. fetch_logs → Download all StoredNotification entries
-3. find_git_checkpoint → Scan backwards for latest _posthog/git_checkpoint
-4. rebuild_conversation → Walk log entries to reconstruct conversation turns
-5. find_device → Scan backwards for last device info (local vs cloud)
+1. fetch_task_run → GET /api/.../runs/{runId}/ to find the log_url
+2. fetch_logs → Download all StoredNotification entries
+3. rebuild_conversation → Walk log entries to reconstruct conversation turns
```
The conversation rebuild (`rebuildConversation`) walks the log entries and reassembles turns from ACP `session/update` notifications:
@@ -242,7 +234,7 @@ The conversation rebuild (`rebuildConversation`) walks the log entries and reass
- `tool_call` / `tool_call_update` → track tool calls with their inputs
- `tool_result` → match results back to tool calls by `toolCallId`
-The result is a `ResumeState` containing the conversation history as `ConversationTurn[]`, the latest git checkpoint, and metadata. This feeds into the ACP `session/load` or `_posthog/session/resume` methods on the Claude adapter, which initializes a new Claude SDK query with the rebuilt context.
+The result is a `ResumeState` containing the conversation history as `ConversationTurn[]` and session metadata. This feeds into the ACP `session/load` or `_posthog/session/resume` methods on the Claude adapter, which initializes a new Claude SDK query with the rebuilt context.
## ACP extensions
@@ -256,10 +248,9 @@ ACP defines standard methods like `session/prompt`, `session/update`, and `sessi
- `_posthog/status` — `{ sessionId, status, message? }` — progress updates
- `_posthog/sdk_session` — `{ taskRunId, sessionId, adapter }` — maps the ACP session to a task run and adapter type (emitted once per session, used by clients to know which adapter is active)
-**State synchronization** — events that keep the client's view of the agent's state in sync. These are essential for the cloud↔local handoff flow and for the client to render accurate UI.
+**State synchronization** — events that keep the client's view of the agent's state in sync.
- `_posthog/branch_created` — `{ branch }` — agent created a git branch (client can update branch display)
-- `_posthog/git_checkpoint` — `{ checkpointId, checkpointRef, branch, head, indexTree, worktreeTree, ... }` — git checkpoint captured for resume and handoff. This is the key event for session resume — the resume saga scans backwards for the latest checkpoint to restore files
- `_posthog/mode_change` — `{ mode, previous_mode }` — permission mode changed (client updates mode selector)
- `_posthog/compact_boundary` — `{ sessionId, timestamp }` — marks where context compaction occurred, so the client knows the conversation was summarized at this point
- `_posthog/task_notification` — `{ sessionId, type, message?, data? }` — generic extensible notification for adapter-specific events
diff --git a/products/desktop/packages/agent/package.json b/products/desktop/packages/agent/package.json
index 70c4124e6177..c94ee1ba7075 100644
--- a/products/desktop/packages/agent/package.json
+++ b/products/desktop/packages/agent/package.json
@@ -112,10 +112,6 @@
"types": "./dist/resume.d.ts",
"import": "./dist/resume.js"
},
- "./handoff-checkpoint": {
- "types": "./dist/handoff-checkpoint.d.ts",
- "import": "./dist/handoff-checkpoint.js"
- },
"./pi": {
"types": "./dist/pi/rpc-client.d.ts",
"import": "./dist/pi/rpc-client.js"
diff --git a/products/desktop/packages/agent/src/acp-extensions.ts b/products/desktop/packages/agent/src/acp-extensions.ts
index 224a455294c4..4c57ad4147e1 100644
--- a/products/desktop/packages/agent/src/acp-extensions.ts
+++ b/products/desktop/packages/agent/src/acp-extensions.ts
@@ -45,9 +45,6 @@ export const POSTHOG_NOTIFICATIONS = {
/** Maps taskRunId to agent's sessionId and adapter type (for resumption) */
SDK_SESSION: "_posthog/sdk_session",
- /** Git checkpoint captured for handoff */
- GIT_CHECKPOINT: "_posthog/git_checkpoint",
-
/** Agent mode changed (interactive/background) */
MODE_CHANGE: "_posthog/mode_change",
diff --git a/products/desktop/packages/agent/src/handoff-checkpoint.test.ts b/products/desktop/packages/agent/src/handoff-checkpoint.test.ts
deleted file mode 100644
index 0f4fa49cbd8e..000000000000
--- a/products/desktop/packages/agent/src/handoff-checkpoint.test.ts
+++ /dev/null
@@ -1,383 +0,0 @@
-import { readdir } from "node:fs/promises";
-import path from "node:path";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import {
- decodeHandoffArtifact,
- HandoffCheckpointTracker,
-} from "./handoff-checkpoint";
-import {
- cloneTestRepo,
- createTestRepo,
- type TestRepo,
-} from "./sagas/test-fixtures";
-import type { HandoffLocalGitState } from "./types";
-
-interface BundleStore {
- artifacts: Record<string, Buffer>;
- storagePath: string;
- manifest: Array<{ storage_path: string }>;
-}
-
-interface HandoffRepos {
- cloudRepo: TestRepo;
- localRepo: TestRepo;
- branch: string;
- localGitState: HandoffLocalGitState;
-}
-
-interface MockApiOptions {
- /** Store inline uploads as base64 text, like the backend did before content_encoding was sent. */
- legacyBase64AtRest?: boolean;
- /** Expose the prepare/finalize direct-upload endpoints. */
- directUploads?: boolean;
- /** Make inline uploads fail, like an API rejecting the request. */
- failInlineUploads?: boolean;
- /** Make finalize omit the uploaded artifact from its response. */
- unconfirmedFinalize?: boolean;
-}
-
-function createMockApi(store: BundleStore, options?: MockApiOptions) {
- let nextId = 0;
- const api: Record<string, unknown> = {
- uploadTaskArtifacts: async (
- _taskId: string,
- _runId: string,
- artifacts: Array<{
- name: string;
- content: string;
- content_encoding?: string;
- }>,
- ) => {
- if (options?.failInlineUploads) {
- throw new Error("Failed request: [413] Payload Too Large");
- }
- const uploaded = artifacts.map((artifact) => {
- const storagePath = `${store.storagePath}-${nextId++}-${artifact.name}`;
- store.artifacts[storagePath] =
- !options?.legacyBase64AtRest && artifact.content_encoding === "base64"
- ? Buffer.from(artifact.content, "base64")
- : Buffer.from(artifact.content, "utf-8");
- return { storage_path: storagePath };
- });
- for (const entry of uploaded) {
- store.manifest.push(entry);
- }
- return store.manifest;
- },
- downloadArtifact: async (
- _taskId: string,
- _runId: string,
- artifactPath: string,
- ) => {
- const content = store.artifacts[artifactPath];
- if (!content) return null;
- return content.buffer.slice(
- content.byteOffset,
- content.byteOffset + content.byteLength,
- );
- },
- };
-
- if (options?.directUploads) {
- api.prepareTaskArtifactUploads = async (
- _taskId: string,
- _runId: string,
- artifacts: Array<{ name: string; type: string; size: number }>,
- ) =>
- artifacts.map((artifact) => {
- const storagePath = `${store.storagePath}-${nextId++}-${artifact.name}`;
- return {
- id: `prepared-${storagePath}`,
- name: artifact.name,
- type: artifact.type,
- size: artifact.size,
- storage_path: storagePath,
- expires_in: 300,
- presigned_post: {
- url: "https://object-storage.test/upload",
- fields: { key: storagePath },
- },
- };
- });
- api.finalizeTaskArtifactUploads = async (
- _taskId: string,
- _runId: string,
- artifacts: Array<{ name: string; type: string; storage_path: string }>,
- ) => {
- if (options?.unconfirmedFinalize) {
- return [];
- }
- const finalized = artifacts.map((artifact) => ({
- name: artifact.name,
- type: artifact.type,
- storage_path: artifact.storage_path,
- }));
- for (const entry of finalized) {
- store.manifest.push(entry);
- }
- return finalized;
- };
- }
-
- return api;
-}
-
-function stubPresignedUploadFetch(store: BundleStore): void {
- vi.stubGlobal("fetch", async (_url: string, init?: { body?: unknown }) => {
- const form = init?.body as FormData;
- const key = form.get("key") as string;
- const file = form.get("file") as Blob;
- store.artifacts[key] = Buffer.from(await file.arrayBuffer());
- return new Response(null, { status: 204 });
- });
-}
-
-function createBundleStore(): BundleStore {
- return {
- storagePath: "gs://bucket/handoff",
- artifacts: {},
- manifest: [
- {
- storage_path: "gs://bucket/handoff-0-existing-checkpoint.pack",
- },
- ],
- };
-}
-
-function createTracker(
- repositoryPath: string,
- apiClient: ReturnType<typeof createMockApi>,
-) {
- return new HandoffCheckpointTracker({
- repositoryPath,
- taskId: "task-1",
- runId: "run-1",
- apiClient: apiClient as never,
- });
-}
-
-async function seedCloudRepo(repo: TestRepo): Promise<void> {
- await repo.writeFile("tracked.txt", "base\n");
- await repo.writeFile("unstaged.txt", "base unstaged\n");
- await repo.git(["add", "tracked.txt", "unstaged.txt"]);
- await repo.git(["commit", "-m", "Add tracked files"]);
-}
-
-async function prepareHandoffRepos(
- cleanups: Array<() => Promise<void>>,
-): Promise<HandoffRepos> {
- const cloudRepo = await createTestRepo("handoff-cloud");
- cleanups.push(cloudRepo.cleanup);
- await seedCloudRepo(cloudRepo);
-
- const localRepo = await cloneTestRepo(cloudRepo.path, "handoff-local");
- cleanups.push(localRepo.cleanup);
-
- const branch = await cloudRepo.git(["rev-parse", "--abbrev-ref", "HEAD"]);
- const localHead = await localRepo.git(["rev-parse", "HEAD"]);
- const upstreamHead = await localRepo.git(["rev-parse", `origin/${branch}`]);
-
- return {
- cloudRepo,
- localRepo,
- branch,
- localGitState: {
- head: localHead,
- branch,
- upstreamHead,
- upstreamRemote: "origin",
- upstreamMergeRef: `refs/heads/${branch}`,
- },
- };
-}
-
-async function makeCloudChanges(repo: TestRepo): Promise<void> {
- await repo.writeFile("committed.txt", "cloud commit\n");
- await repo.git(["add", "committed.txt"]);
- await repo.git(["commit", "-m", "Cloud commit"]);
-
- await repo.writeFile("tracked.txt", "staged change\n");
- await repo.git(["add", "tracked.txt"]);
- await repo.writeFile("unstaged.txt", "unstaged change\n");
- await repo.writeFile("untracked.txt", "untracked\n");
-}
-
-describe("HandoffCheckpointTracker", () => {
- const cleanups: Array<() => Promise<void>> = [];
-
- afterEach(async () => {
- vi.unstubAllGlobals();
- await Promise.all(cleanups.splice(0).map((cleanup) => cleanup()));
- });
-
- it("restores head, worktree, and index state for handoff replay", async () => {
- const { cloudRepo, localRepo, branch, localGitState } =
- await prepareHandoffRepos(cleanups);
- await makeCloudChanges(cloudRepo);
-
- const store = createBundleStore();
- const apiClient = createMockApi(store);
- const captureTracker = createTracker(cloudRepo.path, apiClient);
-
- const checkpoint = await captureTracker.captureForHandoff(localGitState);
-
- expect(checkpoint).not.toBeNull();
- if (!checkpoint) return;
- expect(Object.keys(store.artifacts).length).toBeGreaterThan(0);
- const gitCommonDirRaw = await cloudRepo.git([
- "rev-parse",
- "--git-common-dir",
- ]);
- const gitCommonDir = path.isAbsolute(gitCommonDirRaw)
- ? gitCommonDirRaw
- : path.resolve(cloudRepo.path, gitCommonDirRaw);
- expect(
- (await readdir(gitCommonDir)).filter((entry) =>
- entry.startsWith("posthog-code-handoff-"),
- ),
- ).toEqual([]);
-
- const applyTracker = createTracker(localRepo.path, apiClient);
- await applyTracker.applyFromHandoff(checkpoint);
-
- expect(await localRepo.git(["rev-parse", "HEAD"])).toBe(checkpoint.head);
- expect(await localRepo.git(["rev-parse", "--abbrev-ref", "HEAD"])).toBe(
- branch,
- );
- expect(await localRepo.readFile("committed.txt")).toBe("cloud commit\n");
- expect(await localRepo.readFile("tracked.txt")).toBe("staged change\n");
- expect(await localRepo.readFile("unstaged.txt")).toBe("unstaged change\n");
- expect(await localRepo.readFile("untracked.txt")).toBe("untracked\n");
-
- const status = await localRepo.git(["status", "--porcelain"]);
- expect(status).toContain("M tracked.txt");
- expect(status).toContain(" M unstaged.txt");
- expect(status).toContain("?? untracked.txt");
- expect(localRepo.exists(".posthog/tmp")).toBe(false);
- });
-
- it("round-trips a cloud capture without local git state via direct-to-storage uploads", async () => {
- const originRepo = await createTestRepo("handoff-origin");
- cleanups.push(originRepo.cleanup);
- await seedCloudRepo(originRepo);
-
- const sandboxRepo = await cloneTestRepo(originRepo.path, "handoff-sandbox");
- cleanups.push(sandboxRepo.cleanup);
- const resumeRepo = await cloneTestRepo(originRepo.path, "handoff-resume");
- cleanups.push(resumeRepo.cleanup);
-
- await makeCloudChanges(sandboxRepo);
-
- const store = createBundleStore();
- const apiClient = createMockApi(store, { directUploads: true });
- stubPresignedUploadFetch(store);
-
- const captureTracker = createTracker(sandboxRepo.path, apiClient);
- const checkpoint = await captureTracker.captureForHandoff();
-
- expect(checkpoint).not.toBeNull();
- if (!checkpoint) return;
- expect(checkpoint.artifactPath).toBeDefined();
- expect(checkpoint.indexArtifactPath).toBeDefined();
-
- // Direct uploads store raw bytes, not base64 text.
- const pack = store.artifacts[checkpoint.artifactPath as string];
- expect(pack.subarray(0, 4).toString("utf-8")).toBe("PACK");
-
- const applyTracker = createTracker(resumeRepo.path, apiClient);
- await applyTracker.applyFromHandoff(checkpoint);
-
- expect(await resumeRepo.git(["rev-parse", "HEAD"])).toBe(checkpoint.head);
- expect(await resumeRepo.readFile("committed.txt")).toBe("cloud commit\n");
- expect(await resumeRepo.readFile("tracked.txt")).toBe("staged change\n");
- expect(await resumeRepo.readFile("unstaged.txt")).toBe("unstaged change\n");
- expect(await resumeRepo.readFile("untracked.txt")).toBe("untracked\n");
-
- const status = await resumeRepo.git(["status", "--porcelain"]);
- expect(status).toContain("M tracked.txt");
- expect(status).toContain(" M unstaged.txt");
- expect(status).toContain("?? untracked.txt");
- });
-
- it("applies checkpoints whose artifacts are stored as legacy base64 text", async () => {
- const { cloudRepo, localRepo, localGitState } =
- await prepareHandoffRepos(cleanups);
- await makeCloudChanges(cloudRepo);
-
- const store = createBundleStore();
- const apiClient = createMockApi(store, { legacyBase64AtRest: true });
- const captureTracker = createTracker(cloudRepo.path, apiClient);
-
- const checkpoint = await captureTracker.captureForHandoff(localGitState);
- expect(checkpoint).not.toBeNull();
- if (!checkpoint) return;
-
- // Sanity-check the fixture: artifacts at rest are base64 text, not raw bytes.
- const pack = store.artifacts[checkpoint.artifactPath as string];
- expect(pack.subarray(0, 4).toString("utf-8")).not.toBe("PACK");
-
- const applyTracker = createTracker(localRepo.path, apiClient);
- await applyTracker.applyFromHandoff(checkpoint);
-
- expect(await localRepo.git(["rev-parse", "HEAD"])).toBe(checkpoint.head);
- expect(await localRepo.readFile("committed.txt")).toBe("cloud commit\n");
- expect(await localRepo.readFile("tracked.txt")).toBe("staged change\n");
- });
-
- it("returns null instead of a checkpoint when artifact uploads fail", async () => {
- const { cloudRepo, localGitState } = await prepareHandoffRepos(cleanups);
- await makeCloudChanges(cloudRepo);
-
- const store = createBundleStore();
- const apiClient = createMockApi(store, { failInlineUploads: true });
- const captureTracker = createTracker(cloudRepo.path, apiClient);
-
- const checkpoint = await captureTracker.captureForHandoff(localGitState);
-
- expect(checkpoint).toBeNull();
- });
-
- it("falls back to inline upload when finalize does not confirm the artifact", async () => {
- const { cloudRepo, localRepo, localGitState } =
- await prepareHandoffRepos(cleanups);
- await makeCloudChanges(cloudRepo);
-
- const store = createBundleStore();
- const apiClient = createMockApi(store, {
- directUploads: true,
- unconfirmedFinalize: true,
- });
- stubPresignedUploadFetch(store);
- const captureTracker = createTracker(cloudRepo.path, apiClient);
-
- const checkpoint = await captureTracker.captureForHandoff(localGitState);
-
- expect(checkpoint).not.toBeNull();
- if (!checkpoint) return;
- // The unconfirmed direct upload must not be referenced; the checkpoint
- // points at the inline upload, which stores decoded bytes.
- const pack = store.artifacts[checkpoint.artifactPath as string];
- expect(pack.subarray(0, 4).toString("utf-8")).toBe("PACK");
-
- const applyTracker = createTracker(localRepo.path, apiClient);
- await applyTracker.applyFromHandoff(checkpoint);
- expect(await localRepo.readFile("committed.txt")).toBe("cloud commit\n");
- });
-
- it("decodes raw and legacy base64 artifact buffers", () => {
- const rawPack = Buffer.concat([
- Buffer.from("PACK"),
- Buffer.from([0, 0, 0, 2, 255, 1, 2, 3]),
- ]);
- expect(decodeHandoffArtifact(rawPack)).toEqual(rawPack);
-
- const rawIndex = Buffer.concat([
- Buffer.from("DIRC"),
- Buffer.from([0, 0, 0, 2, 255, 4, 5, 6]),
- ]);
- expect(decodeHandoffArtifact(rawIndex)).toEqual(rawIndex);
-
- const legacyBase64 = Buffer.from(rawPack.toString("base64"), "utf-8");
- expect(decodeHandoffArtifact(legacyBase64)).toEqual(rawPack);
- });
-});
diff --git a/products/desktop/packages/agent/src/handoff-checkpoint.ts b/products/desktop/packages/agent/src/handoff-checkpoint.ts
deleted file mode 100644
index f68cf273e74e..000000000000
--- a/products/desktop/packages/agent/src/handoff-checkpoint.ts
+++ /dev/null
@@ -1,525 +0,0 @@
-import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import {
- type GitHandoffBranchDivergence,
- type GitHandoffCheckpoint,
- GitHandoffTracker,
-} from "@posthog/git/handoff";
-import type {
- PostHogAPIClient,
- PreparedTaskArtifactUpload,
-} from "./posthog-api";
-import type { GitCheckpoint, HandoffLocalGitState } from "./types";
-import { Logger } from "./utils/logger";
-
-/** Server-side cap on a single task-run artifact; larger files are skipped, not failed. */
-const MAX_ARTIFACT_UPLOAD_BYTES = 30 * 1024 * 1024;
-/** Inline uploads travel base64-encoded inside a JSON API body, so they must stay well under API request size limits. */
-const MAX_INLINE_UPLOAD_BYTES = 10 * 1024 * 1024;
-
-const PACK_MAGIC = Buffer.from("PACK");
-const INDEX_MAGIC = Buffer.from("DIRC");
-
-/**
- * Handoff artifacts used to be stored as base64 text (inline uploads without
- * content_encoding); direct-to-storage uploads store raw bytes. Detect raw
- * git payloads by their magic bytes and fall back to the legacy base64
- * decode otherwise.
- */
-export function decodeHandoffArtifact(buffer: Buffer): Buffer {
- const head = buffer.subarray(0, 4);
- if (head.equals(PACK_MAGIC) || head.equals(INDEX_MAGIC)) {
- return buffer;
- }
- const text = buffer.toString("utf-8");
- if (/^[A-Za-z0-9+/]+={0,2}$/.test(text)) {
- return Buffer.from(text, "base64");
- }
- return buffer;
-}
-
-export interface HandoffCheckpointTrackerConfig {
- repositoryPath: string;
- taskId: string;
- runId: string;
- apiClient?: PostHogAPIClient;
- logger?: Logger;
-}
-
-type ArtifactTransfer<T extends object = Record<string, never>> = T & {
- rawBytes: number;
- wireBytes: number;
-};
-
-type UploadedArtifact = ArtifactTransfer<{ storagePath?: string }>;
-type DownloadedArtifact = ArtifactTransfer<{ filePath: string }>;
-
-type ArtifactKey = "pack" | "index";
-type ArtifactSlotMap<T extends object> = Partial<
- Record<ArtifactKey, ArtifactTransfer<T>>
->;
-
-interface UploadArtifactSpec {
- key: ArtifactKey;
- filePath?: string;
- name: string;
- contentType: string;
-}
-
-interface DownloadArtifactSpec {
- key: ArtifactKey;
- storagePath?: string;
- filePath: string;
- label: string;
-}
-
-type Uploads = ArtifactSlotMap<{ storagePath?: string }>;
-type Downloads = ArtifactSlotMap<{ filePath: string }>;
-
-export class HandoffCheckpointTracker {
- private repositoryPath: string;
- private taskId: string;
- private runId: string;
- private apiClient?: PostHogAPIClient;
- private logger: Logger;
-
- constructor(config: HandoffCheckpointTrackerConfig) {
- this.repositoryPath = config.repositoryPath;
- this.taskId = config.taskId;
- this.runId = config.runId;
- this.apiClient = config.apiClient;
- this.logger =
- config.logger ||
- new Logger({ debug: false, prefix: "[HandoffCheckpointTracker]" });
- }
-
- async captureForHandoff(
- localGitState?: HandoffLocalGitState,
- ): Promise<GitCheckpoint | null> {
- if (!this.apiClient) {
- throw new Error(
- "Cannot capture handoff checkpoint: API client not configured",
- );
- }
-
- const gitTracker = this.createGitTracker();
- const capture = await gitTracker.captureForHandoff(localGitState);
-
- try {
- const uploads = await this.uploadArtifacts([
- {
- key: "pack",
- filePath: capture.headPack?.path,
- name: `handoff/${capture.checkpoint.checkpointId}.pack`,
- contentType: "application/x-git-packed-objects",
- },
- {
- key: "index",
- filePath: capture.indexFile.path,
- name: `handoff/${capture.checkpoint.checkpointId}.index`,
- contentType: "application/octet-stream",
- },
- ]);
-
- // A checkpoint that references artifacts which never made it to storage
- // would make resume apply an incomplete git state; drop it instead.
- const packUploadMissing =
- !!capture.headPack && !uploads.pack?.storagePath;
- const indexUploadMissing = !uploads.index?.storagePath;
- if (packUploadMissing || indexUploadMissing) {
- this.logger.warn(
- "Discarding handoff checkpoint: required artifact uploads did not complete",
- {
- checkpointId: capture.checkpoint.checkpointId,
- packUploadMissing,
- indexUploadMissing,
- packBytes: capture.headPack?.rawBytes ?? 0,
- indexBytes: capture.indexFile.rawBytes,
- },
- );
- return null;
- }
-
- this.logCaptureMetrics(capture.checkpoint, uploads);
-
- return {
- ...capture.checkpoint,
- artifactPath: uploads.pack?.storagePath,
- indexArtifactPath: uploads.index?.storagePath,
- };
- } finally {
- await rm(capture.artifactDirectory, {
- recursive: true,
- force: true,
- }).catch(() => {});
- }
- }
-
- async applyFromHandoff(
- checkpoint: GitCheckpoint,
- options?: {
- localGitState?: HandoffLocalGitState;
- onDivergedBranch?: (
- divergence: GitHandoffBranchDivergence,
- ) => Promise<boolean>;
- },
- ): Promise<{ packBytes: number; indexBytes: number; totalBytes: number }> {
- if (!this.apiClient) {
- throw new Error(
- "Cannot apply handoff checkpoint: API client not configured",
- );
- }
-
- const gitTracker = this.createGitTracker();
- const tmpDir = await mkdtemp(
- join(tmpdir(), `posthog-code-handoff-${checkpoint.checkpointId}-`),
- );
-
- const packPath = join(tmpDir, `${checkpoint.checkpointId}.pack`);
- const indexPath = join(tmpDir, `${checkpoint.checkpointId}.index`);
-
- try {
- const downloads = await this.downloadArtifacts([
- {
- key: "pack",
- storagePath: checkpoint.artifactPath,
- filePath: packPath,
- label: "handoff pack",
- },
- {
- key: "index",
- storagePath: checkpoint.indexArtifactPath,
- filePath: indexPath,
- label: "handoff index",
- },
- ]);
-
- const applyResult = await gitTracker.applyFromHandoff({
- checkpoint: this.toGitCheckpoint(checkpoint),
- headPackPath: downloads.pack?.filePath,
- indexPath: downloads.index?.filePath,
- localGitState: options?.localGitState,
- onDivergedBranch: options?.onDivergedBranch,
- });
-
- this.logApplyMetrics(checkpoint, downloads, applyResult.totalBytes);
-
- return {
- packBytes: downloads.pack?.rawBytes ?? 0,
- indexBytes: downloads.index?.rawBytes ?? 0,
- totalBytes: applyResult.totalBytes,
- };
- } finally {
- await this.removeIfPresent(packPath);
- await this.removeIfPresent(indexPath);
- await rm(tmpDir, { recursive: true, force: true }).catch(() => {});
- }
- }
-
- private toGitCheckpoint(checkpoint: GitCheckpoint): GitHandoffCheckpoint {
- return {
- checkpointId: checkpoint.checkpointId,
- commit: checkpoint.commit,
- checkpointRef: checkpoint.checkpointRef,
- headRef: checkpoint.headRef,
- head: checkpoint.head,
- branch: checkpoint.branch,
- indexTree: checkpoint.indexTree,
- worktreeTree: checkpoint.worktreeTree,
- timestamp: checkpoint.timestamp,
- upstreamRemote: checkpoint.upstreamRemote ?? null,
- upstreamMergeRef: checkpoint.upstreamMergeRef ?? null,
- remoteUrl: checkpoint.remoteUrl ?? null,
- };
- }
-
- private async uploadArtifactFile(
- filePath: string,
- name: string,
- contentType: string,
- ): Promise<UploadedArtifact> {
- if (!this.apiClient) {
- return { rawBytes: 0, wireBytes: 0 };
- }
-
- const { size } = await stat(filePath);
- if (size > MAX_ARTIFACT_UPLOAD_BYTES) {
- this.logger.warn(
- "Skipping handoff artifact upload: file exceeds the artifact size limit",
- {
- name,
- rawBytes: size,
- maxBytes: MAX_ARTIFACT_UPLOAD_BYTES,
- },
- );
- return { rawBytes: size, wireBytes: 0 };
- }
-
- const content = await readFile(filePath);
-
- try {
- const storagePath = await this.uploadArtifactDirect(
- content,
- name,
- contentType,
- );
- if (storagePath) {
- return {
- storagePath,
- rawBytes: content.byteLength,
- wireBytes: content.byteLength,
- };
- }
- } catch (error) {
- this.logger.warn(
- "Direct artifact upload failed; falling back to inline upload",
- { name, error: error instanceof Error ? error.message : String(error) },
- );
- }
-
- return this.uploadArtifactInline(content, name, contentType);
- }
-
- private async uploadArtifactDirect(
- content: Buffer,
- name: string,
- contentType: string,
- ): Promise<string | undefined> {
- if (!this.apiClient) {
- return undefined;
- }
-
- const [prepared] = await this.apiClient.prepareTaskArtifactUploads(
- this.taskId,
- this.runId,
- [
- {
- name,
- type: "artifact",
- size: content.byteLength,
- content_type: contentType,
- },
- ],
- );
- if (!prepared) {
- return undefined;
- }
-
- await this.postToPresignedUrl(prepared, content, contentType);
-
- const [finalized] = await this.apiClient.finalizeTaskArtifactUploads(
- this.taskId,
- this.runId,
- [
- {
- id: prepared.id,
- name: prepared.name,
- type: "artifact",
- storage_path: prepared.storage_path,
- content_type: contentType,
- },
- ],
- );
- // An unconfirmed finalize means the artifact was never attached to the
- // run manifest; referencing it would break the download on resume.
- if (!finalized?.storage_path) {
- throw new Error(
- `Artifact finalize did not confirm ${name} at ${prepared.storage_path}`,
- );
- }
- return finalized.storage_path;
- }
-
- private async postToPresignedUrl(
- prepared: PreparedTaskArtifactUpload,
- content: Buffer,
- contentType: string,
- ): Promise<void> {
- const form = new FormData();
- for (const [key, value] of Object.entries(prepared.presigned_post.fields)) {
- form.append(key, value);
- }
- form.append(
- "file",
- new Blob([new Uint8Array(content)], { type: contentType }),
- prepared.name,
- );
-
- const response = await fetch(prepared.presigned_post.url, {
- method: "POST",
- body: form,
- });
- if (!response.ok) {
- throw new Error(
- `Presigned artifact upload failed: [${response.status}] ${response.statusText}`,
- );
- }
- }
-
- private async uploadArtifactInline(
- content: Buffer,
- name: string,
- contentType: string,
- ): Promise<UploadedArtifact> {
- if (!this.apiClient) {
- return { rawBytes: content.byteLength, wireBytes: 0 };
- }
-
- if (content.byteLength > MAX_INLINE_UPLOAD_BYTES) {
- this.logger.warn(
- "Skipping inline handoff artifact upload: file exceeds the inline upload limit",
- {
- name,
- rawBytes: content.byteLength,
- maxBytes: MAX_INLINE_UPLOAD_BYTES,
- },
- );
- return { rawBytes: content.byteLength, wireBytes: 0 };
- }
-
- const base64Content = content.toString("base64");
- try {
- const artifacts = await this.apiClient.uploadTaskArtifacts(
- this.taskId,
- this.runId,
- [
- {
- name,
- type: "artifact",
- content: base64Content,
- content_encoding: "base64",
- content_type: contentType,
- },
- ],
- );
- return {
- storagePath: artifacts.at(-1)?.storage_path,
- rawBytes: content.byteLength,
- wireBytes: Buffer.byteLength(base64Content, "utf-8"),
- };
- } catch (error) {
- this.logger.warn("Inline handoff artifact upload failed", {
- name,
- rawBytes: content.byteLength,
- error: error instanceof Error ? error.message : String(error),
- });
- return { rawBytes: content.byteLength, wireBytes: 0 };
- }
- }
-
- private async uploadArtifacts(specs: UploadArtifactSpec[]): Promise<Uploads> {
- const results: Array<readonly [ArtifactKey, UploadedArtifact | undefined]> =
- [];
- for (const spec of specs) {
- if (!spec.filePath) {
- results.push([spec.key, undefined] as const);
- continue;
- }
- results.push([
- spec.key,
- await this.uploadArtifactFile(
- spec.filePath,
- spec.name,
- spec.contentType,
- ),
- ] as const);
- }
-
- return Object.fromEntries(results) as Uploads;
- }
-
- private async downloadArtifactToFile(
- artifactPath: string,
- filePath: string,
- label: string,
- ): Promise<DownloadedArtifact> {
- if (!this.apiClient) {
- throw new Error(`Cannot download ${label}: API client not configured`);
- }
-
- const arrayBuffer = await this.apiClient.downloadArtifact(
- this.taskId,
- this.runId,
- artifactPath,
- );
- if (!arrayBuffer) {
- throw new Error(`Failed to download ${label} from ${artifactPath}`);
- }
- const binaryContent = decodeHandoffArtifact(Buffer.from(arrayBuffer));
- await writeFile(filePath, binaryContent);
- return {
- filePath,
- rawBytes: binaryContent.byteLength,
- wireBytes: arrayBuffer.byteLength,
- };
- }
-
- private async downloadArtifacts(
- specs: DownloadArtifactSpec[],
- ): Promise<Downloads> {
- const downloads = await Promise.all(
- specs.map(async (spec) => {
- if (!spec.storagePath) {
- return [spec.key, undefined] as const;
- }
- return [
- spec.key,
- await this.downloadArtifactToFile(
- spec.storagePath,
- spec.filePath,
- spec.label,
- ),
- ] as const;
- }),
- );
-
- return Object.fromEntries(downloads) as Downloads;
- }
-
- private createGitTracker(): GitHandoffTracker {
- return new GitHandoffTracker({
- repositoryPath: this.repositoryPath,
- logger: this.logger,
- });
- }
-
- private logCaptureMetrics(
- checkpoint: GitHandoffCheckpoint,
- uploads: Uploads,
- ): void {
- this.logger.debug("Captured handoff checkpoint", {
- branch: checkpoint.branch,
- head: checkpoint.head?.slice(0, 7),
- totalBytes: this.sumRawBytes(uploads.pack, uploads.index),
- });
- }
-
- private logApplyMetrics(
- checkpoint: GitCheckpoint,
- _downloads: Downloads,
- totalBytes: number,
- ): void {
- this.logger.debug("Applied handoff checkpoint", {
- branch: checkpoint.branch,
- head: checkpoint.head?.slice(0, 7),
- totalBytes,
- });
- }
-
- private sumRawBytes(
- ...artifacts: Array<{ rawBytes: number } | undefined>
- ): number {
- return artifacts.reduce(
- (total, artifact) => total + (artifact?.rawBytes ?? 0),
- 0,
- );
- }
-
- private async removeIfPresent(filePath: string | undefined): Promise<void> {
- if (!filePath) {
- return;
- }
- await rm(filePath, { force: true }).catch(() => {});
- }
-}
diff --git a/products/desktop/packages/agent/src/otel-telemetry.test.ts b/products/desktop/packages/agent/src/otel-telemetry.test.ts
index 66ac11c75948..c863e5958e22 100644
--- a/products/desktop/packages/agent/src/otel-telemetry.test.ts
+++ b/products/desktop/packages/agent/src/otel-telemetry.test.ts
@@ -215,14 +215,6 @@ describe("OtelRunTelemetry", () => {
progress_status: "completed",
},
},
- {
- name: "git_checkpoint",
- entry: makeEntry("_posthog/git_checkpoint", {
- branch: "posthog-code/fix",
- }),
- body: "git checkpoint",
- attrs: { branch: "posthog-code/fix" },
- },
{
name: "branch_created",
entry: makeEntry("_posthog/branch_created", { branch: "b1" }),
diff --git a/products/desktop/packages/agent/src/otel-telemetry.ts b/products/desktop/packages/agent/src/otel-telemetry.ts
index 00f5fbc96a67..a9c62f84f728 100644
--- a/products/desktop/packages/agent/src/otel-telemetry.ts
+++ b/products/desktop/packages/agent/src/otel-telemetry.ts
@@ -232,11 +232,6 @@ export function mapNotificationToLogRecord(
attrs,
);
}
- case POSTHOG_NOTIFICATIONS.GIT_CHECKPOINT: {
- const attrs: Attributes = {};
- strAttr(attrs, "branch", params.branch);
- return record(INFO, "git checkpoint", method, attrs);
- }
case POSTHOG_NOTIFICATIONS.BRANCH_CREATED: {
const attrs: Attributes = {};
strAttr(attrs, "branch", params.branch ?? params.branchName);
diff --git a/products/desktop/packages/agent/src/posthog-api.ts b/products/desktop/packages/agent/src/posthog-api.ts
index da3d914fa9e2..d49ca31e812b 100644
--- a/products/desktop/packages/agent/src/posthog-api.ts
+++ b/products/desktop/packages/agent/src/posthog-api.ts
@@ -110,13 +110,7 @@ export interface PeerMessageSendResult {
export type TaskRunUpdate = Partial<
Pick<
TaskRun,
- | "status"
- | "branch"
- | "stage"
- | "error_message"
- | "output"
- | "state"
- | "environment"
+ "status" | "branch" | "stage" | "error_message" | "output" | "state"
>
> & {
state_remove_keys?: string[];
@@ -368,14 +362,6 @@ export class PostHogAPIClient {
);
}
- async resumeRunInCloud(taskId: string, runId: string): Promise<TaskRun> {
- const teamId = this.getTeamId();
- return this.apiRequest<TaskRun>(
- `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/resume_in_cloud/`,
- { method: "POST" },
- );
- }
-
async updateTaskRun(
taskId: string,
runId: string,
diff --git a/products/desktop/packages/agent/src/resume.ts b/products/desktop/packages/agent/src/resume.ts
index f5fab4d5bab2..1ef2debe3ac5 100644
--- a/products/desktop/packages/agent/src/resume.ts
+++ b/products/desktop/packages/agent/src/resume.ts
@@ -3,15 +3,12 @@
*
* Handles resuming a task from any point:
* - Fetches log via the PostHog API
- * - Finds latest git_checkpoint event
* - Rebuilds conversation from log events
- * - Restores working tree from checkpoint
*
* Uses Saga pattern for atomic operations with clear success/failure tracking.
*
* The log is the single source of truth for:
* - Conversation history (user_message, agent_message_chunk, tool_call, tool_result)
- * - Working tree state (git_checkpoint events)
* - Session metadata (device info, mode changes)
*/
@@ -20,15 +17,11 @@ import type { NativeGoalState } from "./acp-extensions";
import { selectRecentTurns } from "./adapters/claude/session/jsonl-hydration";
import type { PostHogAPIClient } from "./posthog-api";
import { ResumeSaga } from "./sagas/resume-saga";
-import type { DeviceInfo, GitCheckpointEvent } from "./types";
import { Logger } from "./utils/logger";
export interface ResumeState {
conversation: ConversationTurn[];
- latestGitCheckpoint: GitCheckpointEvent | null;
- latestGitCheckpoints?: GitCheckpointEvent[];
interrupted: boolean;
- lastDevice?: DeviceInfo;
logEntryCount: number;
sessionId: string | null;
nativeGoal?: NativeGoalState | null;
@@ -58,7 +51,6 @@ export interface ResumeConfig {
/**
* Resume a task from its persisted log.
* Returns the rebuilt state for the agent to continue from.
- * Checkpoint application happens in the agent server after SSE connects.
*/
export async function resumeFromLog(
config: ResumeConfig,
@@ -93,10 +85,7 @@ export async function resumeFromLog(
return {
conversation: result.data.conversation as ConversationTurn[],
- latestGitCheckpoint: result.data.latestGitCheckpoint,
- latestGitCheckpoints: result.data.latestGitCheckpoints,
interrupted: result.data.interrupted,
- lastDevice: result.data.lastDevice,
logEntryCount: result.data.logEntryCount,
sessionId: result.data.sessionId,
nativeGoal: result.data.nativeGoal,
diff --git a/products/desktop/packages/agent/src/sagas/resume-saga.test.ts b/products/desktop/packages/agent/src/sagas/resume-saga.test.ts
index 9d6bc24bb2b8..ba6833f16dbc 100644
--- a/products/desktop/packages/agent/src/sagas/resume-saga.test.ts
+++ b/products/desktop/packages/agent/src/sagas/resume-saga.test.ts
@@ -6,7 +6,6 @@ import { ResumeSaga } from "./resume-saga";
import {
createAgentChunk,
createAgentMessage,
- createGitCheckpointNotification,
createMockApiClient,
createMockLogger,
createNotification,
@@ -50,7 +49,6 @@ describe("ResumeSaga", () => {
expect(result.success).toBe(true);
if (result.success) {
expect(result.data.conversation).toHaveLength(0);
- expect(result.data.latestGitCheckpoint).toBeNull();
expect(result.data.logEntryCount).toBe(0);
}
});
@@ -447,106 +445,6 @@ describe("ResumeSaga", () => {
});
});
- describe("checkpoint finding", () => {
- it("finds latest git checkpoint", async () => {
- (mockApiClient.getTaskRun as ReturnType<typeof vi.fn>).mockResolvedValue(
- createTaskRun(),
- );
- (
- mockApiClient.fetchTaskRunLogs as ReturnType<typeof vi.fn>
- ).mockResolvedValue([
- createGitCheckpointNotification({
- checkpointId: "checkpoint-1",
- checkpointRef: "refs/posthog-code-checkpoint/checkpoint-1",
- head: "head-1",
- }),
- createUserMessage("continue"),
- createGitCheckpointNotification({
- checkpointId: "checkpoint-2",
- checkpointRef: "refs/posthog-code-checkpoint/checkpoint-2",
- head: "head-2",
- }),
- ]);
-
- const saga = new ResumeSaga(mockLogger);
- const result = await saga.run({
- taskId: "task-1",
- runId: "run-1",
- repositoryPath: repo.path,
- apiClient: mockApiClient,
- });
-
- expect(result.success).toBe(true);
- if (!result.success) return;
-
- expect(result.data.latestGitCheckpoint?.checkpointId).toBe(
- "checkpoint-2",
- );
- });
-
- it("does not mark resume as interrupted from checkpoint state", async () => {
- (mockApiClient.getTaskRun as ReturnType<typeof vi.fn>).mockResolvedValue(
- createTaskRun(),
- );
- (
- mockApiClient.fetchTaskRunLogs as ReturnType<typeof vi.fn>
- ).mockResolvedValue([
- createGitCheckpointNotification({
- checkpointId: "checkpoint-1",
- checkpointRef: "refs/posthog-code-checkpoint/checkpoint-1",
- }),
- ]);
-
- const saga = new ResumeSaga(mockLogger);
- const result = await saga.run({
- taskId: "task-1",
- runId: "run-1",
- repositoryPath: repo.path,
- apiClient: mockApiClient,
- });
-
- expect(result.success).toBe(true);
- if (!result.success) return;
-
- expect(result.data.interrupted).toBe(false);
- });
- });
-
- describe("device info", () => {
- it("extracts device info from log entries", async () => {
- (mockApiClient.getTaskRun as ReturnType<typeof vi.fn>).mockResolvedValue(
- createTaskRun(),
- );
- (
- mockApiClient.fetchTaskRunLogs as ReturnType<typeof vi.fn>
- ).mockResolvedValue([
- createGitCheckpointNotification({
- checkpointId: "checkpoint-1",
- checkpointRef: "refs/posthog-code-checkpoint/checkpoint-1",
- device: { type: "local" },
- }),
- createGitCheckpointNotification({
- checkpointId: "checkpoint-2",
- checkpointRef: "refs/posthog-code-checkpoint/checkpoint-2",
- device: { type: "cloud" },
- }),
- ]);
-
- const saga = new ResumeSaga(mockLogger);
- const result = await saga.run({
- taskId: "task-1",
- runId: "run-1",
- repositoryPath: repo.path,
- apiClient: mockApiClient,
- });
-
- expect(result.success).toBe(true);
- if (!result.success) return;
-
- expect(result.data.lastDevice).toEqual({ type: "cloud" });
- });
- });
-
describe("failure handling", () => {
it("fails when getTaskRun throws", async () => {
(mockApiClient.getTaskRun as ReturnType<typeof vi.fn>).mockRejectedValue(
diff --git a/products/desktop/packages/agent/src/sagas/resume-saga.ts b/products/desktop/packages/agent/src/sagas/resume-saga.ts
index d6491a2f0654..6f11e6ebb591 100644
--- a/products/desktop/packages/agent/src/sagas/resume-saga.ts
+++ b/products/desktop/packages/agent/src/sagas/resume-saga.ts
@@ -6,11 +6,7 @@ import {
POSTHOG_NOTIFICATIONS,
} from "../acp-extensions";
import type { PostHogAPIClient } from "../posthog-api";
-import type {
- DeviceInfo,
- GitCheckpointEvent,
- StoredNotification,
-} from "../types";
+import type { StoredNotification } from "../types";
import type { Logger } from "../utils/logger";
export interface ConversationTurn {
@@ -36,10 +32,7 @@ export interface ResumeInput {
export interface ResumeOutput {
conversation: ConversationTurn[];
- latestGitCheckpoint: GitCheckpointEvent | null;
- latestGitCheckpoints: GitCheckpointEvent[];
interrupted: boolean;
- lastDevice?: DeviceInfo;
logEntryCount: number;
sessionId: string | null;
nativeGoal?: NativeGoalState | null;
@@ -73,28 +66,10 @@ export class ResumeSaga extends Saga<ResumeInput, ResumeOutput> {
this.log.info("Fetched log entries", { count: entries.length });
- const latestGitCheckpoints = await this.readOnlyStep(
- "find_git_checkpoint",
- () => Promise.resolve(this.findLatestGitCheckpoints(entries)),
- );
- const latestGitCheckpoint = latestGitCheckpoints.at(-1) ?? null;
-
- if (latestGitCheckpoint) {
- this.log.info("Found git checkpoint", {
- checkpointId: latestGitCheckpoint.checkpointId,
- branch: latestGitCheckpoint.branch,
- });
- }
-
const conversation = await this.readOnlyStep("rebuild_conversation", () =>
Promise.resolve(this.rebuildConversation(entries)),
);
- // Step 6: Find device info (read-only, pure computation)
- const lastDevice = await this.readOnlyStep("find_device", () =>
- Promise.resolve(this.findLastDeviceInfo(entries)),
- );
-
const sessionId = await this.readOnlyStep("find_session_id", () =>
Promise.resolve(this.findSessionId(entries)),
);
@@ -104,17 +79,13 @@ export class ResumeSaga extends Saga<ResumeInput, ResumeOutput> {
this.log.info("Resume state rebuilt", {
turns: conversation.length,
- hasGitCheckpoint: !!latestGitCheckpoint,
hasSessionId: !!sessionId,
interrupted: false,
});
return {
conversation,
- latestGitCheckpoint,
- latestGitCheckpoints,
interrupted: false,
- lastDevice,
logEntryCount: entries.length,
sessionId,
nativeGoal,
@@ -124,8 +95,6 @@ export class ResumeSaga extends Saga<ResumeInput, ResumeOutput> {
private emptyResult(): ResumeOutput {
return {
conversation: [],
- latestGitCheckpoint: null,
- latestGitCheckpoints: [],
interrupted: false,
logEntryCount: 0,
sessionId: null,
@@ -195,46 +164,6 @@ export class ResumeSaga extends Saga<ResumeInput, ResumeOutput> {
return null;
}
- private findLatestGitCheckpoints(
- entries: StoredNotification[],
- ): GitCheckpointEvent[] {
- const sdkPrefixedMethod = `_${POSTHOG_NOTIFICATIONS.GIT_CHECKPOINT}`;
- const checkpoints = new Map<string, GitCheckpointEvent>();
-
- for (let i = entries.length - 1; i >= 0; i--) {
- const entry = entries[i];
- const method = entry.notification?.method;
- if (
- method === sdkPrefixedMethod ||
- method === POSTHOG_NOTIFICATIONS.GIT_CHECKPOINT
- ) {
- const params = entry.notification?.params as
- | GitCheckpointEvent
- | undefined;
- if (params?.checkpointId && params?.checkpointRef) {
- const key = params.repository?.toLowerCase() ?? "legacy";
- if (!checkpoints.has(key)) checkpoints.set(key, params);
- }
- }
- }
- return [...checkpoints.values()].reverse();
- }
-
- private findLastDeviceInfo(
- entries: StoredNotification[],
- ): DeviceInfo | undefined {
- for (let i = entries.length - 1; i >= 0; i--) {
- const entry = entries[i];
- const params = entry.notification?.params as
- | { device?: DeviceInfo }
- | undefined;
- if (params?.device) {
- return params.device;
- }
- }
- return undefined;
- }
-
private rebuildConversation(
entries: StoredNotification[],
): ConversationTurn[] {
diff --git a/products/desktop/packages/agent/src/sagas/test-fixtures.ts b/products/desktop/packages/agent/src/sagas/test-fixtures.ts
index 3baebcdd3d1e..ea5b3ef18fb5 100644
--- a/products/desktop/packages/agent/src/sagas/test-fixtures.ts
+++ b/products/desktop/packages/agent/src/sagas/test-fixtures.ts
@@ -6,9 +6,8 @@ import { join } from "node:path";
import { promisify } from "node:util";
import type { SagaLogger } from "@posthog/shared";
import { vi } from "vitest";
-import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";
import type { PostHogAPIClient } from "../posthog-api";
-import type { GitCheckpointEvent, StoredNotification, TaskRun } from "../types";
+import type { StoredNotification, TaskRun } from "../types";
const execFileAsync = promisify(execFile);
@@ -127,7 +126,7 @@ export function createMockApiClient(
return {
uploadTaskArtifacts: vi
.fn()
- .mockResolvedValue([{ storage_path: "gs://bucket/handoff/test.pack" }]),
+ .mockResolvedValue([{ storage_path: "gs://bucket/artifacts/test.pack" }]),
downloadArtifact: vi.fn(),
getTaskRun: vi.fn(),
fetchTaskRunLogs: vi.fn(),
@@ -225,23 +224,3 @@ export function createToolResult(
},
});
}
-
-export function createGitCheckpointNotification(
- overrides: Partial<GitCheckpointEvent> = {},
-): StoredNotification {
- return createNotification(POSTHOG_NOTIFICATIONS.GIT_CHECKPOINT, {
- checkpointId: "checkpoint-1",
- commit: "commit-1",
- checkpointRef: "refs/posthog-code-checkpoint/checkpoint-1",
- headRef: "refs/posthog-code-handoff/head/checkpoint-1",
- head: "head-1",
- branch: "main",
- indexTree: "index-tree-1",
- worktreeTree: "worktree-tree-1",
- timestamp: new Date().toISOString(),
- upstreamRemote: "origin",
- upstreamMergeRef: "refs/heads/main",
- remoteUrl: "[email protected]:posthog/posthog.git",
- ...overrides,
- });
-}
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 3f5070fa7935..0e95b45e3c12 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -29,7 +29,6 @@ import {
import { POSTHOG_NOTIFICATIONS } from "../acp-extensions";
import { getSessionJsonlPath } from "../adapters/claude/session/jsonl-hydration";
import type { PermissionMode } from "../execution-mode";
-import { HandoffCheckpointTracker } from "../handoff-checkpoint";
import type { PostHogAPIClient } from "../posthog-api";
import type { ResumeState } from "../resume";
import {
@@ -687,7 +686,6 @@ describe("AgentServer HTTP Mode", () => {
};
cleanupServer.session = {
payload: { run_id: "run-1" },
- pendingHandoffGitState: undefined,
logWriter: { flush: vi.fn(async () => {}) },
acpConnection: { cleanup: vi.fn(async () => {}) },
sseController: { close: vi.fn() },
@@ -3629,7 +3627,6 @@ describe("AgentServer HTTP Mode", () => {
content: [{ type: "text", text: "work completed so far" }],
},
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 2,
sessionId: "prior-session",
@@ -3734,7 +3731,6 @@ describe("AgentServer HTTP Mode", () => {
content: [{ type: "text", text: "work completed so far" }],
},
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 2,
sessionId: "prior-session",
@@ -3799,7 +3795,6 @@ describe("AgentServer HTTP Mode", () => {
content: [{ type: "text", text: "work completed so far" }],
},
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 1,
sessionId: "prior-session",
@@ -3817,48 +3812,6 @@ describe("AgentServer HTTP Mode", () => {
expect(internals.resumeState).not.toBeNull();
}, 30000);
- it("applies the resume git checkpoint at most once", async () => {
- // The checkpoint resets the workspace to the resumed run's snapshot. Applying it again after
- // a turn has written files discards that work — including a turn that failed and is retried.
- const s = createServer();
- await s.start();
-
- const applyFromHandoff = vi
- .spyOn(HandoffCheckpointTracker.prototype, "applyFromHandoff")
- .mockResolvedValue({ packBytes: 1, indexBytes: 1, totalBytes: 2 });
- const payload: JwtPayload = {
- run_id: "test-run-id",
- task_id: "test-task-id",
- team_id: 1,
- user_id: 1,
- distinct_id: "test-distinct-id",
- mode: "interactive",
- };
- const internals = s as unknown as {
- resumeState: ResumeState | null;
- resumeGitCheckpointApplied: boolean | null;
- config: { repositoryPath?: string };
- applyResumeGitCheckpoint(payload: JwtPayload): Promise<boolean>;
- };
- internals.config.repositoryPath = "/tmp/workspace";
- internals.resumeGitCheckpointApplied = null;
- internals.resumeState = {
- conversation: [],
- latestGitCheckpoint: { branch: "main", head: "abc123" },
- interrupted: false,
- logEntryCount: 0,
- sessionId: "prior-session",
- } as unknown as ResumeState;
-
- const first = await internals.applyResumeGitCheckpoint(payload);
- const second = await internals.applyResumeGitCheckpoint(payload);
-
- expect(first).toBe(true);
- expect(second).toBe(true);
- expect(applyFromHandoff).toHaveBeenCalledOnce();
- applyFromHandoff.mockRestore();
- }, 30000);
-
it("still continues after /compact sent as the first forwarded message", async () => {
// A summary resume prepends a hidden history block. Reading the slash command off the wrapped
// prompt stops recognizing `/compact`, so the run reports complete instead of carrying on with
@@ -3901,7 +3854,6 @@ describe("AgentServer HTTP Mode", () => {
content: [{ type: "text", text: "work completed so far" }],
},
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 1,
sessionId: "prior-session",
@@ -3989,7 +3941,6 @@ describe("AgentServer HTTP Mode", () => {
content: [{ type: "text", text: "work completed so far" }],
},
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 2,
sessionId: "prior-session",
@@ -4077,7 +4028,6 @@ describe("AgentServer HTTP Mode", () => {
content: [{ type: "text", text: "old answer" }],
},
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 2,
sessionId: "prior-session",
@@ -4130,7 +4080,7 @@ describe("AgentServer HTTP Mode", () => {
});
});
- describe("idle handoff resume", () => {
+ describe("idle same-run resume", () => {
const idlePayload: JwtPayload = {
task_id: "test-task-id",
run_id: "test-run-id",
@@ -4383,7 +4333,6 @@ describe("AgentServer HTTP Mode", () => {
const goal = { objective: "Ship the fix", status: "paused" as const };
s.resumeState = {
conversation: [],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 1,
sessionId: "prior-session",
@@ -4474,7 +4423,6 @@ describe("AgentServer HTTP Mode", () => {
content: [{ type: "text", text: "progress so far" }],
},
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 2,
sessionId: "prior-session",
@@ -4526,7 +4474,6 @@ describe("AgentServer HTTP Mode", () => {
content: [{ type: "text", text: "visible answer only" }],
},
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 3,
sessionId: "prior-session",
@@ -4621,7 +4568,6 @@ describe("AgentServer HTTP Mode", () => {
conversation: [
{ role: "user", content: [{ type: "text", text: "continue" }] },
],
- latestGitCheckpoint: null,
interrupted: false,
logEntryCount: 1,
sessionId,
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index d50839b435bd..c0ea581e4d88 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -70,7 +70,6 @@ import {
} from "../adapters/signed-commit-shared";
import type { PermissionMode } from "../execution-mode";
import { DEFAULT_CODEX_MODEL, fetchGatewayModels } from "../gateway-models";
-import { HandoffCheckpointTracker } from "../handoff-checkpoint";
import { OtelRunTelemetry } from "../otel-telemetry";
import { configurePersistentAgentState } from "../persistent-agent-state";
import { PostHogAPIClient } from "../posthog-api";
@@ -96,8 +95,6 @@ import { SessionLogWriter } from "../session-log-writer";
import type {
AgentMode,
DeviceInfo,
- GitCheckpointEvent,
- HandoffLocalGitState,
LogLevel,
Task,
TaskRun,
@@ -126,11 +123,7 @@ import {
} from "./pr-checkout";
import { resolveRtkSavings } from "./rtk-savings";
import { RunUsageAccumulator } from "./run-usage";
-import {
- handoffLocalGitStateSchema,
- jsonRpcRequestSchema,
- validateCommandParams,
-} from "./schemas";
+import { jsonRpcRequestSchema, validateCommandParams } from "./schemas";
import type { AgentServerConfig, ClaudeCodeConfig } from "./types";
import { waitForFile } from "./wait-for-file";
@@ -323,7 +316,6 @@ interface ActiveSession {
permissionMode: PermissionMode;
/** Whether a desktop client has ever connected via SSE during this session */
hasDesktopConnected: boolean;
- pendingHandoffGitState?: HandoffLocalGitState;
/** Meta the session was created with, reused when a retry needs a fresh session */
sessionMeta: Record<string, unknown>;
}
@@ -538,8 +530,6 @@ export class AgentServer {
// CLI flags can't carry the user's choice. Those settings are read from the
// run's state when the first message arrives (see resolveActivationSettings).
private prewarmedRun = false;
- /** Whether the resume git checkpoint has been attempted, and what it answered. See `applyResumeGitCheckpoint`. */
- private resumeGitCheckpointApplied: boolean | null = null;
private prewarmedStartupTurnPending = false;
private autoPublishStateResolved = false;
private warmReasoningEffortResolved = false;
@@ -990,9 +980,6 @@ export class AgentServer {
});
this.logger.debug("Resume state loaded", {
conversationTurns: this.resumeState.conversation.length,
- hasGitCheckpoint: !!this.resumeState.latestGitCheckpoint,
- gitCheckpointBranch:
- this.resumeState.latestGitCheckpoint?.branch ?? null,
logEntries: this.resumeState.logEntryCount,
});
} catch (error) {
@@ -1533,10 +1520,6 @@ export class AgentServer {
case POSTHOG_NOTIFICATIONS.CLOSE:
case "close": {
this.logger.debug("Close requested");
- const localGitState = this.extractHandoffLocalGitState(params);
- if (localGitState && this.session) {
- this.session.pendingHandoffGitState = localGitState;
- }
await this.cleanupSession();
return { closed: true };
}
@@ -1784,7 +1767,6 @@ export class AgentServer {
this.resumeState = null;
this.nativeResume = null;
- this.resumeGitCheckpointApplied = null;
this.preSessionEvents = [];
this.prewarmedRun = false;
this.prewarmedStartupTurnPending = false;
@@ -2165,7 +2147,6 @@ export class AgentServer {
telemetry,
permissionMode: initialPermissionMode,
hasDesktopConnected: sseController !== null,
- pendingHandoffGitState: undefined,
sessionMeta: effectiveSessionMeta,
};
this.initializingTelemetry = undefined;
@@ -2615,14 +2596,8 @@ export class AgentServer {
resumeState.conversation,
);
- const checkpointApplied = await this.applyResumeGitCheckpoint(payload);
-
const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);
- const checkpointContext = checkpointApplied
- ? `The workspace environment (all files, packages, and code changes) has been fully restored from the latest checkpoint.`
- : `No additional git checkpoint was applied before resuming. Use the current workspace contents together with the preserved conversation history below.`;
-
let resumePromptBlocks: ContentBlock[];
let resumePromptMeta: Record<string, unknown> | undefined;
let resumePromptMessageId: string | undefined;
@@ -2631,7 +2606,7 @@ export class AgentServer {
resumePromptMessageId = pendingUserPrompt.messageId;
resumePromptBlocks = [
hiddenTextBlock(
- `You are resuming a previous conversation. ${checkpointContext}\n\n` +
+ "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +
`Here is the conversation history from the previous session:\n\n` +
`${conversationSummary}\n\n` +
`The user has sent a new message:\n\n`,
@@ -2644,7 +2619,7 @@ export class AgentServer {
} else {
resumePromptBlocks = [
hiddenTextBlock(
- `You are resuming a previous conversation. ${checkpointContext}\n\n` +
+ "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +
`Here is the conversation history from the previous session:\n\n` +
`${conversationSummary}\n\n` +
`Continue from where you left off. The user is waiting for your response.`,
@@ -2657,9 +2632,6 @@ export class AgentServer {
conversationTurns: resumeState.conversation.length,
promptLength: promptBlocksToText(resumePromptBlocks).length,
hasPendingUserMessage: !!pendingUserPrompt?.prompt.length,
- checkpointApplied,
- hasGitCheckpoint: !!resumeState.latestGitCheckpoint,
- gitCheckpointBranch: resumeState.latestGitCheckpoint?.branch ?? null,
});
return {
@@ -2679,16 +2651,11 @@ export class AgentServer {
const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);
if (pendingUserPrompt?.prompt.length) return false;
- const checkpointApplied = this.nativeResume?.warm
- ? false
- : await this.applyResumeGitCheckpoint(payload);
-
this.logger.debug("Idle resume settled without a turn", {
taskId: payload.task_id,
runId: payload.run_id,
sessionId: this.nativeResume?.sessionId,
warm: this.nativeResume?.warm,
- checkpointApplied,
});
this.resumeState = null;
@@ -2708,14 +2675,10 @@ export class AgentServer {
}
if (this.nativeResume) {
- const checkpointApplied = this.nativeResume.warm
- ? false
- : await this.applyResumeGitCheckpoint(payload);
this.logger.debug("Applying deferred native resume to user message", {
taskId: payload.task_id,
sessionId: this.nativeResume.sessionId,
warm: this.nativeResume.warm,
- checkpointApplied,
});
return { prompt, consumed: true };
}
@@ -2725,21 +2688,14 @@ export class AgentServer {
}
const resumeState = this.resumeState;
- const checkpointApplied = await this.applyResumeGitCheckpoint(payload);
this.logger.debug("Applying deferred summary resume to user message", {
taskId: payload.task_id,
conversationTurns: resumeState.conversation.length,
- checkpointApplied,
- hasGitCheckpoint: !!resumeState.latestGitCheckpoint,
});
return {
- prompt: this.wrapPromptWithSummaryResume(
- resumeState,
- checkpointApplied,
- prompt,
- ),
+ prompt: this.wrapPromptWithSummaryResume(resumeState, prompt),
consumed: true,
};
}
@@ -2747,18 +2703,14 @@ export class AgentServer {
/** Wrap the user's message in the previous session's conversation, hidden from the transcript. */
private wrapPromptWithSummaryResume(
resumeState: ResumeState,
- checkpointApplied: boolean,
prompt: ContentBlock[],
): ContentBlock[] {
- const checkpointContext = checkpointApplied
- ? "The workspace environment (all files, packages, and code changes) has been fully restored from the latest checkpoint."
- : "No additional git checkpoint was applied before resuming. Use the current workspace contents together with the preserved conversation history below.";
const conversationSummary = formatConversationForResume(
resumeState.conversation,
);
return [
hiddenTextBlock(
- `You are resuming a previous conversation. ${checkpointContext}\n\n` +
+ "You are resuming a previous conversation. Use the current workspace contents together with the preserved conversation history below.\n\n" +
`Here is the conversation history from the previous session:\n\n` +
`${conversationSummary}\n\n` +
"The user has sent a new message:\n\n",
@@ -2826,11 +2778,7 @@ export class AgentServer {
"Deferred resume prompt exceeded the context window; retrying on a fresh session with summarized history",
{ taskId: payload.task_id, runId: payload.run_id },
);
- return this.wrapPromptWithSummaryResume(
- resumeState,
- await this.applyResumeGitCheckpoint(payload),
- prompt,
- );
+ return this.wrapPromptWithSummaryResume(resumeState, prompt);
}
private async sendResumeContinuation(
@@ -2845,10 +2793,6 @@ export class AgentServer {
taskRun,
"Resume continuation",
async () => {
- const checkpointApplied = this.nativeResume?.warm
- ? false
- : await this.applyResumeGitCheckpoint(payload);
-
const pendingUserPrompt = await this.getPendingUserPrompt(taskRun);
const prompt: ContentBlock[] = pendingUserPrompt?.prompt.length
? pendingUserPrompt.prompt
@@ -2862,7 +2806,6 @@ export class AgentServer {
taskId: payload.task_id,
sessionId: this.nativeResume?.sessionId,
warm: this.nativeResume?.warm,
- checkpointApplied,
hasPendingUserMessage: !!pendingUserPrompt?.prompt.length,
});
@@ -3029,53 +2972,6 @@ export class AgentServer {
}
}
- private async applyResumeGitCheckpoint(
- payload: JwtPayload,
- ): Promise<boolean> {
- // At most once per process, and the answer is replayed afterwards. The checkpoint resets the
- // workspace to the resumed run's snapshot, so a second application discards everything the
- // session has written since — including the work of a turn that failed and is being retried.
- // A failed attempt counts as an attempt: it may have partially applied.
- if (this.resumeGitCheckpointApplied !== null) {
- return this.resumeGitCheckpointApplied;
- }
- if (
- !this.resumeState?.latestGitCheckpoint ||
- !this.config.repositoryPath ||
- !this.posthogAPI
- ) {
- return false;
- }
- try {
- const checkpointTracker = new HandoffCheckpointTracker({
- repositoryPath: this.config.repositoryPath,
- taskId: payload.task_id,
- runId: payload.run_id,
- apiClient: this.posthogAPI,
- logger: this.logger.child("HandoffCheckpoint"),
- });
- const metrics = await checkpointTracker.applyFromHandoff(
- this.resumeState.latestGitCheckpoint,
- );
- this.logger.debug("Git checkpoint applied", {
- branch: this.resumeState.latestGitCheckpoint.branch,
- head: this.resumeState.latestGitCheckpoint.head,
- packBytes: metrics.packBytes,
- indexBytes: metrics.indexBytes,
- totalBytes: metrics.totalBytes,
- });
- this.resumeGitCheckpointApplied = true;
- return true;
- } catch (error) {
- this.logger.warn("Failed to apply git checkpoint", {
- error: error instanceof Error ? error.message : String(error),
- branch: this.resumeState.latestGitCheckpoint.branch,
- });
- this.resumeGitCheckpointApplied = false;
- return false;
- }
- }
-
private getInitialPromptOverride(taskRun: TaskRun): string | null {
const override = taskRun.state.initial_prompt_override;
return typeof override === "string" ? override.trim() || null : null;
@@ -4191,7 +4087,7 @@ export class AgentServer {
## Delivering to Slack
- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.
- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.
-- Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, checkpoints, user uploads) are internal: never deliver them to Slack or mention them in your reply.`;
+- Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, user uploads) are internal: never deliver them to Slack or mention them in your reply.`;
// Charts attach to both modes: they post as an image block referencing a PostHog-hosted
// url, so they work wherever the workspace can post at all.
@@ -5102,29 +4998,6 @@ ${commonInstructions}
}
this.maybeAttachCreatedPr(payload, params.update);
-
- // session/update notifications flow through the tapped stream (like local transport)
- // Capture checkpoints for file-changing tools so cloud resumes restore
- // from git checkpoints rather than tree snapshots.
- if (params.update?.sessionUpdate === "tool_call_update") {
- const meta = (params.update?._meta as Record<string, unknown>)
- ?.claudeCode as Record<string, unknown> | undefined;
- const toolName = meta?.toolName as string | undefined;
- const toolResponse = meta?.toolResponse as
- | Record<string, unknown>
- | undefined;
-
- if (
- (toolName === "Write" ||
- toolName === "Edit" ||
- toolName === "MultiEdit" ||
- toolName === "Delete" ||
- toolName === "Move") &&
- toolResponse?.filePath
- ) {
- await this.captureCheckpointState();
- }
- }
},
};
}
@@ -5457,12 +5330,6 @@ ${commonInstructions}
this.logger.debug("Cleaning up session");
- try {
- await this.captureCheckpointState(this.session.pendingHandoffGitState);
- } catch (error) {
- this.logger.error("Failed to capture final checkpoint state", error);
- }
-
try {
await this.session.logWriter.flush(this.session.payload.run_id, {
coalesce: true,
@@ -5554,79 +5421,6 @@ ${commonInstructions}
}
}
- private async captureCheckpointState(
- localGitState?: HandoffLocalGitState,
- ): Promise<void> {
- if (!this.session) {
- return;
- }
- if (!this.posthogAPI) {
- this.logger.warn(
- "Skipping checkpoint capture: PostHog API client is not configured",
- );
- return;
- }
- const session = this.session;
-
- const repositories =
- this.taskRepositories.length > 1
- ? this.taskRepositories.map((repository) => ({
- repository,
- path: `/tmp/workspace/repos/${repository.toLowerCase()}`,
- }))
- : this.config.repositoryPath
- ? [
- {
- repository: this.taskRepositories[0],
- path: this.config.repositoryPath,
- },
- ]
- : [];
-
- await Promise.all(
- repositories.map(async ({ repository, path }) => {
- const tracker = new HandoffCheckpointTracker({
- repositoryPath: path,
- taskId: session.payload.task_id,
- runId: session.payload.run_id,
- apiClient: this.posthogAPI,
- logger: this.logger.child("HandoffCheckpoint"),
- });
- const checkpoint = await tracker.captureForHandoff(
- repositories.length === 1 ? localGitState : undefined,
- );
- if (!checkpoint) return;
-
- const checkpointWithDevice: GitCheckpointEvent = {
- ...checkpoint,
- repository,
- device: session.deviceInfo,
- };
- const notification = {
- jsonrpc: "2.0" as const,
- method: POSTHOG_NOTIFICATIONS.GIT_CHECKPOINT,
- params: checkpointWithDevice,
- };
- this.broadcastEvent({
- type: "notification",
- timestamp: new Date().toISOString(),
- notification,
- });
- session.logWriter.appendRawLine(
- session.payload.run_id,
- JSON.stringify(notification),
- );
- }),
- );
- }
-
- private extractHandoffLocalGitState(
- params: Record<string, unknown>,
- ): HandoffLocalGitState | null {
- const result = handoffLocalGitStateSchema.safeParse(params.localGitState);
- return result.success ? result.data : null;
- }
-
/**
* Accumulates a settled turn's token usage into the run total and reports it
* to the backend, merged into `TaskRun.state.token_usage`. Best-effort: a
diff --git a/products/desktop/packages/agent/src/server/schemas.ts b/products/desktop/packages/agent/src/server/schemas.ts
index f5ba0c6d7e1c..912e33a5d4ca 100644
--- a/products/desktop/packages/agent/src/server/schemas.ts
+++ b/products/desktop/packages/agent/src/server/schemas.ts
@@ -8,19 +8,6 @@ const httpHeaderSchema = z.object({
value: z.string(),
});
-const nullishString = z
- .string()
- .nullish()
- .transform((value) => value ?? null);
-
-export const handoffLocalGitStateSchema = z.object({
- head: nullishString,
- branch: nullishString,
- upstreamHead: nullishString,
- upstreamRemote: nullishString,
- upstreamMergeRef: nullishString,
-});
-
const remoteMcpServerSchema: z.ZodType<McpServerConnection> = z.object({
type: z.enum(["http", "sse"]),
name: z.string().min(1, "MCP server name is required"),
@@ -127,11 +114,7 @@ export const mcpResponseParamsSchema = z
error: "Exactly one of payload or error is required",
});
-export const closeParamsSchema = z
- .object({
- localGitState: handoffLocalGitStateSchema.optional(),
- })
- .optional();
+export const closeParamsSchema = z.object({}).optional();
export const commandParamsSchemas = {
user_message: userMessageParamsSchema,
diff --git a/products/desktop/packages/agent/src/test/fixtures/api.ts b/products/desktop/packages/agent/src/test/fixtures/api.ts
index 4cc68857fa1e..63cfb80486cc 100644
--- a/products/desktop/packages/agent/src/test/fixtures/api.ts
+++ b/products/desktop/packages/agent/src/test/fixtures/api.ts
@@ -70,7 +70,7 @@ export function createMockApiClient(
return {
uploadTaskArtifacts: vi
.fn()
- .mockResolvedValue([{ storage_path: "gs://bucket/handoff/test.pack" }]),
+ .mockResolvedValue([{ storage_path: "gs://bucket/artifacts/test.pack" }]),
downloadArtifact: vi.fn(),
getTaskRun: vi.fn(),
fetchTaskRunLogs: vi.fn(),
diff --git a/products/desktop/packages/agent/src/types.ts b/products/desktop/packages/agent/src/types.ts
index 2dd3a60a75e2..3a8337693f8b 100644
--- a/products/desktop/packages/agent/src/types.ts
+++ b/products/desktop/packages/agent/src/types.ts
@@ -1,9 +1,4 @@
-import type {
- Adapter,
- GitHandoffCheckpoint,
- HandoffLocalGitState as GitHandoffLocalGitState,
- PostHogAPIConfig,
-} from "@posthog/shared";
+import type { Adapter, PostHogAPIConfig } from "@posthog/shared";
import type { EffortLevel } from "@posthog/shared/domain-types";
export type {
@@ -146,17 +141,6 @@ export interface FileChange {
status: FileStatus;
}
-export type HandoffLocalGitState = GitHandoffLocalGitState;
-
-export interface GitCheckpoint extends GitHandoffCheckpoint {
- artifactPath?: string;
- indexArtifactPath?: string;
-}
-
-export interface GitCheckpointEvent extends GitCheckpoint {
- device?: DeviceInfo;
-}
-
/**
* Keeps the emitted `@posthog/agent/types` entrypoint as a runtime ESM module.
*
diff --git a/products/desktop/packages/agent/tsup.config.ts b/products/desktop/packages/agent/tsup.config.ts
index b8858e24368a..e067b2c54793 100644
--- a/products/desktop/packages/agent/tsup.config.ts
+++ b/products/desktop/packages/agent/tsup.config.ts
@@ -152,7 +152,6 @@ export default defineConfig([
"src/acp-extensions.ts",
"src/agent.ts",
"src/gateway-models.ts",
- "src/handoff-checkpoint.ts",
"src/posthog-api.ts",
"src/posthog-products.ts",
"src/pr-url-detector.ts",
diff --git a/products/desktop/packages/core/src/handoff/handoff-saga.test.ts b/products/desktop/packages/core/src/handoff/handoff-saga.test.ts
deleted file mode 100644
index 5b6a1fde6a24..000000000000
--- a/products/desktop/packages/core/src/handoff/handoff-saga.test.ts
+++ /dev/null
@@ -1,356 +0,0 @@
-import type { GitHandoffCheckpoint } from "@posthog/shared";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import {
- type HandoffResumeState,
- HandoffSaga,
- type HandoffSagaDeps,
- type HandoffSagaInput,
-} from "./handoff-saga";
-
-const DEFAULT_LOCAL_GIT_STATE = {
- head: "abc123",
- branch: "feature/handoff",
- upstreamHead: null,
- upstreamRemote: "origin",
- upstreamMergeRef: "refs/heads/feature/handoff",
-};
-
-function createInput(
- overrides: Partial<HandoffSagaInput> = {},
-): HandoffSagaInput {
- return {
- taskId: "task-1",
- runId: "run-1",
- repoPath: "/repo",
- apiHost: "https://us.posthog.com",
- teamId: 2,
- ...overrides,
- };
-}
-
-function createCheckpoint(
- overrides: Partial<GitHandoffCheckpoint> = {},
-): GitHandoffCheckpoint {
- return {
- checkpointId: "checkpoint-1",
- commit: "checkpointcommit123",
- checkpointRef: "refs/posthog-code-checkpoint/checkpoint-1",
- headRef: "refs/posthog-code-handoff/head/checkpoint-1",
- head: "def456",
- branch: "feature/handoff",
- indexTree: "index123",
- worktreeTree: "worktree123",
- timestamp: "2026-04-07T00:00:00Z",
- upstreamRemote: "origin",
- upstreamMergeRef: "refs/heads/feature/handoff",
- remoteUrl: "[email protected]:PostHog/code.git",
- ...overrides,
- };
-}
-
-function createResumeState(
- overrides: Partial<HandoffResumeState> = {},
-): HandoffResumeState {
- return {
- conversation: [],
- latestGitCheckpoint: null,
- ...overrides,
- };
-}
-
-function createDeps(overrides: Partial<HandoffSagaDeps> = {}): HandoffSagaDeps {
- return {
- markRunEnvironmentLocal: vi.fn().mockResolvedValue(undefined),
- fetchResumeState: vi.fn().mockResolvedValue({
- resumeState: createResumeState(),
- cloudLogUrl: "https://logs.example.com/run-1.ndjson",
- }),
- formatConversation: vi.fn().mockReturnValue("conversation summary"),
- applyGitCheckpoint: vi.fn().mockResolvedValue(undefined),
- updateWorkspaceMode: vi.fn(),
- attachWorkspaceToFolder: vi.fn().mockReturnValue({ revert: vi.fn() }),
- reconnectSession: vi.fn().mockResolvedValue({ sessionId: "session-1" }),
- closeCloudRun: vi.fn().mockResolvedValue(undefined),
- seedLocalLogs: vi.fn().mockResolvedValue(undefined),
- killSession: vi.fn().mockResolvedValue(undefined),
- setPendingContext: vi.fn(),
- onProgress: vi.fn(),
- ...overrides,
- };
-}
-
-function getProgressSteps(deps: HandoffSagaDeps): string[] {
- return (deps.onProgress as ReturnType<typeof vi.fn>).mock.calls.map(
- (call: unknown[]) => call[0] as string,
- );
-}
-
-async function runSaga(
- overrides: {
- input?: Partial<HandoffSagaInput>;
- deps?: Partial<HandoffSagaDeps>;
- resumeState?: Partial<HandoffResumeState>;
- cloudLogUrl?: string | null;
- } = {},
-) {
- const deps = createDeps({
- fetchResumeState: vi.fn().mockResolvedValue({
- resumeState: createResumeState(overrides.resumeState),
- cloudLogUrl:
- overrides.cloudLogUrl === undefined
- ? "https://logs.example.com/run-1.ndjson"
- : overrides.cloudLogUrl,
- }),
- ...overrides.deps,
- });
- const saga = new HandoffSaga(deps);
- const result = await saga.run(createInput(overrides.input));
- return { deps, result };
-}
-
-describe("HandoffSaga", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("completes happy path with checkpoint", async () => {
- const checkpoint = createCheckpoint();
- const { result } = await runSaga({
- resumeState: {
- conversation: [
- { role: "user", content: [{ type: "text", text: "hello" }] },
- ],
- latestGitCheckpoint: checkpoint,
- },
- });
-
- expect(result.success).toBe(true);
- if (!result.success) return;
- expect(result.data.sessionId).toBe("session-1");
- expect(result.data.checkpointApplied).toBe(true);
- expect(result.data.conversationTurns).toBe(1);
- });
-
- it("closes cloud run before fetching logs", async () => {
- const { deps } = await runSaga();
-
- expect(deps.closeCloudRun).toHaveBeenCalledWith(
- "task-1",
- "run-1",
- "https://us.posthog.com",
- 2,
- undefined,
- );
- const closeOrder = (deps.closeCloudRun as ReturnType<typeof vi.fn>).mock
- .invocationCallOrder[0];
- const fetchOrder = (deps.fetchResumeState as ReturnType<typeof vi.fn>).mock
- .invocationCallOrder[0];
- expect(closeOrder).toBeLessThan(fetchOrder);
- });
-
- it("marks the run environment local before rebuilding state", async () => {
- const { deps } = await runSaga();
-
- expect(deps.markRunEnvironmentLocal).toHaveBeenCalledWith(
- "task-1",
- "run-1",
- );
- const envOrder = (deps.markRunEnvironmentLocal as ReturnType<typeof vi.fn>)
- .mock.invocationCallOrder[0];
- const fetchOrder = (deps.fetchResumeState as ReturnType<typeof vi.fn>).mock
- .invocationCallOrder[0];
- expect(envOrder).toBeLessThan(fetchOrder);
- });
-
- it("skips checkpoint apply when no checkpoint is present", async () => {
- const { deps, result } = await runSaga();
-
- expect(result.success).toBe(true);
- if (!result.success) return;
- expect(result.data.checkpointApplied).toBe(false);
- expect(deps.applyGitCheckpoint).not.toHaveBeenCalled();
- });
-
- it("seeds local logs when cloudLogUrl is present", async () => {
- const { deps } = await runSaga();
-
- expect(deps.seedLocalLogs).toHaveBeenCalledWith(
- "run-1",
- "https://logs.example.com/run-1.ndjson",
- );
- });
-
- it("skips seeding logs when cloudLogUrl is falsy", async () => {
- const { deps } = await runSaga({ cloudLogUrl: null });
-
- expect(deps.seedLocalLogs).not.toHaveBeenCalled();
- });
-
- it("sets pending context with handoff summary", async () => {
- const { deps } = await runSaga({
- deps: {
- formatConversation: vi.fn().mockReturnValue("User said hello"),
- },
- resumeState: {
- conversation: [
- { role: "user", content: [{ type: "text", text: "hello" }] },
- ],
- },
- });
-
- expect(deps.setPendingContext).toHaveBeenCalledWith(
- "run-1",
- expect.stringContaining("resuming a previous conversation"),
- );
- expect(deps.setPendingContext).toHaveBeenCalledWith(
- "run-1",
- expect.stringContaining("could not be restored"),
- );
- });
-
- it("context mentions files restored when checkpoint applied", async () => {
- const { deps } = await runSaga({
- resumeState: {
- latestGitCheckpoint: createCheckpoint(),
- },
- });
-
- expect(deps.setPendingContext).toHaveBeenCalledWith(
- "run-1",
- expect.stringContaining("restored from the cloud session checkpoint"),
- );
- });
-
- it("passes sessionId and adapter through to reconnectSession", async () => {
- const { deps } = await runSaga({
- input: { sessionId: "ses-abc", adapter: "codex" },
- });
-
- expect(deps.reconnectSession).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: "ses-abc",
- adapter: "codex",
- }),
- );
- });
-
- it("emits progress events in order", async () => {
- const { deps } = await runSaga({
- resumeState: {
- latestGitCheckpoint: createCheckpoint(),
- },
- });
-
- expect(getProgressSteps(deps)).toEqual([
- "fetching_logs",
- "applying_git_checkpoint",
- "spawning_agent",
- "complete",
- ]);
- });
-
- describe("rollbacks", () => {
- it("reverts workspace attachment when spawn_agent fails", async () => {
- const revert = vi.fn();
- const { deps, result } = await runSaga({
- deps: {
- attachWorkspaceToFolder: vi.fn().mockReturnValue({ revert }),
- reconnectSession: vi
- .fn()
- .mockRejectedValue(new Error("spawn failed")),
- },
- });
-
- expect(result.success).toBe(false);
- if (result.success) return;
- expect(result.failedStep).toBe("spawn_agent");
- expect(deps.attachWorkspaceToFolder).toHaveBeenCalledWith(
- "task-1",
- "/repo",
- );
- expect(revert).toHaveBeenCalledTimes(1);
- });
-
- it("kills session on rollback if spawn partially succeeded", async () => {
- const { result } = await runSaga({
- deps: {
- reconnectSession: vi.fn().mockResolvedValue(null),
- },
- });
-
- expect(result.success).toBe(false);
- if (result.success) return;
- expect(result.failedStep).toBe("spawn_agent");
- });
-
- it("fails at fetch_and_rebuild without touching workspace state", async () => {
- const deps = createDeps({
- fetchResumeState: vi.fn().mockRejectedValue(new Error("API down")),
- });
- const saga = new HandoffSaga(deps);
- const result = await saga.run(createInput());
-
- expect(result.success).toBe(false);
- if (result.success) return;
- expect(result.failedStep).toBe("fetch_and_rebuild");
- expect(deps.attachWorkspaceToFolder).not.toHaveBeenCalled();
- expect(deps.reconnectSession).not.toHaveBeenCalled();
- });
- });
-
- it("applies git checkpoint with local git state during handoff", async () => {
- const { deps, result } = await runSaga({
- input: { localGitState: DEFAULT_LOCAL_GIT_STATE },
- resumeState: {
- latestGitCheckpoint: createCheckpoint(),
- },
- });
-
- expect(result.success).toBe(true);
- if (!result.success) return;
- expect(deps.applyGitCheckpoint).toHaveBeenCalledTimes(1);
- expect(deps.applyGitCheckpoint).toHaveBeenCalledWith(
- expect.any(Object),
- "/repo",
- "task-1",
- "run-1",
- DEFAULT_LOCAL_GIT_STATE,
- );
- });
-
- it("applies each repository checkpoint to its local checkout", async () => {
- const posthog = createCheckpoint({ repository: "PostHog/posthog" });
- const desktop = createCheckpoint({
- repository: "PostHog/desktop",
- checkpointId: "checkpoint-2",
- });
- const { deps, result } = await runSaga({
- input: {
- repositoryPaths: {
- "posthog/posthog": "/repos/posthog",
- "posthog/desktop": "/repos/desktop",
- },
- },
- resumeState: {
- latestGitCheckpoints: [posthog, desktop],
- },
- });
-
- expect(result.success).toBe(true);
- expect(deps.applyGitCheckpoint).toHaveBeenCalledTimes(2);
- expect(deps.applyGitCheckpoint).toHaveBeenCalledWith(
- posthog,
- "/repos/posthog",
- "task-1",
- "run-1",
- undefined,
- );
- expect(deps.applyGitCheckpoint).toHaveBeenCalledWith(
- desktop,
- "/repos/desktop",
- "task-1",
- "run-1",
- undefined,
- );
- });
-});
diff --git a/products/desktop/packages/core/src/handoff/handoff-saga.ts b/products/desktop/packages/core/src/handoff/handoff-saga.ts
deleted file mode 100644
index 963ca11d422c..000000000000
--- a/products/desktop/packages/core/src/handoff/handoff-saga.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-import {
- type Adapter,
- type GitHandoffCheckpoint,
- type HandoffLocalGitState,
- Saga,
- type SagaLogger,
-} from "@posthog/shared";
-import type { HandoffBaseDeps, HandoffSagaInput } from "./types";
-
-export type { HandoffSagaInput } from "./types";
-
-export interface HandoffSagaOutput {
- sessionId: string;
- checkpointApplied: boolean;
- conversationTurns: number;
-}
-
-export interface HandoffResumeState {
- conversation: unknown[];
- latestGitCheckpoint: GitHandoffCheckpoint | null;
- latestGitCheckpoints?: GitHandoffCheckpoint[];
-}
-
-export interface HandoffSagaDeps extends HandoffBaseDeps {
- markRunEnvironmentLocal(taskId: string, runId: string): Promise<void>;
- fetchResumeState(
- taskId: string,
- runId: string,
- ): Promise<{ resumeState: HandoffResumeState; cloudLogUrl: string | null }>;
- formatConversation(conversation: unknown[]): string;
- applyGitCheckpoint(
- checkpoint: GitHandoffCheckpoint,
- repoPath: string,
- taskId: string,
- runId: string,
- localGitState?: HandoffLocalGitState,
- ): Promise<void>;
- reconnectSession(params: {
- taskId: string;
- taskRunId: string;
- repoPath: string;
- apiHost: string;
- projectId: number;
- logUrl: string;
- sessionId?: string;
- adapter?: Adapter;
- }): Promise<{ sessionId: string } | null>;
- closeCloudRun(
- taskId: string,
- runId: string,
- apiHost: string,
- teamId: number,
- localGitState?: HandoffLocalGitState,
- ): Promise<void>;
- attachWorkspaceToFolder(
- taskId: string,
- repoPath: string,
- ): { revert: () => void };
- seedLocalLogs(runId: string, logUrl: string): Promise<void>;
- setPendingContext(taskRunId: string, context: string): void;
-}
-
-export class HandoffSaga extends Saga<HandoffSagaInput, HandoffSagaOutput> {
- readonly sagaName = "HandoffSaga";
- private deps: HandoffSagaDeps;
-
- constructor(deps: HandoffSagaDeps, logger?: SagaLogger) {
- super(logger);
- this.deps = deps;
- }
-
- protected async execute(input: HandoffSagaInput): Promise<HandoffSagaOutput> {
- const { taskId, runId, repoPath, apiHost, teamId } = input;
-
- this.deps.onProgress(
- "fetching_logs",
- "Closing cloud run and capturing snapshot...",
- );
-
- await this.readOnlyStep("close_cloud_run", async () => {
- await this.deps.closeCloudRun(
- taskId,
- runId,
- apiHost,
- teamId,
- input.localGitState,
- );
- });
-
- await this.readOnlyStep("update_run_environment", async () => {
- await this.deps.markRunEnvironmentLocal(taskId, runId);
- });
-
- const { resumeState, cloudLogUrl } = await this.readOnlyStep(
- "fetch_and_rebuild",
- async () => {
- const { resumeState: state, cloudLogUrl: logUrl } =
- await this.deps.fetchResumeState(taskId, runId);
- return { resumeState: state, cloudLogUrl: logUrl };
- },
- );
-
- let checkpointApplied = false;
- const checkpoints = resumeState.latestGitCheckpoints?.length
- ? resumeState.latestGitCheckpoints
- : resumeState.latestGitCheckpoint
- ? [resumeState.latestGitCheckpoint]
- : [];
- if (checkpoints.length > 0) {
- this.deps.onProgress(
- "applying_git_checkpoint",
- "Applying cloud git state locally...",
- );
-
- await this.step({
- name: "apply_git_checkpoint",
- execute: async () => {
- await Promise.all(
- checkpoints.map((checkpoint) => {
- const path = checkpoint.repository
- ? input.repositoryPaths?.[checkpoint.repository.toLowerCase()]
- : repoPath;
- if (!path) {
- throw new Error(
- `No local checkout found for ${checkpoint.repository}`,
- );
- }
- return this.deps.applyGitCheckpoint(
- checkpoint,
- path,
- taskId,
- runId,
- checkpoint.repository ? undefined : input.localGitState,
- );
- }),
- );
- checkpointApplied = true;
- },
- rollback: async () => {},
- });
- }
-
- await this.step<{ revert: () => void }>({
- name: "attach_workspace_to_folder",
- execute: async () => this.deps.attachWorkspaceToFolder(taskId, repoPath),
- rollback: async ({ revert }) => {
- revert();
- },
- });
-
- if (cloudLogUrl) {
- await this.step({
- name: "seed_local_logs",
- execute: async () => {
- await this.deps.seedLocalLogs(runId, cloudLogUrl);
- },
- rollback: async () => {},
- });
- }
-
- this.deps.onProgress("spawning_agent", "Starting local agent...");
-
- let agentSessionId = "";
- await this.step({
- name: "spawn_agent",
- execute: async () => {
- const response = await this.deps.reconnectSession({
- taskId,
- taskRunId: runId,
- repoPath,
- apiHost,
- projectId: teamId,
- logUrl: cloudLogUrl ?? "",
- sessionId: input.sessionId,
- adapter: input.adapter,
- });
- if (!response) {
- throw new Error("Failed to create local agent session");
- }
- agentSessionId = response.sessionId;
- },
- rollback: async () => {
- await this.deps.killSession(runId).catch(() => {});
- },
- });
-
- await this.readOnlyStep("set_context", async () => {
- const context = this.buildHandoffContext(
- resumeState.conversation,
- checkpointApplied,
- );
- this.deps.setPendingContext(runId, context);
- });
-
- this.deps.onProgress("complete", "Handoff complete");
-
- return {
- sessionId: agentSessionId,
- checkpointApplied,
- conversationTurns: resumeState.conversation.length,
- };
- }
-
- private buildHandoffContext(
- conversation: unknown[],
- checkpointApplied: boolean,
- ): string {
- const conversationSummary = this.deps.formatConversation(conversation);
-
- const fileStatus = checkpointApplied
- ? "The workspace git state and files have been restored from the cloud session checkpoint."
- : "The workspace from the cloud session could not be restored from a checkpoint. You are working with the local file state.";
-
- return (
- `You are resuming a previous conversation that was running in a cloud sandbox. ` +
- `The user has transferred you to their local machine. ${fileStatus}\n\n` +
- `Here is the conversation history from the cloud session:\n\n` +
- `${conversationSummary}\n\n` +
- `The user will now send you a message. Respond to it with full context from the session above.`
- );
- }
-}
diff --git a/products/desktop/packages/core/src/handoff/handoff-to-cloud-saga.test.ts b/products/desktop/packages/core/src/handoff/handoff-to-cloud-saga.test.ts
deleted file mode 100644
index 9b1e40fbca58..000000000000
--- a/products/desktop/packages/core/src/handoff/handoff-to-cloud-saga.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import {
- HandoffToCloudSaga,
- type HandoffToCloudSagaDeps,
-} from "./handoff-to-cloud-saga";
-
-function createDeps(
- overrides: Partial<HandoffToCloudSagaDeps> = {},
-): HandoffToCloudSagaDeps {
- return {
- captureGitCheckpoint: vi.fn().mockResolvedValue({
- checkpointId: "checkpoint-1",
- checkpointRef: "refs/posthog-code-checkpoint/checkpoint-1",
- }),
- persistCheckpointToLog: vi.fn().mockResolvedValue(undefined),
- countLocalLogEntries: vi.fn().mockResolvedValue(7),
- resumeRunInCloud: vi.fn().mockResolvedValue(undefined),
- killSession: vi.fn().mockResolvedValue(undefined),
- updateWorkspaceMode: vi.fn(),
- onProgress: vi.fn(),
- ...overrides,
- } as unknown as HandoffToCloudSagaDeps;
-}
-
-describe("HandoffToCloudSaga", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("persists the fresh checkpoint, starts cloud, then kills the local session", async () => {
- const deps = createDeps();
- const order: string[] = [];
-
- vi.mocked(deps.persistCheckpointToLog).mockImplementation(async () => {
- order.push("checkpoint");
- });
- vi.mocked(deps.resumeRunInCloud).mockImplementation(async () => {
- order.push("resume");
- });
- vi.mocked(deps.killSession).mockImplementation(async () => {
- order.push("kill");
- });
-
- const saga = new HandoffToCloudSaga(deps);
- const result = await saga.run({
- taskId: "task-1",
- runId: "run-1",
- repoPath: "/repo/path",
- apiHost: "https://us.posthog.com",
- teamId: 1,
- localGitState: {
- head: "head-1",
- branch: "main",
- upstreamHead: "upstream-head-1",
- upstreamRemote: "origin",
- upstreamMergeRef: "refs/heads/main",
- },
- });
-
- expect(result.success).toBe(true);
- expect(order).toEqual(["checkpoint", "resume", "kill"]);
- expect(deps.countLocalLogEntries).toHaveBeenCalledWith("run-1");
- if (result.success) {
- expect(result.data.logEntryCount).toBe(7);
- expect(result.data.checkpointCaptured).toBe(true);
- }
- });
-
- it("reports logEntryCount of 0 when no local cache exists", async () => {
- const deps = createDeps({
- countLocalLogEntries: vi.fn().mockResolvedValue(0),
- });
-
- const saga = new HandoffToCloudSaga(deps);
- const result = await saga.run({
- taskId: "task-1",
- runId: "run-1",
- repoPath: "/repo/path",
- apiHost: "https://us.posthog.com",
- teamId: 1,
- });
-
- expect(result.success).toBe(true);
- if (result.success) {
- expect(result.data.logEntryCount).toBe(0);
- }
- });
-});
diff --git a/products/desktop/packages/core/src/handoff/handoff-to-cloud-saga.ts b/products/desktop/packages/core/src/handoff/handoff-to-cloud-saga.ts
deleted file mode 100644
index 86c424c2b0cb..000000000000
--- a/products/desktop/packages/core/src/handoff/handoff-to-cloud-saga.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import {
- type GitHandoffCheckpoint,
- type HandoffLocalGitState,
- Saga,
- type SagaLogger,
-} from "@posthog/shared";
-import type { HandoffBaseDeps, HandoffToCloudSagaInput } from "./types";
-
-export type { HandoffToCloudSagaInput } from "./types";
-
-export interface HandoffToCloudSagaOutput {
- checkpointCaptured: boolean;
- logEntryCount: number;
-}
-
-export interface HandoffToCloudSagaDeps extends HandoffBaseDeps {
- captureGitCheckpoint(
- localGitState?: HandoffLocalGitState,
- ): Promise<GitHandoffCheckpoint | null>;
- persistCheckpointToLog(checkpoint: GitHandoffCheckpoint): Promise<void>;
- countLocalLogEntries(runId: string): Promise<number>;
- resumeRunInCloud(): Promise<void>;
-}
-
-export class HandoffToCloudSaga extends Saga<
- HandoffToCloudSagaInput,
- HandoffToCloudSagaOutput
-> {
- readonly sagaName = "HandoffToCloudSaga";
- private deps: HandoffToCloudSagaDeps;
-
- constructor(deps: HandoffToCloudSagaDeps, logger?: SagaLogger) {
- super(logger);
- this.deps = deps;
- }
-
- protected async execute(
- input: HandoffToCloudSagaInput,
- ): Promise<HandoffToCloudSagaOutput> {
- const { taskId, runId } = input;
-
- let checkpointCaptured = false;
-
- this.deps.onProgress(
- "capturing_checkpoint",
- "Capturing local git state...",
- );
-
- const checkpoint = await this.readOnlyStep("capture_git_checkpoint", () =>
- this.deps.captureGitCheckpoint(input.localGitState),
- );
-
- if (checkpoint) {
- await this.readOnlyStep("persist_checkpoint_to_log", () =>
- this.deps.persistCheckpointToLog(checkpoint),
- );
- checkpointCaptured = true;
- }
-
- this.deps.onProgress("starting_cloud_run", "Starting cloud sandbox...");
-
- await this.step({
- name: "start_cloud_run",
- execute: () => this.deps.resumeRunInCloud(),
- rollback: async () => {},
- });
-
- this.deps.onProgress("stopping_agent", "Stopping local agent...");
-
- await this.readOnlyStep("stop_local_agent", () =>
- this.deps.killSession(runId),
- );
-
- const logEntryCount = await this.deps.countLocalLogEntries(runId);
-
- await this.step({
- name: "update_workspace",
- execute: async () => {
- this.deps.updateWorkspaceMode(taskId, "cloud");
- },
- rollback: async () => {
- this.deps.updateWorkspaceMode(taskId, "local");
- },
- });
-
- this.deps.onProgress("complete", "Handoff to cloud complete");
-
- return { checkpointCaptured, logEntryCount };
- }
-}
diff --git a/products/desktop/packages/core/src/handoff/handoff.module.ts b/products/desktop/packages/core/src/handoff/handoff.module.ts
deleted file mode 100644
index a9ac70b0eaa0..000000000000
--- a/products/desktop/packages/core/src/handoff/handoff.module.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { ContainerModule } from "inversify";
-import { HandoffService } from "./handoff";
-import { HANDOFF_SERVICE } from "./identifiers";
-
-export const handoffModule = new ContainerModule(({ bind }) => {
- bind(HANDOFF_SERVICE).to(HandoffService).inSingletonScope();
-});
diff --git a/products/desktop/packages/core/src/handoff/handoff.test.ts b/products/desktop/packages/core/src/handoff/handoff.test.ts
deleted file mode 100644
index 6d0aa7170df8..000000000000
--- a/products/desktop/packages/core/src/handoff/handoff.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import type { HandoffHost } from "@posthog/shared";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { extractHandoffErrorCode, HandoffService } from "./handoff";
-import type { HandoffPreflightInput } from "./schemas";
-
-const DEFAULT_LOCAL_GIT_STATE = {
- head: "abc123",
- branch: "main",
- upstreamHead: "def456",
- upstreamRemote: "origin",
- upstreamMergeRef: "refs/heads/main",
-};
-
-function createService(hostOverrides: Partial<HandoffHost> = {}): {
- service: HandoffService;
- host: HandoffHost;
-} {
- const host = {
- getChangedFiles: vi.fn().mockResolvedValue([]),
- getLocalGitState: vi.fn().mockResolvedValue(DEFAULT_LOCAL_GIT_STATE),
- markRunEnvironmentLocal: vi.fn(),
- fetchResumeState: vi.fn(),
- formatConversation: vi.fn(),
- applyGitCheckpoint: vi.fn(),
- reconnectSession: vi.fn(),
- attachWorkspaceToFolder: vi.fn(),
- seedLocalLogs: vi.fn(),
- setPendingContext: vi.fn(),
- killSession: vi.fn(),
- updateWorkspaceMode: vi.fn(),
- captureGitCheckpoint: vi.fn(),
- persistCheckpointToLog: vi.fn(),
- countLocalLogEntries: vi.fn(),
- resumeRunInCloud: vi.fn(),
- cleanupLocalAfterCloudHandoff: vi.fn(),
- deleteLocalLogCache: vi.fn(),
- ...hostOverrides,
- } as unknown as HandoffHost;
- const cloudTaskService = { sendCommand: vi.fn() } as never;
- const scopedLogger = {
- debug: vi.fn(),
- info: vi.fn(),
- warn: vi.fn(),
- error: vi.fn(),
- };
- const logger = { ...scopedLogger, scope: () => scopedLogger } as never;
-
- return { service: new HandoffService(host, cloudTaskService, logger), host };
-}
-
-function createPreflightInput(
- overrides: Partial<HandoffPreflightInput> = {},
-): HandoffPreflightInput {
- return {
- taskId: "task-1",
- runId: "run-1",
- repoPath: "/repo/path",
- apiHost: "https://us.posthog.com",
- teamId: 2,
- ...overrides,
- };
-}
-
-describe("HandoffService.preflight", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("returns canHandoff=true when working tree is clean", async () => {
- const { service } = createService();
- const result = await service.preflight(createPreflightInput());
-
- expect(result.canHandoff).toBe(true);
- expect(result.localTreeDirty).toBe(false);
- expect(result.reason).toBeUndefined();
- expect(result.localGitState).toEqual(DEFAULT_LOCAL_GIT_STATE);
- });
-
- it("returns canHandoff=false when working tree has changes", async () => {
- const { service } = createService({
- getChangedFiles: vi
- .fn()
- .mockResolvedValue([{ path: "src/index.ts", status: "modified" }]),
- });
- const result = await service.preflight(createPreflightInput());
-
- expect(result.canHandoff).toBe(false);
- expect(result.localTreeDirty).toBe(true);
- expect(result.reason).toContain("uncommitted changes");
- });
-
- it("checks the correct repo path", async () => {
- const { service, host } = createService();
- await service.preflight(createPreflightInput({ repoPath: "/custom/path" }));
-
- expect(host.getChangedFiles).toHaveBeenCalledWith("/custom/path");
- });
-
- it("returns canHandoff=true when git check throws", async () => {
- const { service } = createService({
- getChangedFiles: vi.fn().mockRejectedValue(new Error("git not found")),
- });
- const result = await service.preflight(createPreflightInput());
-
- expect(result.canHandoff).toBe(true);
- expect(result.localTreeDirty).toBe(false);
- });
-});
-
-describe("extractHandoffErrorCode", () => {
- it("detects GitHub authorization failures in backend error payloads", () => {
- const message =
- 'Failed request: [400] {"type":"validation_error","code":"github_authorization_required","detail":"Link a GitHub account"}';
-
- expect(extractHandoffErrorCode(message)).toBe(
- "github_authorization_required",
- );
- });
-
- it("ignores unrelated failures", () => {
- expect(extractHandoffErrorCode("Failed request: [500] boom")).toBe(
- undefined,
- );
- });
-});
diff --git a/products/desktop/packages/core/src/handoff/handoff.ts b/products/desktop/packages/core/src/handoff/handoff.ts
deleted file mode 100644
index c85c2fcfa840..000000000000
--- a/products/desktop/packages/core/src/handoff/handoff.ts
+++ /dev/null
@@ -1,269 +0,0 @@
-import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
-import {
- type HandoffHost,
- type SagaLogger,
- TypedEventEmitter,
-} from "@posthog/shared";
-import { inject, injectable } from "inversify";
-import type { CloudTaskService } from "../cloud-task/cloud-task";
-import { CLOUD_TASK_SERVICE } from "../cloud-task/identifiers";
-import { HandoffSaga, type HandoffSagaDeps } from "./handoff-saga";
-import {
- HandoffToCloudSaga,
- type HandoffToCloudSagaDeps,
-} from "./handoff-to-cloud-saga";
-import { HANDOFF_HOST } from "./identifiers";
-import {
- type HandoffErrorCode,
- HandoffEvent,
- type HandoffExecuteInput,
- type HandoffExecuteResult,
- type HandoffPreflightInput,
- type HandoffPreflightResult,
- type HandoffServiceEvents,
- type HandoffToCloudExecuteInput,
- type HandoffToCloudExecuteResult,
- type HandoffToCloudPreflightInput,
- type HandoffToCloudPreflightResult,
-} from "./schemas";
-
-const GITHUB_AUTHORIZATION_REQUIRED_CODE = "github_authorization_required";
-const GITHUB_AUTHORIZATION_REQUIRED_MESSAGE =
- "Connect GitHub in your browser, then retry Continue in cloud.";
-
-export function extractHandoffErrorCode(
- message: string | undefined,
-): HandoffErrorCode | undefined {
- if (message?.includes(GITHUB_AUTHORIZATION_REQUIRED_CODE)) {
- return GITHUB_AUTHORIZATION_REQUIRED_CODE;
- }
- return undefined;
-}
-
-@injectable()
-export class HandoffService extends TypedEventEmitter<HandoffServiceEvents> {
- private readonly logger: SagaLogger;
-
- constructor(
- @inject(HANDOFF_HOST)
- private readonly host: HandoffHost,
- @inject(CLOUD_TASK_SERVICE)
- private readonly cloudTaskService: CloudTaskService,
- @inject(ROOT_LOGGER)
- rootLogger: RootLogger,
- ) {
- super();
- this.logger = rootLogger.scope("handoff");
- }
-
- async preflight(
- input: HandoffPreflightInput,
- ): Promise<HandoffPreflightResult> {
- const { repoPath } = input;
-
- let localTreeDirty = false;
- let localGitState: HandoffPreflightResult["localGitState"];
- let changedFileDetails: HandoffPreflightResult["changedFiles"];
- try {
- const changedFiles = await this.host.getChangedFiles(repoPath);
- localTreeDirty = changedFiles.length > 0;
- changedFileDetails = changedFiles.map((f) => ({
- path: f.path,
- status: f.status,
- linesAdded: f.linesAdded,
- linesRemoved: f.linesRemoved,
- }));
- localGitState = await this.host.getLocalGitState(repoPath);
- } catch (err) {
- this.logger.warn("Failed to check local working tree", { repoPath, err });
- }
-
- const canHandoff = !localTreeDirty;
- const reason = localTreeDirty
- ? "Local working tree has uncommitted changes. Commit or stash them first."
- : undefined;
-
- return {
- canHandoff,
- reason,
- localTreeDirty,
- localGitState,
- changedFiles: changedFileDetails,
- };
- }
-
- async execute(input: HandoffExecuteInput): Promise<HandoffExecuteResult> {
- const ctx = { apiHost: input.apiHost, teamId: input.teamId };
-
- const deps: HandoffSagaDeps = {
- markRunEnvironmentLocal: (taskId, runId) =>
- this.host.markRunEnvironmentLocal(ctx, taskId, runId),
-
- fetchResumeState: (taskId, runId) =>
- this.host.fetchResumeState(ctx, taskId, runId),
-
- formatConversation: (conversation) =>
- this.host.formatConversation(conversation),
-
- applyGitCheckpoint: (
- checkpoint,
- repoPath,
- taskId,
- runId,
- localGitState,
- ) =>
- this.host.applyGitCheckpoint(
- ctx,
- checkpoint,
- repoPath,
- taskId,
- runId,
- localGitState,
- ),
-
- closeCloudRun: async (taskId, runId, apiHost, teamId, localGitState) => {
- const result = await this.cloudTaskService.sendCommand({
- taskId,
- runId,
- apiHost,
- teamId,
- method: "close",
- params: localGitState ? { localGitState } : undefined,
- });
- if (!result.success) {
- this.logger.warn("Close command failed, continuing with handoff", {
- error: result.error,
- });
- }
- },
-
- updateWorkspaceMode: (taskId, mode) =>
- this.host.updateWorkspaceMode(taskId, mode),
-
- attachWorkspaceToFolder: (taskId, repoPath) =>
- this.host.attachWorkspaceToFolder(taskId, repoPath),
-
- seedLocalLogs: (runId, logUrl) => this.host.seedLocalLogs(runId, logUrl),
-
- reconnectSession: (params) => this.host.reconnectSession(params),
-
- killSession: (taskRunId) => this.host.killSession(taskRunId),
-
- setPendingContext: (taskRunId, context) =>
- this.host.setPendingContext(taskRunId, context),
-
- onProgress: (step, message) => {
- this.emit(HandoffEvent.Progress, {
- taskId: input.taskId,
- step,
- message,
- });
- },
- };
-
- const saga = new HandoffSaga(deps, this.logger);
- const result = await saga.run(input);
-
- if (!result.success) {
- this.logger.error("Handoff saga failed", {
- error: result.error,
- failedStep: result.failedStep,
- });
- deps.onProgress("failed", result.error ?? "Handoff failed");
- return {
- success: false,
- error: `Handoff failed at step '${result.failedStep}': ${result.error}`,
- };
- }
-
- return {
- success: true,
- sessionId: result.data.sessionId,
- };
- }
-
- async preflightToCloud(
- input: HandoffToCloudPreflightInput,
- ): Promise<HandoffToCloudPreflightResult> {
- const { repoPath } = input;
-
- let localGitState: HandoffToCloudPreflightResult["localGitState"];
- try {
- localGitState = await this.host.getLocalGitState(repoPath);
- } catch (err) {
- this.logger.warn("Failed to read local git state for cloud handoff", {
- repoPath,
- err,
- });
- }
-
- return { canHandoff: true, localGitState };
- }
-
- async executeToCloud(
- input: HandoffToCloudExecuteInput,
- ): Promise<HandoffToCloudExecuteResult> {
- const { taskId, runId, repoPath, apiHost, teamId } = input;
- const ctx = { apiHost, teamId };
-
- const deps: HandoffToCloudSagaDeps = {
- captureGitCheckpoint: (localGitState) =>
- this.host.captureGitCheckpoint(
- ctx,
- repoPath,
- taskId,
- runId,
- localGitState,
- ),
-
- persistCheckpointToLog: (checkpoint) =>
- this.host.persistCheckpointToLog(ctx, taskId, runId, checkpoint),
-
- countLocalLogEntries: (taskRunId) =>
- this.host.countLocalLogEntries(taskRunId),
-
- resumeRunInCloud: () => this.host.resumeRunInCloud(ctx, taskId, runId),
-
- killSession: (taskRunId) => this.host.killSession(taskRunId),
-
- updateWorkspaceMode: (tid, mode) =>
- this.host.updateWorkspaceMode(tid, mode),
-
- onProgress: (step, message) => {
- this.emit(HandoffEvent.Progress, { taskId, step, message });
- },
- };
-
- const saga = new HandoffToCloudSaga(deps, this.logger);
- const result = await saga.run(input);
-
- if (!result.success) {
- this.logger.error("Handoff to cloud saga failed", {
- error: result.error,
- failedStep: result.failedStep,
- });
- deps.onProgress("failed", result.error ?? "Handoff to cloud failed");
- const code = extractHandoffErrorCode(result.error);
- return {
- success: false,
- code,
- error:
- code === GITHUB_AUTHORIZATION_REQUIRED_CODE
- ? GITHUB_AUTHORIZATION_REQUIRED_MESSAGE
- : `Handoff to cloud failed at step '${result.failedStep}': ${result.error}`,
- };
- }
-
- await this.host.cleanupLocalAfterCloudHandoff(
- repoPath,
- input.localGitState?.branch ?? null,
- );
-
- await this.host.deleteLocalLogCache(runId);
-
- return {
- success: true,
- logEntryCount: result.data.logEntryCount,
- };
- }
-}
diff --git a/products/desktop/packages/core/src/handoff/identifiers.ts b/products/desktop/packages/core/src/handoff/identifiers.ts
deleted file mode 100644
index 84147800846c..000000000000
--- a/products/desktop/packages/core/src/handoff/identifiers.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export const HANDOFF_SERVICE = Symbol.for("posthog.core.handoffService");
-export const HANDOFF_HOST = Symbol.for("posthog.core.handoffHost");
diff --git a/products/desktop/packages/core/src/handoff/schemas.ts b/products/desktop/packages/core/src/handoff/schemas.ts
deleted file mode 100644
index 1260cc8d0fce..000000000000
--- a/products/desktop/packages/core/src/handoff/schemas.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import { z } from "zod";
-import type { HandoffStep } from "./types";
-
-export type { HandoffStep } from "./types";
-
-export const handoffLocalGitStateSchema = z.object({
- head: z.string().nullable(),
- branch: z.string().nullable(),
- upstreamHead: z.string().nullable(),
- upstreamRemote: z.string().nullable(),
- upstreamMergeRef: z.string().nullable(),
-});
-
-const handoffBaseInput = z.object({
- taskId: z.string(),
- runId: z.string(),
- repoPath: z.string(),
-});
-
-const handoffApiInput = handoffBaseInput.extend({
- apiHost: z.string(),
- teamId: z.number(),
-});
-
-export const handoffErrorCodeSchema = z.enum(["github_authorization_required"]);
-
-export type HandoffErrorCode = z.infer<typeof handoffErrorCodeSchema>;
-
-const handoffBaseResult = z.object({
- success: z.boolean(),
- error: z.string().optional(),
- code: handoffErrorCodeSchema.optional(),
-});
-
-export const handoffPreflightInput = handoffApiInput;
-
-export type HandoffPreflightInput = z.infer<typeof handoffPreflightInput>;
-
-export const handoffPreflightResult = z.object({
- canHandoff: z.boolean(),
- reason: z.string().optional(),
- localTreeDirty: z.boolean(),
- localGitState: handoffLocalGitStateSchema.optional(),
- changedFiles: z
- .array(
- z.object({
- path: z.string(),
- status: z.enum([
- "modified",
- "added",
- "deleted",
- "renamed",
- "untracked",
- ]),
- linesAdded: z.number().optional(),
- linesRemoved: z.number().optional(),
- }),
- )
- .optional(),
-});
-
-export type HandoffPreflightResult = z.infer<typeof handoffPreflightResult>;
-
-export const handoffExecuteInput = handoffApiInput.extend({
- repositoryPaths: z.record(z.string(), z.string()).optional(),
- sessionId: z.string().optional(),
- adapter: z.enum(["claude", "codex"]).optional(),
- localGitState: handoffLocalGitStateSchema.optional(),
-});
-
-export type HandoffExecuteInput = z.infer<typeof handoffExecuteInput>;
-
-export const handoffExecuteResult = handoffBaseResult.extend({
- sessionId: z.string().optional(),
-});
-
-export type HandoffExecuteResult = z.infer<typeof handoffExecuteResult>;
-
-export const handoffToCloudPreflightInput = handoffBaseInput;
-
-export type HandoffToCloudPreflightInput = z.infer<
- typeof handoffToCloudPreflightInput
->;
-
-export const handoffToCloudPreflightResult = z.object({
- canHandoff: z.boolean(),
- reason: z.string().optional(),
- localGitState: handoffLocalGitStateSchema.optional(),
-});
-
-export type HandoffToCloudPreflightResult = z.infer<
- typeof handoffToCloudPreflightResult
->;
-
-export const handoffToCloudExecuteInput = handoffApiInput.extend({
- localGitState: handoffLocalGitStateSchema.optional(),
-});
-
-export type HandoffToCloudExecuteInput = z.infer<
- typeof handoffToCloudExecuteInput
->;
-
-export const handoffToCloudExecuteResult = handoffBaseResult.extend({
- logEntryCount: z.number().optional(),
-});
-
-export type HandoffToCloudExecuteResult = z.infer<
- typeof handoffToCloudExecuteResult
->;
-
-export interface HandoffProgressPayload {
- taskId: string;
- step: HandoffStep;
- message: string;
-}
-
-export const HandoffEvent = {
- Progress: "handoff-progress",
-} as const;
-
-export interface HandoffServiceEvents {
- [HandoffEvent.Progress]: HandoffProgressPayload;
-}
diff --git a/products/desktop/packages/core/src/handoff/types.ts b/products/desktop/packages/core/src/handoff/types.ts
deleted file mode 100644
index 4dcb0ea51926..000000000000
--- a/products/desktop/packages/core/src/handoff/types.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import type {
- Adapter,
- HandoffLocalGitState,
- WorkspaceMode,
-} from "@posthog/shared";
-
-export type HandoffStep =
- | "fetching_logs"
- | "applying_git_checkpoint"
- | "spawning_agent"
- | "capturing_checkpoint"
- | "stopping_agent"
- | "starting_cloud_run"
- | "complete"
- | "failed";
-
-export interface HandoffSagaInput {
- taskId: string;
- runId: string;
- repoPath: string;
- repositoryPaths?: Record<string, string>;
- apiHost: string;
- teamId: number;
- sessionId?: string;
- adapter?: Adapter;
- localGitState?: HandoffLocalGitState;
-}
-
-export interface HandoffToCloudSagaInput {
- taskId: string;
- runId: string;
- repoPath: string;
- apiHost: string;
- teamId: number;
- localGitState?: HandoffLocalGitState;
-}
-
-export interface HandoffBaseDeps {
- killSession(taskRunId: string): Promise<void>;
- updateWorkspaceMode(taskId: string, mode: WorkspaceMode): void;
- onProgress(step: HandoffStep, message: string): void;
-}
diff --git a/products/desktop/packages/core/src/sessions/acpNotifications.ts b/products/desktop/packages/core/src/sessions/acpNotifications.ts
index 80642db79b7d..f713ede6997b 100644
--- a/products/desktop/packages/core/src/sessions/acpNotifications.ts
+++ b/products/desktop/packages/core/src/sessions/acpNotifications.ts
@@ -7,7 +7,6 @@ export const POSTHOG_NOTIFICATIONS = {
ERROR: "_posthog/error",
CONSOLE: "_posthog/console",
SDK_SESSION: "_posthog/sdk_session",
- GIT_CHECKPOINT: "_posthog/git_checkpoint",
MODE_CHANGE: "_posthog/mode_change",
SESSION_RESUME: "_posthog/session/resume",
USER_MESSAGE: "_posthog/user_message",
diff --git a/products/desktop/packages/core/src/sessions/localHandoffService.test.ts b/products/desktop/packages/core/src/sessions/localHandoffService.test.ts
deleted file mode 100644
index c36248a20232..000000000000
--- a/products/desktop/packages/core/src/sessions/localHandoffService.test.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-import type { Task } from "@posthog/shared/domain-types";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import {
- type LocalHandoffDialog,
- type LocalHandoffHost,
- type LocalHandoffNotifier,
- type LocalHandoffPending,
- LocalHandoffService,
-} from "./localHandoffService";
-import type { SessionService } from "./sessionService";
-
-function makeDeps() {
- let pending: LocalHandoffPending | null = null;
-
- const sessionService = {
- preflightToLocal: vi.fn(),
- handoffToLocal: vi.fn().mockResolvedValue(undefined),
- };
-
- const host: LocalHandoffHost = {
- getRepositoryByRemoteUrl: vi.fn().mockResolvedValue(null),
- selectDirectory: vi.fn().mockResolvedValue(null),
- addFolder: vi.fn().mockResolvedValue(undefined),
- getWorktreeLocation: vi.fn().mockResolvedValue("/worktrees"),
- cloneRepository: vi.fn().mockResolvedValue(undefined),
- addAdditionalDirectory: vi.fn().mockResolvedValue(undefined),
- };
-
- const dialog: LocalHandoffDialog = {
- openConfirm: vi.fn(),
- closeConfirm: vi.fn(),
- cancelPendingFlow: vi.fn(),
- hideDirtyTree: vi.fn(),
- getPendingAfterCommit: vi.fn(() => pending),
- clearPendingAfterCommit: vi.fn(() => {
- pending = null;
- }),
- openDirtyTreeForPendingHandoff: vi.fn(),
- };
-
- const notifier: LocalHandoffNotifier = {
- error: vi.fn(),
- warn: vi.fn(),
- logError: vi.fn(),
- };
-
- const service = new LocalHandoffService(
- sessionService as unknown as SessionService,
- host,
- dialog,
- notifier,
- );
-
- return {
- service,
- sessionService,
- host,
- dialog,
- notifier,
- setPending: (value: LocalHandoffPending | null) => {
- pending = value;
- },
- };
-}
-
-describe("LocalHandoffService.continueAfterDirtyTree", () => {
- let deps: ReturnType<typeof makeDeps>;
-
- beforeEach(() => {
- deps = makeDeps();
- });
-
- it("hides the dirty tree dialog regardless of branch state", () => {
- deps.service.continueAfterDirtyTree({
- isFeatureBranch: true,
- suggestedBranchName: "fix/thing",
- });
- expect(deps.dialog.hideDirtyTree).toHaveBeenCalledOnce();
- });
-
- it("routes straight to commit when already on a feature branch", () => {
- const step = deps.service.continueAfterDirtyTree({
- isFeatureBranch: true,
- suggestedBranchName: "fix/thing",
- });
- expect(step).toEqual({ step: "open-commit" });
- });
-
- it("routes to branch creation with the suggested name otherwise", () => {
- const step = deps.service.continueAfterDirtyTree({
- isFeatureBranch: false,
- suggestedBranchName: "fix/thing",
- });
- expect(step).toEqual({ step: "open-branch", suggestedName: "fix/thing" });
- });
-});
-
-describe("LocalHandoffService.afterBranchCreated", () => {
- it("advances to the commit step", () => {
- const { service } = makeDeps();
- expect(service.afterBranchCreated()).toEqual({ step: "open-commit" });
- });
-});
-
-describe("LocalHandoffService.afterCommit", () => {
- it("resumes the pending handoff once a commit succeeds", async () => {
- const deps = makeDeps();
- deps.setPending({
- taskId: "task-1",
- repoPath: "/repo",
- branchName: "fix/thing",
- });
-
- await deps.service.afterCommit();
-
- expect(deps.dialog.clearPendingAfterCommit).toHaveBeenCalledOnce();
- expect(deps.sessionService.handoffToLocal).toHaveBeenCalledWith(
- "task-1",
- "/repo",
- undefined,
- );
- });
-
- it("is a no-op when there is no pending handoff", async () => {
- const deps = makeDeps();
- deps.setPending(null);
-
- await deps.service.afterCommit();
-
- expect(deps.sessionService.handoffToLocal).not.toHaveBeenCalled();
- });
-
- it("reports an error when resuming the handoff fails", async () => {
- const deps = makeDeps();
- deps.setPending({
- taskId: "task-1",
- repoPath: "/repo",
- branchName: null,
- });
- deps.sessionService.handoffToLocal.mockRejectedValueOnce(new Error("boom"));
-
- await deps.service.afterCommit();
-
- expect(deps.notifier.error).toHaveBeenCalledWith(
- "Failed to continue locally: boom",
- );
- });
-});
-
-describe("LocalHandoffService.start", () => {
- const task = { repository: "https://example.com/repo.git" } as Task;
-
- it("hands off immediately when preflight is clean", async () => {
- const deps = makeDeps();
- deps.host.getRepositoryByRemoteUrl = vi
- .fn()
- .mockResolvedValue({ path: "/repo" });
- deps.sessionService.preflightToLocal.mockResolvedValue({
- canHandoff: true,
- });
-
- await deps.service.start("task-1", task);
-
- expect(deps.dialog.closeConfirm).toHaveBeenCalled();
- expect(deps.sessionService.handoffToLocal).toHaveBeenCalledWith(
- "task-1",
- "/repo",
- { "https://example.com/repo.git": "/repo" },
- );
- });
-
- it("opens the dirty-tree dialog when the local tree is dirty", async () => {
- const deps = makeDeps();
- deps.host.getRepositoryByRemoteUrl = vi
- .fn()
- .mockResolvedValue({ path: "/repo" });
- deps.sessionService.preflightToLocal.mockResolvedValue({
- canHandoff: false,
- localTreeDirty: true,
- changedFiles: [{ path: "a.ts" }],
- localGitState: { branch: "main" },
- });
-
- await deps.service.start("task-1", task);
-
- expect(deps.dialog.openDirtyTreeForPendingHandoff).toHaveBeenCalledWith(
- [{ path: "a.ts" }],
- {
- taskId: "task-1",
- repoPath: "/repo",
- branchName: "main",
- repositoryPaths: { "https://example.com/repo.git": "/repo" },
- },
- );
- });
-
- it("reuses local repositories and clones missing ones before handoff", async () => {
- const deps = makeDeps();
- const multiRepoTask = {
- repositories: ["posthog/posthog", "posthog/posthog-js"],
- } as Task;
- deps.host.getRepositoryByRemoteUrl = vi
- .fn()
- .mockResolvedValueOnce({ path: "/repos/posthog" })
- .mockResolvedValueOnce(null);
- deps.sessionService.preflightToLocal.mockResolvedValue({
- canHandoff: true,
- });
-
- await deps.service.start("task-1", multiRepoTask);
-
- expect(deps.host.cloneRepository).toHaveBeenCalledWith(
- expect.objectContaining({
- repoUrl: "https://github.com/posthog/posthog-js.git",
- targetPath: "/worktrees/linked-repositories/posthog/posthog-js",
- }),
- );
- expect(deps.host.addAdditionalDirectory).toHaveBeenCalledWith({
- taskId: "task-1",
- path: "/worktrees/linked-repositories/posthog/posthog-js",
- });
- expect(deps.sessionService.handoffToLocal).toHaveBeenCalledWith(
- "task-1",
- "/repos/posthog",
- {
- "posthog/posthog": "/repos/posthog",
- "posthog/posthog-js":
- "/worktrees/linked-repositories/posthog/posthog-js",
- },
- );
- });
-
- // A task's repositories are team-writable via the API, so an unsafe entry must
- // never reach `git clone` (RCE via git's remote-ext transport) or escape the
- // clone root through path traversal. The safe repo alongside it still clones.
- it.each([
- ["remote-ext RCE", "ext::sh -c 'touch pwned'/repo"],
- ["path traversal", "../evil"],
- ["absolute-ish scheme", "file:///etc/passwd/repo"],
- ["trailing whitespace alias", "posthog/posthog-js "],
- ["extra path segment", "posthog/posthog-js/../../evil"],
- ])("rejects an unsafe repository entry (%s)", async (_label, malicious) => {
- const deps = makeDeps();
- deps.host.getRepositoryByRemoteUrl = vi.fn().mockResolvedValue(null);
- deps.sessionService.preflightToLocal.mockResolvedValue({
- canHandoff: true,
- });
-
- await deps.service.start("task-1", {
- repositories: ["posthog/posthog", malicious],
- } as Task);
-
- // Only the safe repo is cloned, and always through an explicit https URL.
- expect(deps.host.cloneRepository).toHaveBeenCalledTimes(1);
- expect(deps.host.cloneRepository).toHaveBeenCalledWith(
- expect.objectContaining({
- repoUrl: "https://github.com/posthog/posthog.git",
- }),
- );
- expect(deps.notifier.warn).toHaveBeenCalledWith(
- expect.stringContaining(malicious),
- );
- const [, , repositoryPaths] =
- deps.sessionService.handoffToLocal.mock.calls[0];
- expect(repositoryPaths).toEqual({
- "posthog/posthog": "/worktrees/linked-repositories/posthog/posthog",
- });
- });
-
- it("de-duplicates case-variant repository aliases before cloning", async () => {
- const deps = makeDeps();
- deps.host.getRepositoryByRemoteUrl = vi.fn().mockResolvedValue(null);
- deps.sessionService.preflightToLocal.mockResolvedValue({
- canHandoff: true,
- });
-
- await deps.service.start("task-1", {
- repositories: ["PostHog/PostHog", "posthog/posthog"],
- } as Task);
-
- // Both collapse to one target, so the racing double-clone can't happen.
- expect(deps.host.cloneRepository).toHaveBeenCalledTimes(1);
- const [, , repositoryPaths] =
- deps.sessionService.handoffToLocal.mock.calls[0];
- expect(repositoryPaths).toEqual({
- "posthog/posthog": "/worktrees/linked-repositories/posthog/posthog",
- });
- });
-});
diff --git a/products/desktop/packages/core/src/sessions/localHandoffService.ts b/products/desktop/packages/core/src/sessions/localHandoffService.ts
deleted file mode 100644
index d9c59cffcf85..000000000000
--- a/products/desktop/packages/core/src/sessions/localHandoffService.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-import { parseRepository } from "@posthog/shared";
-import type { Task } from "@posthog/shared/domain-types";
-import { inject, injectable } from "inversify";
-import { SESSION_SERVICE, type SessionService } from "./sessionService";
-
-export const LOCAL_HANDOFF_SERVICE = Symbol.for(
- "posthog.core.sessions.localHandoffService",
-);
-
-export const LOCAL_HANDOFF_HOST = Symbol.for(
- "posthog.core.sessions.localHandoffHost",
-);
-
-export const LOCAL_HANDOFF_DIALOG = Symbol.for(
- "posthog.core.sessions.localHandoffDialog",
-);
-
-export const LOCAL_HANDOFF_NOTIFIER = Symbol.for(
- "posthog.core.sessions.localHandoffNotifier",
-);
-
-export interface LocalHandoffHost {
- getRepositoryByRemoteUrl(input: {
- remoteUrl: string;
- }): Promise<{ path: string } | null>;
- selectDirectory(): Promise<string | null>;
- addFolder(input: {
- folderPath: string;
- remoteUrl?: string;
- }): Promise<unknown>;
- getWorktreeLocation(): Promise<string>;
- cloneRepository(input: {
- repoUrl: string;
- targetPath: string;
- cloneId: string;
- }): Promise<unknown>;
- addAdditionalDirectory(input: {
- taskId: string;
- path: string;
- }): Promise<void>;
-}
-
-export interface LocalHandoffPending {
- taskId: string;
- repoPath: string;
- branchName: string | null;
- repositoryPaths?: Record<string, string>;
-}
-
-export interface ContinueAfterDirtyTreeContext {
- isFeatureBranch: boolean;
- suggestedBranchName: string;
-}
-
-export type ContinueAfterDirtyTreeStep =
- | { step: "open-commit" }
- | { step: "open-branch"; suggestedName: string };
-
-export interface LocalHandoffDialog {
- openConfirm(taskId: string, branchName: string | null): void;
- closeConfirm(): void;
- cancelPendingFlow(): void;
- hideDirtyTree(): void;
- getPendingAfterCommit(): LocalHandoffPending | null;
- clearPendingAfterCommit(): void;
- openDirtyTreeForPendingHandoff(
- changedFiles: unknown[],
- pending: LocalHandoffPending,
- ): void;
-}
-
-export interface LocalHandoffNotifier {
- error(message: string): void;
- warn(message: string, data?: unknown): void;
- logError(message: string, data?: unknown): void;
-}
-
-// Only validated GitHub slugs may reach git clone or filesystem paths.
-const SAFE_REPO_SEGMENT = /^[A-Za-z0-9._-]+$/;
-
-function canonicalRepository(
- repository: string,
-): { slug: string; key: string } | null {
- const parsed = parseRepository(repository);
- if (!parsed) return null;
- const { organization, repoName } = parsed;
- for (const segment of [organization, repoName]) {
- if (
- !SAFE_REPO_SEGMENT.test(segment) ||
- segment === "." ||
- segment === ".."
- ) {
- return null;
- }
- }
- const slug = `${organization}/${repoName}`;
- return { slug, key: slug.toLowerCase() };
-}
-
-@injectable()
-export class LocalHandoffService {
- constructor(
- @inject(SESSION_SERVICE)
- private readonly sessionService: SessionService,
- @inject(LOCAL_HANDOFF_HOST)
- private readonly host: LocalHandoffHost,
- @inject(LOCAL_HANDOFF_DIALOG)
- private readonly dialog: LocalHandoffDialog,
- @inject(LOCAL_HANDOFF_NOTIFIER)
- private readonly notifier: LocalHandoffNotifier,
- ) {}
-
- public openConfirm(taskId: string, branchName: string | null): void {
- this.dialog.openConfirm(taskId, branchName);
- }
-
- public closeConfirm(): void {
- this.dialog.closeConfirm();
- }
-
- public cancelPendingFlow(): void {
- this.dialog.cancelPendingFlow();
- }
-
- public hideDirtyTree(): void {
- this.dialog.hideDirtyTree();
- }
-
- public getPendingAfterCommit(): LocalHandoffPending | null {
- return this.dialog.getPendingAfterCommit();
- }
-
- public async start(taskId: string, task: Task): Promise<void> {
- try {
- const repositories = task.repositories?.length
- ? task.repositories
- : task.repository
- ? [task.repository]
- : [];
- const repositoryPaths = await this.resolveRepositoryPaths(repositories);
- const paths = Object.values(repositoryPaths);
- const targetPath =
- paths[0] ?? (await this.resolveRepoPathFromPicker(task.repository));
-
- if (!targetPath) return;
-
- await Promise.all(
- paths
- .slice(1)
- .map((path) => this.host.addAdditionalDirectory({ taskId, path })),
- );
-
- const preflight = await this.sessionService.preflightToLocal(
- taskId,
- targetPath,
- );
-
- if (preflight.canHandoff) {
- this.closeConfirm();
- await this.sessionService.handoffToLocal(
- taskId,
- targetPath,
- repositoryPaths,
- );
- return;
- }
-
- if (preflight.localTreeDirty && preflight.changedFiles) {
- this.dialog.openDirtyTreeForPendingHandoff(preflight.changedFiles, {
- taskId,
- repoPath: targetPath,
- branchName: preflight.localGitState?.branch ?? null,
- repositoryPaths,
- });
- return;
- }
-
- this.notifier.error(preflight.reason ?? "Cannot continue locally");
- this.closeConfirm();
- } catch (error) {
- this.notifier.logError("Failed to hand off to local", error);
- const message = error instanceof Error ? error.message : "Unknown error";
- this.notifier.error(`Failed to continue locally: ${message}`);
- this.closeConfirm();
- }
- }
-
- public continueAfterDirtyTree(
- ctx: ContinueAfterDirtyTreeContext,
- ): ContinueAfterDirtyTreeStep {
- this.dialog.hideDirtyTree();
- if (ctx.isFeatureBranch) {
- return { step: "open-commit" };
- }
- return { step: "open-branch", suggestedName: ctx.suggestedBranchName };
- }
-
- public afterBranchCreated(): ContinueAfterDirtyTreeStep {
- return { step: "open-commit" };
- }
-
- public async afterCommit(): Promise<void> {
- await this.resumePending();
- }
-
- public async resumePending(): Promise<void> {
- const pending = this.getPendingAfterCommit();
- if (!pending) return;
-
- this.dialog.clearPendingAfterCommit();
-
- try {
- await this.sessionService.handoffToLocal(
- pending.taskId,
- pending.repoPath,
- pending.repositoryPaths,
- );
- } catch (error) {
- this.notifier.logError("Failed to resume handoff to local", error);
- const message = error instanceof Error ? error.message : "Unknown error";
- this.notifier.error(`Failed to continue locally: ${message}`);
- }
- }
-
- private async resolveRepoPathFromRemote(
- remoteUrl: string | undefined | null,
- ): Promise<string | null> {
- if (!remoteUrl) return null;
- const repo = await this.host.getRepositoryByRemoteUrl({
- remoteUrl,
- });
- return repo?.path ?? null;
- }
-
- private async resolveRepositoryPaths(
- repositories: string[],
- ): Promise<Record<string, string>> {
- if (repositories.length === 0) return {};
- const cloneRoot = `${(await this.host.getWorktreeLocation()).replace(/\/$/, "")}/linked-repositories`;
-
- // Sequential clones prevent aliases racing on the same target path.
- const resolved: Record<string, string> = {};
- const clonedTargets = new Set<string>();
- for (const repository of repositories) {
- const existing = await this.resolveRepoPathFromRemote(repository);
- if (existing) {
- resolved[repository.toLowerCase()] = existing;
- continue;
- }
- const canonical = canonicalRepository(repository);
- if (!canonical) {
- this.notifier.warn(
- `Skipping repository with an unexpected name: ${repository}`,
- );
- continue;
- }
- if (clonedTargets.has(canonical.key)) continue;
- clonedTargets.add(canonical.key);
- const targetPath = `${cloneRoot}/${canonical.key}`;
- const repoUrl = `https://github.com/${canonical.slug}.git`;
- await this.host.cloneRepository({
- repoUrl,
- targetPath,
- cloneId: globalThis.crypto.randomUUID(),
- });
- await this.host.addFolder({ folderPath: targetPath, remoteUrl: repoUrl });
- resolved[canonical.key] = targetPath;
- }
- return resolved;
- }
-
- private async resolveRepoPathFromPicker(
- remoteUrl: string | null | undefined,
- ): Promise<string | null> {
- const selectedPath = await this.host.selectDirectory();
- if (!selectedPath) return null;
-
- await this.host.addFolder({
- folderPath: selectedPath,
- remoteUrl: remoteUrl ?? undefined,
- });
-
- return selectedPath;
- }
-}
diff --git a/products/desktop/packages/core/src/sessions/sessionEviction.test.ts b/products/desktop/packages/core/src/sessions/sessionEviction.test.ts
index ddc636cc931b..c65cf243e79e 100644
--- a/products/desktop/packages/core/src/sessions/sessionEviction.test.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEviction.test.ts
@@ -25,7 +25,6 @@ describe("isSessionIdle", () => {
["connecting session", { status: "connecting" as const }, false],
["pending prompt", { isPromptPending: true }, false],
["compacting session", { isCompacting: true }, false],
- ["handoff in progress", { handoffInProgress: true }, false],
[
"pending permission",
{ pendingPermissions: new Map([["p1", {} as never]]) },
diff --git a/products/desktop/packages/core/src/sessions/sessionEviction.ts b/products/desktop/packages/core/src/sessions/sessionEviction.ts
index 71b0879d1223..493cddba661a 100644
--- a/products/desktop/packages/core/src/sessions/sessionEviction.ts
+++ b/products/desktop/packages/core/src/sessions/sessionEviction.ts
@@ -8,7 +8,6 @@ export function isSessionIdle(session: AgentSession): boolean {
if (session.status === "connecting") return false;
if (session.isPromptPending) return false;
if (session.isCompacting) return false;
- if (session.handoffInProgress) return false;
if (session.pendingPermissions.size > 0) return false;
if (session.messageQueue.length > 0) return false;
if (session.isCloud) return isTerminalStatus(session.cloudStatus);
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 925e5c7fda5d..cbfe9d88018a 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -150,7 +150,6 @@ const LOCAL_SESSION_RECOVERY_MESSAGE =
"Lost connection to the agent. Reconnecting…";
const LOCAL_SESSION_RECOVERY_FAILED_MESSAGE =
"Connecting to to the agent has been lost. Retry, or start a new session.";
-const GITHUB_AUTHORIZATION_REQUIRED_CODE = "github_authorization_required";
const AUTO_RETRY_MAX_ATTEMPTS = 2;
const AUTO_RETRY_DELAY_MS = 10_000;
const AUTH_RESTORE_MAX_RETRY_WAITS = 6;
@@ -247,15 +246,6 @@ function endsAtConversationClearedBoundary(events: AcpMessage[]): boolean {
);
}
-class GitHubAuthorizationRequiredForCloudHandoffError extends Error {
- constructor(
- message = "Connect GitHub before continuing this task in cloud.",
- ) {
- super(message);
- this.name = "GitHubAuthorizationRequiredForCloudHandoffError";
- }
-}
-
type TrpcMutation = { mutate: (input?: any) => Promise<any> };
type TrpcQuery = { query: (input?: any) => Promise<any> };
type TrpcSubscription = {
@@ -343,12 +333,6 @@ export interface SessionTrpc {
designateRelayedMcpServers: TrpcMutation;
onUpdate: TrpcSubscription;
};
- handoff: {
- execute: TrpcMutation;
- executeToCloud: TrpcMutation;
- preflight: TrpcQuery;
- preflightToCloud: TrpcQuery;
- };
logs: {
readLocalLogs: TrpcQuery;
/** Optional: merges superseded tool_call_update snapshots server-side so
@@ -363,7 +347,6 @@ export interface SessionTrpc {
fetchS3Logs: TrpcQuery;
writeLocalLogs: TrpcMutation;
};
- os: { openExternal: TrpcMutation };
}
export interface ISessionStore {
@@ -3026,7 +3009,7 @@ export class SessionService {
): session is AgentSession {
if (!session || session.isPromptPending) return false;
// A cloud run's `status` can read "disconnected" while the run is still
- // alive (cloud handoff and SSE-retry both write it), so a cloud transcript
+ // alive because SSE retries write it, so a cloud transcript
// is only safe to release once its `cloudStatus` is terminal, mirroring
// isSessionIdle. Local runs still key off `status`.
return session.isCloud
@@ -7703,304 +7686,6 @@ export class SessionService {
this.cloudLogGapReconciler.forgetDeficiency(watcher.runId);
}
- async preflightToLocal(taskId: string, repoPath: string) {
- const session = this.d.store.getSessionByTaskId(taskId);
- if (!session)
- return {
- canHandoff: false as const,
- localTreeDirty: false as const,
- reason: "No session found",
- };
-
- const auth = await this.getHandoffAuth();
- if (!auth)
- return {
- canHandoff: false as const,
- localTreeDirty: false as const,
- reason: "Authentication required",
- };
-
- const preflight = await this.d.trpc.handoff.preflight.query({
- taskId,
- runId: session.taskRunId,
- repoPath,
- apiHost: auth.apiHost,
- teamId: auth.projectId,
- });
-
- return {
- canHandoff: preflight.canHandoff,
- localTreeDirty: preflight.localTreeDirty,
- localGitState: preflight.localGitState,
- changedFiles: preflight.changedFiles,
- reason: preflight.reason,
- };
- }
-
- async handoffToLocal(
- taskId: string,
- repoPath: string,
- repositoryPaths?: Record<string, string>,
- ): Promise<void> {
- const session = this.d.store.getSessionByTaskId(taskId);
- if (!session) {
- this.d.log.warn("No session found for handoff", { taskId });
- return;
- }
-
- const runId = session.taskRunId;
- const auth = await this.getHandoffAuth();
- if (!auth) return;
-
- this.d.store.updateSession(runId, { handoffInProgress: true });
-
- try {
- const paths = [...new Set(Object.values(repositoryPaths ?? {}))];
- if (!paths.includes(repoPath)) paths.unshift(repoPath);
- let localGitState:
- | Awaited<
- ReturnType<typeof this.d.trpc.handoff.preflight.query>
- >["localGitState"]
- | undefined;
- for (const path of paths) {
- const preflight = await this.runHandoffPreflight(
- taskId,
- runId,
- path,
- auth,
- );
- if (path === repoPath) localGitState = preflight.localGitState;
- }
- this.stopCloudTaskWatch(taskId);
- this.d.store.updateSession(runId, { status: "connecting" });
- await this.executeHandoff(
- taskId,
- runId,
- repoPath,
- repositoryPaths,
- auth,
- localGitState,
- );
- this.transitionToLocalSession(runId);
- this.subscribeToChannel(runId);
- await Promise.all([
- this.d.queryClient.refetchQueries({ queryKey: ["tasks"] }),
- this.d.queryClient.refetchQueries({
- queryKey: this.d.WORKSPACE_QUERY_KEY,
- }),
- ]);
- this.d.store.updateSession(runId, { handoffInProgress: false });
- this.d.log.info("Cloud-to-local handoff complete", { taskId, runId });
- } catch (err) {
- this.d.log.error("Handoff failed", { taskId, err });
- this.d.toast.error(
- err instanceof Error ? err.message : "Handoff to local failed",
- );
- this.watchCloudTask(taskId, runId, auth.apiHost, auth.projectId);
- this.d.store.updateSession(runId, {
- handoffInProgress: false,
- status: "disconnected",
- });
- }
- }
-
- async handoffToCloud(taskId: string, repoPath: string): Promise<void> {
- const session = this.d.store.getSessionByTaskId(taskId);
- if (!session) {
- this.d.log.warn("No session found for cloud handoff", { taskId });
- return;
- }
-
- const runId = session.taskRunId;
- const auth = await this.getHandoffAuth();
- if (!auth) return;
-
- this.d.store.updateSession(runId, { handoffInProgress: true });
-
- try {
- const preflight = await this.d.trpc.handoff.preflightToCloud.query({
- taskId,
- runId,
- repoPath,
- });
- if (!preflight.canHandoff) {
- this.d.store.updateSession(runId, {
- handoffInProgress: false,
- });
- throw new Error(preflight.reason ?? "Cannot hand off to cloud");
- }
-
- this.unsubscribeFromChannel(runId);
- this.d.store.updateSession(runId, { status: "connecting" });
-
- const result = await this.d.trpc.handoff.executeToCloud.mutate({
- taskId,
- runId,
- repoPath,
- apiHost: auth.apiHost,
- teamId: auth.projectId,
- localGitState: preflight.localGitState,
- });
- if (!result.success) {
- if (result.code === GITHUB_AUTHORIZATION_REQUIRED_CODE) {
- throw new GitHubAuthorizationRequiredForCloudHandoffError(
- result.error,
- );
- }
- throw new Error(result.error ?? "Handoff to cloud failed");
- }
-
- this.d.store.updateSession(runId, {
- isCloud: true,
- cloudStatus: undefined,
- cloudStage: undefined,
- cloudOutput: undefined,
- cloudErrorMessage: undefined,
- cloudBranch: undefined,
- status: "disconnected",
- processedLineCount: result.logEntryCount ?? 0,
- });
-
- this.watchCloudTask(taskId, runId, auth.apiHost, auth.projectId);
- await Promise.all([
- this.d.queryClient.refetchQueries({ queryKey: ["tasks"] }),
- this.d.queryClient.refetchQueries({
- queryKey: this.d.WORKSPACE_QUERY_KEY,
- }),
- ]);
- this.d.store.updateSession(runId, { handoffInProgress: false });
- this.d.log.info("Local-to-cloud handoff complete", { taskId, runId });
- } catch (err) {
- this.d.log.error("Handoff to cloud failed", { taskId, err });
- if (err instanceof GitHubAuthorizationRequiredForCloudHandoffError) {
- await this.startGithubReauthForCloudHandoff(auth.projectId);
- } else {
- this.d.toast.error(
- err instanceof Error ? err.message : "Handoff to cloud failed",
- );
- }
- this.subscribeToChannel(runId);
- this.d.store.updateSession(runId, {
- handoffInProgress: false,
- status: "disconnected",
- });
- }
- }
-
- private async startGithubReauthForCloudHandoff(
- projectId: number,
- ): Promise<void> {
- const client = await this.d.getAuthenticatedClient();
- if (!client) {
- this.d.toast.error("Sign in before connecting GitHub.");
- return;
- }
-
- try {
- const { install_url: installUrl } =
- await client.startGithubUserIntegrationConnect(projectId);
- const url = installUrl?.trim();
- if (!url) {
- this.d.toast.error(
- "GitHub connection did not return a URL. Please try again.",
- );
- return;
- }
-
- await this.d.trpc.os.openExternal.mutate({ url });
- this.d.toast.info(
- "Connect GitHub to continue in cloud",
- "Complete the authorization in your browser, then click Continue again.",
- );
- } catch (error) {
- this.d.toast.error(
- error instanceof Error
- ? error.message
- : "Failed to start GitHub connection",
- );
- }
- }
-
- private async getHandoffAuth(): Promise<{
- apiHost: string;
- projectId: number;
- } | null> {
- let auth: Awaited<ReturnType<SessionServiceDeps["fetchAuthState"]>>;
- try {
- auth = await this.d.fetchAuthState();
- } catch (err) {
- const message = err instanceof Error ? err.message : "Unknown error";
- this.d.toast.error(`Authentication required for handoff: ${message}`);
- return null;
- }
- if (!auth.currentProjectId || !auth.cloudRegion) {
- this.d.toast.error("Missing project configuration for handoff");
- return null;
- }
- return {
- apiHost: getCloudUrlFromRegion(auth.cloudRegion),
- projectId: auth.currentProjectId,
- };
- }
-
- private async runHandoffPreflight(
- taskId: string,
- runId: string,
- repoPath: string,
- auth: { apiHost: string; projectId: number },
- ): Promise<Awaited<ReturnType<typeof this.d.trpc.handoff.preflight.query>>> {
- const preflight = await this.d.trpc.handoff.preflight.query({
- taskId,
- runId,
- repoPath,
- apiHost: auth.apiHost,
- teamId: auth.projectId,
- });
- if (!preflight.canHandoff) {
- this.d.store.updateSession(runId, {
- handoffInProgress: false,
- });
- throw new Error(preflight.reason ?? "Cannot hand off to local");
- }
- return preflight;
- }
-
- private async executeHandoff(
- taskId: string,
- runId: string,
- repoPath: string,
- repositoryPaths: Record<string, string> | undefined,
- auth: { apiHost: string; projectId: number },
- localGitState?: Awaited<
- ReturnType<typeof this.d.trpc.handoff.preflight.query>
- >["localGitState"],
- ): Promise<void> {
- const result = await this.d.trpc.handoff.execute.mutate({
- taskId,
- runId,
- repoPath,
- repositoryPaths,
- apiHost: auth.apiHost,
- teamId: auth.projectId,
- localGitState,
- });
- if (!result.success) {
- throw new Error(result.error ?? "Handoff failed");
- }
- }
-
- private transitionToLocalSession(runId: string): void {
- this.d.store.updateSession(runId, {
- isCloud: false,
- cloudStatus: undefined,
- cloudStage: undefined,
- cloudOutput: undefined,
- cloudErrorMessage: undefined,
- cloudBranch: undefined,
- status: "connected",
- });
- }
-
async retryCloudTaskWatch(taskId: string): Promise<void> {
const session = this.d.store.getSessionByTaskId(taskId);
if (!session?.isCloud) {
diff --git a/products/desktop/packages/core/src/sessions/sessionViewState.ts b/products/desktop/packages/core/src/sessions/sessionViewState.ts
index f5ddf4c9aebf..6fcff5d11c87 100644
--- a/products/desktop/packages/core/src/sessions/sessionViewState.ts
+++ b/products/desktop/packages/core/src/sessions/sessionViewState.ts
@@ -37,16 +37,9 @@ export function deriveSessionViewState(
const isCloudRunNotTerminal = effectiveIsCloud && !isCloudRunTerminal;
const hasError = session?.status === "error" && !session?.idleKilled;
- const handoffInProgress = session?.handoffInProgress ?? false;
-
- let isRunning = false;
- if (!handoffInProgress) {
- if (effectiveIsCloud) {
- isRunning = !hasError;
- } else {
- isRunning = session?.status === "connected";
- }
- }
+ const isRunning = effectiveIsCloud
+ ? !hasError
+ : session?.status === "connected";
const events = session?.events ?? [];
const isPromptPending = session?.isPromptPending ?? false;
diff --git a/products/desktop/packages/git/src/handoff.test.ts b/products/desktop/packages/git/src/handoff.test.ts
deleted file mode 100644
index 2ef43774aca9..000000000000
--- a/products/desktop/packages/git/src/handoff.test.ts
+++ /dev/null
@@ -1,522 +0,0 @@
-import { execFile } from "node:child_process";
-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import path from "node:path";
-import { promisify } from "node:util";
-import { describe, expect, it, vi } from "vitest";
-import { createGitClient } from "./client";
-import {
- type GitHandoffApplyInput,
- type GitHandoffCaptureResult,
- GitHandoffTracker,
- type HandoffLocalGitState,
-} from "./handoff";
-
-const execFileAsync = promisify(execFile);
-
-async function setupRepo(): Promise<string> {
- const dir = await mkdtemp(path.join(tmpdir(), "posthog-code-handoff-"));
- const git = createGitClient(dir);
- await git.init();
- await git.addConfig("user.name", "PostHog Code Test");
- await git.addConfig("user.email", "[email protected]");
- await git.addConfig("commit.gpgsign", "false");
-
- await writeFile(path.join(dir, "tracked.txt"), "base\n");
- await writeFile(path.join(dir, "unstaged.txt"), "base unstaged\n");
- await git.add(["tracked.txt", "unstaged.txt"]);
- await git.commit("initial");
-
- return dir;
-}
-
-async function cloneRepo(sourcePath: string): Promise<string> {
- const clonePath = await mkdtemp(
- path.join(tmpdir(), "posthog-code-handoff-clone-"),
- );
- await execFileAsync("git", ["clone", sourcePath, clonePath]);
- await execFileAsync("git", ["config", "user.email", "[email protected]"], {
- cwd: clonePath,
- });
- await execFileAsync("git", ["config", "user.name", "Test"], {
- cwd: clonePath,
- });
- await execFileAsync("git", ["config", "commit.gpgsign", "false"], {
- cwd: clonePath,
- });
- return clonePath;
-}
-
-interface RepoHarness {
- cloudRepo: string;
- localRepo: string;
- branch: string;
- cloudGit: ReturnType<typeof createGitClient>;
- localGit: ReturnType<typeof createGitClient>;
- localGitState: HandoffLocalGitState;
-}
-
-async function withRepos<T>(
- fn: (repos: RepoHarness) => Promise<T>,
-): Promise<T> {
- const cloudRepo = await setupRepo();
- const localRepo = await cloneRepo(cloudRepo);
- const cloudGit = createGitClient(cloudRepo);
- const localGit = createGitClient(localRepo);
- try {
- const branch = (await cloudGit.revparse(["--abbrev-ref", "HEAD"])).trim();
- const localHead = (await localGit.revparse(["HEAD"])).trim();
- const upstreamHead = (await localGit.revparse([`origin/${branch}`])).trim();
-
- return await fn({
- cloudRepo,
- localRepo,
- branch,
- cloudGit,
- localGit,
- localGitState: {
- head: localHead,
- branch,
- upstreamHead,
- upstreamRemote: "origin",
- upstreamMergeRef: `refs/heads/${branch}`,
- },
- });
- } finally {
- await rm(localRepo, { recursive: true, force: true });
- await rm(cloudRepo, { recursive: true, force: true });
- }
-}
-
-async function makeCloudChanges(
- cloudRepo: string,
- cloudGit: ReturnType<typeof createGitClient>,
-) {
- await writeFile(path.join(cloudRepo, "committed.txt"), "cloud commit\n");
- await cloudGit.add(["committed.txt"]);
- await cloudGit.commit("Cloud commit");
-
- await writeFile(path.join(cloudRepo, "tracked.txt"), "staged change\n");
- await cloudGit.add(["tracked.txt"]);
- await writeFile(path.join(cloudRepo, "unstaged.txt"), "unstaged change\n");
- await writeFile(path.join(cloudRepo, "untracked.txt"), "untracked\n");
-}
-
-async function cleanupCapture(capture: GitHandoffCaptureResult): Promise<void> {
- await rm(capture.artifactDirectory, { recursive: true, force: true }).catch(
- () => {},
- );
-}
-
-async function captureAndApply(
- repos: RepoHarness,
- options?: {
- captureState?: HandoffLocalGitState;
- applyState?: HandoffLocalGitState;
- onDivergedBranch?: GitHandoffApplyInput["onDivergedBranch"];
- },
-): Promise<GitHandoffCaptureResult> {
- const captureTracker = new GitHandoffTracker({
- repositoryPath: repos.cloudRepo,
- });
- const capture = await captureTracker.captureForHandoff(
- options?.captureState ?? repos.localGitState,
- );
-
- const applyTracker = new GitHandoffTracker({
- repositoryPath: repos.localRepo,
- });
-
- try {
- await applyTracker.applyFromHandoff({
- checkpoint: capture.checkpoint,
- headPackPath: capture.headPack?.path,
- indexPath: capture.indexFile.path,
- localGitState: options?.applyState ?? repos.localGitState,
- onDivergedBranch: options?.onDivergedBranch,
- });
- } catch (error) {
- await cleanupCapture(capture);
- throw error;
- }
-
- return capture;
-}
-
-describe("GitHandoffTracker", () => {
- it("stores capture artifacts beside the git object store", async () => {
- await withRepos(async (repos) => {
- await makeCloudChanges(repos.cloudRepo, repos.cloudGit);
-
- const captureTracker = new GitHandoffTracker({
- repositoryPath: repos.cloudRepo,
- });
- const capture = await captureTracker.captureForHandoff(
- repos.localGitState,
- );
- const gitCommonDir = (
- await repos.cloudGit.raw([
- "rev-parse",
- "--path-format=absolute",
- "--git-common-dir",
- ])
- ).trim();
-
- try {
- expect(path.dirname(capture.artifactDirectory)).toBe(gitCommonDir);
- expect(path.dirname(path.dirname(capture.indexFile.path))).toBe(
- gitCommonDir,
- );
- if (!capture.headPack) {
- throw new Error("Expected handoff capture to include a pack file");
- }
- expect(path.dirname(path.dirname(capture.headPack.path))).toBe(
- gitCommonDir,
- );
- } finally {
- await cleanupCapture(capture);
- }
- });
- }, 15000);
-
- it("captures and reapplies head, worktree, and index state from local files", async () => {
- await withRepos(async (repos) => {
- await makeCloudChanges(repos.cloudRepo, repos.cloudGit);
- const capture = await captureAndApply(repos);
-
- try {
- expect((await repos.localGit.revparse(["HEAD"])).trim()).toBe(
- capture.checkpoint.head,
- );
- expect(
- (await repos.localGit.revparse(["--abbrev-ref", "HEAD"])).trim(),
- ).toBe(repos.branch);
- expect(
- await readFile(path.join(repos.localRepo, "committed.txt"), "utf-8"),
- ).toBe("cloud commit\n");
- expect(
- await readFile(path.join(repos.localRepo, "tracked.txt"), "utf-8"),
- ).toBe("staged change\n");
- expect(
- await readFile(path.join(repos.localRepo, "unstaged.txt"), "utf-8"),
- ).toBe("unstaged change\n");
- expect(
- await readFile(path.join(repos.localRepo, "untracked.txt"), "utf-8"),
- ).toBe("untracked\n");
-
- const status = await repos.localGit.raw(["status", "--porcelain"]);
- expect(status).toContain("M tracked.txt");
- expect(status).toContain(" M unstaged.txt");
- expect(status).toContain("?? untracked.txt");
- } finally {
- await cleanupCapture(capture);
- }
- });
- }, 15000);
-
- it("keeps shipped index consistent with worktreeTree for staged large files", async () => {
- await withRepos(async (repos) => {
- const largePath = path.join(repos.cloudRepo, "tracked.txt");
- const modified = Buffer.alloc(1024 * 1024 + 1, 9);
- await writeFile(largePath, modified);
- await repos.cloudGit.add(["tracked.txt"]);
-
- const capture = await captureAndApply(repos);
-
- try {
- const restored = await readFile(
- path.join(repos.localRepo, "tracked.txt"),
- "utf-8",
- );
- expect(restored).toBe("base\n");
-
- const status = await repos.localGit.raw(["status", "--porcelain"]);
- expect(status).not.toMatch(/^M[ M] tracked\.txt/m);
- expect(status).not.toMatch(/^MM tracked\.txt/m);
- } finally {
- await cleanupCapture(capture);
- }
- });
- }, 20000);
-
- it("removes tracked files absent from the checkpoint worktree", async () => {
- await withRepos(async (repos) => {
- await rm(path.join(repos.cloudRepo, "tracked.txt"));
- await repos.cloudGit.raw(["rm", "--cached", "tracked.txt"]);
- await repos.cloudGit.commit("Remove tracked file");
-
- const capture = await captureAndApply(repos);
-
- try {
- await expect(
- readFile(path.join(repos.localRepo, "tracked.txt"), "utf-8"),
- ).rejects.toThrow();
-
- const status = await repos.localGit.raw(["status", "--porcelain"]);
- expect(status).not.toContain("tracked.txt");
- } finally {
- await cleanupCapture(capture);
- }
- });
- }, 15000);
-
- it("prompts before resetting a diverged local branch", async () => {
- await withRepos(async (repos) => {
- await writeFile(
- path.join(repos.localRepo, "local-only.txt"),
- "local commit\n",
- );
- await repos.localGit.add(["local-only.txt"]);
- await repos.localGit.commit("Local only");
- const localHead = (await repos.localGit.revparse(["HEAD"])).trim();
-
- await writeFile(
- path.join(repos.cloudRepo, "cloud-only.txt"),
- "cloud commit\n",
- );
- await repos.cloudGit.add(["cloud-only.txt"]);
- await repos.cloudGit.commit("Cloud only");
-
- const captureTracker = new GitHandoffTracker({
- repositoryPath: repos.cloudRepo,
- });
- const capture = await captureTracker.captureForHandoff({
- ...repos.localGitState,
- head: localHead,
- upstreamHead: null,
- });
-
- const confirm = vi.fn().mockResolvedValue(false);
- const applyTracker = new GitHandoffTracker({
- repositoryPath: repos.localRepo,
- });
-
- try {
- await expect(
- applyTracker.applyFromHandoff({
- checkpoint: capture.checkpoint,
- headPackPath: capture.headPack?.path,
- indexPath: capture.indexFile.path,
- localGitState: {
- ...repos.localGitState,
- head: localHead,
- upstreamHead: null,
- },
- onDivergedBranch: confirm,
- }),
- ).rejects.toThrow("Handoff aborted");
-
- expect(confirm).toHaveBeenCalledWith(
- expect.objectContaining({
- branch: repos.branch,
- cloudHead: capture.checkpoint.head,
- }),
- );
- expect(
- (
- await repos.localGit.revparse([`refs/heads/${repos.branch}`])
- ).trim(),
- ).not.toBe(capture.checkpoint.head);
- } finally {
- await cleanupCapture(capture);
- }
- });
- }, 15000);
-
- it("preserves existing local upstream config", async () => {
- await withRepos(async (repos) => {
- await repos.localGit.raw([
- "remote",
- "set-url",
- "origin",
- "[email protected]:local/repo.git",
- ]);
- await repos.localGit.raw([
- "config",
- `branch.${repos.branch}.remote`,
- "origin",
- ]);
- await repos.localGit.raw([
- "config",
- `branch.${repos.branch}.merge`,
- `refs/heads/${repos.branch}`,
- ]);
-
- await repos.cloudGit.addRemote(
- "cloud-origin",
- "https://example.com/cloud.git",
- );
- await repos.cloudGit.raw([
- "config",
- `branch.${repos.branch}.remote`,
- "cloud-origin",
- ]);
- await repos.cloudGit.raw([
- "config",
- `branch.${repos.branch}.merge`,
- `refs/heads/${repos.branch}`,
- ]);
-
- await writeFile(
- path.join(repos.cloudRepo, "cloud-only.txt"),
- "cloud commit\n",
- );
- await repos.cloudGit.add(["cloud-only.txt"]);
- await repos.cloudGit.commit("Cloud only");
-
- const capture = await captureAndApply(repos, {
- captureState: {
- ...repos.localGitState,
- upstreamHead: null,
- },
- });
-
- try {
- expect(
- (
- await repos.localGit.raw([
- "config",
- "--get",
- `branch.${repos.branch}.remote`,
- ])
- ).trim(),
- ).toBe("origin");
- expect(
- (await repos.localGit.raw(["remote", "get-url", "origin"])).trim(),
- ).toBe("[email protected]:local/repo.git");
- } finally {
- await cleanupCapture(capture);
- }
- });
- }, 15000);
-
- it("adopts cloud upstream when the local branch has none", async () => {
- await withRepos(async (repos) => {
- await repos.localGit
- .raw(["config", "--unset-all", `branch.${repos.branch}.remote`])
- .catch(() => {});
- await repos.localGit
- .raw(["config", "--unset-all", `branch.${repos.branch}.merge`])
- .catch(() => {});
- await repos.localGit.removeRemote("origin");
-
- await repos.cloudGit.addRemote(
- "cloud-origin",
- "https://example.com/cloud.git",
- );
- await repos.cloudGit.raw([
- "config",
- `branch.${repos.branch}.remote`,
- "cloud-origin",
- ]);
- await repos.cloudGit.raw([
- "config",
- `branch.${repos.branch}.merge`,
- `refs/heads/${repos.branch}`,
- ]);
-
- await writeFile(
- path.join(repos.cloudRepo, "cloud-only.txt"),
- "cloud commit\n",
- );
- await repos.cloudGit.add(["cloud-only.txt"]);
- await repos.cloudGit.commit("Cloud only");
-
- const capture = await captureAndApply(repos, {
- captureState: {
- ...repos.localGitState,
- upstreamHead: null,
- upstreamRemote: null,
- upstreamMergeRef: null,
- },
- applyState: {
- ...repos.localGitState,
- upstreamRemote: null,
- upstreamMergeRef: null,
- },
- });
-
- try {
- expect(
- (
- await repos.localGit.raw([
- "config",
- "--get",
- `branch.${repos.branch}.remote`,
- ])
- ).trim(),
- ).toBe("cloud-origin");
- expect(
- (
- await repos.localGit.raw(["remote", "get-url", "cloud-origin"])
- ).trim(),
- ).toBe("https://example.com/cloud.git");
- } finally {
- await cleanupCapture(capture);
- }
- });
- }, 15000);
-
- it.each([
- ["the branch's upstream tracking ref", false],
- ["the remote default branch when the branch has no upstream", true],
- ])(
- "packs against %s when no local git state is provided",
- async (_label, useBranchWithoutUpstream) => {
- const originRepo = await setupRepo();
- const sandboxRepo = await cloneRepo(originRepo);
- try {
- const sandboxGit = createGitClient(sandboxRepo);
- const branch = (
- await sandboxGit.revparse(["--abbrev-ref", "HEAD"])
- ).trim();
- const baseCommit = (
- await sandboxGit.revparse([`origin/${branch}`])
- ).trim();
- const baseBlob = (
- await sandboxGit.revparse([`origin/${branch}:tracked.txt`])
- ).trim();
-
- if (useBranchWithoutUpstream) {
- await sandboxGit.checkout(["-b", "session-branch"]);
- }
-
- await writeFile(
- path.join(sandboxRepo, "committed.txt"),
- "session commit\n",
- );
- await sandboxGit.add(["committed.txt"]);
- await sandboxGit.commit("Session commit");
- const sessionCommit = (await sandboxGit.revparse(["HEAD"])).trim();
-
- const tracker = new GitHandoffTracker({ repositoryPath: sandboxRepo });
- const capture = await tracker.captureForHandoff();
-
- try {
- expect(capture.headPack).toBeDefined();
- const packPath = capture.headPack?.path as string;
- await execFileAsync("git", ["index-pack", packPath], {
- cwd: sandboxRepo,
- });
- const idxPath = packPath.replace(/\.pack$/, ".idx");
- const { stdout } = await execFileAsync(
- "git",
- ["verify-pack", "-v", idxPath],
- { cwd: sandboxRepo },
- );
- await rm(idxPath, { force: true });
-
- expect(stdout).toContain(sessionCommit);
- expect(stdout).not.toContain(baseCommit);
- expect(stdout).not.toContain(baseBlob);
- } finally {
- await cleanupCapture(capture);
- }
- } finally {
- await rm(sandboxRepo, { recursive: true, force: true });
- await rm(originRepo, { recursive: true, force: true });
- }
- },
- 15000,
- );
-});
diff --git a/products/desktop/packages/git/src/handoff.ts b/products/desktop/packages/git/src/handoff.ts
deleted file mode 100644
index be706e297f2f..000000000000
--- a/products/desktop/packages/git/src/handoff.ts
+++ /dev/null
@@ -1,862 +0,0 @@
-import { spawn } from "node:child_process";
-import { copyFile, mkdtemp, readFile, rm, stat } from "node:fs/promises";
-import path from "node:path";
-import type {
- GitHandoffCheckpoint,
- HandoffLocalGitState,
- SagaLogger,
-} from "@posthog/shared";
-import { createGitClient, type GitClient } from "./client";
-import { CaptureCheckpointSaga, deleteCheckpoint } from "./sagas/checkpoint";
-
-export type {
- GitHandoffCheckpoint,
- HandoffLocalGitState,
-} from "@posthog/shared";
-
-const HANDOFF_HEAD_REF_PREFIX = "refs/posthog-code-handoff/head/";
-const CHECKPOINT_REF_PREFIX = "refs/posthog-code-checkpoint/";
-const MAX_HANDOFF_FILE_BYTES = 1024 * 1024;
-
-export interface GitHandoffArtifactFile {
- path: string;
- rawBytes: number;
-}
-
-export interface GitHandoffCaptureResult {
- checkpoint: GitHandoffCheckpoint;
- artifactDirectory: string;
- headPack?: GitHandoffArtifactFile;
- indexFile: GitHandoffArtifactFile;
- totalBytes: number;
-}
-
-export interface GitHandoffApplyInput {
- checkpoint: GitHandoffCheckpoint;
- headPackPath?: string;
- indexPath?: string;
- localGitState?: HandoffLocalGitState;
- onDivergedBranch?: (
- divergence: GitHandoffBranchDivergence,
- ) => Promise<boolean>;
-}
-
-export interface GitHandoffApplyResult {
- packBytes: number;
- indexBytes: number;
- totalBytes: number;
-}
-
-export interface GitHandoffBranchDivergence {
- branch: string;
- localHead: string;
- cloudHead: string;
-}
-
-export interface GitHandoffTrackerConfig {
- repositoryPath: string;
- logger?: SagaLogger;
-}
-
-interface GitTrackingMetadata {
- upstreamRemote: string | null;
- upstreamMergeRef: string | null;
- remoteUrl: string | null;
-}
-
-type GitBranchRestoreStatus =
- | { kind: "missing" }
- | { kind: "match" }
- | { kind: "fast_forward" }
- | { kind: "diverged"; divergence: GitHandoffBranchDivergence };
-
-export class GitHandoffTracker {
- private repositoryPath: string;
- private logger?: SagaLogger;
-
- constructor(config: GitHandoffTrackerConfig) {
- this.repositoryPath = config.repositoryPath;
- this.logger = config.logger;
- }
-
- async captureForHandoff(
- localGitState?: HandoffLocalGitState,
- ): Promise<GitHandoffCaptureResult> {
- const captureSaga = new CaptureCheckpointSaga(this.logger);
- const result = await captureSaga.run({ baseDir: this.repositoryPath });
- if (!result.success) {
- throw new Error(
- `Failed to capture checkpoint at step '${result.failedStep}': ${result.error}`,
- );
- }
-
- const checkpoint = result.data;
- const git = createGitClient(this.repositoryPath);
- const tempDir = await this.createTempDir(git, checkpoint.checkpointId);
- const checkpointRef = `${CHECKPOINT_REF_PREFIX}${checkpoint.checkpointId}`;
-
- try {
- const reconciledIndex = await this.reconcileHandoffIndex(
- git,
- checkpoint.head,
- checkpoint.indexTree,
- tempDir,
- checkpoint.checkpointId,
- );
-
- const tracking = await getTrackingMetadata(git, checkpoint.branch);
- const baselineRefs = localGitState?.upstreamHead
- ? [localGitState.upstreamHead]
- : await this.resolveDefaultPackBaseline(git, tracking);
- const packRefs = [
- checkpoint.head,
- reconciledIndex.indexTree,
- checkpoint.worktreeTree,
- ...baselineRefs.map((ref) => `^${ref}`),
- ].filter((ref): ref is string => !!ref);
- const headRef = checkpoint.head
- ? `${HANDOFF_HEAD_REF_PREFIX}${checkpoint.checkpointId}`
- : undefined;
- const packPrefix = path.join(tempDir, checkpoint.checkpointId);
-
- const [headPack, indexFile] = await Promise.all([
- this.captureObjectPack(packPrefix, packRefs),
- this.statFileArtifact(reconciledIndex.indexFilePath),
- ]);
-
- return {
- checkpoint: {
- checkpointId: checkpoint.checkpointId,
- commit: checkpoint.commit,
- checkpointRef,
- headRef,
- head: checkpoint.head,
- branch: checkpoint.branch,
- indexTree: reconciledIndex.indexTree,
- worktreeTree: checkpoint.worktreeTree,
- timestamp: checkpoint.timestamp,
- upstreamRemote: tracking.upstreamRemote,
- upstreamMergeRef: tracking.upstreamMergeRef,
- remoteUrl: tracking.remoteUrl,
- },
- artifactDirectory: tempDir,
- headPack,
- indexFile,
- totalBytes: (headPack?.rawBytes ?? 0) + indexFile.rawBytes,
- };
- } catch (error) {
- await rm(tempDir, { recursive: true, force: true }).catch(() => {});
- throw error;
- } finally {
- await deleteCheckpoint(git, checkpoint.checkpointId).catch(() => {});
- }
- }
-
- async applyFromHandoff(
- input: GitHandoffApplyInput,
- ): Promise<GitHandoffApplyResult> {
- const {
- checkpoint,
- headPackPath,
- indexPath,
- localGitState,
- onDivergedBranch,
- } = input;
- const git = createGitClient(this.repositoryPath);
-
- if (headPackPath) {
- await this.ensureBaselineForApply(git, checkpoint, localGitState);
- await this.unpackPackFile(headPackPath);
- }
-
- if (checkpoint.branch && checkpoint.head) {
- const branchStatus = await this.resolveBranchRestoreStatus(
- git,
- checkpoint.branch,
- checkpoint.head,
- localGitState,
- );
- const tracking = this.getPreferredTracking(localGitState, checkpoint);
-
- if (
- branchStatus.kind === "diverged" &&
- !(await onDivergedBranch?.(branchStatus.divergence))
- ) {
- throw new Error(
- `Handoff aborted: local branch '${checkpoint.branch}' has diverged`,
- );
- }
-
- await this.checkoutBranchAtHead(git, checkpoint.branch, checkpoint.head);
-
- if (this.shouldRestoreTracking(branchStatus, localGitState, tracking)) {
- await this.ensureRemoteForTracking(git, tracking);
- await this.configureUpstream(git, checkpoint.branch, tracking);
- }
- } else if (checkpoint.head) {
- await git.checkout(checkpoint.head);
- }
-
- await git.clean(["f", "d"]);
- await git.raw(["read-tree", "--reset", "-u", checkpoint.worktreeTree]);
-
- if (indexPath) {
- await this.restoreIndexFile(git, indexPath);
- }
-
- const packBytes = headPackPath ? await this.getFileSize(headPackPath) : 0;
- const indexBytes = indexPath ? await this.getFileSize(indexPath) : 0;
-
- return {
- packBytes,
- indexBytes,
- totalBytes: packBytes + indexBytes,
- };
- }
-
- /**
- * Without local handoff state the pack baseline must stay limited to
- * objects the apply side is able to restore: the branch's upstream
- * tracking ref (which ensureBaselineForApply fetches before unpacking),
- * or failing that the remote's default branch, which any fresh clone of
- * the repository already contains. Excluding broader refs (e.g. every
- * remote-tracking ref) risks producing a pack that omits objects the
- * resume repository cannot fetch. Without any baseline, a capture with no
- * local handoff state packs the entire repo snapshot, which for large
- * repos exceeds artifact upload limits.
- */
- private async resolveDefaultPackBaseline(
- git: GitClient,
- tracking: GitTrackingMetadata,
- ): Promise<string[]> {
- if (tracking.upstreamRemote && tracking.upstreamMergeRef) {
- const branchName = tracking.upstreamMergeRef.replace(
- /^refs\/heads\//,
- "",
- );
- const upstreamHead = await this.revparseOrNull(
- git,
- `refs/remotes/${tracking.upstreamRemote}/${branchName}`,
- );
- if (upstreamHead) {
- return [upstreamHead];
- }
- }
-
- const defaultHead = await this.revparseOrNull(
- git,
- "refs/remotes/origin/HEAD",
- );
- return defaultHead ? [defaultHead] : [];
- }
-
- private async revparseOrNull(
- git: GitClient,
- ref: string,
- ): Promise<string | null> {
- const value = await git.revparse([ref]).catch(() => null);
- return value ? value.trim() : null;
- }
-
- private async captureObjectPack(
- packPrefix: string,
- refs: string[],
- ): Promise<GitHandoffArtifactFile> {
- const hash = await this.runGitWithInput(
- ["pack-objects", packPrefix, "--revs"],
- `${refs.join("\n")}\n`,
- );
- const packPath = `${packPrefix}-${hash.trim()}.pack`;
- const rawBytes = await this.getFileSize(packPath);
- await rm(`${packPath}.idx`, { force: true }).catch(() => {});
- return { path: packPath, rawBytes };
- }
-
- private async reconcileHandoffIndex(
- git: GitClient,
- head: string | null,
- indexTree: string,
- tempDir: string,
- checkpointId: string,
- ): Promise<{ indexTree: string; indexFilePath: string }> {
- const realIndexPath = await this.getGitPath(git, "index");
- const tempIndexPath = path.join(tempDir, `${checkpointId}.index`);
- await copyFile(realIndexPath, tempIndexPath);
-
- const largePaths = await this.listLargeBlobsInTree(
- indexTree,
- MAX_HANDOFF_FILE_BYTES,
- );
- if (largePaths.length === 0) {
- return { indexTree, indexFilePath: tempIndexPath };
- }
-
- const headBlobs = head
- ? await this.readHeadBlobsForPaths(head, largePaths)
- : new Map<string, { mode: string; hash: string }>();
-
- const env = { ...process.env, GIT_INDEX_FILE: tempIndexPath };
- for (const filePath of largePaths) {
- const headBlob = headBlobs.get(filePath);
- if (headBlob) {
- await this.runGitWithEnv(env, [
- "update-index",
- "--cacheinfo",
- `${headBlob.mode},${headBlob.hash},${filePath}`,
- ]);
- } else {
- await this.runGitWithEnv(env, [
- "update-index",
- "--force-remove",
- filePath,
- ]).catch(() => {});
- }
- }
-
- const reconciledTree = (
- await this.runGitWithEnv(env, ["write-tree"])
- ).trim();
- return { indexTree: reconciledTree, indexFilePath: tempIndexPath };
- }
-
- private async listLargeBlobsInTree(
- tree: string,
- maxBytes: number,
- ): Promise<string[]> {
- const { stdout } = await this.runGitProcess(
- ["ls-tree", "-r", "-l", tree],
- "",
- );
- const result: string[] = [];
- for (const line of stdout.split("\n")) {
- if (!line) continue;
- const tabIndex = line.indexOf("\t");
- if (tabIndex < 0) continue;
- const meta = line.slice(0, tabIndex);
- const filePath = line.slice(tabIndex + 1);
- const parts = meta.split(/\s+/);
- if (parts.length < 4) continue;
- const [, type, , sizeStr] = parts;
- if (type !== "blob") continue;
- if (sizeStr === "-") continue;
- const size = Number.parseInt(sizeStr, 10);
- if (Number.isFinite(size) && size > maxBytes) {
- result.push(filePath);
- }
- }
- return result;
- }
-
- private async readHeadBlobsForPaths(
- head: string,
- paths: string[],
- ): Promise<Map<string, { mode: string; hash: string }>> {
- const result = new Map<string, { mode: string; hash: string }>();
- const CHUNK_SIZE = 100;
- for (let i = 0; i < paths.length; i += CHUNK_SIZE) {
- const chunk = paths.slice(i, i + CHUNK_SIZE);
- const { stdout } = await this.runGitProcess(
- ["ls-tree", "-r", head, "--", ...chunk],
- "",
- ).catch(() => ({ stdout: "", stderr: "" }));
- for (const line of stdout.split("\n")) {
- if (!line) continue;
- const tabIndex = line.indexOf("\t");
- if (tabIndex < 0) continue;
- const meta = line.slice(0, tabIndex);
- const filePath = line.slice(tabIndex + 1);
- const parts = meta.split(/\s+/);
- if (parts.length < 3) continue;
- const [mode, type, hash] = parts;
- if (type !== "blob") continue;
- result.set(filePath, { mode, hash });
- }
- }
- return result;
- }
-
- private async statFileArtifact(
- filePath: string,
- ): Promise<GitHandoffArtifactFile> {
- return { path: filePath, rawBytes: await this.getFileSize(filePath) };
- }
-
- private async restoreIndexFile(
- git: GitClient,
- indexPath: string,
- ): Promise<void> {
- const gitIndexPath = await this.getGitPath(git, "index");
- await copyFile(indexPath, gitIndexPath);
- }
-
- private async unpackPackFile(packPath: string): Promise<void> {
- const content = await readFile(packPath);
- await this.runGitWithBuffer(["unpack-objects", "-r"], content);
- }
-
- private getPreferredTracking(
- localGitState: HandoffLocalGitState | undefined,
- checkpoint: GitHandoffCheckpoint,
- ): GitTrackingMetadata {
- const state = localGitState;
- if (state && hasTrackingConfig(state)) {
- return {
- upstreamRemote: state.upstreamRemote ?? null,
- upstreamMergeRef: state.upstreamMergeRef ?? null,
- remoteUrl:
- state.upstreamRemote &&
- state.upstreamRemote === checkpoint.upstreamRemote
- ? checkpoint.remoteUrl
- : null,
- };
- }
-
- return {
- upstreamRemote: checkpoint.upstreamRemote,
- upstreamMergeRef: checkpoint.upstreamMergeRef,
- remoteUrl: checkpoint.remoteUrl,
- };
- }
-
- private shouldRestoreTracking(
- branchStatus: GitBranchRestoreStatus,
- localGitState: HandoffLocalGitState | undefined,
- tracking: GitTrackingMetadata,
- ): boolean {
- return (
- branchStatus.kind === "missing" ||
- (!hasTrackingConfig(localGitState) &&
- (tracking.upstreamRemote !== null ||
- tracking.upstreamMergeRef !== null))
- );
- }
-
- private async ensureBaselineForApply(
- git: GitClient,
- checkpoint: GitHandoffCheckpoint,
- localGitState: HandoffLocalGitState | undefined,
- ): Promise<void> {
- const tracking = this.getPreferredTracking(localGitState, checkpoint);
- if (!tracking.upstreamRemote || !tracking.upstreamMergeRef) return;
-
- await this.ensureRemoteForTracking(git, tracking).catch(() => {});
- await git
- .raw(["fetch", tracking.upstreamRemote, tracking.upstreamMergeRef])
- .catch((err) => {
- this.logger?.error(
- "Handoff baseline fetch failed; if the pack excludes commits the receiver does not already have, the subsequent unpack/read-tree will fail with an object-missing error",
- {
- err: String(err),
- remote: tracking.upstreamRemote,
- ref: tracking.upstreamMergeRef,
- },
- );
- });
- }
-
- private async ensureRemoteForTracking(
- git: GitClient,
- tracking: GitTrackingMetadata,
- ): Promise<void> {
- if (!tracking.upstreamRemote || !tracking.remoteUrl) return;
-
- const remotes = await git.getRemotes(true);
- const existing = remotes.find(
- (remote) => remote.name === tracking.upstreamRemote,
- );
-
- if (!existing) {
- await git.addRemote(tracking.upstreamRemote, tracking.remoteUrl);
- }
- }
-
- private async configureUpstream(
- git: GitClient,
- branch: string,
- tracking: GitTrackingMetadata,
- ): Promise<void> {
- if (tracking.upstreamRemote) {
- await git.raw([
- "config",
- `branch.${branch}.remote`,
- tracking.upstreamRemote,
- ]);
- }
-
- if (tracking.upstreamMergeRef) {
- await git.raw([
- "config",
- `branch.${branch}.merge`,
- tracking.upstreamMergeRef,
- ]);
- }
- }
-
- private async resolveBranchRestoreStatus(
- git: GitClient,
- branch: string,
- cloudHead: string,
- localGitState?: HandoffLocalGitState,
- ): Promise<GitBranchRestoreStatus> {
- const branchRef = `refs/heads/${branch}`;
- const branchExists = await this.refExists(git, branchRef);
- if (!branchExists) {
- return { kind: "missing" };
- }
-
- const currentBranchHead = (await git.revparse([branchRef])).trim();
- const candidateHeads = [
- currentBranchHead,
- ...(localGitState?.branch === branch && localGitState.head
- ? [localGitState.head]
- : []),
- ].filter((value, index, array) => array.indexOf(value) === index);
-
- if (candidateHeads.every((head) => head === cloudHead)) {
- return { kind: "match" };
- }
-
- const nonAncestorHead = await this.findNonAncestorHead(
- git,
- candidateHeads,
- cloudHead,
- );
- if (!nonAncestorHead) {
- return { kind: "fast_forward" };
- }
-
- return {
- kind: "diverged",
- divergence: {
- branch,
- localHead: nonAncestorHead,
- cloudHead,
- },
- };
- }
-
- private async findNonAncestorHead(
- _git: GitClient,
- heads: string[],
- cloudHead: string,
- ): Promise<string | null> {
- for (const head of heads) {
- if (head === cloudHead) {
- continue;
- }
- if (!(await this.isAncestor(head, cloudHead))) {
- return head;
- }
- }
- return null;
- }
-
- private async checkoutBranchAtHead(
- git: GitClient,
- branch: string,
- head: string,
- ): Promise<void> {
- const currentBranch = await getCurrentBranchName(git);
- if (currentBranch === branch) {
- await git.reset(["--hard", head]);
- return;
- }
-
- const branchRef = `refs/heads/${branch}`;
- if (await this.refExists(git, branchRef)) {
- await git.branch(["-f", branch, head]);
- await git.checkout(branch);
- return;
- }
-
- await git.checkout(["-b", branch, head]);
- }
-
- private async refExists(git: GitClient, ref: string): Promise<boolean> {
- try {
- await git.revparse(["--verify", ref]);
- return true;
- } catch {
- return false;
- }
- }
-
- private async isAncestor(
- ancestor: string,
- descendant: string,
- ): Promise<boolean> {
- const exitCode = await this.runGitProcessAllowingFailure([
- "merge-base",
- "--is-ancestor",
- ancestor,
- descendant,
- ]);
- return exitCode === 0;
- }
-
- private async createTempDir(
- git: GitClient,
- checkpointId: string,
- ): Promise<string> {
- // Git stages packs in the object store, so the destination must share its filesystem.
- const gitCommonDir = await this.resolveGitCommonDir(git);
- return mkdtemp(
- path.join(gitCommonDir, `posthog-code-handoff-${checkpointId}-`),
- );
- }
-
- private async resolveGitCommonDir(git: GitClient): Promise<string> {
- const raw = await git.raw([
- "rev-parse",
- "--path-format=absolute",
- "--git-common-dir",
- ]);
- const resolved = raw.trim() || ".git";
- return path.isAbsolute(resolved)
- ? resolved
- : path.resolve(this.repositoryPath, resolved);
- }
-
- private async getGitPath(git: GitClient, gitPath: string): Promise<string> {
- const raw = await git.raw(["rev-parse", "--git-path", gitPath]);
- const resolved = raw.trim();
- return path.isAbsolute(resolved)
- ? resolved
- : path.resolve(this.repositoryPath, resolved);
- }
-
- private async getFileSize(filePath: string): Promise<number> {
- return (await stat(filePath)).size;
- }
-
- private async runGitWithInput(
- args: string[],
- input: string,
- ): Promise<string> {
- const { stdout } = await this.runGitProcess(args, input);
- return stdout;
- }
-
- private async runGitWithBuffer(args: string[], input: Buffer): Promise<void> {
- await this.runGitProcess(args, input);
- }
-
- private async runGitProcessAllowingFailure(args: string[]): Promise<number> {
- return new Promise((resolve, reject) => {
- const child = spawn("git", args, {
- cwd: this.repositoryPath,
- stdio: ["ignore", "ignore", "pipe"],
- });
-
- let stderr = "";
- child.stderr.on("data", (chunk: Buffer | string) => {
- stderr += chunk.toString();
- });
- child.on("error", reject);
- child.on("close", (code) => {
- if (code === null) {
- reject(new Error(`git ${args.join(" ")} exited unexpectedly`));
- return;
- }
- if (code > 1) {
- reject(
- new Error(
- stderr || `git ${args.join(" ")} failed with code ${code}`,
- ),
- );
- return;
- }
- resolve(code);
- });
- });
- }
-
- private async runGitWithEnv(
- env: NodeJS.ProcessEnv,
- args: string[],
- ): Promise<string> {
- return new Promise((resolve, reject) => {
- const child = spawn("git", args, {
- cwd: this.repositoryPath,
- stdio: ["ignore", "pipe", "pipe"],
- env,
- });
- let stdout = "";
- let stderr = "";
- child.stdout.on("data", (chunk: Buffer | string) => {
- stdout += chunk.toString();
- });
- child.stderr.on("data", (chunk: Buffer | string) => {
- stderr += chunk.toString();
- });
- child.on("error", reject);
- child.on("close", (code) => {
- if (code === 0) {
- resolve(stdout);
- return;
- }
- reject(
- new Error(stderr || `git ${args.join(" ")} failed with code ${code}`),
- );
- });
- });
- }
-
- private runGitProcess(
- args: string[],
- input: string | Buffer,
- ): Promise<{ stdout: string; stderr: string }> {
- return new Promise((resolve, reject) => {
- const child = spawn("git", args, {
- cwd: this.repositoryPath,
- stdio: "pipe",
- });
-
- let stdout = "";
- let stderr = "";
-
- child.stdout.on("data", (chunk: Buffer | string) => {
- stdout += chunk.toString();
- });
- child.stderr.on("data", (chunk: Buffer | string) => {
- stderr += chunk.toString();
- });
- child.on("error", reject);
- child.on("close", (code) => {
- if (code === 0) {
- resolve({ stdout, stderr });
- return;
- }
- reject(
- new Error(stderr || `git ${args.join(" ")} failed with code ${code}`),
- );
- });
-
- child.stdin.on("error", () => {});
- child.stdin.end(input);
- });
- }
-}
-
-export async function readHandoffLocalGitState(
- repositoryPath: string,
-): Promise<HandoffLocalGitState> {
- const git = createGitClient(repositoryPath);
- const head = await readCurrentHead(git);
- const branch = await getCurrentBranchName(git);
- const tracking = await getTrackingMetadata(git, branch);
-
- if (tracking.upstreamRemote && tracking.upstreamMergeRef) {
- await git
- .raw(["fetch", tracking.upstreamRemote, tracking.upstreamMergeRef])
- .catch(() => {});
- }
-
- const upstreamHead =
- tracking.upstreamRemote && tracking.upstreamMergeRef
- ? await resolveUpstreamHead(
- git,
- tracking.upstreamRemote,
- tracking.upstreamMergeRef,
- )
- : null;
-
- return {
- head,
- branch,
- upstreamHead,
- upstreamRemote: tracking.upstreamRemote,
- upstreamMergeRef: tracking.upstreamMergeRef,
- };
-}
-
-async function readCurrentHead(git: GitClient): Promise<string | null> {
- try {
- return (await git.revparse(["HEAD"])).trim() || null;
- } catch {
- return null;
- }
-}
-
-async function getCurrentBranchName(git: GitClient): Promise<string | null> {
- try {
- const raw = await git.revparse(["--abbrev-ref", "HEAD"]);
- const branch = raw.trim();
- return branch === "HEAD" ? null : branch;
- } catch {
- return null;
- }
-}
-
-async function getTrackingMetadata(
- git: GitClient,
- branch: string | null,
-): Promise<GitTrackingMetadata> {
- if (!branch) {
- return {
- upstreamRemote: null,
- upstreamMergeRef: null,
- remoteUrl: null,
- };
- }
-
- const upstreamRemote = await getGitConfigValue(
- git,
- `branch.${branch}.remote`,
- );
- const upstreamMergeRef = await getGitConfigValue(
- git,
- `branch.${branch}.merge`,
- );
- const remoteUrl = upstreamRemote
- ? await getRemoteUrl(git, upstreamRemote)
- : null;
-
- return { upstreamRemote, upstreamMergeRef, remoteUrl };
-}
-
-async function getGitConfigValue(
- git: GitClient,
- key: string,
-): Promise<string | null> {
- try {
- const value = await git.raw(["config", "--get", key]);
- return value.trim() || null;
- } catch {
- return null;
- }
-}
-
-async function getRemoteUrl(
- git: GitClient,
- remote: string,
-): Promise<string | null> {
- try {
- const value = await git.remote(["get-url", remote]);
- return typeof value === "string" ? value.trim() || null : null;
- } catch {
- return null;
- }
-}
-
-async function resolveUpstreamHead(
- git: GitClient,
- upstreamRemote: string,
- upstreamMergeRef: string,
-): Promise<string | null> {
- const upstreamBranch = upstreamMergeRef.replace("refs/heads/", "");
- try {
- return (
- (await git.revparse([`${upstreamRemote}/${upstreamBranch}`])).trim() ||
- null
- );
- } catch {
- return null;
- }
-}
-
-function hasTrackingConfig(
- localGitState: HandoffLocalGitState | undefined,
-): boolean {
- return !!(localGitState?.upstreamRemote || localGitState?.upstreamMergeRef);
-}
diff --git a/products/desktop/packages/host-router/src/router.ts b/products/desktop/packages/host-router/src/router.ts
index b3a828558103..7df718e58ee9 100644
--- a/products/desktop/packages/host-router/src/router.ts
+++ b/products/desktop/packages/host-router/src/router.ts
@@ -23,7 +23,6 @@ import { foldersRouter } from "./routers/folders.router";
import { fsRouter } from "./routers/fs.router";
import { gitRouter } from "./routers/git.router";
import { githubIntegrationRouter } from "./routers/github-integration.router";
-import { handoffRouter } from "./routers/handoff.router";
import { integrationRouter } from "./routers/integration.router";
import { linearIntegrationRouter } from "./routers/linear-integration.router";
import { llmGatewayRouter } from "./routers/llm-gateway.router";
@@ -75,7 +74,6 @@ export const hostRouter = router({
folders: foldersRouter,
fs: fsRouter,
git: gitRouter,
- handoff: handoffRouter,
integration: integrationRouter,
githubIntegration: githubIntegrationRouter,
releaseFeed: releaseFeedRouter,
diff --git a/products/desktop/packages/host-router/src/routers/handoff.router.ts b/products/desktop/packages/host-router/src/routers/handoff.router.ts
deleted file mode 100644
index 61e7715eef1f..000000000000
--- a/products/desktop/packages/host-router/src/routers/handoff.router.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import type { HandoffService } from "@posthog/core/handoff/handoff";
-import { HANDOFF_SERVICE } from "@posthog/core/handoff/identifiers";
-import {
- HandoffEvent,
- handoffExecuteInput,
- handoffExecuteResult,
- handoffPreflightInput,
- handoffPreflightResult,
- handoffToCloudExecuteInput,
- handoffToCloudExecuteResult,
- handoffToCloudPreflightInput,
- handoffToCloudPreflightResult,
-} from "@posthog/core/handoff/schemas";
-import type { ServiceResolver } from "@posthog/host-trpc/context";
-import { publicProcedure, router } from "@posthog/host-trpc/trpc";
-import { z } from "zod";
-
-const getService = (container: ServiceResolver) =>
- container.get<HandoffService>(HANDOFF_SERVICE);
-
-export const handoffRouter = router({
- preflight: publicProcedure
- .input(handoffPreflightInput)
- .output(handoffPreflightResult)
- .query(({ ctx, input }) => getService(ctx.container).preflight(input)),
-
- execute: publicProcedure
- .input(handoffExecuteInput)
- .output(handoffExecuteResult)
- .mutation(({ ctx, input }) => getService(ctx.container).execute(input)),
-
- preflightToCloud: publicProcedure
- .input(handoffToCloudPreflightInput)
- .output(handoffToCloudPreflightResult)
- .query(({ ctx, input }) =>
- getService(ctx.container).preflightToCloud(input),
- ),
-
- executeToCloud: publicProcedure
- .input(handoffToCloudExecuteInput)
- .output(handoffToCloudExecuteResult)
- .mutation(({ ctx, input }) =>
- getService(ctx.container).executeToCloud(input),
- ),
-
- onProgress: publicProcedure
- .input(z.object({ taskId: z.string() }))
- .subscription(async function* (opts) {
- const service = getService(opts.ctx.container);
- for await (const data of service.toIterable(HandoffEvent.Progress, {
- signal: opts.signal,
- })) {
- if (data.taskId === opts.input.taskId) {
- yield data;
- }
- }
- }),
-});
diff --git a/products/desktop/packages/shared/src/git-handoff.ts b/products/desktop/packages/shared/src/git-handoff.ts
deleted file mode 100644
index 8ce195fa43ad..000000000000
--- a/products/desktop/packages/shared/src/git-handoff.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-export interface HandoffLocalGitState {
- head: string | null;
- branch: string | null;
- upstreamHead: string | null;
- upstreamRemote: string | null;
- upstreamMergeRef: string | null;
-}
-
-export interface GitHandoffCheckpoint {
- repository?: string;
- checkpointId: string;
- commit: string;
- checkpointRef: string;
- headRef?: string;
- head: string | null;
- branch: string | null;
- indexTree: string;
- worktreeTree: string;
- timestamp: string;
- upstreamRemote: string | null;
- upstreamMergeRef: string | null;
- remoteUrl: string | null;
-}
diff --git a/products/desktop/packages/shared/src/handoff-host.ts b/products/desktop/packages/shared/src/handoff-host.ts
deleted file mode 100644
index 682c4e0968c2..000000000000
--- a/products/desktop/packages/shared/src/handoff-host.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import type { Adapter } from "./adapter";
-import type { GitHandoffCheckpoint, HandoffLocalGitState } from "./git-handoff";
-import type { WorkspaceMode } from "./workspace";
-
-export interface HandoffApiContext {
- apiHost: string;
- teamId: number;
-}
-
-export interface HandoffChangedFile {
- path: string;
- status: "modified" | "added" | "deleted" | "renamed" | "untracked";
- linesAdded?: number;
- linesRemoved?: number;
-}
-
-export interface HandoffReconnectParams {
- taskId: string;
- taskRunId: string;
- repoPath: string;
- apiHost: string;
- projectId: number;
- logUrl: string;
- sessionId?: string;
- adapter?: Adapter;
-}
-
-export interface HandoffResumeStateResult {
- resumeState: {
- conversation: unknown[];
- latestGitCheckpoint: GitHandoffCheckpoint | null;
- latestGitCheckpoints?: GitHandoffCheckpoint[];
- };
- cloudLogUrl: string | null;
-}
-
-/**
- * Host capabilities the core handoff orchestration depends on. The
- * implementation lives in workspace-server (agent runtime, workspace/repository
- * repos, git, local log cache, divergence dialog); core only orchestrates over
- * this port. Declared in shared so core and workspace-server can both reference
- * it without importing each other.
- */
-export interface HandoffHost {
- getChangedFiles(repoPath: string): Promise<readonly HandoffChangedFile[]>;
- getLocalGitState(repoPath: string): Promise<HandoffLocalGitState>;
-
- markRunEnvironmentLocal(
- ctx: HandoffApiContext,
- taskId: string,
- runId: string,
- ): Promise<void>;
- fetchResumeState(
- ctx: HandoffApiContext,
- taskId: string,
- runId: string,
- ): Promise<HandoffResumeStateResult>;
- formatConversation(conversation: unknown[]): string;
- applyGitCheckpoint(
- ctx: HandoffApiContext,
- checkpoint: GitHandoffCheckpoint,
- repoPath: string,
- taskId: string,
- runId: string,
- localGitState?: HandoffLocalGitState,
- ): Promise<void>;
- reconnectSession(
- params: HandoffReconnectParams,
- ): Promise<{ sessionId: string } | null>;
- attachWorkspaceToFolder(
- taskId: string,
- repoPath: string,
- ): { revert: () => void };
- seedLocalLogs(runId: string, logUrl: string): Promise<void>;
- setPendingContext(taskRunId: string, context: string): void;
- killSession(taskRunId: string): Promise<void>;
- updateWorkspaceMode(taskId: string, mode: WorkspaceMode): void;
-
- captureGitCheckpoint(
- ctx: HandoffApiContext,
- repoPath: string,
- taskId: string,
- runId: string,
- localGitState?: HandoffLocalGitState,
- ): Promise<GitHandoffCheckpoint | null>;
- persistCheckpointToLog(
- ctx: HandoffApiContext,
- taskId: string,
- runId: string,
- checkpoint: GitHandoffCheckpoint,
- ): Promise<void>;
- countLocalLogEntries(runId: string): Promise<number>;
- resumeRunInCloud(
- ctx: HandoffApiContext,
- taskId: string,
- runId: string,
- ): Promise<void>;
- cleanupLocalAfterCloudHandoff(
- repoPath: string,
- branchName: string | null,
- ): Promise<void>;
- deleteLocalLogCache(runId: string): Promise<void>;
-}
diff --git a/products/desktop/packages/shared/src/index.ts b/products/desktop/packages/shared/src/index.ts
index 389182dd2110..a1dc4136a3c2 100644
--- a/products/desktop/packages/shared/src/index.ts
+++ b/products/desktop/packages/shared/src/index.ts
@@ -188,16 +188,8 @@ export {
} from "./execution-modes";
export * from "./flags";
export * from "./git-domain";
-export type { GitHandoffCheckpoint, HandoffLocalGitState } from "./git-handoff";
export * from "./git-naming";
export type { GitFileStatus } from "./git-types";
-export type {
- HandoffApiContext,
- HandoffChangedFile,
- HandoffHost,
- HandoffReconnectParams,
- HandoffResumeStateResult,
-} from "./handoff-host";
export {
ALLOWED_IMAGE_MIME_TYPES,
buildImageDataUrl,
diff --git a/products/desktop/packages/shared/src/sessions.ts b/products/desktop/packages/shared/src/sessions.ts
index afe621c23109..f987fae5a8cb 100644
--- a/products/desktop/packages/shared/src/sessions.ts
+++ b/products/desktop/packages/shared/src/sessions.ts
@@ -121,7 +121,6 @@ export interface AgentSession {
cloudErrorMessage?: string | null;
initialPrompt?: ContentBlock[];
cloudBranch?: string | null;
- handoffInProgress?: boolean;
stopRequested?: boolean;
optimisticItems: OptimisticItem[];
contextUsed?: number;
diff --git a/products/desktop/packages/ui/src/features/git-interaction/components/CloudGitInteractionHeader.tsx b/products/desktop/packages/ui/src/features/git-interaction/components/CloudGitInteractionHeader.tsx
deleted file mode 100644
index 564db72b7957..000000000000
--- a/products/desktop/packages/ui/src/features/git-interaction/components/CloudGitInteractionHeader.tsx
+++ /dev/null
@@ -1,209 +0,0 @@
-import { Laptop, Spinner } from "@phosphor-icons/react";
-import type { ContinueAfterDirtyTreeStep } from "@posthog/core/sessions/localHandoffService";
-import { useService } from "@posthog/di/react";
-import { Button as QuillButton } from "@posthog/quill";
-import type { Task } from "@posthog/shared/domain-types";
-import {
- LOCAL_HANDOFF_SERVICE,
- type LocalHandoffService,
-} from "@posthog/ui/features/sessions/localHandoffService";
-import { useQueryClient } from "@tanstack/react-query";
-import { useState } from "react";
-import { useHostCapabilities } from "../../../shell/useHostCapabilities";
-import { useFeatureFlag } from "../../feature-flags/useFeatureFlag";
-import { DirtyTreeDialog } from "../../sessions/components/DirtyTreeDialog";
-import { HandoffConfirmDialog } from "../../sessions/components/HandoffConfirmDialog";
-import { useHandoffDialogStore } from "../../sessions/handoffDialogStore";
-import { useSessionForTask } from "../../sessions/useSession";
-import {
- GIT_CACHE_KEY_PROVIDER,
- type GitCacheKeyProvider,
-} from "../gitCacheProvider";
-import { useGitInteractionStore } from "../state/gitInteractionStore";
-import { useGitInteraction } from "../useGitInteraction";
-import { getSuggestedBranchName } from "../utils/getSuggestedBranchName";
-import { GitBranchDialog, GitCommitDialog } from "./GitInteractionDialogs";
-
-const CLOUD_HANDOFF_FLAG = "phc-cloud-handoff";
-
-interface CloudGitInteractionHeaderProps {
- taskId: string;
- task: Task;
-}
-
-export function CloudGitInteractionHeader({
- taskId,
- task,
-}: CloudGitInteractionHeaderProps) {
- const session = useSessionForTask(taskId);
- const queryClient = useQueryClient();
- const cacheKeyProvider = useService<GitCacheKeyProvider>(
- GIT_CACHE_KEY_PROVIDER,
- );
- const localHandoff = useService<LocalHandoffService>(LOCAL_HANDOFF_SERVICE);
- const { localWorkspaces } = useHostCapabilities();
- const cloudHandoffEnabled =
- useFeatureFlag(CLOUD_HANDOFF_FLAG) || import.meta.env.DEV;
-
- const confirmOpen = useHandoffDialogStore((s) => s.confirmOpen);
- const direction = useHandoffDialogStore((s) => s.direction);
- const branchName = useHandoffDialogStore((s) => s.branchName);
- const dirtyTreeOpen = useHandoffDialogStore((s) => s.dirtyTreeOpen);
- const changedFiles = useHandoffDialogStore((s) => s.changedFiles);
- const closeConfirm = useHandoffDialogStore((s) => s.closeConfirm);
- const pendingAfterCommit = useHandoffDialogStore((s) => s.pendingAfterCommit);
-
- const commitRepoPath = pendingAfterCommit?.repoPath;
- const git = useGitInteraction(taskId, commitRepoPath);
-
- const [isPreflighting, setIsPreflighting] = useState(false);
- const [preflightError, setPreflightError] = useState<string | null>(null);
-
- const handleConfirm = async () => {
- setPreflightError(null);
- setIsPreflighting(true);
- try {
- await localHandoff.start(taskId, task);
- } catch (err) {
- setPreflightError(
- err instanceof Error ? err.message : "Preflight failed",
- );
- } finally {
- setIsPreflighting(false);
- }
- };
-
- const applyStep = (step: ContinueAfterDirtyTreeStep) => {
- const actions = useGitInteractionStore.getState().actions;
- if (step.step === "open-commit") {
- actions.openCommit("commit");
- return;
- }
- actions.openBranch(step.suggestedName);
- };
-
- const handleCommitAndContinue = async () => {
- applyStep(
- localHandoff.continueAfterDirtyTree({
- isFeatureBranch: git.state.isFeatureBranch,
- suggestedBranchName: getSuggestedBranchName(
- queryClient,
- cacheKeyProvider,
- taskId,
- commitRepoPath,
- ),
- }),
- );
- };
-
- const handleBranchConfirm = async () => {
- const branchCreated = await git.actions.runBranch();
- if (!branchCreated) return;
- applyStep(localHandoff.afterBranchCreated());
- };
-
- const handleCommitConfirm = async () => {
- const committed = await git.actions.runCommit();
- if (!committed) return;
- await localHandoff.afterCommit();
- };
-
- // "Continue locally" hands the task off to a local checkout
- if (!cloudHandoffEnabled || !localWorkspaces) return null;
- if (task.origin_product === "image_builder") return null;
-
- const inProgress = session?.handoffInProgress ?? false;
-
- return (
- <>
- <div className="no-drag flex items-center">
- <QuillButton
- size="sm"
- disabled={inProgress}
- onClick={() =>
- localHandoff.openConfirm(taskId, session?.cloudBranch ?? null)
- }
- >
- {inProgress ? (
- <Spinner size={14} className="shrink-0 animate-spin" />
- ) : (
- <Laptop size={14} weight="regular" className="shrink-0" />
- )}
- {inProgress ? "Transferring..." : "Continue locally"}
- </QuillButton>
- </div>
- {confirmOpen && direction === "to-local" && (
- <HandoffConfirmDialog
- open={confirmOpen}
- onOpenChange={(open) => {
- if (!open) {
- closeConfirm();
- setPreflightError(null);
- }
- }}
- direction="to-local"
- branchName={branchName}
- onConfirm={handleConfirm}
- isSubmitting={isPreflighting}
- error={preflightError}
- />
- )}
- {dirtyTreeOpen && (
- <DirtyTreeDialog
- open={dirtyTreeOpen}
- onOpenChange={(open) => {
- if (!open) localHandoff.cancelPendingFlow();
- }}
- changedFiles={changedFiles}
- onCommitAndContinue={handleCommitAndContinue}
- />
- )}
- {pendingAfterCommit && (
- <GitCommitDialog
- open={git.modals.commitOpen}
- onOpenChange={(open) => {
- if (!open) {
- git.actions.closeCommit();
- localHandoff.cancelPendingFlow();
- }
- }}
- branchName={git.state.currentBranch ?? pendingAfterCommit.branchName}
- diffStats={git.state.diffStats}
- commitMessage={git.modals.commitMessage}
- onCommitMessageChange={git.actions.setCommitMessage}
- nextStep={git.modals.commitNextStep}
- onNextStepChange={git.actions.setCommitNextStep}
- pushDisabledReason={git.state.pushDisabledReason}
- onContinue={handleCommitConfirm}
- isSubmitting={git.modals.isSubmitting}
- error={git.modals.commitError}
- onGenerateMessage={git.actions.generateCommitMessage}
- isGeneratingMessage={git.modals.isGeneratingCommitMessage}
- showCommitAllToggle={
- git.state.stagedFiles.length > 0 &&
- git.state.unstagedFiles.length > 0
- }
- commitAll={git.modals.commitAll}
- onCommitAllChange={git.actions.setCommitAll}
- stagedFileCount={git.state.stagedFiles.length}
- />
- )}
- {pendingAfterCommit && (
- <GitBranchDialog
- open={git.modals.branchOpen}
- onOpenChange={(open) => {
- if (!open) {
- git.actions.closeBranch();
- localHandoff.cancelPendingFlow();
- }
- }}
- branchName={git.modals.branchName}
- onBranchNameChange={git.actions.setBranchName}
- onConfirm={handleBranchConfirm}
- isSubmitting={git.modals.isSubmitting}
- error={git.modals.branchError}
- />
- )}
- </>
- );
-}
diff --git a/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.tsx b/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.tsx
index c9c38fd101b3..038993b785d1 100644
--- a/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.tsx
+++ b/products/desktop/packages/ui/src/features/git-interaction/components/TaskActionsMenu.tsx
@@ -441,9 +441,7 @@ export function GitActionControl({
const showDropdown = actions.length > 1;
const isPrimaryDisabled = !primaryAction.enabled || isBusy;
- // Outlined rather than solid: the git action is one of several things the
- // header offers, not the header's call to action, and "Continue in cloud"
- // sits right beside it.
+ // Outlined rather than solid because the git action is one of several header actions.
const primaryButton = (
<QButton
size="sm"
diff --git a/products/desktop/packages/ui/src/features/sessions/components/DirtyTreeDialog.tsx b/products/desktop/packages/ui/src/features/sessions/components/DirtyTreeDialog.tsx
deleted file mode 100644
index c4a51dfcfbd4..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/DirtyTreeDialog.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-import { Warning } from "@phosphor-icons/react";
-import { GitDialog } from "@posthog/ui/features/git-interaction/components/GitInteractionDialogs";
-import {
- getStatusIndicator,
- type StatusIndicator,
-} from "@posthog/ui/features/git-interaction/utils/gitStatusUtils";
-import type { HandoffChangedFile } from "@posthog/ui/features/sessions/handoffDialogStore";
-import { FileIcon } from "@posthog/ui/primitives/FileIcon";
-import { Badge, Box, Flex, Text } from "@radix-ui/themes";
-
-interface DirtyTreeDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- changedFiles: HandoffChangedFile[];
- onCommitAndContinue: () => void;
-}
-
-function FileLineStats({ file }: { file: HandoffChangedFile }) {
- const hasStats =
- file.linesAdded !== undefined || file.linesRemoved !== undefined;
- if (!hasStats) return null;
-
- return (
- <Flex
- align="center"
- gap="1"
- className="shrink-0 font-mono text-[10px] leading-none"
- >
- {(file.linesAdded ?? 0) > 0 && (
- <Text className="text-(--green-9)">+{file.linesAdded}</Text>
- )}
- {(file.linesRemoved ?? 0) > 0 && (
- <Text className="text-(--red-9)">-{file.linesRemoved}</Text>
- )}
- </Flex>
- );
-}
-
-function StatusBadge({ indicator }: { indicator: StatusIndicator }) {
- return (
- <Badge
- size="1"
- color={indicator.color}
- className="shrink-0 px-[4px] py-0 text-[10px]"
- >
- {indicator.label}
- </Badge>
- );
-}
-
-export function DirtyTreeDialog({
- open,
- onOpenChange,
- changedFiles,
- onCommitAndContinue,
-}: DirtyTreeDialogProps) {
- return (
- <GitDialog
- open={open}
- onOpenChange={onOpenChange}
- icon={<Warning size={14} weight="fill" color="var(--amber-9)" />}
- title="Uncommitted changes"
- error={null}
- buttonLabel="Commit and continue"
- isSubmitting={false}
- onSubmit={onCommitAndContinue}
- >
- <Flex direction="column" gap="2">
- <Text color="gray" className="text-[13px]">
- The following local files have uncommitted changes that would be
- overwritten by the handoff. Commit them to continue.
- </Text>
- <Box className="max-h-[200px] overflow-auto rounded-(--radius-2) border border-(--gray-6)">
- {changedFiles.map((file) => {
- const fileName = file.path.split("/").pop() || file.path;
- const indicator = getStatusIndicator(file.status);
- return (
- <Flex
- key={file.path}
- align="center"
- gap="1"
- px="2"
- className="h-[28px]"
- >
- <FileIcon filename={fileName} size={14} />
- <span className="ml-[4px] min-w-0 flex-1 select-none overflow-hidden text-ellipsis whitespace-nowrap text-[13px]">
- {fileName}
- </span>
- <FileLineStats file={file} />
- <StatusBadge indicator={indicator} />
- </Flex>
- );
- })}
- </Box>
- </Flex>
- </GitDialog>
- );
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/HandoffConfirmDialog.tsx b/products/desktop/packages/ui/src/features/sessions/components/HandoffConfirmDialog.tsx
deleted file mode 100644
index 89cfa5661d33..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/components/HandoffConfirmDialog.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { ArrowLineDown, Cloud } from "@phosphor-icons/react";
-import { GitDialog } from "@posthog/ui/features/git-interaction/components/GitInteractionDialogs";
-import { Code, Text } from "@radix-ui/themes";
-
-interface HandoffConfirmDialogProps {
- open: boolean;
- onOpenChange: (open: boolean) => void;
- direction: "to-local" | "to-cloud";
- branchName: string | null;
- onConfirm: () => void;
- isSubmitting: boolean;
- error: string | null;
-}
-
-export function HandoffConfirmDialog({
- open,
- onOpenChange,
- direction,
- branchName,
- onConfirm,
- isSubmitting,
- error,
-}: HandoffConfirmDialogProps) {
- const isToLocal = direction === "to-local";
-
- return (
- <GitDialog
- open={open}
- onOpenChange={onOpenChange}
- icon={isToLocal ? <ArrowLineDown size={14} /> : <Cloud size={14} />}
- title={isToLocal ? "Continue locally" : "Continue in cloud"}
- error={error}
- buttonLabel="Continue"
- isSubmitting={isSubmitting}
- onSubmit={onConfirm}
- >
- <Text color="gray" className="text-[13px]">
- {isToLocal ? (
- "This will bring your changes from the cloud run into your local environment."
- ) : (
- <>
- This will send your changes on branch{" "}
- <Code className="text-[13px]">{branchName ?? "unknown"}</Code> to
- the cloud and continue running there.
- </>
- )}
- </Text>
- </GitDialog>
- );
-}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
index dd353ac91c28..7a7f425e29ae 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
@@ -77,7 +77,6 @@ import {
useShowRawLogs,
} from "@posthog/ui/features/sessions/sessionViewStore";
import type { Plan } from "@posthog/ui/features/sessions/types";
-import { useSessionHandoffInProgress } from "@posthog/ui/features/sessions/useSession";
import { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";
import { useIsWorkspaceCloudRun } from "@posthog/ui/features/workspace/useWorkspace";
import { useConnectivity } from "@posthog/ui/hooks/useConnectivity";
@@ -196,7 +195,6 @@ export function SessionView({
const spendStop = useSpendStop();
const { isOnline } = useConnectivity();
const currentModeId = modeOption?.currentValue;
- const handoffInProgress = useSessionHandoffInProgress(taskId);
const showInlineBanner = hasError && errorRetryable && events.length > 0;
const olderHistoryCursor = useSessionSelector(taskId, (session) =>
isCloud ? (session?.transcriptWindowStart ?? 0) : 0,
@@ -806,9 +804,8 @@ export function SessionView({
ref={editorRef}
sessionId={sessionId}
placeholder="Type a message... ! for bash mode, / for skills"
- disabled={!isRunning && !handoffInProgress}
+ disabled={!isRunning}
submitDisabledExternal={
- handoffInProgress ||
!isOnline ||
attachmentsUploading ||
attachmentUploadFailed ||
diff --git a/products/desktop/packages/ui/src/features/sessions/handoffDialogStore.ts b/products/desktop/packages/ui/src/features/sessions/handoffDialogStore.ts
deleted file mode 100644
index cfc22e3b09e8..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/handoffDialogStore.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import type { GitFileStatus } from "@posthog/shared";
-import { create } from "zustand";
-
-type HandoffDirection = "to-local" | "to-cloud";
-
-export interface HandoffChangedFile {
- path: string;
- status: GitFileStatus;
- linesAdded?: number;
- linesRemoved?: number;
-}
-
-interface HandoffDialogState {
- confirmOpen: boolean;
- direction: HandoffDirection | null;
- taskId: string | null;
- branchName: string | null;
- dirtyTreeOpen: boolean;
- changedFiles: HandoffChangedFile[];
- pendingAfterCommit: {
- taskId: string;
- repoPath: string;
- branchName: string | null;
- } | null;
-}
-
-interface HandoffDialogActions {
- openConfirm: (
- taskId: string,
- direction: HandoffDirection,
- branchName: string | null,
- ) => void;
- closeConfirm: () => void;
- openDirtyTreeForPendingHandoff: (
- changedFiles: HandoffChangedFile[],
- pending: {
- taskId: string;
- repoPath: string;
- branchName: string | null;
- },
- ) => void;
- hideDirtyTree: () => void;
- cancelPendingHandoff: () => void;
- clearPendingAfterCommit: () => void;
- reset: () => void;
-}
-
-type HandoffDialogStore = HandoffDialogState & HandoffDialogActions;
-
-const initialState: HandoffDialogState = {
- confirmOpen: false,
- direction: null,
- taskId: null,
- branchName: null,
- dirtyTreeOpen: false,
- changedFiles: [],
- pendingAfterCommit: null,
-};
-
-const closedDirtyTreeState = {
- dirtyTreeOpen: false,
- changedFiles: [],
-} satisfies Pick<HandoffDialogState, "dirtyTreeOpen" | "changedFiles">;
-
-export const useHandoffDialogStore = create<HandoffDialogStore>((set) => ({
- ...initialState,
- openConfirm: (taskId, direction, branchName) =>
- set({ confirmOpen: true, taskId, direction, branchName }),
- closeConfirm: () => set({ confirmOpen: false }),
- openDirtyTreeForPendingHandoff: (changedFiles, pending) =>
- set({
- confirmOpen: false,
- dirtyTreeOpen: true,
- changedFiles,
- pendingAfterCommit: pending,
- }),
- hideDirtyTree: () => set(closedDirtyTreeState),
- cancelPendingHandoff: () =>
- set({
- ...closedDirtyTreeState,
- pendingAfterCommit: null,
- }),
- clearPendingAfterCommit: () => set({ pendingAfterCommit: null }),
- reset: () => set(initialState),
-}));
diff --git a/products/desktop/packages/ui/src/features/sessions/hooks/useSessionCallbacks.ts b/products/desktop/packages/ui/src/features/sessions/hooks/useSessionCallbacks.ts
index c081e0b96b7d..9cc9ffde16e8 100644
--- a/products/desktop/packages/ui/src/features/sessions/hooks/useSessionCallbacks.ts
+++ b/products/desktop/packages/ui/src/features/sessions/hooks/useSessionCallbacks.ts
@@ -281,23 +281,11 @@ export function useSessionCallbacks({
[taskId, repoPath, sessionService, shellClient],
);
- const initiateHandoffToCloud = useCallback(async () => {
- if (!repoPath) return;
- try {
- await sessionService.handoffToCloud(taskId, repoPath);
- } catch (error) {
- log.error("Failed to hand off to cloud", error);
- const message = error instanceof Error ? error.message : "Unknown error";
- toast.error(`Failed to continue in cloud: ${message}`);
- }
- }, [taskId, repoPath, sessionService]);
-
return {
handleSendPrompt,
handleCancelPrompt,
handleRetry,
handleNewSession,
handleBashCommand,
- initiateHandoffToCloud,
};
}
diff --git a/products/desktop/packages/ui/src/features/sessions/identifiers.ts b/products/desktop/packages/ui/src/features/sessions/identifiers.ts
deleted file mode 100644
index 01291b05369e..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/identifiers.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export type { LocalHandoffHost } from "@posthog/core/sessions/localHandoffService";
-export { LOCAL_HANDOFF_HOST } from "@posthog/core/sessions/localHandoffService";
diff --git a/products/desktop/packages/ui/src/features/sessions/localHandoffService.ts b/products/desktop/packages/ui/src/features/sessions/localHandoffService.ts
deleted file mode 100644
index 7c65a40b42d0..000000000000
--- a/products/desktop/packages/ui/src/features/sessions/localHandoffService.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import type {
- LocalHandoffDialog,
- LocalHandoffNotifier,
- LocalHandoffPending,
-} from "@posthog/core/sessions/localHandoffService";
-import { useHandoffDialogStore } from "@posthog/ui/features/sessions/handoffDialogStore";
-import { toast } from "@posthog/ui/primitives/toast";
-import { logger } from "@posthog/ui/shell/logger";
-
-export type {
- LocalHandoffDialog,
- LocalHandoffHost,
- LocalHandoffNotifier,
- LocalHandoffPending,
-} from "@posthog/core/sessions/localHandoffService";
-export {
- LOCAL_HANDOFF_DIALOG,
- LOCAL_HANDOFF_HOST,
- LOCAL_HANDOFF_NOTIFIER,
- LOCAL_HANDOFF_SERVICE,
- LocalHandoffService,
-} from "@posthog/core/sessions/localHandoffService";
-
-const log = logger.scope("local-handoff-service");
-
-export const localHandoffDialog: LocalHandoffDialog = {
- openConfirm: (taskId, branchName) =>
- useHandoffDialogStore
- .getState()
- .openConfirm(taskId, "to-local", branchName),
- closeConfirm: () => useHandoffDialogStore.getState().closeConfirm(),
- cancelPendingFlow: () =>
- useHandoffDialogStore.getState().cancelPendingHandoff(),
- hideDirtyTree: () => useHandoffDialogStore.getState().hideDirtyTree(),
- getPendingAfterCommit: (): LocalHandoffPending | null =>
- useHandoffDialogStore.getState().pendingAfterCommit,
- clearPendingAfterCommit: () =>
- useHandoffDialogStore.getState().clearPendingAfterCommit(),
- openDirtyTreeForPendingHandoff: (changedFiles, pending) =>
- useHandoffDialogStore
- .getState()
- .openDirtyTreeForPendingHandoff(
- changedFiles as Parameters<
- ReturnType<
- typeof useHandoffDialogStore.getState
- >["openDirtyTreeForPendingHandoff"]
- >[0],
- pending,
- ),
-};
-
-export const localHandoffNotifier: LocalHandoffNotifier = {
- error: (message) => toast.error(message),
- warn: (message, data) => log.warn(message, data),
- logError: (message, data) => log.error(message, data),
-};
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts
index e4f2ee819039..b851dc6b48f8 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.recovery.integration.test.ts
@@ -50,15 +50,6 @@ const mockTrpcFs = vi.hoisted(() => ({
readFileAsBase64: { query: vi.fn() },
}));
-const mockTrpcHandoff = vi.hoisted(() => ({
- preflightToCloud: { query: vi.fn() },
- executeToCloud: { mutate: vi.fn() },
-}));
-
-const mockTrpcOs = vi.hoisted(() => ({
- openExternal: { mutate: vi.fn() },
-}));
-
const mockAuthenticatedClient = vi.hoisted(() => ({
createTaskRun: vi.fn(),
appendTaskRunLog: vi.fn(),
@@ -174,8 +165,6 @@ vi.mock("@posthog/di/container", () => ({
logs: mockTrpcLogs,
cloudTask: mockTrpcCloudTask,
fs: mockTrpcFs,
- handoff: mockTrpcHandoff,
- os: mockTrpcOs,
};
}
if (token === Symbol.for("posthog.ui.ImperativeQueryClient")) {
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
index ac294efc13fc..d3b05270cec9 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -55,15 +55,6 @@ const mockTrpcSkills = vi.hoisted(() => ({
resolveDependencies: { query: vi.fn() },
}));
-const mockTrpcHandoff = vi.hoisted(() => ({
- preflightToCloud: { query: vi.fn() },
- executeToCloud: { mutate: vi.fn() },
-}));
-
-const mockTrpcOs = vi.hoisted(() => ({
- openExternal: { mutate: vi.fn() },
-}));
-
const mockSessionStoreSetters = vi.hoisted(() => ({
setSession: vi.fn(),
removeSession: vi.fn(),
@@ -341,8 +332,6 @@ vi.mock("@posthog/di/container", () => ({
cloudTask: mockTrpcCloudTask,
fs: mockTrpcFs,
skills: mockTrpcSkills,
- handoff: mockTrpcHandoff,
- os: mockTrpcOs,
};
}
if (token === Symbol.for("posthog.ui.ImperativeQueryClient")) {
@@ -446,7 +435,6 @@ vi.mock("@posthog/core/sessions/sessionEvents", async () => {
};
});
-import { toast } from "@posthog/ui/primitives/toast";
import {
getSessionService,
resetSessionService,
@@ -550,14 +538,6 @@ describe("SessionService", () => {
mockTrpcSkills.resolveDependencies.query.mockImplementation(
async (refs: unknown) => refs,
);
- mockTrpcHandoff.preflightToCloud.query.mockResolvedValue({
- canHandoff: true,
- });
- mockTrpcHandoff.executeToCloud.mutate.mockResolvedValue({
- success: true,
- logEntryCount: 0,
- });
- mockTrpcOs.openExternal.mutate.mockResolvedValue(undefined);
mockAuthenticatedClient.prepareTaskRunArtifactUploads.mockResolvedValue([]);
mockAuthenticatedClient.finalizeTaskRunArtifactUploads.mockResolvedValue(
[],
@@ -10030,43 +10010,6 @@ describe("SessionService", () => {
});
});
- describe("handoffToCloud", () => {
- it("starts GitHub reauth when cloud handoff needs user authorization", async () => {
- const service = getSessionService();
- mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
- createMockSession(),
- );
- mockTrpcHandoff.executeToCloud.mutate.mockResolvedValue({
- success: false,
- code: "github_authorization_required",
- error: "Connect GitHub in your browser, then retry Continue in cloud.",
- });
-
- await service.handoffToCloud("task-123", "/repo/path");
-
- expect(
- mockAuthenticatedClient.startGithubUserIntegrationConnect,
- ).toHaveBeenCalledWith(123);
- expect(mockTrpcOs.openExternal.mutate).toHaveBeenCalledWith({
- url: "https://github.com/login/oauth/authorize",
- });
- expect(toast.info).toHaveBeenCalledWith(
- "Connect GitHub to continue in cloud",
- "Complete the authorization in your browser, then click Continue again.",
- );
- expect(toast.error).not.toHaveBeenCalledWith(
- expect.stringContaining("github_authorization_required"),
- );
- expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(
- "run-123",
- {
- handoffInProgress: false,
- status: "disconnected",
- },
- );
- });
- });
-
describe("automatic local recovery", () => {
it("reconnects automatically after a subscription error", async () => {
vi.useFakeTimers();
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionStore.ts b/products/desktop/packages/ui/src/features/sessions/sessionStore.ts
index 2734a5585458..ae76cb2e0fa4 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionStore.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionStore.ts
@@ -86,7 +86,6 @@ export {
usePendingPermissionsForTask,
useQueuedMessagesForTask,
useSessionForTask,
- useSessionHandoffInProgress,
useSessionIsCloud,
useSessionSelector,
useSessions,
diff --git a/products/desktop/packages/ui/src/features/sessions/useSession.ts b/products/desktop/packages/ui/src/features/sessions/useSession.ts
index 4770381c960e..868d1b1166eb 100644
--- a/products/desktop/packages/ui/src/features/sessions/useSession.ts
+++ b/products/desktop/packages/ui/src/features/sessions/useSession.ts
@@ -186,19 +186,6 @@ export const useSessionIsCloud = (taskId: string | undefined): boolean => {
});
};
-/** Whether a cloud handoff is in progress for a task. Primitive selector — see
- * {@link useSessionIsCloud}. */
-export const useSessionHandoffInProgress = (
- taskId: string | undefined,
-): boolean => {
- return useSessionStore((s) => {
- if (!taskId) return false;
- const taskRunId = s.taskIdIndex[taskId];
- if (!taskRunId) return false;
- return s.sessions[taskRunId]?.handoffInProgress ?? false;
- });
-};
-
export const useTaskSessionStarting = (taskId: string | undefined): boolean => {
return useSessionStore((s) => {
if (!taskId) return false;
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.test.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.test.tsx
index 99d4f884ea8b..1b142c982718 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.test.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.test.tsx
@@ -1,5 +1,4 @@
import type { Task } from "@posthog/shared/domain-types";
-import { Theme } from "@radix-ui/themes";
import { render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
@@ -24,29 +23,6 @@ vi.mock(
};
},
);
-vi.mock("@posthog/ui/features/auth/store", () => ({
- useAuthStateValue: (selector: (state: { status: string }) => unknown) =>
- selector({ status: "authenticated" }),
-}));
-vi.mock("@posthog/ui/features/feature-flags/useFeatureFlag", () => ({
- useFeatureFlag: () => true,
-}));
-vi.mock("@posthog/ui/features/sessions/useSession", () => ({
- useSessionForTask: () => null,
-}));
-vi.mock("@posthog/ui/features/sessions/hooks/useSessionCallbacks", () => ({
- useSessionCallbacks: () => ({ initiateHandoffToCloud: vi.fn() }),
-}));
-vi.mock("@posthog/ui/features/sessions/handoffDialogStore", () => ({
- useHandoffDialogStore: (selector: (state: object) => unknown) =>
- selector({
- confirmOpen: false,
- direction: null,
- branchName: null,
- openConfirm: vi.fn(),
- closeConfirm: vi.fn(),
- }),
-}));
vi.mock("@posthog/ui/features/code-review/hooks/useDiffStatsToggle", () => ({
useDiffStatsToggle: () => ({
filesChanged: 0,
@@ -65,10 +41,6 @@ vi.mock(
BranchSelector: () => null,
}),
);
-vi.mock(
- "@posthog/ui/features/git-interaction/components/CloudGitInteractionHeader",
- () => ({ CloudGitInteractionHeader: () => <div>cloud actions</div> }),
-);
vi.mock(
"@posthog/ui/features/git-interaction/components/TaskActionsMenu",
() => ({
@@ -99,11 +71,7 @@ import { TaskHeaderActions } from "./TaskHeaderActions";
function renderActions(
task: Task = { id: "task-1", title: "Fix the bug" } as Task,
) {
- render(
- <Theme>
- <TaskHeaderActions task={task} />
- </Theme>,
- );
+ render(<TaskHeaderActions task={task} />);
}
describe("TaskHeaderActions", () => {
@@ -113,7 +81,6 @@ describe("TaskHeaderActions", () => {
renderActions();
- expect(screen.queryByText("Continue in cloud")).not.toBeInTheDocument();
expect(screen.queryByText("task menu")).not.toBeInTheDocument();
});
@@ -124,9 +91,7 @@ describe("TaskHeaderActions", () => {
renderActions();
expect(screen.getByText("stop cloud run")).toBeInTheDocument();
- expect(screen.getByText("cloud actions")).toBeInTheDocument();
expect(screen.getByText("task menu")).toBeInTheDocument();
- expect(screen.queryByText("Continue in cloud")).not.toBeInTheDocument();
});
it("shows cloud controls for a cloud run without a local workspace row", () => {
@@ -140,7 +105,5 @@ describe("TaskHeaderActions", () => {
} as Task);
expect(screen.getByText("stop cloud run")).toBeInTheDocument();
- expect(screen.getByText("cloud actions")).toBeInTheDocument();
- expect(screen.queryByText("Continue in cloud")).not.toBeInTheDocument();
});
});
diff --git a/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.tsx b/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.tsx
index 62349e48d4e8..9057cd58faea 100644
--- a/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.tsx
+++ b/products/desktop/packages/ui/src/features/task-detail/components/TaskHeaderActions.tsx
@@ -1,7 +1,4 @@
-import { Cloud, Spinner } from "@phosphor-icons/react";
-import { Button as QuillButton } from "@posthog/quill";
import type { Task } from "@posthog/shared/domain-types";
-import { useAuthStateValue } from "@posthog/ui/features/auth/store";
import { AutoresearchHeaderButton } from "@posthog/ui/features/autoresearch/AutoresearchHeaderButton";
import { useDiffStatsToggle } from "@posthog/ui/features/code-review/hooks/useDiffStatsToggle";
import {
@@ -9,106 +6,18 @@ import {
SHORTCUTS,
} from "@posthog/ui/features/command/keyboard-shortcuts";
import { DiffStatsBadge } from "@posthog/ui/features/diff-stats/DiffStatsBadge";
-import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";
import { BranchSelector } from "@posthog/ui/features/git-interaction/components/BranchSelector";
-import { CloudGitInteractionHeader } from "@posthog/ui/features/git-interaction/components/CloudGitInteractionHeader";
import { TaskActionsMenu } from "@posthog/ui/features/git-interaction/components/TaskActionsMenu";
import { useReviewInRightPanel } from "@posthog/ui/features/navigation/useReviewInRightPanel";
-import { HandoffConfirmDialog } from "@posthog/ui/features/sessions/components/HandoffConfirmDialog";
import { StopCloudRunButton } from "@posthog/ui/features/sessions/components/StopCloudRunButton";
-import { useHandoffDialogStore } from "@posthog/ui/features/sessions/handoffDialogStore";
-import { useSessionCallbacks } from "@posthog/ui/features/sessions/hooks/useSessionCallbacks";
-import { useSessionForTask } from "@posthog/ui/features/sessions/useSession";
import {
useIsCloudTask,
useWorkspace,
useWorkspaceLoaded,
} from "@posthog/ui/features/workspace/useWorkspace";
import { Tooltip } from "@posthog/ui/primitives/Tooltip";
-import { Flex } from "@radix-ui/themes";
-import { useState } from "react";
import { TaskAnalysisButton } from "./TaskAnalysisButton";
-const CLOUD_HANDOFF_FLAG = "phc-cloud-handoff";
-
-function LocalHandoffButton({ taskId, task }: { taskId: string; task: Task }) {
- const session = useSessionForTask(taskId);
- const workspace = useWorkspace(taskId);
- const repoPath = workspace?.folderPath ?? null;
- const authStatus = useAuthStateValue((s) => s.status);
- const cloudHandoffEnabled =
- useFeatureFlag(CLOUD_HANDOFF_FLAG) || import.meta.env.DEV;
- const { initiateHandoffToCloud } = useSessionCallbacks({
- taskId,
- task,
- session: session ?? undefined,
- repoPath,
- });
-
- const confirmOpen = useHandoffDialogStore((s) => s.confirmOpen);
- const direction = useHandoffDialogStore((s) => s.direction);
- const branchName = useHandoffDialogStore((s) => s.branchName);
- const openConfirm = useHandoffDialogStore((s) => s.openConfirm);
- const closeConfirm = useHandoffDialogStore((s) => s.closeConfirm);
-
- const [isSubmitting, setIsSubmitting] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- if (authStatus !== "authenticated") return null;
- if (!cloudHandoffEnabled) return null;
-
- const handleConfirm = async () => {
- setError(null);
- setIsSubmitting(true);
- try {
- await initiateHandoffToCloud();
- } catch (err) {
- setError(err instanceof Error ? err.message : "Handoff failed");
- } finally {
- setIsSubmitting(false);
- }
- };
-
- const inProgress = session?.handoffInProgress ?? false;
-
- return (
- <>
- <div className="no-drag flex items-center">
- <QuillButton
- size="sm"
- disabled={inProgress}
- onClick={() =>
- openConfirm(taskId, "to-cloud", workspace?.branchName ?? null)
- }
- >
- {inProgress ? (
- <Spinner size={14} className="shrink-0 animate-spin" />
- ) : (
- <Cloud size={14} weight="regular" className="shrink-0" />
- )}
- {inProgress ? "Transferring..." : "Continue in cloud"}
- </QuillButton>
- </div>
- {confirmOpen && direction === "to-cloud" && (
- <HandoffConfirmDialog
- open={confirmOpen}
- onOpenChange={(open) => {
- if (!open) {
- closeConfirm();
- setError(null);
- }
- }}
- direction="to-cloud"
- branchName={branchName}
- onConfirm={handleConfirm}
- isSubmitting={isSubmitting}
- error={error}
- />
- )}
- </>
- );
-}
-
function TaskDiffStatsBadge({ task }: { task: Task }) {
const { filesChanged, linesAdded, linesRemoved, isOpen, toggle } =
useDiffStatsToggle(task);
@@ -138,14 +47,7 @@ export function TaskHeaderActions({ task }: { task: Task }) {
const showDiffBadge = !useReviewInRightPanel();
return (
- <Flex
- align="center"
- justify="end"
- gap="1"
- pr="1"
- pl="1"
- className="h-full max-w-[50%] shrink-0 overflow-hidden"
- >
+ <div className="flex h-full max-w-[50%] shrink-0 items-center justify-end gap-1 overflow-hidden px-1">
<div className="no-drag">
<AutoresearchHeaderButton taskId={task.id} />
</div>
@@ -165,19 +67,10 @@ export function TaskHeaderActions({ task }: { task: Task }) {
{workspaceLoaded && (
<>
- {isCloudTask ? (
- <>
- {/* Stopping the run comes after the handoff: it ends the session,
- and the last thing in a row reads as the last resort. */}
- <CloudGitInteractionHeader taskId={task.id} task={task} />
- <StopCloudRunButton taskId={task.id} />
- </>
- ) : (
- <LocalHandoffButton taskId={task.id} task={task} />
- )}
+ {isCloudTask && <StopCloudRunButton taskId={task.id} />}
<TaskActionsMenu taskId={task.id} isCloud={isCloudTask} />
</>
)}
- </Flex>
+ </div>
);
}
diff --git a/products/desktop/packages/ui/src/features/workspace/useWorkspace.ts b/products/desktop/packages/ui/src/features/workspace/useWorkspace.ts
index 131c1b98ba2d..d5b7ea98d582 100644
--- a/products/desktop/packages/ui/src/features/workspace/useWorkspace.ts
+++ b/products/desktop/packages/ui/src/features/workspace/useWorkspace.ts
@@ -34,7 +34,7 @@ export function useIsWorkspaceCloudRun(taskId: string | undefined): boolean {
return workspace?.mode === "cloud";
}
-// The workspace row wins when present: handoff updates it before latest_run refreshes.
+// The workspace row is the local source of truth for the active execution mode.
export function isCloudTask(task: Task, workspace: Workspace | null): boolean {
if (workspace) {
return workspace.mode === "cloud";
diff --git a/products/desktop/packages/ui/src/shell/ContentHeader.tsx b/products/desktop/packages/ui/src/shell/ContentHeader.tsx
index 54356f30d435..cb13a0e35281 100644
--- a/products/desktop/packages/ui/src/shell/ContentHeader.tsx
+++ b/products/desktop/packages/ui/src/shell/ContentHeader.tsx
@@ -7,7 +7,7 @@ import { Flex } from "@radix-ui/themes";
// The in-pane content header for the unified Bluebird chrome. Shows the active
// view's title (pushed into the header store by each view) on the left and that
// task's action row (TaskHeaderActions) on the right — the branch selector,
-// review-panel toggle, cloud/local handoff, skill buttons and task actions that
+// review-panel toggle, skill buttons and task actions that
// used to live in the Code header bar.
//
// This breadcrumb row is scoped to views that have somewhere to walk back to:
diff --git a/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts b/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts
index 67adcd67a1c0..5185b8329f1e 100644
--- a/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts
+++ b/products/desktop/packages/ui/src/shell/requiredHostCapabilities.ts
@@ -35,7 +35,7 @@ import { DIFF_WORKER_FACTORY } from "@posthog/ui/shell/diffWorkerHost";
*
* Excluded on purpose: core-module services (they fail at module load, a
* different and already-loud failure mode) and host-specific/local-only
- * capabilities (e.g. file watchers, local handoff) that not every host provides.
+ * capabilities such as file watchers that not every host provides.
*/
export const REQUIRED_HOST_CAPABILITIES: readonly HostCapabilityRequirement[] =
[
diff --git a/products/desktop/packages/workspace-server/src/services/git/schemas.ts b/products/desktop/packages/workspace-server/src/services/git/schemas.ts
index b974dd014820..6c641ab3f52b 100644
--- a/products/desktop/packages/workspace-server/src/services/git/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/schemas.ts
@@ -534,31 +534,6 @@ export const getGithubIssueOutput = githubRefSchema.nullable();
export const getGithubPullRequestInput = getGithubIssueInput;
export const getGithubPullRequestOutput = getGithubIssueOutput;
-export const handoffLocalGitStateSchema = z.object({
- head: z.string().nullable(),
- branch: z.string().nullable(),
- upstreamHead: z.string().nullable(),
- upstreamRemote: z.string().nullable(),
- upstreamMergeRef: z.string().nullable(),
-});
-
-export type HandoffLocalGitState = z.infer<typeof handoffLocalGitStateSchema>;
-
-export const readHandoffLocalGitStateInput = z.object({
- directoryPath: z.string(),
-});
-export const readHandoffLocalGitStateOutput = handoffLocalGitStateSchema;
-
-export const cleanupAfterCloudHandoffInput = z.object({
- directoryPath: z.string(),
- branchName: z.string().nullable(),
-});
-export const cleanupAfterCloudHandoffOutput = z.object({
- stashed: z.boolean(),
- switched: z.boolean(),
- defaultBranch: z.string().nullable(),
-});
-
export const gitStatusOutput = z.object({
installed: z.boolean(),
version: z.string().nullable(),
diff --git a/products/desktop/packages/workspace-server/src/services/git/service.ts b/products/desktop/packages/workspace-server/src/services/git/service.ts
index 36b3eb964fc7..d25aca4ff8db 100644
--- a/products/desktop/packages/workspace-server/src/services/git/service.ts
+++ b/products/desktop/packages/workspace-server/src/services/git/service.ts
@@ -3,7 +3,6 @@ import fs from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import { execGh } from "@posthog/git/gh";
-import { readHandoffLocalGitState } from "@posthog/git/handoff";
import { getGitOperationManager } from "@posthog/git/operation-manager";
import {
type DiffStats,
@@ -32,18 +31,13 @@ import {
unstageFiles as gitUnstageFiles,
isGitRepository,
} from "@posthog/git/queries";
-import {
- CreateBranchSaga,
- ResetToDefaultBranchSaga,
- SwitchBranchSaga,
-} from "@posthog/git/sagas/branch";
+import { CreateBranchSaga, SwitchBranchSaga } from "@posthog/git/sagas/branch";
import { CleanWorkingTreeSaga } from "@posthog/git/sagas/clean";
import { CloneSaga } from "@posthog/git/sagas/clone";
import { CommitSaga } from "@posthog/git/sagas/commit";
import { DiscardFileChangesSaga } from "@posthog/git/sagas/discard";
import { PullSaga } from "@posthog/git/sagas/pull";
import { PushSaga } from "@posthog/git/sagas/push";
-import { StashPushSaga } from "@posthog/git/sagas/stash";
import { parseGithubUrl } from "@posthog/git/utils";
import { TypedEventEmitter } from "@posthog/shared";
import { injectable } from "inversify";
@@ -69,7 +63,6 @@ import type {
GitStateSnapshot,
GitStatusOutput,
GitSyncStatus,
- HandoffLocalGitState,
MergePrOutput,
OpenPrOutput,
PrActionType,
@@ -1969,48 +1962,4 @@ export class GitService extends TypedEventEmitter<GitCloneEvents> {
return [];
}
}
-
- async readHandoffLocalGitState(
- directoryPath: string,
- ): Promise<HandoffLocalGitState> {
- return readHandoffLocalGitState(directoryPath);
- }
-
- async cleanupAfterCloudHandoff(
- directoryPath: string,
- branchName: string | null,
- ): Promise<{
- stashed: boolean;
- switched: boolean;
- defaultBranch: string | null;
- }> {
- let stashed = false;
- const hasChanges =
- (await this.getChangedFilesHead(directoryPath)).length > 0;
-
- if (hasChanges) {
- const label = branchName ?? "unknown";
- const stashResult = await new StashPushSaga().run({
- baseDir: directoryPath,
- message: `posthog-code: handoff backup (${label})`,
- });
- if (!stashResult.success) {
- return { stashed: false, switched: false, defaultBranch: null };
- }
- stashed = true;
- }
-
- const resetResult = await new ResetToDefaultBranchSaga().run({
- baseDir: directoryPath,
- });
- if (!resetResult.success) {
- return { stashed, switched: false, defaultBranch: null };
- }
-
- return {
- stashed,
- switched: resetResult.data.switched,
- defaultBranch: resetResult.data.defaultBranch,
- };
- }
}
diff --git a/products/desktop/packages/workspace-server/src/services/handoff/identifiers.ts b/products/desktop/packages/workspace-server/src/services/handoff/identifiers.ts
deleted file mode 100644
index f1b1cc58a1f4..000000000000
--- a/products/desktop/packages/workspace-server/src/services/handoff/identifiers.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const HANDOFF_GIT_GATEWAY = Symbol.for(
- "posthog.workspaceServer.handoffGitGateway",
-);
-export const HANDOFF_LOG_GATEWAY = Symbol.for(
- "posthog.workspaceServer.handoffLogGateway",
-);
diff --git a/products/desktop/packages/workspace-server/src/services/handoff/ports.ts b/products/desktop/packages/workspace-server/src/services/handoff/ports.ts
deleted file mode 100644
index ef6e685c225a..000000000000
--- a/products/desktop/packages/workspace-server/src/services/handoff/ports.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { HandoffChangedFile, HandoffLocalGitState } from "@posthog/shared";
-
-/**
- * Git operations the handoff host needs. The git CLI runs in the
- * workspace-server child process, so the desktop fulfills this with a thin
- * transport adapter over the workspace client.
- */
-export interface HandoffGitGateway {
- getChangedFiles(repoPath: string): Promise<readonly HandoffChangedFile[]>;
- getLocalGitState(repoPath: string): Promise<HandoffLocalGitState>;
- cleanupAfterCloudHandoff(
- repoPath: string,
- branchName: string | null,
- ): Promise<{
- stashed: boolean;
- switched: boolean;
- defaultBranch: string | null;
- }>;
-}
-
-/**
- * Local NDJSON log-cache operations the handoff host needs, served by the
- * workspace-server local-logs capability.
- */
-export interface HandoffLogGateway {
- seedLocalLogs(taskRunId: string, content: string): Promise<void>;
- countLocalLogEntries(taskRunId: string): Promise<number>;
- deleteLocalLogCache(taskRunId: string): Promise<void>;
-}
diff --git a/products/desktop/packages/workspace-server/src/services/handoff/service.test.ts b/products/desktop/packages/workspace-server/src/services/handoff/service.test.ts
deleted file mode 100644
index 92c2123657fb..000000000000
--- a/products/desktop/packages/workspace-server/src/services/handoff/service.test.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { HandoffHostService } from "./service";
-
-function createService(overrides: {
- workspaceRepo?: Partial<{
- findByTaskId: ReturnType<typeof vi.fn>;
- setModeAndRepository: ReturnType<typeof vi.fn>;
- updateMode: ReturnType<typeof vi.fn>;
- }>;
- repositoryRepo?: Partial<{ findByPath: ReturnType<typeof vi.fn> }>;
- git?: object;
- logs?: object;
-}) {
- const workspaceRepo = {
- findByTaskId: vi.fn(),
- setModeAndRepository: vi.fn(),
- updateMode: vi.fn(),
- ...overrides.workspaceRepo,
- };
- const repositoryRepo = {
- findByPath: vi.fn(),
- ...overrides.repositoryRepo,
- };
- const git = {
- getChangedFiles: vi.fn(),
- getLocalGitState: vi.fn(),
- cleanupAfterCloudHandoff: vi.fn(),
- ...overrides.git,
- };
- const logs = {
- seedLocalLogs: vi.fn().mockResolvedValue(undefined),
- countLocalLogEntries: vi.fn(),
- deleteLocalLogCache: vi.fn(),
- ...overrides.logs,
- };
-
- const service = new HandoffHostService(
- {} as never,
- {} as never,
- workspaceRepo as never,
- repositoryRepo as never,
- {} as never,
- {} as never,
- git as never,
- logs as never,
- );
- return { service, workspaceRepo, repositoryRepo, git, logs };
-}
-
-describe("HandoffHostService.attachWorkspaceToFolder", () => {
- it("throws when the folder is not registered", () => {
- const { service } = createService({
- repositoryRepo: { findByPath: vi.fn().mockReturnValue(null) },
- });
- expect(() => service.attachWorkspaceToFolder("task-1", "/repo")).toThrow(
- "No registered folder",
- );
- });
-
- it("throws when the task has no workspace", () => {
- const { service } = createService({
- repositoryRepo: { findByPath: vi.fn().mockReturnValue({ id: "r1" }) },
- workspaceRepo: { findByTaskId: vi.fn().mockReturnValue(null) },
- });
- expect(() => service.attachWorkspaceToFolder("task-1", "/repo")).toThrow(
- "No workspace exists",
- );
- });
-
- it("is a no-op revert when already local on the same repository", () => {
- const { service, workspaceRepo } = createService({
- repositoryRepo: { findByPath: vi.fn().mockReturnValue({ id: "r1" }) },
- workspaceRepo: {
- findByTaskId: vi
- .fn()
- .mockReturnValue({ mode: "local", repositoryId: "r1" }),
- },
- });
- const { revert } = service.attachWorkspaceToFolder("task-1", "/repo");
- revert();
- expect(workspaceRepo.setModeAndRepository).not.toHaveBeenCalled();
- });
-
- it("attaches and reverts to the previous mode/repository", () => {
- const { service, workspaceRepo } = createService({
- repositoryRepo: { findByPath: vi.fn().mockReturnValue({ id: "r1" }) },
- workspaceRepo: {
- findByTaskId: vi
- .fn()
- .mockReturnValue({ mode: "cloud", repositoryId: "old" }),
- },
- });
- const { revert } = service.attachWorkspaceToFolder("task-1", "/repo");
- expect(workspaceRepo.setModeAndRepository).toHaveBeenCalledWith(
- "task-1",
- "local",
- "r1",
- );
- revert();
- expect(workspaceRepo.setModeAndRepository).toHaveBeenLastCalledWith(
- "task-1",
- "cloud",
- "old",
- );
- });
-});
-
-describe("HandoffHostService.seedLocalLogs", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- });
-
- it("seeds fetched content into the log gateway", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue({ ok: true, text: () => "a\nb\n" }),
- );
- const { service, logs } = createService({});
- await service.seedLocalLogs("run-1", "https://logs");
- expect(logs.seedLocalLogs).toHaveBeenCalledWith("run-1", "a\nb\n");
- });
-
- it("skips seeding when the fetch fails", async () => {
- vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: false }));
- const { service, logs } = createService({});
- await service.seedLocalLogs("run-1", "https://logs");
- expect(logs.seedLocalLogs).not.toHaveBeenCalled();
- });
-
- it("skips seeding when the content is blank", async () => {
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue({ ok: true, text: () => " " }),
- );
- const { service, logs } = createService({});
- await service.seedLocalLogs("run-1", "https://logs");
- expect(logs.seedLocalLogs).not.toHaveBeenCalled();
- });
-});
-
-describe("HandoffHostService delegation", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("delegates git + log reads to their gateways", async () => {
- const { service, git, logs } = createService({
- git: {
- getChangedFiles: vi.fn().mockResolvedValue([]),
- getLocalGitState: vi.fn().mockResolvedValue({ branch: "main" }),
- },
- logs: { countLocalLogEntries: vi.fn().mockResolvedValue(3) },
- });
- await service.getChangedFiles("/repo");
- await service.getLocalGitState("/repo");
- await service.countLocalLogEntries("run-1");
- expect(git.getChangedFiles).toHaveBeenCalledWith("/repo");
- expect(git.getLocalGitState).toHaveBeenCalledWith("/repo");
- expect(logs.countLocalLogEntries).toHaveBeenCalledWith("run-1");
- });
-});
diff --git a/products/desktop/packages/workspace-server/src/services/handoff/service.ts b/products/desktop/packages/workspace-server/src/services/handoff/service.ts
deleted file mode 100644
index 97eec889bbbc..000000000000
--- a/products/desktop/packages/workspace-server/src/services/handoff/service.ts
+++ /dev/null
@@ -1,279 +0,0 @@
-import { POSTHOG_NOTIFICATIONS } from "@posthog/agent";
-import { HandoffCheckpointTracker } from "@posthog/agent/handoff-checkpoint";
-import { PostHogAPIClient } from "@posthog/agent/posthog-api";
-import type * as AgentResume from "@posthog/agent/resume";
-import {
- formatConversationForResume,
- resumeFromLog,
-} from "@posthog/agent/resume";
-import type { GitHandoffBranchDivergence } from "@posthog/git/handoff";
-import {
- APP_LIFECYCLE_SERVICE,
- type IAppLifecycle,
-} from "@posthog/platform/app-lifecycle";
-import { DIALOG_SERVICE, type IDialog } from "@posthog/platform/dialog";
-import type {
- GitHandoffCheckpoint,
- HandoffApiContext,
- HandoffChangedFile,
- HandoffHost,
- HandoffLocalGitState,
- HandoffReconnectParams,
- HandoffResumeStateResult,
- WorkspaceMode,
-} from "@posthog/shared";
-import { inject, injectable } from "inversify";
-import {
- REPOSITORY_REPOSITORY,
- WORKSPACE_REPOSITORY,
-} from "../../db/identifiers";
-import type { IRepositoryRepository } from "../../db/repositories/repository-repository";
-import type { IWorkspaceRepository } from "../../db/repositories/workspace-repository";
-import type { AgentService } from "../agent/agent";
-import type { AgentAuthAdapter } from "../agent/auth-adapter";
-import { AGENT_AUTH_ADAPTER, AGENT_SERVICE } from "../agent/identifiers";
-import { HANDOFF_GIT_GATEWAY, HANDOFF_LOG_GATEWAY } from "./identifiers";
-import type { HandoffGitGateway, HandoffLogGateway } from "./ports";
-
-const CONTINUE_DIVERGENCE_BUTTON = 1;
-
-/**
- * Host implementation of the core handoff orchestration's HANDOFF_HOST port.
- * Owns the agent runtime glue (api client, checkpoint tracker, log resume),
- * workspace/repository persistence, and the diverged-branch confirmation. Git
- * and local-log syscalls run in the workspace-server child process, reached
- * through the injected gateways.
- */
-@injectable()
-export class HandoffHostService implements HandoffHost {
- constructor(
- @inject(AGENT_SERVICE)
- private readonly agentService: AgentService,
- @inject(AGENT_AUTH_ADAPTER)
- private readonly agentAuthAdapter: AgentAuthAdapter,
- @inject(WORKSPACE_REPOSITORY)
- private readonly workspaceRepo: IWorkspaceRepository,
- @inject(REPOSITORY_REPOSITORY)
- private readonly repositoryRepo: IRepositoryRepository,
- @inject(DIALOG_SERVICE)
- private readonly dialog: IDialog,
- @inject(APP_LIFECYCLE_SERVICE)
- private readonly appLifecycle: IAppLifecycle,
- @inject(HANDOFF_GIT_GATEWAY)
- private readonly git: HandoffGitGateway,
- @inject(HANDOFF_LOG_GATEWAY)
- private readonly logs: HandoffLogGateway,
- ) {}
-
- getChangedFiles(repoPath: string): Promise<readonly HandoffChangedFile[]> {
- return this.git.getChangedFiles(repoPath);
- }
-
- getLocalGitState(repoPath: string): Promise<HandoffLocalGitState> {
- return this.git.getLocalGitState(repoPath);
- }
-
- async markRunEnvironmentLocal(
- ctx: HandoffApiContext,
- taskId: string,
- runId: string,
- ): Promise<void> {
- const apiClient = this.createApiClient(ctx);
- await apiClient.updateTaskRun(taskId, runId, { environment: "local" });
- }
-
- async fetchResumeState(
- ctx: HandoffApiContext,
- taskId: string,
- runId: string,
- ): Promise<HandoffResumeStateResult> {
- const apiClient = this.createApiClient(ctx);
- const taskRun = await apiClient.getTaskRun(taskId, runId);
- const resumeState = await resumeFromLog({ taskId, runId, apiClient });
- return {
- resumeState: {
- conversation: resumeState.conversation,
- latestGitCheckpoint: resumeState.latestGitCheckpoint,
- latestGitCheckpoints: resumeState.latestGitCheckpoints,
- },
- cloudLogUrl: taskRun.log_url ?? null,
- };
- }
-
- formatConversation(conversation: unknown[]): string {
- return formatConversationForResume(
- conversation as AgentResume.ConversationTurn[],
- );
- }
-
- async applyGitCheckpoint(
- ctx: HandoffApiContext,
- checkpoint: GitHandoffCheckpoint,
- repoPath: string,
- taskId: string,
- runId: string,
- localGitState?: HandoffLocalGitState,
- ): Promise<void> {
- const apiClient = this.createApiClient(ctx);
- const tracker = new HandoffCheckpointTracker({
- repositoryPath: repoPath,
- taskId,
- runId,
- apiClient,
- });
- await tracker.applyFromHandoff(checkpoint, {
- localGitState,
- onDivergedBranch: (divergence) =>
- this.confirmDivergedBranchReset(divergence),
- });
- }
-
- reconnectSession(
- params: HandoffReconnectParams,
- ): Promise<{ sessionId: string } | null> {
- return this.agentService.reconnectSession(params);
- }
-
- attachWorkspaceToFolder(
- taskId: string,
- repoPath: string,
- ): { revert: () => void } {
- const repository = this.repositoryRepo.findByPath(repoPath);
- if (!repository) {
- throw new Error(
- `No registered folder for path '${repoPath}' — cannot attach workspace`,
- );
- }
- const previous = this.workspaceRepo.findByTaskId(taskId);
- if (!previous) {
- throw new Error(`No workspace exists for task ${taskId}`);
- }
- if (previous.mode === "local" && previous.repositoryId === repository.id) {
- return { revert: () => {} };
- }
- this.workspaceRepo.setModeAndRepository(taskId, "local", repository.id);
- return {
- revert: () => {
- this.workspaceRepo.setModeAndRepository(
- taskId,
- previous.mode,
- previous.repositoryId,
- );
- },
- };
- }
-
- async seedLocalLogs(runId: string, logUrl: string): Promise<void> {
- const response = await fetch(logUrl);
- if (!response.ok) return;
- const content = await response.text();
- if (!content?.trim()) return;
- await this.logs.seedLocalLogs(runId, content);
- }
-
- setPendingContext(taskRunId: string, context: string): void {
- this.agentService.setPendingContext(taskRunId, context);
- }
-
- async killSession(taskRunId: string): Promise<void> {
- await this.agentService.cancelSession(taskRunId);
- }
-
- updateWorkspaceMode(taskId: string, mode: WorkspaceMode): void {
- this.workspaceRepo.updateMode(taskId, mode);
- }
-
- async captureGitCheckpoint(
- ctx: HandoffApiContext,
- repoPath: string,
- taskId: string,
- runId: string,
- localGitState?: HandoffLocalGitState,
- ): Promise<GitHandoffCheckpoint | null> {
- const apiClient = this.createApiClient(ctx);
- const tracker = new HandoffCheckpointTracker({
- repositoryPath: repoPath,
- taskId,
- runId,
- apiClient,
- });
- const checkpoint = await tracker.captureForHandoff(localGitState);
- if (!checkpoint) return null;
- const localCheckpoint = {
- ...checkpoint,
- device: { type: "local" as const },
- };
- return localCheckpoint;
- }
-
- async persistCheckpointToLog(
- ctx: HandoffApiContext,
- taskId: string,
- runId: string,
- checkpoint: GitHandoffCheckpoint,
- ): Promise<void> {
- const apiClient = this.createApiClient(ctx);
- await apiClient.appendTaskRunLog(taskId, runId, [
- {
- type: "notification",
- timestamp: new Date().toISOString(),
- notification: {
- jsonrpc: "2.0",
- method: POSTHOG_NOTIFICATIONS.GIT_CHECKPOINT,
- params: checkpoint as unknown as Record<string, unknown>,
- },
- },
- ]);
- }
-
- countLocalLogEntries(runId: string): Promise<number> {
- return this.logs.countLocalLogEntries(runId);
- }
-
- async resumeRunInCloud(
- ctx: HandoffApiContext,
- taskId: string,
- runId: string,
- ): Promise<void> {
- const apiClient = this.createApiClient(ctx);
- await apiClient.resumeRunInCloud(taskId, runId);
- }
-
- async cleanupLocalAfterCloudHandoff(
- repoPath: string,
- branchName: string | null,
- ): Promise<void> {
- await this.git.cleanupAfterCloudHandoff(repoPath, branchName);
- }
-
- deleteLocalLogCache(runId: string): Promise<void> {
- return this.logs.deleteLocalLogCache(runId);
- }
-
- private createApiClient(ctx: HandoffApiContext): PostHogAPIClient {
- const config = this.agentAuthAdapter.createPosthogConfig({
- apiHost: ctx.apiHost,
- projectId: ctx.teamId,
- });
- return new PostHogAPIClient(config);
- }
-
- private async confirmDivergedBranchReset(
- divergence: GitHandoffBranchDivergence,
- ): Promise<boolean> {
- await this.appLifecycle.whenReady();
-
- const response = await this.dialog.confirm({
- severity: "warning",
- options: ["Cancel", "Continue"],
- defaultIndex: 0,
- cancelIndex: 0,
- title: "Local branch has diverged",
- message: `The local branch '${divergence.branch}' has commits that are not in the cloud handoff.`,
- detail:
- `Continuing will reset '${divergence.branch}' from ${divergence.localHead.slice(0, 7)} to ${divergence.cloudHead.slice(0, 7)}.\n\n` +
- "Cancel if you want to keep the current local branch tip.",
- });
- return response === CONTINUE_DIVERGENCE_BUTTON;
- }
-}
diff --git a/products/desktop/packages/workspace-server/src/services/local-logs/schemas.ts b/products/desktop/packages/workspace-server/src/services/local-logs/schemas.ts
index dc6f36eace6f..4c30ac41b526 100644
--- a/products/desktop/packages/workspace-server/src/services/local-logs/schemas.ts
+++ b/products/desktop/packages/workspace-server/src/services/local-logs/schemas.ts
@@ -28,17 +28,3 @@ export const writeLocalLogsInput = z.object({
taskRunId: z.string().min(1),
content: z.string(),
});
-
-export const seedLocalLogsInput = z.object({
- taskRunId: z.string().min(1),
- content: z.string(),
-});
-
-export const countLocalLogEntriesInput = z.object({
- taskRunId: z.string().min(1),
-});
-export const countLocalLogEntriesOutput = z.number();
-
-export const deleteLocalLogCacheInput = z.object({
- taskRunId: z.string().min(1),
-});
diff --git a/products/desktop/packages/workspace-server/src/services/local-logs/service.test.ts b/products/desktop/packages/workspace-server/src/services/local-logs/service.test.ts
index c6d93d849309..4574f7033c58 100644
--- a/products/desktop/packages/workspace-server/src/services/local-logs/service.test.ts
+++ b/products/desktop/packages/workspace-server/src/services/local-logs/service.test.ts
@@ -2,11 +2,10 @@ import os from "node:os";
import path from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const { mockMkdir, mockWriteFile, mockReadFile, mockRm } = vi.hoisted(() => ({
+const { mockMkdir, mockWriteFile, mockReadFile } = vi.hoisted(() => ({
mockMkdir: vi.fn(),
mockWriteFile: vi.fn(),
mockReadFile: vi.fn(),
- mockRm: vi.fn(),
}));
vi.mock("node:fs", () => ({
@@ -15,7 +14,6 @@ vi.mock("node:fs", () => ({
mkdir: mockMkdir,
writeFile: mockWriteFile,
readFile: mockReadFile,
- rm: mockRm,
},
},
}));
@@ -54,7 +52,6 @@ describe("LocalLogsService", () => {
mockMkdir.mockReset().mockResolvedValue(undefined);
mockWriteFile.mockReset().mockResolvedValue(undefined);
mockReadFile.mockReset();
- mockRm.mockReset().mockResolvedValue(undefined);
});
describe("readLocalLogs", () => {
@@ -223,60 +220,4 @@ describe("LocalLogsService", () => {
expect(mockMkdir).toHaveBeenCalledTimes(1);
});
});
-
- describe("seedLocalLogs", () => {
- it("appends a seed boundary marker and writes the NDJSON", async () => {
- const service = new LocalLogsService();
- await service.seedLocalLogs(RUN_ID, "a\nb\n");
- expect(mockMkdir).toHaveBeenCalledWith(path.dirname(expectedPath), {
- recursive: true,
- });
- expect(mockWriteFile).toHaveBeenCalledWith(
- expectedPath,
- `a\nb\n${JSON.stringify({ type: "seed_boundary" })}\n`,
- "utf-8",
- );
- });
-
- it("adds a trailing newline before the marker when missing", async () => {
- const service = new LocalLogsService();
- await service.seedLocalLogs(RUN_ID, "no-newline");
- expect(mockWriteFile).toHaveBeenCalledWith(
- expectedPath,
- `no-newline\n${JSON.stringify({ type: "seed_boundary" })}\n`,
- "utf-8",
- );
- });
-
- it("skips empty content", async () => {
- const service = new LocalLogsService();
- await service.seedLocalLogs(RUN_ID, " ");
- expect(mockWriteFile).not.toHaveBeenCalled();
- });
- });
-
- describe("countLocalLogEntries", () => {
- it("counts non-blank lines", async () => {
- mockReadFile.mockResolvedValue("a\n\nb\n c \n\n");
- const service = new LocalLogsService();
- await expect(service.countLocalLogEntries(RUN_ID)).resolves.toBe(3);
- expect(mockReadFile).toHaveBeenCalledWith(expectedPath, "utf-8");
- });
-
- it("returns 0 when the log is missing", async () => {
- mockReadFile.mockRejectedValue(
- Object.assign(new Error("nope"), { code: "ENOENT" }),
- );
- const service = new LocalLogsService();
- await expect(service.countLocalLogEntries(RUN_ID)).resolves.toBe(0);
- });
- });
-
- describe("deleteLocalLogCache", () => {
- it("force-removes the run's NDJSON path", async () => {
- const service = new LocalLogsService();
- await service.deleteLocalLogCache(RUN_ID);
- expect(mockRm).toHaveBeenCalledWith(expectedPath, { force: true });
- });
- });
});
diff --git a/products/desktop/packages/workspace-server/src/services/local-logs/service.ts b/products/desktop/packages/workspace-server/src/services/local-logs/service.ts
index b139d950a2e0..5a95549a5c43 100644
--- a/products/desktop/packages/workspace-server/src/services/local-logs/service.ts
+++ b/products/desktop/packages/workspace-server/src/services/local-logs/service.ts
@@ -218,34 +218,6 @@ export class LocalLogsService implements ILogsService {
return inFlight;
}
- async seedLocalLogs(taskRunId: string, content: string): Promise<void> {
- if (!content?.trim()) return;
- const logPath = this.getLocalLogPath(taskRunId);
- const marker = JSON.stringify({ type: "seed_boundary" });
- const trailingNewline = content.endsWith("\n") ? "" : "\n";
- await fs.promises.mkdir(path.dirname(logPath), { recursive: true });
- await fs.promises.writeFile(
- logPath,
- `${content}${trailingNewline}${marker}\n`,
- "utf-8",
- );
- }
-
- async countLocalLogEntries(taskRunId: string): Promise<number> {
- const logPath = this.getLocalLogPath(taskRunId);
- try {
- const content = await fs.promises.readFile(logPath, "utf-8");
- return content.split("\n").filter((line) => line.trim()).length;
- } catch {
- return 0;
- }
- }
-
- async deleteLocalLogCache(taskRunId: string): Promise<void> {
- const logPath = this.getLocalLogPath(taskRunId);
- await fs.promises.rm(logPath, { force: true });
- }
-
private async drain(
taskRunId: string,
initialContent: string,
diff --git a/products/desktop/packages/workspace-server/src/trpc.ts b/products/desktop/packages/workspace-server/src/trpc.ts
index 499d3579558b..24c193d27f33 100644
--- a/products/desktop/packages/workspace-server/src/trpc.ts
+++ b/products/desktop/packages/workspace-server/src/trpc.ts
@@ -50,8 +50,6 @@ import {
changedFilesOutput,
checkoutBranchInput,
checkoutBranchOutput,
- cleanupAfterCloudHandoffInput,
- cleanupAfterCloudHandoffOutput,
cloneRepositoryInput,
cloneRepositoryOutput,
commitInput,
@@ -121,8 +119,6 @@ import {
pullOutput,
pushInput,
pushOutput,
- readHandoffLocalGitStateInput,
- readHandoffLocalGitStateOutput,
replyToPrCommentInput,
replyToPrCommentOutput,
resetSoftInput,
@@ -139,16 +135,12 @@ import {
} from "./services/git/schemas";
import type { GitService } from "./services/git/service";
import {
- countLocalLogEntriesInput,
- countLocalLogEntriesOutput,
- deleteLocalLogCacheInput,
readLocalLogsCollapsedInput,
readLocalLogsCollapsedOutput,
readLocalLogsInput,
readLocalLogsOutput,
readLocalLogsTailInput,
readLocalLogsTailOutput,
- seedLocalLogsInput,
writeLocalLogsInput,
} from "./services/local-logs/schemas";
import type { LocalLogsService } from "./services/local-logs/service";
@@ -714,23 +706,6 @@ export function createAppRouter({
),
),
- readHandoffLocalGitState: t.procedure
- .input(readHandoffLocalGitStateInput)
- .output(readHandoffLocalGitStateOutput)
- .query(({ input }) =>
- gitService().readHandoffLocalGitState(input.directoryPath),
- ),
-
- cleanupAfterCloudHandoff: t.procedure
- .input(cleanupAfterCloudHandoffInput)
- .output(cleanupAfterCloudHandoffOutput)
- .mutation(({ input }) =>
- gitService().cleanupAfterCloudHandoff(
- input.directoryPath,
- input.branchName,
- ),
- ),
-
getDiffStats: t.procedure
.input(diffStatsInput)
.output(diffStatsSchema)
@@ -924,25 +899,6 @@ export function createAppRouter({
.mutation(({ input }) =>
localLogsService().writeLocalLogs(input.taskRunId, input.content),
),
-
- seed: t.procedure
- .input(seedLocalLogsInput)
- .mutation(({ input }) =>
- localLogsService().seedLocalLogs(input.taskRunId, input.content),
- ),
-
- count: t.procedure
- .input(countLocalLogEntriesInput)
- .output(countLocalLogEntriesOutput)
- .query(({ input }) =>
- localLogsService().countLocalLogEntries(input.taskRunId),
- ),
-
- delete: t.procedure
- .input(deleteLocalLogCacheInput)
- .mutation(({ input }) =>
- localLogsService().deleteLocalLogCache(input.taskRunId),
- ),
}),
connectivity: t.router({
getStatus: t.procedure