SIGN IN SIGN UP

feat(desktop): import sessions from Claude Code, Codex, and opencode (#13744)

* feat(core): session import service for Claude Code, Codex, and opencode history

Adds a SessionImportService to @cline/core that discovers sessions in the
on-disk stores of Claude Code (~/.claude/projects JSONL), Codex
(~/.codex/sessions rollouts + session_index titles), and opencode
(opencode.db sqlite), translates each conversation into Cline's native
MessageWithMetadata format, and persists it through CoreSessionService as
a completed, listable, resumable session.

Key mechanics:
- Claude Code: parentUuid tree walk from the newest leaf picks the active
  branch (edits/retries branch the log); same-message.id assistant lines
  merge back into one turn; sidechains, meta lines, and slash-command
  wrappers are excluded; ai-title/summary lines provide titles.
- Codex: real prompts come from user_message event_msg lines (user-role
  response_items are injected AGENTS/environment context, with a fallback
  for old rollouts); function_call/output pairs map to tool_use/tool_result;
  resumed rollouts that re-embed the original session id dedupe to the
  richest file; token_count events stamp per-turn metrics.
- opencode: reads a temp snapshot of the WAL-mode db; inline tool parts
  split into tool_use + tool_result to preserve provider-valid structure;
  child (subagent) sessions and synthetic parts are skipped.
- Shared sanitizer guarantees replayability: orphaned tool_use gets a
  placeholder result, orphaned tool_results and empty text blocks drop,
  provider-session-scoped signatures/encrypted reasoning strip.
- Imported sessions pass every history-visibility gate (terminal status,
  non-empty provider/model, chat-workspace fallback cwd, no fabricated
  checkpoint metadata) and carry metadata.importedFrom for idempotent
  re-discovery (alreadyImportedSessionId).

* feat(desktop): sidecar commands for importing sessions from other tools

Adds two sidecar WebSocket commands backed by @cline/core's
SessionImportService:

- list_importable_sessions: returns { installedTools, sessions } where
  sessions are ImportableSessionSummary rows (tool, sourceId, title, cwd,
  timestamps, messageCount, preview, alreadyImportedSessionId) discovered
  in the local Claude Code / Codex / opencode stores.
- import_sessions: takes { selections: [{ tool, sourceId }] }, validates
  each selection against the known tool list, imports sequentially
  (per-session transactional), and broadcasts session_import_progress
  events ({ index, total, result }) so the UI can render live progress.
  Returns { results } with per-item ok/sessionId/title/error.

* feat(desktop): import sessions UI for Claude Code, Codex, and opencode

Adds an Import Sessions dialog to the desktop app driven by the sidecar's
list_importable_sessions / import_sessions commands:

- Scan phase discovers local history from all three tools and groups it
  per tool with select-all checkboxes, per-row title, relative time,
  message count, and workspace folder; rows already imported are disabled
  and badged (idempotent re-open).
- Text filter across title, folder, and first-prompt preview.
- Import phase streams session_import_progress events into a progress bar
  and per-item result list; the dialog cannot be dismissed mid-import via
  overlay click. Done phase summarizes successes and lists failures with
  their error messages.
- Entry points: an Import button in the Sessions view header and an
  "Import sessions" row in Settings → General.
- use-session-history subscribes to session_import_progress so history
  refreshes no matter which surface started the import.
- Wire types live in webview/lib/session-import.ts (mirrors the core
  module's types so the client bundle never imports node-only code).

* fix(desktop): import dialog crash rendering session timestamps

formatRelativeTime takes a string (parseTimestamp calls .trim() on any
truthy value), but the import dialog passed the numeric updatedAtMs,
crashing the page with 'e.trim is not a function' as soon as scanned rows
rendered. Convert to an ISO string at the call site.

Slipped through because the webview has no typechecking anywhere:
tsconfig.dev.json excludes webview/ and next.config sets
typescript.ignoreBuildErrors, and the webview's own tsconfig currently
carries 64 pre-existing errors.

* feat(desktop): offer session import during onboarding

Adds an 'import' onboarding step between connect/github and done. The
step scans for importable Claude Code / Codex / opencode history on
entry and silently advances when nothing (new) is found or the scan
fails, so only people with actual history from other tools ever see it.
When sessions are found it summarizes the count and source tools, opens
the same ImportSessionsDialog used by the Sessions page for picking, and
flips to a confirmation state once at least one session imports. Skip is
always available, including while the scan is still running.

* fix(desktop): import dialog text overflow, collapsible sections, select all

- Titles no longer clip or push the row wide: they word-wrap up to two
  lines (line-clamp-2 + break-words, with min-w-0 down the flex chain so
  long unbroken Codex prompt titles can actually shrink); the meta line
  keeps time/count fixed and truncates only the workspace name; progress
  rows get the same min-w-0 treatment.
- Each tool section header is now a collapse toggle (chevron +
  aria-expanded) so one tool with hundreds of sessions doesn't force
  scrolling past it; collapsed headers still show count and selected
  count, and filtering forces sections open so search matches can't hide
  in a collapsed group. Collapse state resets per dialog open.
- New global Select all row above the list with indeterminate state and
  an x-of-y selected counter; it operates on the currently visible
  (filtered) selectable sessions, matching the per-section checkboxes.

* fix(desktop): import dialog header and search clipped by intrinsic column width

The dialog grid used the default auto column track, so a single
unbreakable string in a session title (Codex titles often contain URLs)
set the column's min-content width wider than the fixed 620px dialog --
break-words affects layout but not intrinsic sizing -- and
overflow-hidden then clipped everything in the column, including the
description and the search field. Pin the column to minmax(0,1fr) so the
container width always wins and long words wrap at the box edge instead.

Also add sm:max-w-none (the primitive's sm:max-w-lg survives
tailwind-merge across variants and was silently capping the dialog at
512px) and shrink-0 on the search and select-all rows so a tall list can
never compress them vertically.

* fix(desktop): onboarding import step rescanned after import and looped to done screen

The import step's scan effect depended on onContinue, an inline arrow the
parent recreates every render — and importing itself re-renders the app
shell via the history refresh. Each re-render re-ran the scan, and when
the user had imported everything (select all), the re-scan found zero
remaining sessions and hit the nothing-to-import auto-advance, yanking
them past their own import confirmation onto the done screen. The scan
now runs exactly once per step entry (onContinue held in a ref for the
async auto-skip paths).

Also, after a successful import the button is now 'Start building' and
completes onboarding directly instead of routing through the separate
done screen — two consecutive confirmation screens read as a loop. The
skip and nothing-found paths still go through the done screen so those
users get the 'You're all set' confirmation.

* fix(core): consolidate imported tool_results into the message after their tool_use

The import sanitizer answered missing tool_use ids with a separate
placeholder user message while leaving real results for the same turn in
later user messages. Anthropic requires every tool_result for a turn in
the user message immediately following it, so a partially-answered turn
would still 400 on resume. Rebuild any incomplete or split span as one
consolidated results message in tool_use order (placeholders for missing
ids, duplicates dropped) followed by a message carrying whatever else the
span held, mirroring the legacy migration sanitizer.

* fix(desktop): imported sessions resume on the user's configured provider; batch adapter caches

Opening a history session adopts the row's provider/model
(use-chat-session: session.provider || prev.provider), so imported rows
stamped with the source tool's provider — openai-native for Codex,
whatever opencode reported — resumed on providers the user may never have
configured and failed on first send. The dialog now passes the app's
current model selection (lastProvider/lastModelByProvider, i.e. what a
new chat would run on) and the service stamps it on the row; both halves
must be present so a Cline provider is never paired with a foreign model
id. The source provider/model are preserved in metadata.importedFrom and
per-message modelInfo stays accurate. Codex's provider id is corrected to
Cline's openai-native, and opencode's openai/google map to
openai-native/gemini.

Adapters also gain per-batch caches released via dispose(): Codex's
convert() re-walked the sessions tree and re-read every rollout head per
imported session (O(sessions x files)); it now builds the session-id ->
richest-file index once per batch. opencode copied the whole WAL db per
imported session; it now snapshots once per batch.

* fix(core): roll back failed imports and dedupe at import time

Addresses both Greptile P1s on #13744:

- A write failing after createRootSessionWithArtifacts (messages, status,
  manifest, title) left a half-written pid-0 session in history whose
  importedFrom marker also blocked retrying the source. persistConverted
  now deletes the session on any later failure and rethrows.
- Dedup markers were read through listSessions, which caps its scan at
  2000 rows, so a prior import older than the newest 2000 sessions was
  invisible and the source could be imported again. Add
  listSessionMetadata (ids + metadata for every row, no manifest reads or
  reconciliation) and use it for markers. Also check idempotency at
  import time, not only at discovery: a request for an already-imported
  source resolves to the existing session (alreadyImported: true) instead
  of writing a copy, covering stale pickers and repeated requests.

* fix(core): create imported sessions terminal and mark them imported last

Two failure modes shared one root cause -- the import wrote its session
in stages and claimed success too early:

- The row was created running/pid-0 and flipped to completed afterwards.
  The stale-session reconciler runs in the hub daemon against the same
  SQLite DB and, in that window, marks such rows failed and stamps
  terminal_marker metadata. createRootSessionWithArtifacts now accepts
  status/endedAt/exitCode so imports are created completed with the
  source session's end time; the separate status flip and manifest
  rewrite are gone.
- The importedFrom marker was written at creation, so a session whose
  later writes failed (and whose rollback delete also failed) still
  blocked retrying its source. The marker is now the final write, so it
  means 'this import finished' and a half-written session can never
  claim the source.

listSessionMetadata is unbounded by default so dedup sees every row.

* fix(core): resolve TS2352 casts in session-import tests (#13746)

tsc rejects casting ContentBlock[] straight to Record<string, unknown>[]
(RedactedThinkingContent is not comparable), which failed the Quality
Checks typecheck. Route the five assertion-site casts through a small
blocks() helper that widens via unknown.

* fix(core): flatten Codex content-block tool outputs during import

Newer Codex rollouts write custom_tool_call_output.output as an array of
Responses-API content blocks ({type:"input_text", text}) instead of a
plain string. The importer JSON.stringified that array into the
tool_result content, and the chat UI's tool-summary parser then rendered
each non-text block as its type label, so imported exec calls showed up
as "[input_text][input_text]" with no output.

Concatenate the text of string/text-bearing blocks (they are stream
chunks, so no separator) and keep the JSON fallback for anything else.

* fix(desktop): edit-and-resend on runs without a checkpoint

Editing a message forks the session before that run, and the sidecar
always routed that through manager.restore with workspace: true. Imported
sessions carry no checkpoint history, so editing any of their prompts
failed with "No checkpoint found at or before run N" — even after the
user had continued the session in Cline, since only the new runs get
checkpoints.

When no checkpoint exists at or before the edited run there is no
workspace state to roll back, so fork the trimmed transcript onto the
current workspace (the same path a full-history fork takes) instead of
erroring. Runs that do have a checkpoint still restore the workspace.

* fix(core): roll back failed session creation and coalesce overlapping imports

Two gaps Greptile flagged on the import path:

createRootSessionWithArtifacts upserts the row before writing the messages
file and manifest, and the call sat above persistConverted's rollback try.
A file write failing there left a completed row with no transcript in
history. Creation now runs inside the rollback, and deleteSession already
tolerates a missing row or missing files.

Each import_sessions request builds its own service and snapshots the
existing-import markers once, so two overlapping requests for one source
(a second window, a double-fired command) both passed the dedupe check and
persisted two sessions. A module-level in-flight map keyed by tool:sourceId
makes the later caller wait on the first write and report its session as
already imported.

* fix(desktop): resolve the import resume target like a new chat does

An imported Claude Code session resumed on the Anthropic provider instead
of the user's Cline selection. The dialog read model-selection storage
directly and required both a remembered provider and a remembered model;
the composer only records a model from the explicit picker handlers, so
anyone running on the default model has no entry, the lookup came back
empty, and the service fell back to the source tool's provider.

Resolve the target with getInitialChatConfig() -- the same chain a new
chat uses (remembered selection, then the built-in default), which is
never empty -- and have the import_sessions handler default to the cline
provider and CLINE_DEFAULT_MODEL_ID when a caller sends nothing, matching
other server-started sessions. The source provider can no longer become
the resume target.
S
Saoud Rizwan committed
b9977a139f9828f93e59a0fa757cd96f9f205382
Parent: 6d5a979
Committed by GitHub <noreply@github.com> on 9/2/2026, 2:39:20 AM