Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
minor: support current DSH CLI and integrate DSH Desktop (#1961)
Ali Khokhar6b2989d4fbb9
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 0bc27f38..04b5616a 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -105,7 +105,7 @@ jobs:prepare-node: "true"- name: Run pytest- run: uv run --locked pytest -v --tb=short --durations=50+ run: uv run --locked pytest -v --tb=short -o thread_dump_timeout=15 --durations=50playwright:name: playwright (${{ matrix.os }})diff --git a/README.md b/README.mdindex 76682879..2a4b9c62 100644--- a/README.md+++ b/README.md@@ -160,6 +160,16 @@ DeepSeek Harness Web:fcc-dsh```+For DeepSeek Harness Desktop, install and open the app once, then select **Connect** under **Integrations → DeepSeek Harness Desktop** in FCC. Keep FCC running while using its models. FCC becomes the default for new sessions. Select **Disconnect** to remove the connection. Native DeepSeek account features still need a DeepSeek login.++Use DeepSeek Harness 0.2.0-rc.2 or newer. Update the CLI with:++```bash+npm install -g @deepseek-ai/dsh@latest+```++For headless tasks, run `fcc-dsh headless "your task"`. Extra `--patch` files apply after FCC's settings. After disconnecting Desktop, select another model to continue an existing FCC session. If another DSH setting uses FCC's Desktop credential, Disconnect keeps that credential and reports why.+Grok Build:```bashdiff --git a/e2e/conftest.py b/e2e/conftest.pyindex 1aed39c5..9072f422 100644--- a/e2e/conftest.py+++ b/e2e/conftest.py@@ -158,6 +158,8 @@ def admin_base_url("""Serve one fully isolated Admin application on an OS-assigned port."""config_dir = tmp_path / ".fcc"+ monkeypatch.setenv("DSH_HOME", str(tmp_path / ".dsh"))+ monkeypatch.delenv("FCC_DSH_DESKTOP_API_KEY", raising=False)monkeypatch.setattr(jetbrains_acp_integration,"config_path",diff --git a/e2e/test_dsh_desktop_integration.py b/e2e/test_dsh_desktop_integration.pynew file mode 100644index 00000000..6f9b8e33--- /dev/null+++ b/e2e/test_dsh_desktop_integration.py@@ -0,0 +1,131 @@+"""The DSH Desktop card uses real isolated native configuration files."""++import asyncio+import json+import threading++from playwright.sync_api import expect+from ruamel.yaml import YAML+++def install(tmp_path):+ home = tmp_path / ".dsh"+ profile = home / "profiles/desktop"+ profile.mkdir(parents=True, exist_ok=True)+ (profile / "package.json").write_text(+ json.dumps(+ {+ "dsh": {+ "profile": {+ "bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app"]+ }+ },+ }+ )+ )+ return home+++def test_connect_disconnect_preserves_native_settings(page, admin_base_url, tmp_path):+ home = install(tmp_path)+ patch = home / "profiles/desktop/cordis.patch.yml"+ patch.write_text("- id: unrelated\n config: {keep: unchanged}\n")+ page.goto(admin_base_url + "/admin/integrations")+ opener = page.locator("#openDshDesktopIntegration")+ expect(opener).to_have_text("Connect")+ opener.click()+ dialog = page.locator("#dshDesktopIntegrationDialog")+ expect(dialog).to_be_visible()+ expect(dialog.locator("#dshDesktopIntegrationFiles")).to_contain_text(+ str(patch.resolve())+ )+ dialog.get_by_role("button", name="Connect", exact=True).click()+ expect(dialog).not_to_be_visible()+ expect(opener).to_have_text("Disconnect")+ expect(opener).to_have_css("color", "rgb(239, 68, 68)")+ page.screenshot(path=str(tmp_path / "dsh-integrations.png"), full_page=True)+ assert "free-claude-code" in patch.read_text()+ page.reload()+ expect(opener).to_have_text("Disconnect")+ opener.click()+ expect(dialog.locator("#dshDesktopIntegrationDescription")).to_contain_text(+ "Existing"+ )+ dialog.get_by_role("button", name="Disconnect", exact=True).click()+ expect(opener).to_have_text("Connect")+ assert "free-claude-code" not in patch.read_text()+ rows = YAML().load(patch.read_text())+ assert rows[0] == {"id": "unrelated", "config": {"keep": "unchanged"}}+ expect(page.locator("#dirtyState")).to_have_text("No changes")+++def test_setup_error_and_retry_remain_in_dialog(page, admin_base_url, tmp_path):+ page.goto(admin_base_url + "/admin/integrations")+ opener = page.locator("#openDshDesktopIntegration")+ expect(opener).to_have_text("Connect")+ opener.click()+ dialog = page.locator("#dshDesktopIntegrationDialog")+ dialog.get_by_role("button", name="Connect", exact=True).click()+ expect(dialog.get_by_role("alert")).to_contain_text("open")+ expect(dialog.get_by_role("button", name="Connect", exact=True)).to_be_enabled()+ install(tmp_path)+ dialog.get_by_role("button", name="Connect", exact=True).click()+ expect(dialog).not_to_be_visible()+ expect(opener).to_have_text("Disconnect")+++def test_superseded_connect_notice_matches_real_disconnect(+ page, admin_base_url, tmp_path, monkeypatch+):+ from free_claude_code.runtime.provider_manager import ProviderRuntimeManager++ home = install(tmp_path)+ page.goto(admin_base_url + "/admin/integrations")+ opener = page.locator("#openDshDesktopIntegration")+ expect(opener).to_have_text("Connect")+ entered, release = threading.Event(), threading.Event()+ original = ProviderRuntimeManager.wait_for_catalog++ async def held(manager):+ entered.set()+ assert await asyncio.to_thread(release.wait, 10)+ return await original(manager)++ monkeypatch.setattr(ProviderRuntimeManager, "wait_for_catalog", held)+ endpoint = admin_base_url + "/admin/api/integrations/dsh-desktop"+ try:+ opener.click()+ page.locator("#confirmDshDesktopIntegration").click()+ assert entered.wait(5)+ response = page.request.post(endpoint + "/disconnect")+ assert response.ok+ assert not response.json()["connected"]+ finally:+ release.set()+ expect(page.locator("#dshDesktopIntegrationDialog")).not_to_be_visible()+ expect(opener).to_have_text("Connect")+ notice = page.locator("#dshDesktopIntegrationMessage")+ expect(notice).to_contain_text("disconnected")+ expect(notice).not_to_contain_text("Connected.")+ assert not page.request.get(endpoint).json()["connected"]+ assert not (home / "profiles/desktop/cordis.patch.yml").exists()+++def test_changed_fcc_setting_shows_connect_and_is_replaced(+ page, admin_base_url, tmp_path+):+ home = install(tmp_path)+ page.goto(admin_base_url + "/admin/integrations")+ opener = page.locator("#openDshDesktopIntegration")+ expect(opener).to_have_text("Connect")+ opener.click()+ page.locator("#confirmDshDesktopIntegration").click()+ expect(opener).to_have_text("Disconnect")+ credentials = home / ".credentials.yaml"+ credentials.write_text("version: 1\nrefs: {FCC_DSH_DESKTOP_API_KEY: edited}\n")+ page.reload()+ expect(opener).to_have_text("Connect")+ opener.click()+ page.locator("#confirmDshDesktopIntegration").click()+ expect(opener).to_have_text("Disconnect")+ assert "edited" not in credentials.read_text()diff --git a/e2e/test_integration_notices.py b/e2e/test_integration_notices.pyindex eb83f338..56290e2c 100644--- a/e2e/test_integration_notices.py+++ b/e2e/test_integration_notices.py@@ -13,6 +13,7 @@ from playwright.sync_api import expect"openClaudeDesktopIntegration","claudeDesktopIntegrationMessage",),+ ("dsh-desktop", "openDshDesktopIntegration", "dshDesktopIntegrationMessage"),])def notice(page, admin_base_url, request):@@ -28,7 +29,14 @@ def notice(page, admin_base_url, request):route.fulfill(response=response, json=payload)def status(route):- route.fulfill(json={"connected": True, "paths": None, "update": dict(progress)})+ route.fulfill(+ json={+ "connected": True,+ "configured": True,+ "paths": None,+ "update": dict(progress),+ }+ )page.route("**/admin/api/status", startup)page.route(f"**/admin/api/integrations/{integration}", status)@@ -54,10 +62,13 @@ def notice(page, admin_base_url, request):def test_notices_require_a_live_changed_completion(page, notice):- _, button, message, observe = notice+ integration, button, message, observe = noticeexpect(message).to_be_hidden()observe("starting")- expect(button).to_be_disabled()+ if integration == "dsh-desktop":+ expect(button).to_be_enabled()+ else:+ expect(button).to_be_disabled()observe("ready", changed=True)expect(message).to_be_visible()expect(message).not_to_have_class("message-area error")@@ -97,12 +108,15 @@ def test_settled_poll_after_mutation_preserves_next_action(page, notice):endpoint = f"**/admin/api/integrations/{integration}"page.route(endpoint, fail_status)dialog = page.get_by_role("dialog")- for action, connected in [("Disconnect", False), ("Connect", True)]:+ connect_label = "Connect"+ for action, connected in [("Disconnect", False), (connect_label, True)]:+ operation = "connect" if connected else "disconnect"page.route(- f"{endpoint}/{action.lower()}",+ f"{endpoint}/{operation}",lambda route: route.fulfill(json={"connected": route.request.url.endswith("/connect"),+ "configured": route.request.url.endswith("/connect"),"disconnect_pending": False,"paths": None,}@@ -111,7 +125,7 @@ def test_settled_poll_after_mutation_preserves_next_action(page, notice):button.click()dialog.get_by_role("button", name=action, exact=True).click()expect(dialog).not_to_be_visible()- next_action = "Disconnect" if connected else "Connect"+ next_action = "Disconnect" if connected else connect_labelexpect(button).to_have_text(next_action)button.click()observe("ready")@@ -177,6 +191,7 @@ def test_busy_status_recovery_preserves_notice_without_replaying_it(lambda route: route.fulfill(json={"connected": True,+ "configured": True,"paths": None,"update": {"state": "ready", "changed": True},}@@ -234,6 +249,7 @@ def test_missed_transition_during_status_read_is_reconciled(page, notice):pending[0].fulfill(json={"connected": True,+ "configured": True,"paths": None,"update": {"state": "ready", "changed": False, "message": None},}diff --git a/pyproject.toml b/pyproject.tomlindex 9b5d4306..65b1a3af 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -40,6 +40,7 @@ dependencies = ["nvidia-riva-client>=2.26.0","pyperclip>=1.11.0","sqlalchemy>=2.1.1",+ "ruamel-yaml>=0.19.1",][project.scripts]diff --git a/scripts/install.ps1 b/scripts/install.ps1index b82c65de..2608e927 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -20,8 +20,8 @@ $CodexInstallUrl = "https://chatgpt.com/codex/install.ps1"$PiInstallUrl = "https://pi.dev/install.ps1"$OpenCodeReleaseBaseUrl = "https://opencode.ai/files/bin"$HermesInstallUrl = "https://hermes-agent.nousresearch.com/install.ps1"-$DshVersion = "0.1.0-rc.8"-$DshPackage = "@deepseek-ai/dsh@$DshVersion"+$DshMinimumVersion = "0.2.0-rc.2"+$DshPackage = "@deepseek-ai/dsh@latest"$GrokInstallUrl = "https://x.ai/cli/install.ps1"$MuseInstallUrl = "https://raw.githubusercontent.com/Alishahryar1/free-claude-code/main/scripts/install-muse.ps1"$RtkVersion = "0.44.2"@@ -1114,11 +1114,45 @@ function Get-DshVersion {param([string] $DshPath)$output = Invoke-Utf8NativeCapture -FilePath $DshPath -Arguments @("--version")- $version = Convert-SemanticVersionOutput $output- if ([string]::IsNullOrWhiteSpace($version) -or (-not $version.Contains("-"))) {- throw "DeepSeek Harness is present, but 'dsh --version' did not return its preview semantic version."+ if ($output -notmatch '(?m)^\s*(?:dsh\s+)?v?(?<version>(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)\s*$') {+ throw "DeepSeek Harness is present, but 'dsh --version' did not return a semantic version."}- return $version+ return $Matches['version']+}++function Test-DshVersion {+ param([string] $Version)++ $versionParts = ($Version -replace '\+.*$', '') -split '-', 2+ $minimumParts = $DshMinimumVersion -split '-', 2+ if ($versionParts[0] -notmatch '^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$') {+ return $false+ }+ $preview = @()+ if ($versionParts.Count -gt 1) {+ $preview = @($versionParts[1] -split '\.')+ foreach ($part in $preview) {+ if ($part -notmatch '^[0-9A-Za-z-]+$' -or $part -match '^0[0-9]+$') { return $false }+ }+ }+ $release = [version] $versionParts[0]+ $minimum = [version] $minimumParts[0]+ if ($release -ne $minimum) { return $release -gt $minimum }+ if ($preview.Count -eq 0) { return $true }+ $floor = @($minimumParts[1] -split '\.')+ for ($index = 0; $index -lt [Math]::Min($preview.Count, $floor.Count); $index++) {+ $part = $preview[$index]+ $base = $floor[$index]+ if ($part -ceq $base) { continue }+ $numeric = $part -match '^[0-9]+$'+ $baseNumeric = $base -match '^[0-9]+$'+ if ($numeric -and $baseNumeric) {+ if ($part.Length -ne $base.Length) { return $part.Length -gt $base.Length }+ }+ elseif ($numeric -ne $baseNumeric) { return $baseNumeric }+ return [string]::CompareOrdinal($part, $base) -gt 0+ }+ return $preview.Count -ge $floor.Count}function Get-DshNodeVersion {@@ -1188,8 +1222,8 @@ function Confirm-DshApplication {throw "DeepSeek Harness was installed, but 'dsh' is not available on PATH."}$version = Get-DshVersion $command.Source- if ($version -ne $DshVersion) {- throw "DeepSeek Harness $DshVersion is required; found $version after installation."+ if (-not (Test-DshVersion $version)) {+ throw "DeepSeek Harness requires >=$DshMinimumVersion; found $version after installation."}Write-Host "Verified DeepSeek Harness $version."}@@ -1206,7 +1240,7 @@ function Ensure-Dsh {if ($DryRun) {if (Get-ApplicationCommand "dsh") {Write-Host "+ dsh --version"- Write-Host "The exact supported DeepSeek Harness preview will be preserved; another version will be replaced."+ Write-Host "DeepSeek Harness >=$DshMinimumVersion will be preserved; an older version will be upgraded to latest."}else {$node = Get-ApplicationCommand "node"@@ -1225,11 +1259,11 @@ function Ensure-Dsh {$command = Get-ApplicationCommand "dsh"if ($command) {$version = Get-DshVersion $command.Source- if ($version -eq $DshVersion) {- Write-Host "DeepSeek Harness $version already matches the supported preview; leaving it unchanged."+ if (Test-DshVersion $version) {+ Write-Host "DeepSeek Harness $version already satisfies >=$DshMinimumVersion; leaving it unchanged."return}- Write-Host "DeepSeek Harness $version does not match $DshVersion; replacing it with the supported preview."+ Write-Host "DeepSeek Harness requires >=$DshMinimumVersion; upgrading $version to latest."}Install-Dsh@@ -1660,7 +1694,7 @@ else {Write-Host "Run DeepSeek Harness with: fcc-dsh"}else {- Write-Host "The fcc-dsh wrapper is ready after you install DeepSeek Harness $DshVersion."+ Write-Host "The fcc-dsh wrapper is ready after you install DeepSeek Harness >=$DshMinimumVersion."}if ($script:InstallGrok) {Write-Host "Run Grok Build with: fcc-grok"diff --git a/scripts/install.sh b/scripts/install.shindex 437562a1..0ffcec5c 100644--- a/scripts/install.sh+++ b/scripts/install.sh@@ -8,8 +8,8 @@ CODEX_INSTALL_URL="https://chatgpt.com/codex/install.sh"PI_INSTALL_URL="https://pi.dev/install.sh"OPENCODE_INSTALL_URL="https://opencode.ai/v2/install"HERMES_INSTALL_URL="https://hermes-agent.nousresearch.com/install.sh"-DSH_VERSION="0.1.0-rc.8"-DSH_PACKAGE="@deepseek-ai/dsh@$DSH_VERSION"+MIN_DSH_VERSION="0.2.0-rc.2"+DSH_PACKAGE="@deepseek-ai/dsh@latest"GROK_INSTALL_URL="https://x.ai/cli/install.sh"MUSE_INSTALL_URL="https://dev.meta.ai/install.sh"RTK_VERSION="0.44.2"@@ -904,15 +904,50 @@ current_dsh_version() {fiversion=$(printf '%s\n' "$output" | awk '- match($0, /[0-9]+\.[0-9]+\.[0-9]+-[0-9A-Za-z][0-9A-Za-z.-]*/) {- print substr($0, RSTART, RLENGTH)- exit- }+ { sub(/^[[:space:]]*(dsh[[:space:]]+)?v?/, ""); sub(/[[:space:]]*$/, "") }+ /^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/ { print; exit }')[ -n "$version" ] || return 1printf '%s\n' "$version"}+dsh_version_is_supported() {+ LC_ALL=C awk -v version="$1" -v minimum="$MIN_DSH_VERSION" '+ function numeric(value) { return value ~ /^[0-9]+$/ }+ function compare(left, right) {+ if (left == right) return 0+ if (numeric(left) && numeric(right)) {+ if (length(left) != length(right)) return length(left) > length(right) ? 1 : -1+ } else if (numeric(left) != numeric(right)) return numeric(left) ? -1 : 1+ return ("x" left) > ("x" right) ? 1 : -1+ }+ BEGIN {+ sub(/\+.*/, "", version)+ dash = index(version, "-")+ core = dash ? substr(version, 1, dash - 1) : version+ count = dash ? split(substr(version, dash + 1), preview, ".") : 0+ if (split(core, release, ".") != 3) exit 1+ for (i = 1; i <= 3; i++) if (release[i] !~ /^(0|[1-9][0-9]*)$/) exit 1+ for (i = 1; i <= count; i++) {+ if (preview[i] !~ /^[0-9A-Za-z-]+$/ || preview[i] ~ /^0[0-9]+$/) exit 1+ }+ split(minimum, parts, "-")+ split(parts[1], base, ".")+ for (i = 1; i <= 3; i++) {+ diff = compare(release[i], base[i])+ if (diff) exit (diff < 0)+ }+ if (!count) exit 0+ floorCount = split(parts[2], floor, ".")+ for (i = 1; i <= count && i <= floorCount; i++) {+ diff = compare(preview[i], floor[i])+ if (diff) exit (diff < 0)+ }+ exit (count < floorCount)+ }+ '+}+current_node_version() {if output=$(node --version 2>/dev/null); then:@@ -967,8 +1002,8 @@ verify_dsh_command() {ficommand -v dsh >/dev/null 2>&1 || fail "DeepSeek Harness was installed, but 'dsh' is not available on PATH."- version=$(current_dsh_version) || fail "DeepSeek Harness is present, but 'dsh --version' did not return its preview semantic version."- [ "$version" = "$DSH_VERSION" ] || fail "DeepSeek Harness $DSH_VERSION is required; found $version after installation."+ version=$(current_dsh_version) || fail "DeepSeek Harness is present, but 'dsh --version' did not return a semantic version."+ dsh_version_is_supported "$version" || fail "DeepSeek Harness requires >=$MIN_DSH_VERSION; found $version after installation."printf 'Verified DeepSeek Harness %s.\n' "$version"}@@ -984,7 +1019,7 @@ ensure_dsh() {if [ "$dry_run" -eq 1 ]; thenif command -v dsh >/dev/null 2>&1; thenprint_command dsh --version- printf 'The exact supported DeepSeek Harness preview will be preserved; another version will be replaced.\n'+ printf 'DeepSeek Harness >=%s will be preserved; an older version will be upgraded to latest.\n' "$MIN_DSH_VERSION"elsecommand -v node >/dev/null 2>&1 || fail "DeepSeek Harness requires Node.js ^22.19.0 or >=24.0.0 and npm. Install Node.js, then rerun the installer."command -v npm >/dev/null 2>&1 || fail "DeepSeek Harness requires npm. Install npm, then rerun the installer."@@ -996,12 +1031,12 @@ ensure_dsh() {require_dsh_toolchainif command -v dsh >/dev/null 2>&1; then- version=$(current_dsh_version) || fail "DeepSeek Harness is present, but 'dsh --version' did not return its preview semantic version."- if [ "$version" = "$DSH_VERSION" ]; then- printf 'DeepSeek Harness %s already matches the supported preview; leaving it unchanged.\n' "$version"+ version=$(current_dsh_version) || fail "DeepSeek Harness is present, but 'dsh --version' did not return a semantic version."+ if dsh_version_is_supported "$version"; then+ printf 'DeepSeek Harness %s already satisfies >=%s; leaving it unchanged.\n' "$version" "$MIN_DSH_VERSION"return 0fi- printf 'DeepSeek Harness %s does not match %s; replacing it with the supported preview.\n' "$version" "$DSH_VERSION"+ printf 'DeepSeek Harness requires >=%s; upgrading %s to latest.\n' "$MIN_DSH_VERSION" "$version"fiinstall_dsh_package@@ -1515,7 +1550,7 @@ elseif [ "$install_dsh" -eq 1 ]; thenprintf 'Run DeepSeek Harness with: fcc-dsh\n'else- printf 'The fcc-dsh wrapper is ready after you install DeepSeek Harness %s.\n' "$DSH_VERSION"+ printf 'The fcc-dsh wrapper is ready after you install DeepSeek Harness >=%s.\n' "$MIN_DSH_VERSION"fiif [ "$install_grok" -eq 1 ]; thenprintf 'Run Grok Build with: fcc-grok\n'diff --git a/smoke/capabilities.py b/smoke/capabilities.pyindex a1db5ff7..ea251f21 100644--- a/smoke/capabilities.py+++ b/smoke/capabilities.py@@ -654,7 +654,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("dsh_cli_integration","dsh_cli_integration","free_claude_code.cli.launchers.dsh",- "DeepSeek Harness 0.1.0-rc.8, live FCC catalog, and process-only patch",+ "DeepSeek Harness >=0.2.0-rc.2, live FCC catalog, and process-only patch","Responses provider scoped to FCC for attached Web and headless sessions","version, proxy, catalog, or private-config failure exits before inference",(@@ -665,6 +665,29 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("test_dsh_cli_headless_e2e","test_dsh_cli_terminal_failure_e2e","test_dsh_cli_web_startup_e2e",+ "test_dsh_cli_tools_and_resume_e2e",+ "test_dsh_native_operations_e2e",+ "test_dsh_native_settings_migration_and_dump_e2e",+ ),+ ),+ CapabilityContract(+ "cli",+ "dsh_desktop_integration",+ "dsh_desktop_integration",+ "free_claude_code.harnesses.dsh_desktop_integration",+ "Initialized stock Desktop profile, FCC catalog, and proxy credentials",+ "Owned Responses route, synchronized models, and restorable new-session default",+ "Conflicts leave native settings intact and interrupted changes remain retryable",+ (+ "tests/harnesses/test_dsh_desktop_integration.py",+ "tests/harnesses/test_dsh_files.py",+ "tests/runtime/test_dsh_desktop_sync.py",+ "tests/api/test_dsh_desktop_integration.py",+ "e2e/test_dsh_desktop_integration.py",+ ),+ (+ "test_dsh_desktop_live_catalog_credentials_and_restart_e2e",+ "test_dsh_desktop_native_composition_e2e",),),CapabilityContract(diff --git a/smoke/features.py b/smoke/features.pyindex 550d3c38..cfb141b2 100644--- a/smoke/features.py+++ b/smoke/features.py@@ -211,11 +211,34 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = ("test_dsh_cli_headless_e2e","test_dsh_cli_terminal_failure_e2e","test_dsh_cli_web_startup_e2e",+ "test_dsh_cli_tools_and_resume_e2e",+ "test_dsh_native_operations_e2e",+ "test_dsh_native_settings_migration_and_dump_e2e",),("clients",),- ("DeepSeek Harness 0.1.0-rc.8",),+ ("DeepSeek Harness >=0.2.0-rc.2",),"skip only when DSH is absent; the local fake upstream must pass",),+ FeatureCoverage(+ "dsh_desktop_integration",+ "DSH Desktop uses a persistent FCC model catalog and credential",+ (+ "tests/harnesses/test_dsh_desktop_integration.py",+ "tests/harnesses/test_dsh_files.py",+ "tests/runtime/test_dsh_desktop_sync.py",+ "tests/api/test_dsh_desktop_integration.py",+ "e2e/test_dsh_desktop_integration.py",+ ),+ (),+ ("test_dsh_desktop_live_catalog_credentials_and_restart_e2e",),+ ("clients",),+ (+ "DSH Desktop >=0.2.0-rc.2",+ "Node.js",+ "FCC_SMOKE_DSH_DESKTOP_BIN for a custom installation",+ ),+ "skip when Desktop or Node is absent; native acceptance uses isolated profiles and local providers",+ ),FeatureCoverage("grok_cli_integration","Grok Build discovers FCC models and sends Responses through the proxy",diff --git a/smoke/installers/test_installers.py b/smoke/installers/test_installers.pyindex 9c280171..98190b86 100644--- a/smoke/installers/test_installers.py+++ b/smoke/installers/test_installers.py@@ -80,7 +80,7 @@ def _posix_command(name: str, *, version_output: str | None = None) -> str:"opencode": "v2.0.10","cline": "3.0.55","hermes": "0.20.4",- "dsh": "0.1.0-rc.8",+ "dsh": "0.2.0-rc.2","grok": "1.0.5","muse": "0.2.1","node": "22.19.0",@@ -132,7 +132,7 @@ if [ "${1:-}" = "install" ] && [ "${2:-}" = "-g" ] && [ "${3:-}" = "cline" ]; thchmod +x "$FAKE_NPM_PREFIX/bin/cline"exit 0fi-if [ "${1:-}" = "install" ] && [ "${2:-}" = "-g" ] && [ "${3:-}" = "@deepseek-ai/[email protected]" ]; then+if [ "${1:-}" = "install" ] && [ "${2:-}" = "-g" ] && [ "${3:-}" = "@deepseek-ai/dsh@latest" ]; then[ "$FAIL_STEP" = "dsh-install" ] && exit 73mkdir -p "$FAKE_NPM_PREFIX/bin"cp "$FAKE_FIXTURES/dsh-command.sh" "$FAKE_NPM_PREFIX/bin/dsh"@@ -826,7 +826,7 @@ def test_install_sh_fresh_install_is_verified(posix_harness: PosixHarness) -> Noassert calls.index("hermes-install:--non-interactive --skip-setup") < calls.index("hermes:--version")- assert calls.index("npm:install -g @deepseek-ai/[email protected]") < calls.index(+ assert calls.index("npm:install -g @deepseek-ai/dsh@latest") < calls.index("dsh:--version")assert calls.index("grok-install") < calls.index("grok:--version")@@ -1075,7 +1075,7 @@ def test_install_sh_rejects_broken_existing_aider_without_replacing_it(assert not any("aider.chat" in call for call in calls)-def test_install_sh_installs_selected_dsh_at_exact_preview(+def test_install_sh_installs_latest_selected_dsh(posix_harness: PosixHarness,) -> None:(posix_harness.bin_dir / "opencode").unlink()@@ -1083,8 +1083,8 @@ def test_install_sh_installs_selected_dsh_at_exact_preview(assert result.returncode == 0, result.stdoutcalls = posix_harness.calls()- assert "npm:install -g @deepseek-ai/[email protected]" in calls- assert calls.index("npm:install -g @deepseek-ai/[email protected]") < calls.index(+ assert "npm:install -g @deepseek-ai/dsh@latest" in calls+ assert calls.index("npm:install -g @deepseek-ai/dsh@latest") < calls.index("dsh:--version")assert "Run DeepSeek Harness with: fcc-dsh" in result.stdout@@ -1092,13 +1092,13 @@ def test_install_sh_installs_selected_dsh_at_exact_preview(@pytest.mark.parametrize("interactive", (False, True))-def test_install_sh_replaces_mismatched_dsh_preview(+def test_install_sh_upgrades_older_dsh_to_latest(posix_harness: PosixHarness,interactive: bool,) -> None:_write_executable(posix_harness.bin_dir / "dsh",- _posix_command("dsh").replace("0.1.0-rc.8", "0.1.0-rc.7"),+ _posix_command("dsh").replace("0.2.0-rc.2", "0.1.0-rc.7"),)result = (@@ -1106,8 +1106,8 @@ def test_install_sh_replaces_mismatched_dsh_preview()assert result.returncode == 0, result.stdout + result.stderr- assert "does not match 0.1.0-rc.8" in result.stdout- assert "npm:install -g @deepseek-ai/[email protected]" in posix_harness.calls()+ assert "requires >=0.2.0-rc.2" in result.stdout+ assert "npm:install -g @deepseek-ai/dsh@latest" in posix_harness.calls()def test_install_sh_rejects_exact_dsh_on_unsupported_node(@@ -2007,7 +2007,7 @@ def _batch_client(name: str, *, version_output: str | None = None) -> str:"opencode": "v2.0.10","cline": "3.0.55","hermes": "0.20.4",- "dsh": "0.1.0-rc.8",+ "dsh": "0.2.0-rc.2","grok": "1.0.5","muse": "0.2.1","node": "22.19.0",@@ -2017,7 +2017,7 @@ def _batch_client(name: str, *, version_output: str | None = None) -> str:elif name == "hermes":version_command = (f'if "%1"=="--version" echo Hermes Agent v{version} '- "(2026.8.18) · upstream deadbeef\n"+ "(2026.8.18) · upstream deadbeef\n"'if "%1"=="--version" echo Install directory: C:\\fake-hermes\n''if "%1"=="--version" echo Install method: git\n''if "%1"=="--version" echo Python: 3.12.11\n'@@ -2062,7 +2062,7 @@ def _batch_npm() -> str:return r"""@echo offecho npm:%*>>"%CALL_LOG%"if "%1"=="install" if "%2"=="-g" if "%3"=="cline" goto install_cline-if "%1"=="install" if "%2"=="-g" if "%3"=="@deepseek-ai/[email protected]" goto install_dsh+if "%1"=="install" if "%2"=="-g" if "%3"=="@deepseek-ai/dsh@latest" goto install_dshif "%1"=="prefix" if "%2"=="-g" echo %FAKE_NPM_PREFIX%& exit /b 0if "%1"=="config" if "%2"=="get" if "%3"=="prefix" echo %FAKE_NPM_PREFIX%& exit /b 0exit /b 71@@ -2851,7 +2851,7 @@ def _assert_setup_preserves_other_commands(if installing == "dsh":_write_executable(npm_bin / f"dsh{suffix}",- make_command("dsh").replace("0.1.0-rc.8", "0.1.0-rc.7"),+ make_command("dsh").replace("0.2.0-rc.2", "0.1.0-rc.7"),)installed.add("dsh")answers = [@@ -3174,7 +3174,7 @@ def test_install_ps1_fresh_install_is_verified(assert calls.index("npm:install -g cline") < calls.index("cline:--version")assert any("hermes-agent.nousresearch.com/install.ps1" in call for call in calls)assert "hermes-install:True" in calls- assert calls.index("npm:install -g @deepseek-ai/[email protected]") < calls.index(+ assert calls.index("npm:install -g @deepseek-ai/dsh@latest") < calls.index("dsh:--version")assert calls.index("grok-install") < calls.index("grok:--version")@@ -3422,31 +3422,35 @@ def test_install_ps1_rejects_broken_existing_aider_without_replacing_it(assert not any("aider.chat" in call for call in calls)-def test_install_ps1_preserves_exact_dsh_preview(+ "version", ["0.2.0-rc.2", "0.2.0-rc.10", "0.2.0", "1.0.0", "0.2.0-rc.2+build.7"]+)+def test_install_ps1_preserves_supported_dsh(powershell_harness: PowerShellHarness,+ version: str,) -> None:powershell_harness.add_uv("0.12.13")- powershell_harness.add_client("dsh")+ (powershell_harness.bin_dir / "dsh.cmd").write_text(+ _batch_client("dsh").replace("0.2.0-rc.2", version), encoding="utf-8"+ )result = powershell_harness.run_functions("Add-KnownBinDirectories\nEnsure-Uv\nEnsure-Dsh")assert result.returncode == 0, result.stderr- assert "already matches the supported preview" in result.stdout- assert "npm:install -g @deepseek-ai/[email protected]" not in (- powershell_harness.calls()- )+ assert "already satisfies >=0.2.0-rc.2" in result.stdout+ assert "npm:install -g @deepseek-ai/dsh@latest" not in (powershell_harness.calls())@pytest.mark.parametrize("interactive", (False, True))-def test_install_ps1_replaces_mismatched_dsh_preview(+def test_install_ps1_upgrades_older_dsh_to_latest(powershell_harness: PowerShellHarness,interactive: bool,) -> None:powershell_harness.add_uv("0.12.13")(powershell_harness.bin_dir / "dsh.cmd").write_text(- _batch_client("dsh").replace("0.1.0-rc.8", "0.1.0-rc.7"),+ _batch_client("dsh").replace("0.2.0-rc.2", "0.1.0-rc.7"),encoding="utf-8",)@@ -3459,8 +3463,8 @@ def test_install_ps1_replaces_mismatched_dsh_preview()assert result.returncode == 0, result.stdout + result.stderr- assert "does not match 0.1.0-rc.8" in result.stdout- assert "npm:install -g @deepseek-ai/[email protected]" in (powershell_harness.calls())+ assert "requires >=0.2.0-rc.2" in result.stdout+ assert "npm:install -g @deepseek-ai/dsh@latest" in (powershell_harness.calls())def test_install_ps1_rejects_exact_dsh_on_unsupported_node(@@ -3491,7 +3495,7 @@ def test_install_ps1_rejects_incompatible_node_for_selected_dsh() -> None:powershell_harness.add_uv("0.12.13")(powershell_harness.bin_dir / "dsh.cmd").write_text(- _batch_client("dsh").replace("0.1.0-rc.8", "0.1.0-rc.7"),+ _batch_client("dsh").replace("0.2.0-rc.2", "0.1.0-rc.7"),encoding="utf-8",)(powershell_harness.bin_dir / "node.cmd").write_text(diff --git a/smoke/lib/dsh_desktop.cjs b/smoke/lib/dsh_desktop.cjsnew file mode 100644index 00000000..06339fc9--- /dev/null+++ b/smoke/lib/dsh_desktop.cjs@@ -0,0 +1,96 @@+// Installed Electron acceptance driver. Each run owns its home and user-data directory.+const fs = require('node:fs');+const path = require('node:path');+const readline = require('node:readline');+const { _electron } = require(process.argv[2]);+const options = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));+const input = readline.createInterface({ input: process.stdin });+let app;++// The Python controller interrupts this process when an assertion fails.+// Let Electron close before exiting so the next test can use its native port.+for (const signal of ['SIGINT', 'SIGTERM', ...(process.platform === 'win32' ? ['SIGBREAK'] : [])]) {+ process.once(signal, () => {+ void (async () => {+ try { if (app) await app.close(); }+ finally { process.exit(1); }+ })();+ });+}++function host(action) {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error(`Host did not finish ${action}`)), 45000);+ input.once('line', line => { clearTimeout(timer); resolve(JSON.parse(line)); });+ process.stdout.write(JSON.stringify({ action }) + '\n');+ });+}++async function launch() {+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const app = await _electron.launch({+ executablePath: options.executable,+ args: [`--user-data-dir=${options.userData}`],+ env,+ timeout: 45000,+ });+ app.on('window', () => {+ void app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().forEach(w => w.hide()));+ });+ return app;+}++async function turn(window, label, marker, newSession = true) {+ await window.getByText(label, { exact: true }).waitFor({ timeout: 30000 });+ const composer = window.locator('[contenteditable="true"]');+ if (newSession) {+ const previous = await composer.elementHandle();+ await window.getByRole('button', { name: 'New session', exact: true }).last().click();+ // Native session creation is asynchronous and replaces the session-scoped editor.+ await previous.waitForElementState('hidden');+ await previous.dispose();+ }+ await composer.click();+ await window.keyboard.insertText(`Read the local fixture and reply ${marker}`);+ await window.getByRole('button', { name: 'Send message', exact: true }).click();+ await window.getByText(marker, { exact: true }).waitFor({ timeout: 30000 });+}++(async () => {+ try {+ app = await launch();+ let window = await app.firstWindow();+ if (options.phase === 'initialize') {+ // The shell window can precede profile initialization by a few events.+ const manifest = path.join(process.env.DSH_HOME, 'profiles/desktop/package.json');+ const deadline = Date.now() + 30000;+ while (!fs.existsSync(manifest)) {+ if (Date.now() >= deadline) throw new Error('Desktop did not initialize its profile');+ await new Promise(resolve => setTimeout(resolve, 50));+ }+ return;+ }+ await turn(window, 'FCC Desktop Fixture', 'FCC_DESKTOP_DONE', false);+ await host('refresh');+ await turn(window, 'FCC Updated Fixture', 'FCC_DESKTOP_UPDATED');+ await window.screenshot({ path: path.join(options.artifacts, 'desktop-connected.png') });+ await app.close();+ app = await launch();+ window = await app.firstWindow();+ await turn(window, 'FCC Updated Fixture', 'FCC_DESKTOP_UPDATED');+ await host('disconnect');+ await window.getByRole('button', { name: 'New session', exact: true }).last().click();+ await window.getByText('FCC Updated Fixture', { exact: true }).waitFor({ state: 'hidden', timeout: 30000 });+ await host('reconnect');+ await turn(window, 'FCC Updated Fixture', 'FCC_DESKTOP_UPDATED', false);+ await host('final_disconnect');+ await window.getByRole('button', { name: 'New session', exact: true }).last().click();+ await window.getByText('FCC Updated Fixture', { exact: true }).waitFor({ state: 'hidden', timeout: 30000 });+ await window.screenshot({ path: path.join(options.artifacts, 'desktop-disconnected.png') });+ process.stdout.write(JSON.stringify({ completed: true }) + '\n');+ } finally {+ if (app) await app.close();+ input.close();+ }+})().catch(error => { console.error(error); process.exitCode = 1; });diff --git a/smoke/lib/dsh_provider.py b/smoke/lib/dsh_provider.pynew file mode 100644index 00000000..f8921ba2--- /dev/null+++ b/smoke/lib/dsh_provider.py@@ -0,0 +1,293 @@+"""A deterministic local model for native DSH protocol and title smoke tests."""++import json+import threading+from collections.abc import Iterator+from contextlib import contextmanager+from dataclasses import dataclass, field+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Literal++from free_claude_code.core.json_types import JsonObject+++@dataclass+class DshProvider:+ model: str+ marker: str+ failure: Literal["none", "main", "title"] = "none"+ read_path: str | None = None+ tool_call: tuple[str, JsonObject] | None = None+ protocol: Literal["chat", "responses"] = "chat"+ hold_release: threading.Event | None = None+ hold_started: threading.Event = field(default_factory=threading.Event)+ requests: list[JsonObject] = field(default_factory=list)+ title_started: threading.Event = field(default_factory=threading.Event)+ title_finished: threading.Event = field(default_factory=threading.Event)++ def purpose(self, body: JsonObject) -> str:+ messages = body.get("messages", body.get("input"))+ if str(body.get("instructions", "")).startswith(+ "Create a concise title for an AI coding-assistant session"+ ):+ return "title"+ if isinstance(messages, list) and messages:+ if "You are now acting as a compaction engine" in str(messages[-1]):+ return "compaction"+ first = messages[0]+ if isinstance(+ first, dict+ ) and "Create a concise title for an AI coding-assistant session" in str(+ first.get("content", "")+ ):+ assert body.get("max_tokens", body.get("max_output_tokens")) == 64+ assert not body.get("tools")+ return "title"+ if any(+ isinstance(message, dict)+ and message.get("role") == "user"+ and "FCC_CHILD_TASK" in str(message.get("content", ""))+ for message in messages+ ):+ return "subagent"+ return "main"+++@contextmanager+def dsh_provider(scenario: DshProvider) -> Iterator[str]:+ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def do_GET(self) -> None:+ if self.path == "/v1/models":+ self.json_response(+ 200, {"data": [{"id": scenario.model, "object": "model"}]}+ )+ elif self.path == "/api/v0/models":+ self.json_response(200, {"data": []})+ elif self.path.startswith("/api/v1/models?"):+ self.json_response(+ 200,+ {+ "success": True,+ "output": {+ "total": 1,+ "page_no": 1,+ "models": [+ {+ "model": scenario.model,+ "features": ["function-calling"],+ "capabilities": ["TG", "VU"],+ "inference_metadata": {+ "request_modality": ["TEXT", "IMAGE"]+ },+ "model_info": {+ "context_window": 200000,+ "max_output_tokens": 4096,+ },+ }+ ],+ },+ },+ )+ else:+ self.json_response(404, {"error": "not found"})++ def do_POST(self) -> None:+ body = json.loads(+ self.rfile.read(int(self.headers.get("content-length", "0")))+ )+ purpose = scenario.purpose(body)+ scenario.requests.append(+ {"path": self.path, "purpose": purpose, "body": body}+ )+ try:+ if purpose == "title":+ scenario.title_started.set()+ elif purpose == "main" and not scenario.title_started.wait(10):+ self.json_response(+ 500,+ {"error": {"message": "Native title request did not arrive"}},+ )+ return+ if scenario.failure == purpose:+ self.json_response(+ 400,+ {+ "error": {+ "type": "invalid_request_error",+ "message": "DSH fixture rejected this request",+ }+ },+ )+ return+ self.send_response(200)+ self.send_header("content-type", "text/event-stream")+ self.send_header("connection", "close")+ self.end_headers()+ if scenario.protocol == "responses":+ self.responses_stream(+ "Local fixture task" if purpose == "title" else scenario.marker+ )+ elif purpose == "title":+ self.chunk({"role": "assistant", "content": "Local fixture task"})+ self.chunk({}, "stop")+ elif purpose == "subagent":+ self.chunk({"role": "assistant", "content": "FCC_CHILD_DONE"})+ self.chunk({}, "stop")+ elif purpose == "compaction":+ self.chunk(+ {+ "role": "assistant",+ "content": "## Current Work\nThe fixture task succeeded. Continue the local smoke check.",+ }+ )+ self.chunk({}, "stop")+ elif (scenario.read_path or scenario.tool_call) and not any(+ message.get("role") == "tool" for message in body["messages"]+ ):+ self.chunk(+ {+ "role": "assistant",+ "reasoning_content": "Reading the local fixture.",+ }+ )+ self.chunk(+ {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_fixture_read",+ "type": "function",+ "function": {+ "name": scenario.tool_call[0]+ if scenario.tool_call+ else "read",+ "arguments": json.dumps(+ scenario.tool_call[1]+ if scenario.tool_call+ else {"file_path": scenario.read_path}+ ),+ },+ }+ ]+ }+ )+ self.chunk({}, "tool_calls")+ else:+ self.chunk({"role": "assistant", "content": scenario.marker})+ if scenario.hold_release is not None:+ scenario.hold_started.set()+ scenario.hold_release.wait(30)+ self.chunk({}, "stop")+ self.wfile.write(b"data: [DONE]\n\n")+ self.wfile.flush()+ except BrokenPipeError, ConnectionResetError, ConnectionAbortedError:+ # DSH can cancel title work while closing a one-shot runtime.+ pass+ finally:+ if purpose == "title":+ scenario.title_finished.set()+ self.close_connection = True++ def responses_stream(self, text: str) -> None:+ message = {+ "id": "msg_fixture",+ "type": "message",+ "role": "assistant",+ "status": "completed",+ "content": [{"type": "output_text", "text": text, "annotations": []}],+ }+ response = {+ "id": "resp_fixture",+ "object": "response",+ "created_at": 0,+ "status": "completed",+ "model": scenario.model,+ "output": [message],+ "usage": {"input_tokens": 10, "output_tokens": 3, "total_tokens": 13},+ }+ events = [+ {+ "type": "response.created",+ "response": {**response, "status": "in_progress", "output": []},+ },+ {+ "type": "response.output_item.added",+ "output_index": 0,+ "item": {**message, "status": "in_progress", "content": []},+ },+ {+ "type": "response.content_part.added",+ "item_id": "msg_fixture",+ "output_index": 0,+ "content_index": 0,+ "part": {"type": "output_text", "text": "", "annotations": []},+ },+ {+ "type": "response.output_text.delta",+ "item_id": "msg_fixture",+ "output_index": 0,+ "content_index": 0,+ "delta": text,+ },+ {+ "type": "response.output_text.done",+ "item_id": "msg_fixture",+ "output_index": 0,+ "content_index": 0,+ "text": text,+ },+ {+ "type": "response.content_part.done",+ "item_id": "msg_fixture",+ "output_index": 0,+ "content_index": 0,+ "part": message["content"][0],+ },+ {+ "type": "response.output_item.done",+ "output_index": 0,+ "item": message,+ },+ {"type": "response.completed", "response": response},+ ]+ for sequence, event in enumerate(events):+ self.wfile.write(+ f"event: {event['type']}\ndata: {json.dumps(event | {'sequence_number': sequence})}\n\n".encode()+ )+ self.wfile.flush()++ def chunk(self, delta: JsonObject, finish: str | None = None) -> None:+ payload = {+ "id": "chatcmpl-dsh-fixture",+ "object": "chat.completion.chunk",+ "created": 0,+ "model": scenario.model,+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],+ }+ self.wfile.write(f"data: {json.dumps(payload)}\n\n".encode())+ self.wfile.flush()++ def json_response(self, status: int, value: object) -> None:+ body = json.dumps(value).encode()+ self.send_response(status)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", str(len(body)))+ self.send_header("connection", "close")+ self.end_headers()+ self.wfile.write(body)+ self.close_connection = True++ def log_message(self, format: str, *args: object) -> None:+ return++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_address[1]}/v1"+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)diff --git a/smoke/product/test_client_product_live.py b/smoke/product/test_client_product_live.pyindex 03405673..ade178b3 100644--- a/smoke/product/test_client_product_live.py+++ b/smoke/product/test_client_product_live.py@@ -1,5 +1,6 @@import jsonimport os+import reimport shutilimport signalimport subprocess@@ -14,6 +15,7 @@ from pathlib import Pathimport httpximport pytest+from playwright.sync_api import Pagefrom free_claude_code.config.paths import managed_env_pathfrom free_claude_code.config.provider_catalog import PROVIDER_CATALOG@@ -21,6 +23,7 @@ from free_claude_code.core.json_types import JsonObject, JsonValuefrom smoke.lib.child_process import cmd_python_cfrom smoke.lib.claude_cli_matrix import run_claude_clifrom smoke.lib.config import SmokeConfig+from smoke.lib.dsh_provider import DshProvider, dsh_providerfrom smoke.lib.e2e import (ClientProtocolDriver,ConversationDriver,@@ -525,11 +528,9 @@ def test_dsh_cli_headless_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> Noneauth_token = smoke_config.settings.proxy_auth_tokencredential_env_keys = _provider_credential_env_keys()+ scenario = DshProvider(model_id, marker)with (- _successful_openai_provider(model_id=model_id, marker=marker) as (- provider_base_url,- provider_requests,- ),+ dsh_provider(scenario) as provider_base_url,SmokeServerDriver(smoke_config,name="product-dsh-cli-headless",@@ -564,17 +565,24 @@ def test_dsh_cli_headless_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> None)server_log = server.log_path.read_text(encoding="utf-8", errors="replace")+ (tmp_path / "dsh-provider-requests.json").write_text(+ json.dumps(scenario.requests, indent=2), encoding="utf-8"+ )combined = f"{result.stdout}\n{result.stderr}"assert result.returncode == 0, result.stderr or result.stdoutassert result.stdout.strip() == markerassert auth_token not in combinedassert "GET /v1/models" in server_log- assert server_log.count("POST /v1/responses") == 1+ assert "POST /v1/responses" in server_logassert "POST /v1/chat/completions" not in server_log- assert [request["path"] for request in provider_requests] == [- "/v1/chat/completions"- ]- provider_body = provider_requests[0]["body"]+ assert scenario.title_finished.is_set()+ assert [request["purpose"] for request in scenario.requests].count("title") == 1+ main = [request for request in scenario.requests if request["purpose"] == "main"]+ assert len(main) == 1+ assert all(+ request["path"] == "/v1/chat/completions" for request in scenario.requests+ )+ provider_body = main[0]["body"]assert isinstance(provider_body, dict)assert provider_body["model"] == model_id@@ -592,11 +600,9 @@ def test_dsh_cli_terminal_failure_e2e(full_model = "lmstudio/fcc-smoke-failing-model"auth_token = smoke_config.settings.proxy_auth_tokencredential_env_keys = _provider_credential_env_keys()+ scenario = DshProvider("fcc-smoke-failing-model", "unused", failure="main")with (- _deliberately_failing_openai_provider() as (- provider_base_url,- provider_requests,- ),+ dsh_provider(scenario) as provider_base_url,SmokeServerDriver(smoke_config,name="product-dsh-cli-provider-error",@@ -634,12 +640,139 @@ def test_dsh_cli_terminal_failure_e2e(combined = f"{result.stdout}\n{result.stderr}"assert result.returncode != 0assert auth_token not in combined- assert server_log.count("POST /v1/responses") == 1- assert provider_requests == ["/v1/chat/completions"]+ assert "POST /v1/responses" in server_log+ assert [request["purpose"] for request in scenario.requests].count("main") == 1+ assert [request["purpose"] for request in scenario.requests].count("title") == 1+ assert scenario.title_finished.is_set()@pytest.mark.smoke_target("clients")-def test_dsh_cli_web_startup_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> None:[email protected]("title_failure", [False, True])+def test_dsh_cli_tools_and_resume_e2e(+ smoke_config: SmokeConfig,+ tmp_path: Path,+ title_failure: bool,+) -> None:+ if not shutil.which("dsh") or not (uv_bin := shutil.which("uv")):+ pytest.skip("missing_env: DeepSeek Harness and uv are required")+ witness = tmp_path / "witness.txt"+ witness.write_text("FCC_NATIVE_TOOL_WITNESS", encoding="utf-8")+ model_id = "fcc-smoke-dsh-tools"+ full_model = f"lmstudio/{model_id}"+ scenario = DshProvider(+ model_id,+ "FCC_TOOL_DONE",+ failure="title" if title_failure else "none",+ read_path=str(witness),+ )+ credentials = _provider_credential_env_keys()+ with (+ dsh_provider(scenario) as provider_url,+ SmokeServerDriver(+ smoke_config,+ name="product-dsh-tools",+ env_overrides=_local_provider_overrides(full_model, provider_url),+ env_unset=credentials,+ ).run() as server,+ ):+ env = _isolated_dsh_env(+ tmp_path=tmp_path,+ server_port=server.port,+ auth_token=smoke_config.settings.proxy_auth_token,+ credential_env_keys=credentials,+ )+ patch = tmp_path / "reasoning.patch.yml"+ patch.write_text(+ json.dumps(+ [+ {+ "id": "agent-default-model",+ "config": {+ "provider": "free-claude-code",+ "model": full_model,+ "reasoningEffort": "high",+ },+ }+ ]+ ),+ encoding="utf-8",+ )+ command = [+ uv_bin,+ "run",+ "--project",+ str(smoke_config.root),+ "--no-sync",+ "fcc-dsh",+ "headless",+ "--patch",+ str(patch),+ "--json",+ ]+ first = subprocess.run(+ [*command, "Read witness.txt and reply FCC_TOOL_DONE"],+ cwd=tmp_path,+ env=env,+ capture_output=True,+ text=True,+ timeout=smoke_config.timeout_s + 30,+ )+ assert first.returncode == 0, first.stdout + first.stderr+ events = _json_object_lines(first.stdout)+ (tmp_path / "dsh-tool-events.json").write_text(+ json.dumps(events, indent=2), encoding="utf-8"+ )+ assert any(+ event.get("type") == "thinking"+ and event.get("text") == "Reading the local fixture."+ for event in events+ )+ assert any(+ event.get("type") == "tool_result"+ and "FCC_NATIVE_TOOL_WITNESS" in str(event.get("result"))+ for event in events+ )+ assert any(+ event.get("type") == "final" and event.get("text") == "FCC_TOOL_DONE"+ for event in events+ )+ session_id = next(+ event["sessionId"] for event in events if event.get("type") == "session"+ )+ assert isinstance(session_id, str)+ assert scenario.title_finished.is_set()+ before_resume = len(scenario.requests)+ resumed = subprocess.run(+ [*command, "--session-id", session_id, "Continue the same task."],+ cwd=tmp_path,+ env=env,+ capture_output=True,+ text=True,+ timeout=smoke_config.timeout_s + 30,+ )+ assert resumed.returncode == 0, resumed.stdout + resumed.stderr+ resumed_events = _json_object_lines(resumed.stdout)+ assert any(+ event.get("type") == "final" and event.get("text") == "FCC_TOOL_DONE"+ for event in resumed_events+ )+ (tmp_path / "dsh-tool-requests.json").write_text(+ json.dumps(scenario.requests, indent=2), encoding="utf-8"+ )+ main = [request for request in scenario.requests if request["purpose"] == "main"]+ assert len(main) == 3+ assert [request["purpose"] for request in scenario.requests].count("title") == 1+ assert all(+ request["purpose"] == "main" for request in scenario.requests[before_resume:]+ )+ assert "FCC_NATIVE_TOOL_WITNESS" in json.dumps(main[-1]["body"])++[email protected]_target("clients")[email protected]("workflow", ["chat", "cancel", "approval", "compact"])+def test_dsh_cli_web_startup_e2e(+ smoke_config: SmokeConfig, tmp_path: Path, page: Page, workflow: str+) -> None:if not shutil.which("dsh"):pytest.skip("missing_env: DeepSeek Harness not found")uv_bin = shutil.which("uv")@@ -651,11 +784,23 @@ def test_dsh_cli_web_startup_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> Nauth_token = smoke_config.settings.proxy_auth_tokencredential_env_keys = _provider_credential_env_keys()web_port = find_free_port()+ scenario = DshProvider(model_id, "FCC_WEB_DONE")+ if workflow == "cancel":+ scenario.hold_release = threading.Event()+ elif workflow == "approval":+ scenario.tool_call = (+ "pwsh" if os.name == "nt" else "bash",+ {+ "command": "Write-Output 'FCC_APPROVAL_DONE'"+ if os.name == "nt"+ else "printf FCC_APPROVAL_DONE",+ "description": "Print a local approval fixture marker",+ "sandbox_permissions": "danger-full-access",+ "justification": "Allow this local smoke test to print its fixed marker.",+ },+ )with (- _successful_openai_provider(model_id=model_id, marker="unused") as (- provider_base_url,- provider_requests,- ),+ dsh_provider(scenario) as provider_base_url,SmokeServerDriver(smoke_config,name="product-dsh-cli-web",@@ -669,6 +814,26 @@ def test_dsh_cli_web_startup_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> Nauth_token=auth_token,credential_env_keys=credential_env_keys,)+ patches = []+ if workflow == "compact":+ patch = tmp_path / "compact.patch.yml"+ patch.write_text(+ json.dumps(+ [+ {+ "id": "compaction-basic",+ "config": {+ "retainTokens": 32,+ "headroomTokens": 1024,+ "maxTokens": 512,+ "auto": False,+ },+ }+ ]+ ),+ encoding="utf-8",+ )+ patches = ["--patch", str(patch)]command = [uv_bin,"run",@@ -677,11 +842,24 @@ def test_dsh_cli_web_startup_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> N"--no-sync","fcc-dsh","web",+ *patches,"--no-open","--port",str(web_port),]- process = _start_attached_process(command, cwd=tmp_path, env=env)+ log_path = tmp_path / "dsh-web.log"+ output = log_path.open("w", encoding="utf-8")+ process = subprocess.Popen(+ command,+ cwd=tmp_path,+ env=env,+ stdout=output,+ stderr=output,+ text=True,+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0,+ start_new_session=os.name != "nt",+ )+ startup_error = Nonetry:_wait_for_web_root(process,@@ -689,14 +867,101 @@ def test_dsh_cli_web_startup_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> Ntimeout_s=smoke_config.timeout_s + 30,)assert process.poll() is None+ deadline = time.monotonic() + 10+ login = None+ while time.monotonic() < deadline:+ login = re.search(+ r"dsh web: (http://\S+)", log_path.read_text(encoding="utf-8")+ )+ if login:+ break+ time.sleep(0.1)+ assert login is not None, "DSH did not print its authenticated browser URL"+ page.goto(login[1])+ page.get_by_role("button", name="Continue", exact=True).click(timeout=30000)+ page.get_by_text("Preview Notice", exact=True).wait_for(+ state="hidden", timeout=30000+ )+ composer = page.locator('[contenteditable="true"]')+ composer.wait_for(timeout=30000)+ assert "token=" not in page.url+ composer.click()+ page.keyboard.insert_text(+ "Remember these fixture facts: " + "recorded fact " * 200+ if workflow == "compact"+ else "Reply FCC_WEB_DONE"+ )+ page.get_by_role("button", name="Send message", exact=True).click()+ if workflow == "approval":+ page.get_by_role("button", name="Allow once", exact=True).click(+ timeout=30000+ )+ if workflow == "cancel":+ assert scenario.hold_started.wait(10)+ assert scenario.hold_release is not None+ page.get_by_role("button", name="Stop generating", exact=True).click()+ page.get_by_role("button", name="Stop generating", exact=True).wait_for(+ state="hidden", timeout=10000+ )+ scenario.hold_release.set()+ else:+ page.get_by_text("FCC_WEB_DONE", exact=True).wait_for(timeout=30000)+ if workflow == "compact":+ composer.click()+ page.keyboard.insert_text("Remember the second fixture turn.")+ page.get_by_role("button", name="Send message", exact=True).click()+ page.get_by_text("FCC_WEB_DONE", exact=True).nth(1).wait_for(+ timeout=30000+ )+ composer.click()+ composer.press_sequentially("/compact")+ composer.press("Enter")+ page.get_by_text(re.compile(r"Compacted \d+ history items")).wait_for(+ timeout=30000+ )+ scenario.marker = "FCC_AFTER_COMPACTION"+ composer.click()+ page.keyboard.insert_text("Finish after compaction.")+ page.get_by_role("button", name="Send message", exact=True).click()+ page.get_by_text("FCC_AFTER_COMPACTION", exact=True).wait_for(+ timeout=30000+ )+ except AssertionError as exc:+ startup_error = excfinally:- stdout, stderr = _stop_attached_process(process)+ if scenario.hold_release is not None:+ scenario.hold_release.set()+ page.screenshot(path=str(tmp_path / "dsh-web.png"))+ (tmp_path / "dsh-web-body.txt").write_text(+ page.locator("body").inner_text(), encoding="utf-8"+ )+ _stop_attached_process(process)+ output.close()+ stdout = log_path.read_text(encoding="utf-8")+ stderr = ""+ if startup_error is not None:+ raise AssertionError(+ f"{startup_error}\n{stdout}\n{stderr}"+ ) from startup_errorserver_log = server.log_path.read_text(encoding="utf-8", errors="replace")assert process.poll() is not Noneassert auth_token not in f"{stdout}\n{stderr}"assert "GET /v1/models" in server_log- assert provider_requests == []+ (tmp_path / "dsh-web-requests.json").write_text(+ json.dumps(scenario.requests, indent=2), encoding="utf-8"+ )+ main = [+ request["body"] for request in scenario.requests if request["purpose"] == "main"+ ]+ assert len(main) == (+ 3 if workflow == "compact" else 2 if workflow == "approval" else 1+ )+ if workflow == "compact":+ assert sum(item["purpose"] == "compaction" for item in scenario.requests) == 1+ assert "compacted-summary" in json.dumps(main[-1])+ if workflow == "approval":+ assert "FCC_APPROVAL_DONE" in json.dumps(main[-1])@pytest.mark.smoke_target("clients")@@ -1207,6 +1472,36 @@ def _isolated_dsh_env(dsh_home = tmp_path / "dsh-home"isolated_home.mkdir(exist_ok=True)dsh_home.mkdir(exist_ok=True)+ # DSH otherwise resolves the OS Documents folder even with an isolated HOME.+ storage = dsh_home / "storages"+ storage.mkdir(exist_ok=True)+ workspace_id = str(uuid.uuid4())+ (storage / "workspace.json").write_text(+ json.dumps(+ {+ "unit": {"name": "workspace", "version": 2},+ "global": {+ "initialized": True,+ "workspaceIds": [workspace_id],+ "archivedSessionIds": [],+ "pinnedSessionIds": [],+ "defaultWorkspaceId": workspace_id,+ },+ "tables": {+ "workspaces": {+ workspace_id: {+ "path": str(tmp_path),+ "title": "Smoke workspace",+ "sessionIds": [],+ "createdAt": "2026-01-01T00:00:00.000Z",+ "updatedAt": "2026-01-01T00:00:00.000Z",+ }+ }+ },+ }+ ),+ encoding="utf-8",+ )env = os.environ.copy()for key in credential_env_keys:@@ -1262,7 +1557,8 @@ def _wait_for_web_root(breaktry:response = httpx.get(url, timeout=2.0, follow_redirects=True)- if response.status_code == HTTPStatus.OK:+ # DSH now protects the Web root with its per-launch browser token.+ if response.status_code in (HTTPStatus.OK, HTTPStatus.UNAUTHORIZED):returnlast_error = f"HTTP {response.status_code}: {response.text[:200]}"except httpx.HTTPError as exc:diff --git a/smoke/product/test_dsh_desktop_live.py b/smoke/product/test_dsh_desktop_live.pynew file mode 100644index 00000000..4e23f668--- /dev/null+++ b/smoke/product/test_dsh_desktop_live.py@@ -0,0 +1,374 @@+"""Real installed DSH Desktop, isolated profiles, and scripted local inference."""++import copy+import json+import os+import queue+import shutil+import subprocess+import sys+import threading+from pathlib import Path++import playwright+import pytest++from free_claude_code.application.model_catalog import CatalogModel, ModelCatalog+from free_claude_code.harnesses import dsh_desktop_integration as desktop+from free_claude_code.harnesses import dsh_files+from smoke.lib.config import SmokeConfig+from smoke.lib.dsh_provider import DshProvider, dsh_provider+from smoke.lib.e2e import SmokeServerDriver+from smoke.product.test_client_product_live import (+ _isolated_dsh_env,+ _local_provider_overrides,+ _provider_credential_env_keys,+ _start_attached_process,+ _stop_attached_process,+)++pytestmark = [pytest.mark.live, pytest.mark.smoke_target("clients")]++[email protected]("copied_config", [False, True])+def test_dsh_desktop_native_composition_e2e(+ tmp_path: Path, copied_config: bool+) -> None:+ node, npm = shutil.which("node"), shutil.which("npm")+ if not node or not npm or not shutil.which("dsh"):+ pytest.skip(+ "missing_env: installed DSH CLI, Node, and npm required for native composition"+ )+ result = subprocess.run(+ [npm, "root", "-g"], capture_output=True, text=True, timeout=15+ )+ assert result.returncode == 0, result.stderr+ native_package = Path(result.stdout.strip()) / "@deepseek-ai/dsh"+ app_boot = native_package / "node_modules/@deepseek-ai/dsh-app-boot/lib/index.js"+ if not app_boot.is_file():+ pytest.skip("missing_env: DSH native app-boot package unavailable")+ profile = tmp_path / "home/profiles/desktop"+ profile.mkdir(parents=True)+ (profile / "package.json").write_text(+ json.dumps(+ {+ "dsh": {+ "profile": {+ "bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app"]+ }+ }+ }+ ),+ encoding="utf-8",+ )+ path = profile / "cordis.patch.yml"+ path.write_text(+ "- id: llm-pi-ai\n config:\n providers:\n native-user-provider:\n api: openai-responses\n baseURL: http://127.0.0.1:9999/v1\n models: [{id: native-model}]\n",+ encoding="utf-8",+ )+ rows = dsh_files.read_yaml(path, sequence=True)+ rows.append(copy.deepcopy(rows[0]) if copied_config else {"id": "llm-pi-ai"})+ dsh_files.write_yaml(path, rows)+ script = (+ "import { loadProfileDirectory, composeEntries } from "+ + json.dumps(app_boot.as_uri())+ + ";\n"+ "const loaded = loadProfileDirectory('dsh', process.argv[1], process.argv[2]);\n"+ "const entries = composeEntries([...loaded.layers.map(layer => layer.patches), loaded.patches]);\n"+ "const row = entries.find(entry => entry.id === 'llm-pi-ai');\n"+ "const selection = entries.find(entry => entry.id === 'agent-default-model');\n"+ "console.log(JSON.stringify({ providers: Object.keys(row.config?.providers ?? {}).sort(), default: selection.config }));\n"+ )++ def composed() -> dict[str, object]:+ result = subprocess.run(+ [+ node,+ "--input-type=module",+ "-e",+ script,+ str(profile),+ str(native_package / "package.json"),+ ],+ capture_output=True,+ text=True,+ timeout=15,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ return json.loads(result.stdout.splitlines()[-1])++ assert composed()["providers"] == ["native-user-provider"]+ native_default = composed()["default"]+ model = CatalogModel("fixture/model", "fixture/model", "Fixture", True)+ desktop.configure(+ tmp_path / "home",+ "http://127.0.0.1:8182",+ "fixture-only",+ ModelCatalog((model,), model.wire_slug),+ provider_progress_timeout=600,+ )+ assert composed()["providers"] == ["free-claude-code", "native-user-provider"]+ assert composed()["default"] == {+ "provider": "free-claude-code",+ "model": "fixture/model",+ }+ rows = dsh_files.read_yaml(path, sequence=True)+ rows.append(copy.deepcopy(rows[-1]))+ dsh_files.write_yaml(path, rows)+ desktop.disconnect(tmp_path / "home")+ assert composed()["providers"] == ["native-user-provider"]+ assert composed()["default"] == native_default++ atomic_write = (+ native_package / "node_modules/@deepseek-ai/dsh-atomic-write/lib/index.js"+ )+ import_lock = (+ "import { withFileLock } from " + json.dumps(atomic_write.as_uri()) + ";\n"+ )+ contender = (+ import_lock+ + """+try {+ await withFileLock(process.argv[1], async () => {}, { waitMs: 0 });+ process.exitCode = 1;+} catch (error) {+ if (!error.message.includes('timed out waiting for the writer lock')) throw error;+}+"""+ )+ lock = profile / "package.json.lock"+ with dsh_files.file_lock(lock, wait=0):+ result = subprocess.run(+ [+ node,+ "--input-type=module",+ "-e",+ contender,+ str(profile / "package.json"),+ ],+ capture_output=True,+ text=True,+ timeout=15,+ )+ assert result.returncode == 0, result.stderr+ assert lock.exists()+ python_contender = """+import sys+from pathlib import Path+from free_claude_code.harnesses.dsh_files import file_lock+try:+ with file_lock(Path(sys.argv[1]), wait=0):+ sys.exit(1)+except TimeoutError:+ pass+"""+ holder = (+ import_lock+ + """+import { spawnSync } from 'node:child_process';+await withFileLock(process.argv[1], async () => {+ const child = spawnSync(process.argv[2], ['-c', process.argv[3], process.argv[1] + '.lock'], { encoding: 'utf8' });+ if (child.status !== 0) throw new Error(child.stderr || 'FCC did not honor the native lock');+});+"""+ )+ result = subprocess.run(+ [+ node,+ "--input-type=module",+ "-e",+ holder,+ str(profile / "package.json"),+ sys.executable,+ python_contender,+ ],+ capture_output=True,+ text=True,+ timeout=15,+ )+ assert result.returncode == 0, result.stderr+ assert not lock.exists()+++def test_dsh_desktop_live_catalog_credentials_and_restart_e2e(+ smoke_config: SmokeConfig, tmp_path: Path+) -> None:+ executable = os.environ.get("FCC_SMOKE_DSH_DESKTOP_BIN")+ if not executable and os.name == "nt":+ executable = str(+ Path(os.environ["LOCALAPPDATA"])+ / "Programs/DeepSeek Harness/DeepSeek Harness.exe"+ )+ if (+ not executable+ or not Path(executable).is_file()+ or not (node := shutil.which("node"))+ ):+ pytest.skip(+ "missing_env: installed DSH Desktop and Node required; set FCC_SMOKE_DSH_DESKTOP_BIN for a custom installation"+ )+ credentials = _provider_credential_env_keys()+ env = _isolated_dsh_env(+ tmp_path=tmp_path,+ server_port=0,+ auth_token="desktop-local-only",+ credential_env_keys=credentials,+ )+ env["DSH_TELEMETRY_DISABLED"] = "1"+ home = Path(env["DSH_HOME"])+ options = {+ "executable": executable,+ "userData": str(tmp_path / "electron"),+ "artifacts": str(tmp_path),+ "phase": "initialize",+ }+ config_file = tmp_path / "driver.json"+ driver = [+ node,+ str(smoke_config.root / "smoke/lib/dsh_desktop.cjs"),+ str(Path(playwright.__file__).parent / "driver/package"),+ str(config_file),+ ]+ config_file.write_text(json.dumps(options), encoding="utf-8")+ process = _start_attached_process(driver, cwd=tmp_path, env=env)+ try:+ stdout, stderr = process.communicate(timeout=90)+ assert process.returncode == 0, stdout + stderr+ finally:+ _stop_attached_process(process)+ witness = tmp_path / "witness.txt"+ witness.write_text("DESKTOP_TOOL_WITNESS", encoding="utf-8")+ model = "fcc-desktop-native"+ full_model = f"lmstudio/{model}"+ first = DshProvider(model, "FCC_DESKTOP_DONE", read_path=str(witness))+ second = DshProvider(model, "FCC_DESKTOP_UPDATED", read_path=str(witness))++ def server_env(upstream: str, token: str, name: str) -> dict[str, str]:+ root = tmp_path / name+ (root / ".fcc").mkdir(parents=True)+ (root / ".fcc/.env").write_text(+ f"FCC_CONFIG_SCHEMA=1\nANTHROPIC_AUTH_TOKEN={token}\nPROXY_AUTH_ENABLED=true\n",+ encoding="utf-8",+ )+ return _local_provider_overrides(full_model, upstream) | {+ "HOME": str(root),+ "USERPROFILE": str(root),+ # These inference servers must not refresh the driver's profile.+ "DSH_HOME": str(root / ".dsh"),+ }++ with (+ dsh_provider(first) as upstream,+ dsh_provider(second) as updated,+ SmokeServerDriver(+ smoke_config,+ name="dsh-desktop-native",+ env_overrides=server_env(upstream, "desktop-first", "fcc-first"),+ env_unset=credentials,+ ).run() as server,+ SmokeServerDriver(+ smoke_config,+ name="dsh-desktop-rotated",+ env_overrides=server_env(updated, "desktop-rotated", "fcc-second"),+ env_unset=credentials,+ ).run() as rotated,+ ):++ def configure(url: str, token: str, label: str) -> None:+ catalog = ModelCatalog(+ (CatalogModel(full_model, full_model, label, True),), full_model+ )+ desktop.configure(+ home,+ url,+ token,+ catalog,+ provider_progress_timeout=600,+ )++ configure(server.base_url, "desktop-first", "FCC Desktop Fixture")+ config_file.write_text(+ json.dumps(options | {"phase": "exercise"}), encoding="utf-8"+ )+ # The controller exchanges one acknowledgement for each native lifecycle action.+ import subprocess++ process = subprocess.Popen(+ driver,+ cwd=tmp_path,+ env=env,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == "nt" else 0,+ start_new_session=os.name != "nt",+ )+ lines: queue.Queue[str | None] = queue.Queue()+ assert process.stdout is not None and process.stdin is not None+ output = process.stdout++ def collect() -> None:+ for line in output:+ lines.put(line)+ lines.put(None)++ reader = threading.Thread(target=collect, daemon=True)+ reader.start()+ transcript = []+ completed = False+ try:+ while (line := lines.get(timeout=60)) is not None:+ transcript.append(line)+ try:+ event = json.loads(line)+ except ValueError:+ continue+ if not isinstance(event, dict):+ continue+ if event.get("action") == "refresh":+ configure(+ rotated.base_url, "desktop-rotated", "FCC Updated Fixture"+ )+ elif event.get("action") == "disconnect":+ assert not desktop.disconnect(home)["connected"]+ assert (+ desktop.DSH_DESKTOP_API_KEY+ not in (home / ".credentials.yaml").read_text()+ )+ elif event.get("action") == "reconnect":+ configure(+ rotated.base_url, "desktop-rotated", "FCC Updated Fixture"+ )+ elif event.get("action") == "final_disconnect":+ assert not desktop.disconnect(home)["connected"]+ else:+ completed |= event.get("completed") is True+ continue+ process.stdin.write("{}\n")+ process.stdin.flush()+ process.wait(timeout=15)+ assert process.returncode == 0 and completed, "".join(transcript)+ finally:+ _stop_attached_process(process)+ reader.join(timeout=5)+ (tmp_path / "desktop-driver.log").write_text(+ "".join(transcript), encoding="utf-8"+ )+ (tmp_path / "desktop-requests.json").write_text(+ json.dumps(+ {"first": first.requests, "rotated": second.requests}, indent=2+ ),+ encoding="utf-8",+ )+ assert sum(item["purpose"] == "main" for item in first.requests) == 2+ assert sum(item["purpose"] == "main" for item in second.requests) == 6+ for requests in (first.requests, second.requests):+ assert any(+ "DESKTOP_TOOL_WITNESS" in json.dumps(item["body"]) for item in requests+ )+ saved = (home / "profiles/desktop/cordis.patch.yml").read_text(encoding="utf-8")+ assert "free-claude-code" not in saved+ assert (+ "ui-settings-account" in saved+ ) # Native onboarding writes survived all FCC edits.diff --git a/smoke/product/test_dsh_native_live.py b/smoke/product/test_dsh_native_live.pynew file mode 100644index 00000000..014a7025--- /dev/null+++ b/smoke/product/test_dsh_native_live.py@@ -0,0 +1,227 @@+"""Native DSH operations against local, isolated FCC providers."""++import json+import os+import shutil+import subprocess+from pathlib import Path++import pytest+from ruamel.yaml import YAML++from smoke.lib.config import SmokeConfig+from smoke.lib.dsh_provider import DshProvider, dsh_provider+from smoke.lib.e2e import SmokeServerDriver+from smoke.product.test_client_product_live import (+ _isolated_dsh_env,+ _json_object_lines,+ _local_provider_overrides,+ _provider_credential_env_keys,+)++pytestmark = [pytest.mark.live, pytest.mark.smoke_target("clients")]+++def command(config: SmokeConfig) -> list[str]:+ if not shutil.which("dsh") or not (uv := shutil.which("uv")):+ pytest.skip("missing_env: DeepSeek Harness and uv are required")+ return [uv, "run", "--project", str(config.root), "--no-sync", "fcc-dsh"]+++ "operation", ["subagent", "idle_tool", "native_responses", "vision_no_thinking"]+)+def test_dsh_native_operations_e2e(+ smoke_config: SmokeConfig, tmp_path: Path, operation: str+) -> None:+ native = command(smoke_config)+ model = "fcc-dsh-operations"+ full_model = f"lmstudio/{model}"+ scenario = DshProvider(model, "FCC_NATIVE_DONE")+ if operation == "subagent":+ scenario.tool_call = (+ "subagent",+ {+ "description": "Read a fixture instruction",+ "prompt": "FCC_CHILD_TASK: Reply FCC_CHILD_DONE",+ "run_in_background": False,+ },+ )+ elif operation == "idle_tool":+ scenario.tool_call = (+ "pwsh" if os.name == "nt" else "bash",+ {+ "command": "Start-Sleep -Seconds 3; Write-Output 'FCC_IDLE_TOOL_DONE'"+ if os.name == "nt"+ else "sleep 3; printf FCC_IDLE_TOOL_DONE",+ "description": "Wait briefly and print a fixture marker",+ "timeoutMs": 10000,+ },+ )+ elif operation == "vision_no_thinking":+ full_model = f"alibaba_cloud/{model}"+ image = tmp_path / "vision.png"+ shutil.copyfile(smoke_config.root / "smoke/assets/vision-fcc.png", image)+ scenario.tool_call = ("read_image", {"file_path": str(image)})+ else:+ scenario.protocol = "responses"+ full_model = "custom_" + "d" * 32 + "/" + model+ credentials = _provider_credential_env_keys()+ with dsh_provider(scenario) as upstream:+ overrides = _local_provider_overrides(full_model, upstream)+ if operation == "vision_no_thinking":+ overrides.update(+ ALIBABA_CLOUD_BASE_URL=upstream,+ ALIBABA_CLOUD_API_KEY="local-fixture-only",+ )+ if operation == "native_responses":+ overrides["FCC_CUSTOM_PROVIDERS"] = json.dumps(+ [+ {+ "provider_id": full_model.split("/")[0],+ "display_name": "Native Responses fixture",+ "base_url": upstream,+ "api_format": "openai_responses",+ "model_ids": [model],+ }+ ]+ )+ with SmokeServerDriver(+ smoke_config,+ name=f"dsh-native-{operation}",+ env_overrides=overrides,+ env_unset=credentials,+ ).run() as server:+ env = _isolated_dsh_env(+ tmp_path=tmp_path,+ server_port=server.port,+ auth_token=smoke_config.settings.proxy_auth_token,+ credential_env_keys=credentials,+ )+ result = subprocess.run(+ [*native, "headless", "--json", "Complete the fixture task."],+ cwd=tmp_path,+ env=env,+ capture_output=True,+ text=True,+ timeout=90,+ )+ (tmp_path / "native-requests.json").write_text(+ json.dumps(scenario.requests, indent=2), encoding="utf-8"+ )+ (tmp_path / "native-output.log").write_text(+ result.stdout + result.stderr, encoding="utf-8"+ )+ assert result.returncode == 0, result.stdout + result.stderr+ events = _json_object_lines(result.stdout)+ assert any(+ item.get("type") == "final" and item.get("text") == "FCC_NATIVE_DONE"+ for item in events+ )+ if operation in ("subagent", "idle_tool"):+ witness = "FCC_CHILD_DONE" if operation == "subagent" else "FCC_IDLE_TOOL_DONE"+ assert any(+ item.get("type") == "tool_result"+ and item.get("status") == "completed"+ and witness in str(item.get("result"))+ for item in events+ )+ assert sum(item["purpose"] == "main" for item in scenario.requests) == 2+ if operation == "subagent":+ assert sum(item["purpose"] == "subagent" for item in scenario.requests) == 1+ if operation == "native_responses":+ assert all(item["path"] == "/v1/responses" for item in scenario.requests)+ assert sum(item["purpose"] == "main" for item in scenario.requests) == 1+ if operation == "vision_no_thinking":+ assert any(+ item.get("type") == "tool_result" and item.get("status") == "completed"+ for item in events+ )+ assert not any(item.get("type") == "thinking" for item in events)+ main = [item["body"] for item in scenario.requests if item["purpose"] == "main"]+ assert len(main) == 2+ assert all(isinstance(body, dict) and body["model"] == model for body in main)+ assert "data:image/png;base64," in json.dumps(main[-1])+++def test_dsh_native_settings_migration_and_dump_e2e(+ smoke_config: SmokeConfig, tmp_path: Path+) -> None:+ native = command(smoke_config)+ scenario = DshProvider("fcc-dsh-migration", "FCC_MIGRATED")+ full_model = "lmstudio/fcc-dsh-migration"+ credentials = _provider_credential_env_keys()+ with (+ dsh_provider(scenario) as upstream,+ SmokeServerDriver(+ smoke_config,+ name="dsh-native-migration",+ env_overrides=_local_provider_overrides(full_model, upstream),+ env_unset=credentials,+ ).run() as server,+ ):+ env = _isolated_dsh_env(+ tmp_path=tmp_path,+ server_port=server.port,+ auth_token=smoke_config.settings.proxy_auth_token,+ credential_env_keys=credentials,+ )+ home = Path(env["DSH_HOME"])+ legacy = home / "settings.yaml"+ legacy.write_text("agent-loop:\n maxParallelToolCalls: 3\n", encoding="utf-8")+ result = subprocess.run(+ [*native, "headless", "Reply FCC_MIGRATED"],+ cwd=tmp_path,+ env=env,+ capture_output=True,+ text=True,+ timeout=90,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert not legacy.exists()+ assert legacy.with_suffix(".yaml.imported").exists()+ persisted = (home / "profiles/headless/cordis.patch.yml").read_text(+ encoding="utf-8"+ )+ assert "maxParallelToolCalls: 3" in persisted+ assert (+ "free-claude-code" not in persisted and "FCC_DSH_API_KEY" not in persisted+ )+ assert smoke_config.settings.proxy_auth_token not in persisted+ user_patch = tmp_path / "caller.patch.yml"+ user_patch.write_text(+ "- id: agent-default-model\n config:\n provider: free-claude-code\n model: caller-precedence\n",+ encoding="utf-8",+ )+ for selection in (+ ["headless"],+ ["--profile=headless"],+ ["--profile", "headless"],+ ):+ dumped = subprocess.run(+ [*native, *selection, "--patch", str(user_patch), "--dump-config"],+ cwd=tmp_path,+ env=env,+ capture_output=True,+ text=True,+ timeout=45,+ )+ assert dumped.returncode == 0, dumped.stdout + dumped.stderr+ parsed = YAML(typ="rt").load(dumped.stdout)+ assert "caller-precedence" in str(parsed)+ assert "openai-responses" in str(parsed)+ for invalid in (+ ["headless", "--profile", "web"],+ ["desktop"],+ ["headless", "--dump-config", "--dump-config-schema"],+ ):+ error = subprocess.run(+ [*native, *invalid],+ cwd=tmp_path,+ env=env,+ capture_output=True,+ text=True,+ timeout=45,+ )+ assert error.returncode != 0+ assert sum(item["purpose"] == "main" for item in scenario.requests) == 1diff --git a/src/free_claude_code/api/admin_routes.py b/src/free_claude_code/api/admin_routes.pyindex e3fefe48..0f13cd01 100644--- a/src/free_claude_code/api/admin_routes.py+++ b/src/free_claude_code/api/admin_routes.py@@ -331,6 +331,38 @@ async def disconnect_claude_vscode(return await _integration_response(services.admin.disconnect_claude_vscode)[email protected]("/admin/api/integrations/dsh-desktop")+async def dsh_desktop_status(+ request: Request, services: ApiServices = Depends(get_services)+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.dsh_desktop_status)++[email protected]("/admin/api/integrations/dsh-desktop/connect")+async def connect_dsh_desktop(+ request: Request, services: ApiServices = Depends(get_services)+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.connect_dsh_desktop)++[email protected]("/admin/api/integrations/dsh-desktop/disconnect")+async def disconnect_dsh_desktop(+ request: Request, services: ApiServices = Depends(get_services)+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.disconnect_dsh_desktop)++[email protected]("/admin/api/integrations/dsh-desktop/refresh")+async def refresh_dsh_desktop(+ request: Request, services: ApiServices = Depends(get_services)+):+ require_loopback_admin(request)+ return await _integration_response(services.admin.refresh_dsh_desktop)++@router.get("/admin/api/integrations/claude-desktop")async def claude_desktop_status(request: Request, services: ApiServices = Depends(get_services)diff --git a/src/free_claude_code/api/admin_static/admin.js b/src/free_claude_code/api/admin_static/admin.jsindex 2afb166d..4fe64c9c 100644--- a/src/free_claude_code/api/admin_static/admin.js+++ b/src/free_claude_code/api/admin_static/admin.js@@ -145,6 +145,7 @@ function renderStartup() {renderJetBrainsIntegration();renderCodexIntegration();renderClaudeDesktopIntegration();+ renderDshDesktopIntegration();}async function refreshStartup() {@@ -296,6 +297,7 @@ function setActiveView(viewId, { scroll = false } = {}) {refreshJetBrainsIntegration();refreshCodexIntegration();refreshClaudeDesktopIntegration();+ refreshDshDesktopIntegration();}}@@ -1618,6 +1620,7 @@ function refreshIntegrationUpdates(previous, current) {["jetbrains-acp", jetBrainsIntegration, refreshJetBrainsIntegration, "jetBrainsIntegrationMessage", "Settings updated. Reopen JetBrains and start a new chat."],["codex", codexIntegration, refreshCodexIntegration, "codexIntegrationMessage", "Settings updated. Restart Codex."],["claude-desktop", claudeDesktopIntegration, refreshClaudeDesktopIntegration, "claudeDesktopIntegrationMessage", "Settings updated. Reopen Claude Desktop."],+ ["dsh-desktop", dshDesktopIntegration, refreshDshDesktopIntegration, "dshDesktopIntegrationMessage", "DSH Desktop configuration updated."],]) {const phase = current?.[id]?.state;// Successful actions clear update metadata, not the last observed state.@@ -2138,6 +2141,123 @@ claudeDesktopIntegrationDialog.addEventListener("click", (event) => {}});+const dshDesktopIntegrationDialog = byId("dshDesktopIntegrationDialog");+const dshDesktopIntegration = { connected: null, actionRevision: 0, busy: false, paths: null, update: null };+const dshDesktopIntegrationPath = "/admin/api/integrations/dsh-desktop";++function applyDshDesktopStatus(result) {+ dshDesktopIntegration.connected = result.connected;+ dshDesktopIntegration.paths = result.paths ?? dshDesktopIntegration.paths;+ dshDesktopIntegration.update = result.update ?? null;+}++function renderDshDesktopIntegration() {+ const { connected, paths } = dshDesktopIntegration;+ const updating = integrationUpdating(dshDesktopIntegration, "dsh-desktop");+ const busy = dshDesktopIntegration.busy || (updating && !connected);+ byId("retryDshDesktopIntegration").hidden = dshDesktopIntegration.update?.state !== "failed";+ byId("retryDshDesktopIntegration").disabled = busy || updating;+ const action = connected === null ? "Retry" : connected ? "Disconnect" : "Connect";+ byId("openDshDesktopIntegration").textContent = busy ? "Loading…" : action;+ byId("openDshDesktopIntegration").disabled = busy;+ byId("openDshDesktopIntegration").setAttribute("aria-busy", String(busy));+ byId("confirmDshDesktopIntegration").textContent = busy ? "Saving…" : action;+ byId("confirmDshDesktopIntegration").disabled = busy || connected === null;+ byId("openDshDesktopIntegration").className = connected && !busy ? "danger-button" : "primary-button";+ byId("confirmDshDesktopIntegration").className = connected ? "danger-button" : "primary-button";+ byId("dshDesktopIntegrationDescription").textContent = connected+ ? "Remove FCC's Desktop connection. Existing FCC sessions need another model selected to continue."+ : "Install and open DSH Desktop once, then connect FCC as the default for new sessions.";+ const files = byId("dshDesktopIntegrationFiles");+ files.replaceChildren();+ if (paths) {+ const targets = Object.values(paths);+ targets.forEach((path) => {+ const item = document.createElement("li");+ const code = document.createElement("code");+ code.textContent = path;+ item.appendChild(code);+ files.appendChild(item);+ });+ }+}++async function refreshDshDesktopIntegration(retry = false, { background = false } = {}) {+ if (!background) integrationMessage("dshDesktopIntegrationMessage", "");+ const request = beginIntegrationCheck(dshDesktopIntegration);+ if (!request) return;+ renderDshDesktopIntegration();+ try {+ if (retry) await api(`${dshDesktopIntegrationPath}/refresh`, { method: "POST" });+ const result = await api(dshDesktopIntegrationPath);+ if (!currentIntegrationCheck(dshDesktopIntegration, request)) return;+ applyDshDesktopStatus(result);+ if (result.update?.state === "failed") integrationMessage("dshDesktopIntegrationMessage", result.update.message, true);+ else if (byId("dshDesktopIntegrationMessage").classList.contains("error")) integrationMessage("dshDesktopIntegrationMessage", "");+ } catch (error) {+ if (!currentIntegrationCheck(dshDesktopIntegration, request)) return;+ integrationMessage("dshDesktopIntegrationMessage", error.message, true);+ } finally {+ finishIntegrationCheck(dshDesktopIntegration, request, renderDshDesktopIntegration);+ }+}++byId("openDshDesktopIntegration").addEventListener("click", () => {+ if (dshDesktopIntegration.connected === null) {+ refreshDshDesktopIntegration(dshDesktopIntegration.update?.state === "failed");+ return;+ }+ integrationMessage("dshDesktopIntegrationDialogMessage", "");+ dshDesktopIntegrationDialog.showModal();+});+byId("confirmDshDesktopIntegration").addEventListener("click", async () => {+ if (byId("confirmDshDesktopIntegration").disabled) return;+ const disconnect = dshDesktopIntegration.connected === true;+ const config = state.config;+ const actionRevision = ++dshDesktopIntegration.actionRevision;+ const current = () => config === state.config && actionRevision === dshDesktopIntegration.actionRevision;+ dshDesktopIntegration.checkRequest = null;+ dshDesktopIntegration.busy = true;+ renderDshDesktopIntegration();+ integrationMessage("dshDesktopIntegrationDialogMessage", "");+ integrationMessage("dshDesktopIntegrationMessage", "");+ try {+ const result = await api(`${dshDesktopIntegrationPath}/${disconnect ? "disconnect" : "connect"}`, { method: "POST" });+ if (!current()) return;+ applyDshDesktopStatus(result);+ dshDesktopIntegrationDialog.close();+ integrationMessage("dshDesktopIntegrationMessage", result.connected+ ? "Connected. New DSH sessions use FCC. Reopen DSH if it does not reload the changes."+ : "DSH Desktop is disconnected. Select another model in existing DSH sessions.");+ } catch (error) {+ if (!current()) return;+ try {+ const result = await api(dshDesktopIntegrationPath);+ if (!current()) return;+ applyDshDesktopStatus(result);+ } catch {+ // Keep the last known status if the follow-up read also fails.+ }+ if (!current()) return;+ integrationMessage("dshDesktopIntegrationDialogMessage", error.message, true);+ integrationMessage("dshDesktopIntegrationMessage", error.message, true);+ } finally {+ if (actionRevision !== dshDesktopIntegration.actionRevision) return;+ dshDesktopIntegration.busy = false;+ renderDshDesktopIntegration();+ if (config !== state.config) void refreshDshDesktopIntegration();+ }+});+byId("retryDshDesktopIntegration").addEventListener("click", () => refreshDshDesktopIntegration(true));+byId("closeDshDesktopIntegration").addEventListener("click", () => dshDesktopIntegrationDialog.close());+dshDesktopIntegrationDialog.addEventListener("click", (event) => {+ if (event.target !== dshDesktopIntegrationDialog) return;+ const bounds = dshDesktopIntegrationDialog.getBoundingClientRect();+ if (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom) {+ dshDesktopIntegrationDialog.close();+ }+});+// Keep footer clearance exact when messages wrap or a view hides the bar.new ResizeObserver(([entry]) => {document.documentElement.style.setProperty(diff --git a/src/free_claude_code/api/admin_static/index.html b/src/free_claude_code/api/admin_static/index.htmlindex 1cf05d8d..94e95d0c 100644--- a/src/free_claude_code/api/admin_static/index.html+++ b/src/free_claude_code/api/admin_static/index.html@@ -183,6 +183,32 @@<button id="confirmClaudeDesktopIntegration" class="primary-button" type="button">Connect</button><p id="claudeDesktopIntegrationDialogMessage" class="message-area error" role="alert" hidden></p></dialog>+ <article class="provider-strip integration-card">+ <div class="section-heading">+ <div>+ <h3>DeepSeek Harness Desktop</h3>+ <p>Use FCC's models in the DeepSeek Harness desktop app.</p>+ </div>+ </div>+ <p id="dshDesktopIntegrationMessage" class="message-area" role="status" hidden></p>+ <div class="integration-actions">+ <button id="openDshDesktopIntegration" class="primary-button" type="button" aria-busy="true" disabled>Loading…</button>+ <button id="retryDshDesktopIntegration" class="secondary-button" type="button" hidden>Retry update</button>+ </div>+ </article>+ <dialog id="dshDesktopIntegrationDialog" class="integration-dialog" aria-labelledby="dshDesktopIntegrationTitle" aria-describedby="dshDesktopIntegrationDescription">+ <div class="section-heading">+ <h3 id="dshDesktopIntegrationTitle">DeepSeek Harness Desktop</h3>+ <button id="closeDshDesktopIntegration" class="ghost-button" type="button" aria-label="Close" autofocus>×</button>+ </div>+ <p id="dshDesktopIntegrationDescription">Install and open DSH Desktop once, then connect FCC as the default for new sessions.</p>+ <div class="integration-files">+ <strong>Files to modify</strong>+ <ul id="dshDesktopIntegrationFiles"></ul>+ </div>+ <button id="confirmDshDesktopIntegration" class="primary-button" type="button">Connect</button>+ <p id="dshDesktopIntegrationDialogMessage" class="message-area error" role="alert" hidden></p>+ </dialog></section><section id="view-code" class="admin-view" data-view="code" hidden>diff --git a/src/free_claude_code/api/ports.py b/src/free_claude_code/api/ports.pyindex 34ba3f30..5a5c33bf 100644--- a/src/free_claude_code/api/ports.py+++ b/src/free_claude_code/api/ports.py@@ -48,6 +48,14 @@ class AdminRuntimePort(Protocol):async def refresh_claude_vscode(self) -> JsonObject: ...+ async def dsh_desktop_status(self) -> JsonObject: ...++ async def connect_dsh_desktop(self) -> JsonObject: ...++ async def disconnect_dsh_desktop(self) -> JsonObject: ...++ async def refresh_dsh_desktop(self) -> JsonObject: ...+async def claude_desktop_status(self) -> JsonObject: ...async def jetbrains_acp_status(self) -> JsonObject: ...diff --git a/src/free_claude_code/cli/launchers/dsh.py b/src/free_claude_code/cli/launchers/dsh.pyindex f61dbc82..fd56936e 100644--- a/src/free_claude_code/cli/launchers/dsh.py+++ b/src/free_claude_code/cli/launchers/dsh.py@@ -1,40 +1,97 @@"""Installed DeepSeek Harness launcher with an FCC connection patch."""+import osimport re+import sysfrom collections.abc import Sequence+from free_claude_code.harnesses.dsh_config import (+ DSH_API_KEY_ENV,+ DSH_ENV_PREFIX,+ build_dsh_launch_config,+)from free_claude_code.harnesses.environment import client_environmentfrom free_claude_code.harnesses.launch import NativeCheck, PreparedLaunchfrom free_claude_code.harnesses.resources import LaunchResources-from .dsh_config import DSH_API_KEY_ENV, DSH_ENV_PREFIX, build_dsh_launch_config+from .common import resolve_client_binary, run_client_processfrom .runner import HarnessSpec, LaunchContext, launch_harness_VERSION_PATTERN = re.compile(- r"(?im)^\s*(?:dsh\s+)?v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?)\s*$"+ r"(?im)^\s*(?:dsh\s+)?v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"+ r"(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?"+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\s*$")+def _supported_version(output: str) -> bool:+ match = _VERSION_PATTERN.search(output)+ if match is None:+ return False+ release = tuple(int(match[index]) for index in (1, 2, 3))+ preview = match[4].split(".") if match[4] is not None else []+ if any(part.isdigit() and len(part) > 1 and part[0] == "0" for part in preview):+ return False+ if release != (0, 2, 0):+ return release > (0, 2, 0)+ if not preview:+ return True+ if preview[0] != "rc":+ return not preview[0].isdigit() and preview[0] > "rc"+ return len(preview) > 1 and (not preview[1].isdigit() or int(preview[1]) >= 2)+++def _launcher_options(args: list[str]) -> list[str]:+ """Scan option names only, stopping at DSH's first inner-app argument."""+ expanded = ["--profile", *args] if args and not args[0].startswith("-") else args+ index = 0+ options = []+ while index < len(expanded):+ option = expanded[index].split("=", 1)[0]+ if option in {"--profile", "--from-default-profile", "--patch"}:+ options.append(option)+ index += 1 if "=" in expanded[index] else 2+ elif option in {+ "--dump-config",+ "--dump-config-schema",+ "--dump-default-config",+ "--version",+ "-V",+ }:+ options.append(option)+ index += 1+ else:+ if option in {"--help", "-h"}:+ options.append(option)+ break+ return options+++def _has_profile(prefix: list[str]) -> bool:+ return any(arg == "--profile" or arg.startswith("--profile=") for arg in prefix)++def _configure(ctx: LaunchContext, args: list[str], files: LaunchResources) -> PreparedLaunch:catalog = ctx.require_catalog()- settings_path = files.write_json("settings.yaml", {})credentials_path = files.write_json(".credentials.yaml", {})config = build_dsh_launch_config(catalog.models,default_model_id=catalog.default_model_id,proxy_root_url=ctx.proxy_root_url,- settings_path=settings_path,credentials_path=credentials_path,provider_progress_timeout=ctx.settings.provider_progress_timeout,)patch_path = files.write_json("fcc.patch.yml", config)patch_args = ["--patch", str(patch_path)]+ native_args = _launcher_options(args)if not args:command = [ctx.binary_path, "web", *patch_args]- elif args[0] == "web":- command = [ctx.binary_path, "web", *patch_args, *args[1:]]+ elif not args[0].startswith("-"):+ command = [ctx.binary_path, args[0], *patch_args, *args[1:]]+ elif _has_profile(native_args):+ command = [ctx.binary_path, *patch_args, *args]else:command = [ctx.binary_path, "--profile", "web", *patch_args, *args]return PreparedLaunch(@@ -51,19 +108,39 @@ def _configure(SPEC = HarnessSpec(binary_name="dsh",display_name="DeepSeek Harness",- install_hint="Install the supported DeepSeek Harness release with: npm install -g @deepseek-ai/[email protected]",+ install_hint="Install DeepSeek Harness with: npm install -g @deepseek-ai/dsh@latest",configure=_configure,catalog_view="responses",compatibility_check=NativeCheck(("--version",),- lambda output: (- bool(match := _VERSION_PATTERN.search(output))- and match.group(1) == "0.1.0-rc.8"- ),- "FCC requires DeepSeek Harness 0.1.0-rc.8.",+ _supported_version,+ "FCC requires DeepSeek Harness >=0.2.0-rc.2.",),)def launch(argv: Sequence[str] | None = None) -> None:- launch_harness(SPEC, argv)+ args = list(sys.argv[1:] if argv is None else argv)+ prefix = _launcher_options(args)+ if (+ args[:1] == ["plugin"]+ or any(flag in prefix for flag in ("--version", "-V", "--dump-default-config"))+ or (+ any(flag in prefix for flag in ("--help", "-h"))+ and not _has_profile(prefix)+ )+ ):+ binary = resolve_client_binary(+ binary_name=SPEC.binary_name,+ display_name=SPEC.display_name,+ install_hint=SPEC.install_hint,+ )+ run_client_process(+ command=[binary, *args],+ env=os.environ,+ binary_name=SPEC.binary_name,+ display_name=SPEC.display_name,+ install_hint=SPEC.install_hint,+ )+ return+ launch_harness(SPEC, args)diff --git a/src/free_claude_code/cli/launchers/dsh_config.py b/src/free_claude_code/harnesses/dsh_config.pysimilarity index 84%rename from src/free_claude_code/cli/launchers/dsh_config.pyrename to src/free_claude_code/harnesses/dsh_config.pyindex a8df724f..f6998330 100644--- a/src/free_claude_code/cli/launchers/dsh_config.py+++ b/src/free_claude_code/harnesses/dsh_config.py@@ -1,4 +1,4 @@-"""Process-local DeepSeek Harness configuration for FCC model routing."""+"""DeepSeek Harness provider metadata and process-local CLI overlays."""import mathfrom pathlib import Path@@ -33,32 +33,18 @@ def build_dsh_launch_config(*,default_model_id: str,proxy_root_url: str,- settings_path: Path,credentials_path: Path,provider_progress_timeout: float,) -> tuple[JsonObject, ...]:"""Translate FCC's catalog and timeout into an isolated DSH overlay."""- if not models:- raise ValueError("DeepSeek Harness requires at least one routable FCC model")-- stream_idle_timeout_ms = _stream_idle_timeout_ms(provider_progress_timeout)- provider: JsonObject = {- "displayName": "Free Claude Code",- "apiKeyEnv": DSH_API_KEY_ENV,- "api": "openai-responses",- "baseURL": proxy_v1_url(proxy_root_url),- "models": [_model_profile(model) for model in models],- "defaultInput": ["text"],- "retryPolicy": {"mode": "normal", "maxRetries": 0},- "streamIdleTimeoutMs": stream_idle_timeout_ms,- }+ provider = build_dsh_provider(+ models,+ proxy_root_url=proxy_root_url,+ credential_ref=DSH_API_KEY_ENV,+ provider_progress_timeout=provider_progress_timeout,+ )return (- _configured_row(- "settings",- "@deepseek-ai/dsh-settings-file",- {"path": str(settings_path), "watch": False},- ),_configured_row("credentials","@deepseek-ai/dsh-credentials-local",@@ -74,7 +60,8 @@ def build_dsh_launch_config("@deepseek-ai/dsh-agent-default-model",{"provider": DSH_PROVIDER_ID, "model": default_model_id},),- _disabled_row("llm-deepseek", "@deepseek-ai/dsh-llm-deepseek"),+ _disabled_row("llm-deepseek", "@deepseek-ai/dsh-llm-deepseek-api-key"),+ _disabled_row("llm-deepseek-account", "@deepseek-ai/dsh-llm-deepseek-account"),_disabled_row("web-search-deepseek","@deepseek-ai/dsh-web-search-deepseek",@@ -83,6 +70,30 @@ def build_dsh_launch_config()+def build_dsh_provider(+ models: tuple[CatalogModel, ...],+ *,+ proxy_root_url: str,+ credential_ref: str,+ provider_progress_timeout: float,+) -> JsonObject:+ """Build the same FCC Responses route for temporary and persistent clients."""+ if not models:+ raise ValueError("DeepSeek Harness requires at least one routable FCC model")++ stream_idle_timeout_ms = _stream_idle_timeout_ms(provider_progress_timeout)+ return {+ "displayName": "Free Claude Code",+ "apiKeyEnv": credential_ref,+ "api": "openai-responses",+ "baseURL": proxy_v1_url(proxy_root_url),+ "models": [_model_profile(model) for model in models],+ "defaultInput": ["text"],+ "retryPolicy": {"mode": "normal", "maxRetries": 0},+ "streamIdleTimeoutMs": stream_idle_timeout_ms,+ }++def _stream_idle_timeout_ms(provider_progress_timeout: float) -> int:if not math.isfinite(provider_progress_timeout) or provider_progress_timeout <= 0:raise ValueError("PROVIDER_PROGRESS_TIMEOUT must be a positive finite value")diff --git a/src/free_claude_code/harnesses/dsh_desktop_integration.py b/src/free_claude_code/harnesses/dsh_desktop_integration.pynew file mode 100644index 00000000..483e6552--- /dev/null+++ b/src/free_claude_code/harnesses/dsh_desktop_integration.py@@ -0,0 +1,224 @@+"""Write, compare, and remove FCC's entries in DSH Desktop's native files."""++import copy+import os+from collections.abc import Iterator+from contextlib import ExitStack, contextmanager+from pathlib import Path++from ruamel.yaml.comments import CommentedMap, CommentedSeq++from free_claude_code.application.model_catalog import ModelCatalog+from free_claude_code.core.json_types import JsonObject+from free_claude_code.harnesses import dsh_files+from free_claude_code.harnesses.dsh_config import DSH_PROVIDER_ID, build_dsh_provider+from free_claude_code.harnesses.dsh_files import DshConfigError, mapping++DSH_DESKTOP_API_KEY = "FCC_DSH_DESKTOP_API_KEY"+++def config_home() -> Path:+ value = os.environ.get("DSH_HOME", "").strip()+ if value == "~":+ return Path.home()+ if value.startswith(("~/", "~\\")):+ return (Path.home() / value[2:]).resolve()+ return Path(value).resolve() if value else Path.home() / ".dsh"+++def _paths(home: Path) -> JsonObject:+ return {+ "desktop_profile": str(home / "profiles/desktop/cordis.patch.yml"),+ "credentials": str(home / ".credentials.yaml"),+ }+++def _read(home: Path) -> tuple[CommentedSeq, CommentedMap]:+ for name in ("profiles/desktop/cordis.patch.yml", ".credentials.yaml"):+ dsh_files.regular_path(home / name, root=home)+ rows = dsh_files.read_yaml(+ home / "profiles/desktop/cordis.patch.yml", sequence=True+ )+ credentials = dsh_files.read_yaml(home / ".credentials.yaml")+ assert isinstance(rows, CommentedSeq) and isinstance(credentials, CommentedMap)+ return rows, credentials+++def _rows(rows: CommentedSeq, identity: str) -> list[CommentedMap]:+ return [+ row+ for row in rows+ if isinstance(row, CommentedMap) and row.get("id") == identity+ ]+++def _configs(+ rows: CommentedSeq, identity: str, *, create: bool = False+) -> list[CommentedMap]:+ matches = _rows(rows, identity)+ configs = [mapping(row["config"]) for row in matches if "config" in row]+ if not configs and create:+ row = matches[-1] if matches else CommentedMap(id=identity)+ if not matches:+ rows.append(row)+ row["config"] = CommentedMap()+ configs.append(row["config"])+ return configs+++def _providers(config: CommentedMap) -> CommentedMap:+ return mapping(config["providers"]) if "providers" in config else CommentedMap()+++def has_provider(home: Path) -> bool:+ rows, _ = _read(home)+ return any(+ DSH_PROVIDER_ID in _providers(config) for config in _configs(rows, "llm-pi-ai")+ )+++@contextmanager+def _locked(home: Path) -> Iterator[None]:+ # Use DSH's locks so a native edit cannot lose unrelated settings during our write.+ _read(home)+ with ExitStack() as locks:+ if (home / "profiles/desktop").is_dir():+ locks.enter_context(+ dsh_files.file_lock(home / "profiles/desktop/package.json.lock", wait=2)+ )+ if home.is_dir():+ locks.enter_context(+ dsh_files.file_lock(home / ".credentials.yaml.lock", wait=30)+ )+ yield+++def _provider(catalog: ModelCatalog, url: str, timeout: float) -> JsonObject:+ return build_dsh_provider(+ catalog.models,+ proxy_root_url=url,+ credential_ref=DSH_DESKTOP_API_KEY,+ provider_progress_timeout=timeout,+ )+++def status(+ home: Path,+ proxy_root_url: str,+ auth_token: str,+ catalog: ModelCatalog,+ *,+ provider_progress_timeout: float,+) -> JsonObject:+ home = home.resolve()+ rows, credentials = _read(home)+ providers = _configs(rows, "llm-pi-ai")+ defaults = _configs(rows, "agent-default-model")+ refs = mapping(credentials["refs"]) if "refs" in credentials else CommentedMap()+ connected = bool(+ auth_token+ and providers+ and defaults+ and _providers(providers[-1]).get(DSH_PROVIDER_ID)+ == _provider(catalog, proxy_root_url, provider_progress_timeout)+ and defaults[-1]+ == {"provider": DSH_PROVIDER_ID, "model": catalog.default_model_id}+ and refs.get(DSH_DESKTOP_API_KEY) == auth_token+ and credentials.get("version") == 1+ )+ return {"connected": connected, "paths": _paths(home)}+++def configure(+ home: Path,+ proxy_root_url: str,+ auth_token: str,+ catalog: ModelCatalog,+ *,+ provider_progress_timeout: float,+ only_existing: bool = False,+) -> JsonObject:+ home = home.resolve()+ if not auth_token.strip():+ raise DshConfigError(+ "Set an FCC proxy authentication token before connecting DSH Desktop."+ )+ with _locked(home):+ if only_existing and not has_provider(home):+ return {"connected": False, "changed": False, "paths": _paths(home)}+ if not (home / "profiles/desktop/package.json").is_file():+ raise DshConfigError(+ "Install and open DeepSeek Harness Desktop once, then retry Connect."+ )+ rows, credentials = _read(home)+ provider = _provider(catalog, proxy_root_url, provider_progress_timeout)+ for config in _configs(rows, "llm-pi-ai", create=True):+ providers = _providers(config)+ providers[DSH_PROVIDER_ID] = CommentedMap(copy.deepcopy(provider))+ config["providers"] = providers+ _configs(rows, "agent-default-model", create=True)+ for row in _rows(rows, "agent-default-model"):+ if "config" in row:+ row["config"] = CommentedMap(+ provider=DSH_PROVIDER_ID, model=catalog.default_model_id+ )+ refs = mapping(credentials["refs"]) if "refs" in credentials else CommentedMap()+ refs[DSH_DESKTOP_API_KEY] = auth_token+ credentials["version"], credentials["refs"] = 1, refs+ changed = dsh_files.write_yaml(home / "profiles/desktop/cordis.patch.yml", rows)+ changed |= dsh_files.write_yaml(+ home / ".credentials.yaml", credentials, private=True+ )+ return status(+ home,+ proxy_root_url,+ auth_token,+ catalog,+ provider_progress_timeout=provider_progress_timeout,+ ) | {"changed": changed}+++def disconnect(home: Path) -> JsonObject:+ home = home.resolve()+ with _locked(home):+ rows, credentials = _read(home)+ profile_changed = False+ for config in _configs(rows, "llm-pi-ai"):+ providers = _providers(config)+ if DSH_PROVIDER_ID in providers:+ del providers[DSH_PROVIDER_ID]+ profile_changed = True+ for row in _rows(rows, "agent-default-model"):+ if (+ "config" in row+ and mapping(row["config"]).get("provider") == DSH_PROVIDER_ID+ ):+ # Removing our selection override lets the native bundle supply its default.+ del row["config"]+ profile_changed = True+ if profile_changed:+ dsh_files.write_yaml(home / "profiles/desktop/cordis.patch.yml", rows)+ refs = mapping(credentials["refs"]) if "refs" in credentials else CommentedMap()+ if DSH_DESKTOP_API_KEY in refs:+ del refs[DSH_DESKTOP_API_KEY]+ dsh_files.write_yaml(home / ".credentials.yaml", credentials, private=True)+ return {"connected": False, "paths": _paths(home)}+++def refresh_connected(+ home: Path,+ proxy_root_url: str,+ auth_token: str,+ catalog: ModelCatalog,+ *,+ provider_progress_timeout: float,+) -> bool:+ result = configure(+ home,+ proxy_root_url,+ auth_token,+ catalog,+ provider_progress_timeout=provider_progress_timeout,+ only_existing=True,+ )+ return result["changed"] is Truediff --git a/src/free_claude_code/harnesses/dsh_files.py b/src/free_claude_code/harnesses/dsh_files.pynew file mode 100644index 00000000..db8c2ace--- /dev/null+++ b/src/free_claude_code/harnesses/dsh_files.py@@ -0,0 +1,170 @@+"""Round-trip YAML and cooperative locks for DSH-owned configuration files."""++import errno+import io+import os+import stat+import time+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path++from ruamel.yaml import YAML+from ruamel.yaml.comments import CommentedMap, CommentedSeq+from ruamel.yaml.error import YAMLError++from free_claude_code.harnesses.config_file import atomic_write_text+++class DshConfigError(ValueError):+ """A native configuration cannot be changed without losing user intent."""+++def regular_path(path: Path, *, root: Path | None = None) -> None:+ """Reject redirected files and managed directory ancestors without following them."""+ candidates = [path]+ if root is not None:+ if not path.is_relative_to(root):+ raise DshConfigError(+ "DSH configuration must remain inside its selected home."+ )+ candidates.extend(+ parent+ for parent in path.parents+ if parent != root and parent.is_relative_to(root)+ )+ for item in candidates:+ try:+ info = item.lstat()+ except FileNotFoundError:+ continue+ if stat.S_ISLNK(info.st_mode) or getattr(+ info, "st_file_attributes", 0+ ) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0):+ raise DshConfigError(+ "DSH integration files and directories must be regular paths, not links. Keep the managed files in the selected DSH home."+ )+ expected = stat.S_ISREG if item == path else stat.S_ISDIR+ if not expected(info.st_mode):+ raise DshConfigError(+ "DSH integration needs regular configuration files and directories."+ )+++def yaml_parser() -> YAML:+ parser = YAML(typ="rt", pure=True)+ parser.preserve_quotes = True+ parser.allow_duplicate_keys = False+ return parser+++def read_yaml(path: Path, *, sequence: bool = False) -> CommentedMap | CommentedSeq:+ try:+ source = path.read_text(encoding="utf-8-sig")+ except FileNotFoundError:+ source = ""+ try:+ document = yaml_parser().load(source)+ except YAMLError, UnicodeError:+ # YAML parser messages can quote a line containing a credential.+ raise DshConfigError(+ f"Invalid YAML in {path.name}. Correct it and retry."+ ) from None+ if document is None:+ document = CommentedSeq() if sequence else CommentedMap()+ expected = CommentedSeq if sequence else CommentedMap+ if not isinstance(document, expected):+ raise DshConfigError(f"Unexpected document structure in {path.name}.")+ return document+++def mapping(value: object) -> CommentedMap:+ if not isinstance(value, CommentedMap) or value.tag.value not in (+ None,+ "tag:yaml.org,2002:map",+ ):+ raise DshConfigError(+ "DSH settings need a plain YAML mapping at the FCC integration fields."+ )+ if value.anchor.value:+ raise DshConfigError(+ "DSH settings use an anchor at an FCC integration field. Separate that field before configuring FCC."+ )+ return value+++def write_text(path: Path, content: str, *, private: bool = False) -> bool:+ try:+ if path.read_text(encoding="utf-8") == content:+ return False+ except FileNotFoundError:+ pass+ deadline = time.monotonic() + 2+ while True:+ try:+ atomic_write_text(path, content, private=private)+ return True+ except OSError as exc:+ if (+ os.name != "nt"+ or exc.errno not in (errno.EACCES, errno.EBUSY, errno.EPERM)+ or time.monotonic() >= deadline+ ):+ raise+ time.sleep(0.05)+++def yaml_text(document: CommentedMap | CommentedSeq) -> str:+ # ruamel's flow emitter cannot round-trip a commented empty root sequence.+ # Both styles spell an empty sequence as []; block style retains its comment.+ if isinstance(document, CommentedSeq) and not document:+ document.fa.set_block_style()+ stream = io.StringIO()+ yaml_parser().dump(document, stream)+ return stream.getvalue()+++def write_yaml(+ path: Path, document: CommentedMap | CommentedSeq, *, private: bool = False+) -> bool:+ return write_text(path, yaml_text(document), private=private)+++@contextmanager+def file_lock(path: Path, *, wait: float) -> Iterator[None]:+ """Honor DSH's exclusive PID-file lock; leave stale takeover to DSH."""+ deadline = time.monotonic() + wait+ delay = 0.02+ while True:+ try:+ descriptor = os.open(+ path,+ os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, "O_BINARY", 0),+ 0o600,+ )+ break+ except FileExistsError:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise TimeoutError(+ "DSH is updating its configuration. Finish the native edit and retry."+ ) from None+ time.sleep(min(delay, remaining))+ delay = min(delay * 2, 0.2)+ record = f"{os.getpid()}\n".encode()+ identity = os.fstat(descriptor)+ try:+ os.write(descriptor, record)+ os.fsync(descriptor)+ yield+ finally:+ os.close(descriptor)+ try:+ current = path.stat()+ if (current.st_dev, current.st_ino) == (+ identity.st_dev,+ identity.st_ino,+ ) and path.read_bytes() == record:+ path.unlink()+ except FileNotFoundError:+ passdiff --git a/src/free_claude_code/runtime/application.py b/src/free_claude_code/runtime/application.pyindex 7f0d8a12..aaa5132b 100644--- a/src/free_claude_code/runtime/application.py+++ b/src/free_claude_code/runtime/application.py@@ -404,6 +404,18 @@ class ApplicationRuntime:async def refresh_jetbrains_acp(self) -> JsonObject:return await self._integrations.refresh_jetbrains_acp()+ async def dsh_desktop_status(self) -> JsonObject:+ return await self._integrations.dsh_desktop_status()++ async def connect_dsh_desktop(self) -> JsonObject:+ return await self._integrations.connect_dsh_desktop()++ async def disconnect_dsh_desktop(self) -> JsonObject:+ return await self._integrations.disconnect_dsh_desktop()++ async def refresh_dsh_desktop(self) -> JsonObject:+ return await self._integrations.refresh_dsh_desktop()+async def claude_desktop_status(self) -> JsonObject:return await self._integrations.claude_desktop_status()diff --git a/src/free_claude_code/runtime/folder_picker.py b/src/free_claude_code/runtime/folder_picker.pyindex 6de4af64..d580aaa9 100644--- a/src/free_claude_code/runtime/folder_picker.py+++ b/src/free_claude_code/runtime/folder_picker.py@@ -1,11 +1,9 @@"""Own the native folder dialog for one client request at a time."""import asyncio-import json-import os-import signalimport subprocessimport sys+import tempfilefrom contextlib import suppressfrom pathlib import Path@@ -13,6 +11,7 @@ from loguru import loggerfrom free_claude_code.application.errors import ApplicationUnavailableErrorfrom free_claude_code.cli.process_registry import register_pid, unregister_pid+from free_claude_code.runtime.native_folder_dialog import decode_result_UNAVAILABLE = "Could not open the folder picker. Enter the path manually."@@ -72,15 +71,17 @@ class NativeFolderPicker:raise cancellationreturn task.result()- async def _spawn(self, initial_path: str | None) -> asyncio.subprocess.Process:+ async def _spawn(+ self, initial_path: str | None, stdout: int, stderr: int+ ) -> asyncio.subprocess.Process:return await asyncio.create_subprocess_exec(sys.executable,"-m","free_claude_code.runtime.native_folder_dialog",initial_path or "",stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,+ stdout=stdout,+ stderr=stderr,creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,start_new_session=sys.platform != "win32",)@@ -88,47 +89,41 @@ class NativeFolderPicker:async def _select(self, initial_path: str | None, stop: asyncio.Event) -> str | None:+ process = Nonetry:- process = await self._spawn(initial_path)- except (OSError, ValueError) as exc:- raise _unavailable(exc) from exc- register_pid(process.pid)- reading = asyncio.create_task(process.communicate())- stopped = asyncio.create_task(stop.wait())- try:- await asyncio.wait((reading, stopped), return_when=asyncio.FIRST_COMPLETED)- if stop.is_set():- return None- stdout, stderr = reading.result()- if process.returncode != 0:- raise RuntimeError(stderr.decode("utf-8", errors="replace"))- result = json.loads(stdout)- if not isinstance(result, dict) or "path" not in result:- raise ValueError("Missing folder selection")- path = result["path"]- if path is not None and (- not isinstance(path, str)- or not path- or "\0" in path- or not Path(path).is_absolute()- ):- raise ValueError("Invalid folder selection")- return path+ with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:+ process = await self._spawn(+ initial_path, stdout.fileno(), stderr.fileno()+ )+ register_pid(process.pid)+ exited = asyncio.create_task(process.wait())+ stopped = asyncio.create_task(stop.wait())+ try:+ await asyncio.wait(+ (exited, stopped), return_when=asyncio.FIRST_COMPLETED+ )+ if stop.is_set():+ return None+ returncode = exited.result()+ stdout.seek(0)+ stderr.seek(0)+ path = decode_result(+ stdout.read(), stderr.read(), returncode, platform=sys.platform+ )+ if path is not None and (+ not path or "\0" in path or not Path(path).is_absolute()+ ):+ raise ValueError("Invalid folder selection")+ return path+ finally:+ if process.returncode is None:+ with suppress(ProcessLookupError):+ process.kill()+ await exited+ stopped.cancel()+ await asyncio.gather(stopped, return_exceptions=True)except Exception as exc:raise _unavailable(exc) from excfinally:- try:- if process.returncode is None or not reading.done():- try:- if sys.platform == "win32":- process.kill()- else:- os.killpg(process.pid, signal.SIGKILL)- except ProcessLookupError:- pass- await process.wait()- await reading- finally:- stopped.cancel()- await asyncio.gather(stopped, return_exceptions=True)+ if process is not None:unregister_pid(process.pid)diff --git a/src/free_claude_code/runtime/integration_service.py b/src/free_claude_code/runtime/integration_service.pyindex 1b261cad..37246db5 100644--- a/src/free_claude_code/runtime/integration_service.py+++ b/src/free_claude_code/runtime/integration_service.py@@ -28,6 +28,7 @@ from free_claude_code.harnesses import (claude_desktop_integration,claude_integration,codex_integration,+ dsh_desktop_integration,jetbrains_acp_integration,vscode_chat_integration,)@@ -75,6 +76,9 @@ class IntegrationService:self._jetbrains_update = _IntegrationUpdate()self._vscode_update = _IntegrationUpdate()self._vscode_dirty = False+ self._dsh_update = _IntegrationUpdate()+ self._dsh_dirty = False+ self._dsh_action_revision = 0@propertydef settings(self) -> Settings:@@ -85,6 +89,7 @@ class IntegrationService:"vscode-chat": self._vscode_update,"claude-vscode": self._claude_update,"claude-desktop": self._desktop_update,+ "dsh-desktop": self._dsh_update,"codex": self._codex_update,"jetbrains-acp": self._jetbrains_update,}@@ -135,6 +140,7 @@ class IntegrationService:def catalog_changed(self) -> None:if self._is_draining():return+ self._schedule_dsh_refresh()self._vscode_dirty = Trueupdate = self._vscode_updateif update.task is not None and not update.task.done():@@ -161,6 +167,164 @@ class IntegrationService:update.task = asyncio.create_task(drain(), name="fcc-vscode-models")+ def _schedule_dsh_refresh(self) -> None:+ self._dsh_dirty = True+ update = self._dsh_update+ if update.task is not None and not update.task.done():+ return+ update.state, update.changed, update.message = "starting", False, None++ async def drain() -> None:+ while self._dsh_dirty:+ self._dsh_dirty = False+ try:+ result = await self._dsh_desktop("refresh")+ update.complete(update.changed or result.get("changed") is True)+ except ApplicationError as exc:+ update.state, update.message = "failed", exc.message+ except Exception as exc:+ update.state = "failed"+ update.message = "Could not update DSH Desktop. Retry shortly."+ logger.warning(+ "DSH Desktop update failed: exc_type={}", type(exc).__name__+ )+ if self._dsh_dirty:+ update.state = "starting"++ update.task = asyncio.create_task(drain(), name="fcc-dsh-desktop-models")++ async def dsh_desktop_status(self) -> JsonObject:+ return await self._dsh_desktop("status")++ async def connect_dsh_desktop(self) -> JsonObject:+ return await self._dsh_desktop("connect")++ async def disconnect_dsh_desktop(self) -> JsonObject:+ return await self._dsh_desktop("disconnect")++ async def refresh_dsh_desktop(self) -> JsonObject:+ self._check_integration_available()+ self._schedule_dsh_refresh()+ return {"update": self._dsh_update.snapshot()}++ async def _dsh_desktop(self, action: IntegrationAction) -> JsonObject:+ if action in {"connect", "disconnect"}:+ self._check_integration_available()+ self._dsh_action_revision += 1+ action_revision = self._dsh_action_revision++ def status_reader() -> Callable[[str, str, bool], JsonObject]:+ catalog = read_model_catalog(self.provider_manager)+ timeout = self.settings.provider_progress_timeout+ return lambda url, token, ready: dsh_desktop_integration.status(+ dsh_desktop_integration.config_home(),+ url,+ token,+ catalog,+ provider_progress_timeout=timeout,+ )++ def disconnect(url: str, token: str, ready: bool) -> JsonObject:+ return dsh_desktop_integration.disconnect(+ dsh_desktop_integration.config_home(),+ )++ try:+ if action == "status":+ for _ in range(2):+ settings = self.settings+ revision = self.provider_manager.catalog_status()[+ "catalog_revision"+ ]+ result = await self._read_status(self._dsh_update, status_reader())+ if (+ settings is self.settings+ and revision+ == self.provider_manager.catalog_status()["catalog_revision"]+ ):+ return result+ raise ApplicationUnavailableError(+ "FCC models changed during the check. Retry shortly."+ )+ if action == "disconnect":+ return await self._run_integration(self._dsh_update, action, disconnect)+ if action == "refresh":+ current = await self._read_status(+ self._dsh_update,+ lambda url, token, ready: {+ "connected": dsh_desktop_integration.has_provider(+ dsh_desktop_integration.config_home()+ )+ },+ )+ if not current["connected"]:+ return {"changed": False}+ while True:+ snapshot = await self.provider_manager.wait_for_catalog()+ revision = self.provider_manager.catalog_status()["catalog_revision"]+ async with self._config_lock, self._dsh_update.access.write():+ self._check_integration_available()+ if action_revision != self._dsh_action_revision:+ return await run_sync_owned(+ partial(+ status_reader(),+ local_proxy_root_url(self.settings),+ self.settings.proxy_auth_token,+ True,+ )+ )+ if (+ snapshot.current_settings() is not self.settings+ or revision+ != self.provider_manager.catalog_status()["catalog_revision"]+ or self.provider_manager.catalog_status()["catalog"] != "ready"+ ):+ continue+ catalog = read_model_catalog(snapshot)+ url = local_proxy_root_url(self.settings)+ token = self.settings.proxy_auth_token+ timeout = self.settings.provider_progress_timeout++ def operate(+ catalog: ModelCatalog = catalog,+ url: str = url,+ token: str = token,+ timeout: float = timeout,+ ) -> JsonObject:+ home = dsh_desktop_integration.config_home()+ if action == "refresh":+ return {+ "changed": dsh_desktop_integration.refresh_connected(+ home,+ url,+ token,+ catalog,+ provider_progress_timeout=timeout,+ )+ }+ return dsh_desktop_integration.configure(+ home,+ url,+ token,+ catalog,+ provider_progress_timeout=timeout,+ )++ result = await run_sync_owned(operate)+ if action == "connect":+ self._dsh_update.complete()+ return result+ except dsh_desktop_integration.DshConfigError as exc:+ raise InvalidRequestError(str(exc)) from None+ except ValueError, UnicodeError:+ raise InvalidRequestError(+ "Could not read DSH Desktop configuration. Correct the invalid document and retry."+ ) from None+ except OSError:+ raise ApplicationUnavailableError(+ "Could not update DSH Desktop files. Finish native configuration edits, check file permissions, and retry."+ ) from None+async def _vscode_chat(self, action: IntegrationAction) -> JsonObject:try:if action == "status":diff --git a/src/free_claude_code/runtime/native_folder_dialog.py b/src/free_claude_code/runtime/native_folder_dialog.pyindex 39a1288a..f1c79c69 100644--- a/src/free_claude_code/runtime/native_folder_dialog.py+++ b/src/free_claude_code/runtime/native_folder_dialog.py@@ -1,9 +1,8 @@-"""Short-lived OS dialog helper; stdout carries only its JSON result."""+"""Prepare native dialogs and decode their platform-specific results."""import jsonimport osimport shutil-import subprocessimport sysfrom pathlib import Path@@ -64,16 +63,13 @@ def _windows(initial: str | None) -> str | None:root.destroy()-def _macos(initial: str | None) -> str | None:- result = subprocess.run(- ["/usr/bin/osascript", "-e", _MAC_SCRIPT, initial or ""],- capture_output=True,- check=True,+def _macos(initial: str | None) -> None:+ os.execv(+ "/usr/bin/osascript", ["/usr/bin/osascript", "-e", _MAC_SCRIPT, initial or ""])- return result.stdout.decode("utf-8").removesuffix("\n") or None-def _linux(initial: str | None) -> str | None:+def _linux(initial: str | None) -> None:env = os.environ.copy()if executable := shutil.which("zenity"):command = [executable, "--file-selection", "--directory", f"--title={_TITLE}"]@@ -88,16 +84,34 @@ def _linux(initial: str | None) -> str | None:command.append(initial)else:raise RuntimeError("No desktop folder picker is available")- result = subprocess.run(command, capture_output=True, env=env, check=False)- path = result.stdout.decode("utf-8").removesuffix("\n")- if result.returncode == 0 and path:+ os.execve(executable, command, env)+++def decode_result(+ stdout: bytes, stderr: bytes, returncode: int, *, platform: str+) -> str | None:+ diagnostic = stderr.decode("utf-8", errors="replace")+ if platform.startswith("linux"):+ path = stdout.decode("utf-8").removesuffix("\n")+ if returncode == 0 and path:+ return path+ if any(message in diagnostic.lower() for message in _DISPLAY_ERRORS):+ raise RuntimeError(diagnostic)+ if returncode == 1:+ return None+ raise RuntimeError(diagnostic or "Folder picker returned no directory")+ if returncode != 0:+ raise RuntimeError(diagnostic or "Folder picker failed")+ if platform == "win32":+ result = json.loads(stdout)+ if not isinstance(result, dict) or "path" not in result:+ raise ValueError("Missing folder selection")+ path = result["path"]+ if path is not None and not isinstance(path, str):+ raise ValueError("Invalid folder selection")return path- diagnostic = result.stderr.decode("utf-8", errors="replace")- if any(message in diagnostic.lower() for message in _DISPLAY_ERRORS):- raise RuntimeError(diagnostic)- if result.returncode == 1:- return None- raise RuntimeError(diagnostic or "Folder picker returned no directory")+ path = stdout.decode("utf-8").removesuffix("\n")+ return path or Nonedef main() -> int:@@ -105,18 +119,17 @@ def main() -> int:initial = _initial_directory(sys.argv[1] if len(sys.argv) > 1 else "")if sys.platform == "win32":path = _windows(initial)+ print(json.dumps({"path": path}, ensure_ascii=True))elif sys.platform == "darwin":- path = _macos(initial)+ _macos(initial)elif sys.platform.startswith("linux"):- path = _linux(initial)+ _linux(initial)else:raise RuntimeError("No native folder picker for this platform")- print(json.dumps({"path": path}, ensure_ascii=True))return 0except Exception as exc:print(f"{type(exc).__name__}: {exc}", file=sys.stderr)- print(json.dumps({"error": "unavailable"}))- return 1+ return 2if __name__ == "__main__":diff --git a/tests/api/test_dsh_desktop_integration.py b/tests/api/test_dsh_desktop_integration.pynew file mode 100644index 00000000..62643e5a--- /dev/null+++ b/tests/api/test_dsh_desktop_integration.py@@ -0,0 +1,82 @@+"""The DSH desktop card persists through the existing admin/service boundary."""++import json++import pytest+from fastapi.testclient import TestClient++from free_claude_code.config.settings import Settings+from free_claude_code.harnesses import dsh_desktop_integration as desktop+from tests.api.support import create_test_app++ROOT = "/admin/api/integrations/dsh-desktop"+++def client():+ profile = desktop.config_home() / "profiles/desktop"+ profile.mkdir(parents=True)+ (profile / "package.json").write_text(+ json.dumps(+ {+ "dsh": {+ "profile": {+ "bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app"]+ }+ },+ }+ )+ )+ app = create_test_app(+ Settings(host="0.0.0.0", port=4321, proxy_auth_token="desktop-secret")+ )+ with TestClient(+ app, base_url="http://127.0.0.1", client=("127.0.0.1", 50000)+ ) as client:+ yield client+++def test_configure_status_disconnect_hide_credentials(client):+ before = client.get(ROOT)+ assert before.status_code == 200+ assert not before.json()["connected"]+ response = client.post(ROOT + "/connect")+ assert response.status_code == 200, response.text+ assert response.json()["connected"]+ assert "desktop-secret" not in response.text+ status = client.get(ROOT)+ assert status.json()["connected"]+ assert status.headers["cache-control"] == "no-store"+ assert "desktop-secret" not in status.text+ response = client.post(ROOT + "/disconnect")+ assert response.status_code == 200+ assert not response.json()["connected"]+ assert not client.get(ROOT).json()["connected"]++[email protected]("action", ["", "/connect", "/disconnect", "/refresh"])+def test_routes_reject_foreign_origins(client, action):+ response = client.request(+ "POST" if action else "GET",+ ROOT + action,+ headers={"Origin": "https://evil.test"},+ )+ assert response.status_code == 403+ assert not (desktop.config_home() / ".credentials.yaml").exists()+++def test_invalid_yaml_does_not_leak_its_secret_line(client):+ path = desktop.config_home() / ".credentials.yaml"+ path.write_text("refs: {KEY: secret-one, KEY: secret-two}")+ response = client.post(ROOT + "/connect")+ assert response.status_code == 400+ assert "secret-one" not in response.text+ assert "secret-two" not in response.text+++def test_missing_native_app_returns_setup_guidance(client):+ (desktop.config_home() / "profiles/desktop/package.json").unlink()+ response = client.post(ROOT + "/connect")+ assert response.status_code == 400+ assert "open" in response.json()["detail"].lower()+ assert not (desktop.config_home() / ".credentials.yaml").exists()diff --git a/tests/cli/conftest.py b/tests/cli/conftest.pyindex 0fd20ba2..ec3f34b3 100644--- a/tests/cli/conftest.py+++ b/tests/cli/conftest.py@@ -50,7 +50,7 @@ class LaunchCapture:"opencode": "opencode v2.0.10","cline": "3.0.55","hermes": "Hermes Agent 0.20.4",- "dsh": "0.1.0-rc.8",+ "dsh": "0.2.0-rc.2","grok": '{"currentVersion":"1.0.5"}',"muse": "Muse Code 1.0.3 (1.0.3-R2198.1)",}diff --git a/tests/cli/test_dsh_config.py b/tests/cli/test_dsh_config.pyindex 4b6f23ef..b343ac23 100644--- a/tests/cli/test_dsh_config.py+++ b/tests/cli/test_dsh_config.py@@ -7,8 +7,8 @@ from pathlib import Pathimport pytestfrom free_claude_code.application.model_catalog import CatalogModel-from free_claude_code.cli.launchers.dsh_config import build_dsh_launch_configfrom free_claude_code.core.model_capabilities import ModelInputModality+from free_claude_code.harnesses.dsh_config import build_dsh_launch_configdef _models() -> tuple[CatalogModel, ...]:@@ -48,23 +48,16 @@ def _row_by_id(patch: tuple[dict, ...], row_id: str) -> dict:def test_dsh_config_pins_responses_models_retries_and_private_state(tmp_path: Path,) -> None:- settings_path = tmp_path / "settings.yaml"credentials_path = tmp_path / ".credentials.yaml"launch = build_dsh_launch_config(_models(),default_model_id="nvidia_nim/vendor/model",proxy_root_url="http://127.0.0.1:9191/",- settings_path=settings_path,credentials_path=credentials_path,provider_progress_timeout=600.0,)- settings = _row_by_id(launch, "settings")- assert settings == {- "id": "settings",- "name": "@deepseek-ai/dsh-settings-file",- "config": {"path": str(settings_path), "watch": False},- }+ assert all(row["id"] != "settings" for row in launch)credentials = _row_by_id(launch, "credentials")assert credentials == {"id": "credentials",@@ -133,7 +126,8 @@ def test_dsh_config_pins_responses_models_retries_and_private_state(}for row_id, package in (- ("llm-deepseek", "@deepseek-ai/dsh-llm-deepseek"),+ ("llm-deepseek", "@deepseek-ai/dsh-llm-deepseek-api-key"),+ ("llm-deepseek-account", "@deepseek-ai/dsh-llm-deepseek-account"),("web-search-deepseek", "@deepseek-ai/dsh-web-search-deepseek"),("tool-web", "@deepseek-ai/dsh-tool-web"),):@@ -154,7 +148,6 @@ def test_dsh_config_rounds_fractional_progress_timeout_up() -> None:_models(),default_model_id="nvidia_nim/vendor/model",proxy_root_url="http://127.0.0.1:9191",- settings_path=Path("settings.yaml"),credentials_path=Path("credentials.yaml"),provider_progress_timeout=0.0001,)@@ -171,7 +164,6 @@ def test_dsh_config_rejects_empty_catalog() -> None:(),default_model_id="nvidia_nim/vendor/model",proxy_root_url="http://127.0.0.1:9191",- settings_path=Path("settings.yaml"),credentials_path=Path("credentials.yaml"),provider_progress_timeout=600,)@@ -184,7 +176,6 @@ def test_dsh_config_rejects_invalid_progress_timeout(timeout: float) -> None:_models(),default_model_id="nvidia_nim/vendor/model",proxy_root_url="http://127.0.0.1:9191",- settings_path=Path("settings.yaml"),credentials_path=Path("credentials.yaml"),provider_progress_timeout=timeout,)@@ -196,7 +187,6 @@ def test_dsh_config_rejects_timeout_beyond_node_timer_limit() -> None:_models(),default_model_id="nvidia_nim/vendor/model",proxy_root_url="http://127.0.0.1:9191",- settings_path=Path("settings.yaml"),credentials_path=Path("credentials.yaml"),provider_progress_timeout=2_147_424,)diff --git a/tests/cli/test_dsh_launcher.py b/tests/cli/test_dsh_launcher.pyindex 70efce9b..d58489bb 100644--- a/tests/cli/test_dsh_launcher.py+++ b/tests/cli/test_dsh_launcher.py@@ -2,25 +2,78 @@import jsonfrom pathlib import Path+from unittest.mock import patch+from urllib.error import URLErrorimport pytest+from free_claude_code.cli.launchers import runnerfrom tests.cli.conftest import LaunchCapturefrom tests.cli.test_launcher_workflow import launch@pytest.mark.parametrize(- "args",+ ("args", "expected"),[- [],- ["web", "--port", "8000"],- ["--profile", "headless", "--prompt", "hello"],- ["--profile", "future-native-profile", "--patch", "user.patch.yml"],- ["--", "--help"],+ ([], ["dsh", "web", "--patch", "<patch>"]),+ (+ ["web", "--port", "8000"],+ ["dsh", "web", "--patch", "<patch>", "--port", "8000"],+ ),+ (["headless", "hello"], ["dsh", "headless", "--patch", "<patch>", "hello"]),+ (+ ["--profile", "headless", "hello"],+ ["dsh", "--patch", "<patch>", "--profile", "headless", "hello"],+ ),+ (+ ["--profile=headless", "hello"],+ ["dsh", "--patch", "<patch>", "--profile=headless", "hello"],+ ),+ (+ ["--profile", "future-native-profile", "--patch", "user.patch.yml"],+ [+ "dsh",+ "--patch",+ "<patch>",+ "--profile",+ "future-native-profile",+ "--patch",+ "user.patch.yml",+ ],+ ),+ (+ ["--patch", "user.patch.yml", "--profile", "future-native-profile"],+ [+ "dsh",+ "--patch",+ "<patch>",+ "--patch",+ "user.patch.yml",+ "--profile",+ "future-native-profile",+ ],+ ),+ (+ ["--", "--profile", "app-value"],+ [+ "dsh",+ "--profile",+ "web",+ "--patch",+ "<patch>",+ "--",+ "--profile",+ "app-value",+ ],+ ),+ (+ ["--", "--help"],+ ["dsh", "--profile", "web", "--patch", "<patch>", "--", "--help"],+ ),],)-def test_dsh_attaches_patch_without_classifying_native_profiles(- args: list[str], launch_capture: LaunchCapture+def test_dsh_attaches_patch_without_overriding_native_profile(+ args: list[str], expected: list[str], launch_capture: LaunchCapture) -> None:def inspect(command, env):path = Path(command[command.index("--patch") + 1])@@ -29,7 +82,7 @@ def test_dsh_attaches_patch_without_classifying_native_profiles(assert "openai-responses" in serializedassert "http://127.0.0.1:8182/v1" in serializedassert "nvidia_nim/catalog-model:variant" in serialized- assert json.loads((path.parent / "settings.yaml").read_text()) == {}+ assert not (path.parent / "settings.yaml").exists()assert json.loads((path.parent / ".credentials.yaml").read_text()) == {}assert env["FCC_DSH_API_KEY"] == "launcher-test-token"assert env["DSH_TELEMETRY_DISABLED"] == "1"@@ -38,9 +91,68 @@ def test_dsh_attaches_patch_without_classifying_native_profiles(launch_capture.on_start = inspectlaunch("dsh", args)command = launch_capture.commands[0]- if not args or args[0] == "web":- assert command[:3] == ["dsh", "web", "--patch"]- assert command[4:] == args[1:]- else:- assert command[:4] == ["dsh", "--profile", "web", "--patch"]- assert command[5:] == args+ command[command.index("--patch") + 1] = "<patch>"+ assert command == expected+++ "args",+ [+ ["--port", "9000", "--profile", "app-value"],+ ["--future-app-option", "--profile=headless"],+ ["--", "--profile", "headless"],+ ],+)+def test_app_arguments_cannot_select_the_launch_profile(+ args: list[str], launch_capture: LaunchCapture+) -> None:+ launch("dsh", args)+ command = launch_capture.commands[0]+ prefix = command[: -len(args)]+ assert "web" in prefix+ assert prefix.count("--profile") == 1+ assert command[-len(args) :] == args+++ "args",+ [+ ["--help"],+ ["-h"],+ ["--version"],+ ["-V"],+ ["plugin", "--profile", "web", "list"],+ ["web", "--dump-default-config"],+ ["--patch", "user.patch.yml", "--help"],+ ],+)+def test_control_commands_do_not_require_fcc(+ args: list[str], launch_capture: LaunchCapture+) -> None:+ launch_capture.health_error = URLError("FCC is stopped")+ with patch.object(runner, "get_settings") as settings:+ launch("dsh", args)+ settings.assert_not_called()+ assert not launch_capture.requests+ assert launch_capture.commands == [["dsh", *args]]+ assert "FCC_DSH_API_KEY" not in launch_capture.environments[0]+++ "args",+ [+ ["web", "--help"],+ ["headless", "prompt", "--version"],+ ["--profile", "web", "--port", "9000", "--dump-default-config"],+ ["web", "--dump-config"],+ ["web", "--dump-config-schema"],+ ["--profile", "--version"],+ ["--patch", "--dump-default-config"],+ ],+)+def test_profile_operations_receive_fcc_configuration(+ args: list[str], launch_capture: LaunchCapture+) -> None:+ launch("dsh", args)+ assert len(launch_capture.requests) == 2+ assert "--patch" in launch_capture.commands[0]diff --git a/tests/cli/test_launcher_checks.py b/tests/cli/test_launcher_checks.pyindex 835e52f4..4b179ba4 100644--- a/tests/cli/test_launcher_checks.py+++ b/tests/cli/test_launcher_checks.py@@ -33,9 +33,19 @@ from tests.cli.test_launcher_workflow import HARNESSES, launch("cline", "3.1.0-beta", False),("hermes", "Hermes Agent v0.20.4", True),("hermes", "Hermes Agent 0.20.3", False),- ("dsh", "dsh v0.1.0-rc.8", True),- ("dsh", "0.1.0-rc.7", False),- ("dsh", "0.1.0-rc.9", False),+ ("dsh", "dsh v0.2.0-rc.2", True),+ ("dsh", "0.1.0-rc.8", False),+ ("dsh", "0.2.0-rc.1", False),+ ("dsh", "0.2.0-rc.3", True),+ ("dsh", "0.2.0-rc.10", True),+ ("dsh", "0.2.0", True),+ ("dsh", "v1.0.0", True),+ ("dsh", "0.2.0-rc.2+build.7", True),+ ("dsh", "0.2.0-alpha.9", False),+ ("dsh", "0.2.0-rc.02", False),+ ("dsh", "0.2.0-rc", False),+ ("dsh", "0.2.0-zeta", True),+ ("dsh", "opaque upstream output", False),("grok", '{"currentVersion":"1.0.5"}', True),("grok", '{"currentVersion":"1.1.0+build (build info)"}', True),("grok", '{"currentVersion":"1.0.4"}', False),@@ -56,7 +66,7 @@ def test_native_compatibility_precedes_fcc_setup(name: str, output: str, compatible: bool, launch_capture: LaunchCapture) -> None:launch_capture.versions[name] = output- launch(name, ["--help"], exit_code=23 if compatible else 126)+ launch(name, [], exit_code=23 if compatible else 126)assert bool(launch_capture.commands) is compatibleassert bool(launch_capture.requests) is compatiblediff --git a/tests/cli/test_launcher_workflow.py b/tests/cli/test_launcher_workflow.pyindex 8127903f..6da2c006 100644--- a/tests/cli/test_launcher_workflow.py+++ b/tests/cli/test_launcher_workflow.py@@ -103,7 +103,7 @@ def test_launch_default_is_server_selection_not_first_row_or_local_settings(launch(name, [])[email protected]("name", HARNESSES)[email protected]("name", tuple(name for name in HARNESSES if name != "dsh"))def test_help_receives_normal_fcc_setup(name: str, launch_capture: LaunchCapture) -> None:@@ -123,7 +123,7 @@ def test_help_receives_normal_fcc_setup(][email protected]("name", HARNESSES)[email protected]("name", tuple(name for name in HARNESSES if name != "dsh"))def test_help_does_not_bypass_failed_setup(name: str, launch_capture: LaunchCapture) -> None:diff --git a/tests/conftest.py b/tests/conftest.pyindex e2799bf4..158e0e3d 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -35,6 +35,8 @@ def _isolate_managed_config(monkeypatch, tmp_path):"""Keep every test away from real home, checkout, and running-server config."""config_dir = tmp_path / ".fcc"+ monkeypatch.setenv("DSH_HOME", str(tmp_path / ".dsh"))+ monkeypatch.delenv("FCC_DSH_DESKTOP_API_KEY", raising=False)monkeypatch.setattr(vscode_chat_integration,"config_path",diff --git a/tests/harnesses/test_dsh_desktop_integration.py b/tests/harnesses/test_dsh_desktop_integration.pynew file mode 100644index 00000000..ec3eba79--- /dev/null+++ b/tests/harnesses/test_dsh_desktop_integration.py@@ -0,0 +1,256 @@+"""FCC compares and changes only its native DSH Desktop entries."""++import copy+import json++import pytest+from ruamel.yaml import YAML++from free_claude_code.application.model_catalog import CatalogModel, ModelCatalog+from free_claude_code.harnesses import dsh_desktop_integration as desktop+from free_claude_code.harnesses import dsh_files++URL = "http://127.0.0.1:8182"+TOKEN = "desktop-test-token"+ROUTE = "free-claude-code"+REF = desktop.DSH_DESKTOP_API_KEY+++def catalog(name="fixture/model"):+ return ModelCatalog((CatalogModel(name, name, name, True),), name)+++def read(path):+ return YAML(typ="rt").load(path.read_text(encoding="utf-8"))+++def write(path, value):+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("w", encoding="utf-8") as stream:+ YAML(typ="rt").dump(value, stream)+++def config(rows, identity):+ return next(+ row["config"]+ for row in reversed(rows)+ if row.get("id") == identity and "config" in row+ )+++def home(tmp_path):+ root = tmp_path / "dsh"+ profile = root / "profiles/desktop"+ profile.mkdir(parents=True)+ (profile / "package.json").write_text('{"dsh":{"profile":{"bundles":[]}}}')+ (profile / "cordis.patch.yml").write_text("# native settings\n[]\n")+ return root+++def connect(home, token=TOKEN, model="fixture/model"):+ return desktop.configure(+ home, URL, token, catalog(model), provider_progress_timeout=600+ )+++def status(home):+ return desktop.status(home, URL, TOKEN, catalog(), provider_progress_timeout=600)+++def test_connect_status_disconnect_and_reconnect(home):+ assert not status(home)["connected"]+ result = connect(home)+ assert result["connected"]+ patch = home / "profiles/desktop/cordis.patch.yml"+ provider = config(read(patch), "llm-pi-ai")["providers"][ROUTE]+ assert provider["api"] == "openai-responses"+ assert provider["baseURL"] == URL + "/v1"+ assert provider["models"][0]["id"] == "fixture/model"+ assert provider["apiKeyEnv"] == REF+ assert read(home / ".credentials.yaml")["refs"][REF] == TOKEN+ assert config(read(patch), "agent-default-model") == {+ "provider": ROUTE,+ "model": "fixture/model",+ }+ assert TOKEN not in patch.read_text() + json.dumps(result)+ assert status(home)["connected"]+ assert not connect(home)["changed"]+ assert not desktop.disconnect(home)["connected"]+ assert ROUTE not in patch.read_text()+ assert REF not in (home / ".credentials.yaml").read_text()+ assert not status(home)["connected"]+ assert not desktop.disconnect(home)["connected"]+ assert connect(home)["connected"]+++ "field",+ [+ "provider",+ "baseURL",+ "models",+ "apiKeyEnv",+ "streamIdleTimeoutMs",+ "displayName",+ "api",+ "defaultInput",+ "retryPolicy",+ "default",+ "token",+ "missing-token",+ ],+)+def test_status_requires_all_fcc_keys_and_connect_replaces_them(home, field):+ connect(home)+ patch = home / "profiles/desktop/cordis.patch.yml"+ credentials = home / ".credentials.yaml"+ rows = read(patch)+ providers = config(rows, "llm-pi-ai")["providers"]+ if field == "provider":+ del providers[ROUTE]+ elif field == "default":+ config(rows, "agent-default-model")["model"] = "other"+ elif field in {"token", "missing-token"}:+ data = read(credentials)+ if field == "token":+ data["refs"][REF] = "edited"+ else:+ del data["refs"][REF]+ write(credentials, data)+ else:+ providers[ROUTE][field] = [] if field == "models" else "changed"+ write(patch, rows)+ assert not status(home)["connected"]+ assert connect(home)["connected"]+ assert status(home)["connected"]+++def test_status_compares_current_catalog_url_token_and_timeout(home):+ connect(home)+ for url, token, models, timeout in [+ (URL + "-changed", TOKEN, catalog(), 600),+ (URL, "rotated", catalog(), 600),+ (URL, TOKEN, catalog("fixture/new"), 600),+ (URL, TOKEN, catalog(), 30),+ ]:+ assert not desktop.status(+ home, url, token, models, provider_progress_timeout=timeout+ )["connected"]+++def test_other_settings_accounts_comments_tags_and_peer_files_are_preserved(home):+ patch = home / "profiles/desktop/cordis.patch.yml"+ patch.write_text("""# keep native settings+- id: unrelated+ config:+ computed: !!js "ctx.get('something')"+- id: llm-pi-ai+ config:+ anotherSetting: unchanged+ providers:+ other:+ apiKeyEnv: OTHER_KEY # keep comment+ models: [unchanged]+""")+ credentials = home / ".credentials.yaml"+ credentials.write_text(+ 'version: 1\nrefs:\n OTHER_KEY: "keep-secret" # keep key\nrecords: {native: unchanged}\n'+ )+ peer = home / "profiles/web/cordis.patch.yml"+ peer.parent.mkdir()+ peer.write_text("unreadable unrelated profile, even if it names " + REF)+ before = read(patch)+ connect(home)+ connect(home, token="rotated", model="fixture/new")+ assert read(credentials)["refs"] == {"OTHER_KEY": "keep-secret", REF: "rotated"}+ desktop.disconnect(home)+ after = read(patch)+ assert after[1] == before[1]+ assert after[0]["config"]["computed"].value == before[0]["config"]["computed"].value+ assert after[0]["config"]["computed"].tag == before[0]["config"]["computed"].tag+ assert "# keep native settings" in patch.read_text()+ assert "# keep comment" in patch.read_text()+ assert read(credentials) == {+ "version": 1,+ "refs": {"OTHER_KEY": "keep-secret"},+ "records": {"native": "unchanged"},+ }+ assert "# keep key" in credentials.read_text()+ assert peer.read_text() == "unreadable unrelated profile, even if it names " + REF+++def test_disconnect_removes_all_fcc_copies_and_preserves_other_default(home):+ connect(home)+ patch = home / "profiles/desktop/cordis.patch.yml"+ rows = read(patch)+ rows.append(copy.deepcopy(rows[0]))+ rows.append(+ {+ "id": "agent-default-model",+ "config": {"provider": "other", "model": "other-model"},+ }+ )+ write(patch, rows)+ desktop.disconnect(home)+ assert ROUTE not in patch.read_text()+ assert config(read(patch), "agent-default-model") == {+ "provider": "other",+ "model": "other-model",+ }++[email protected]("operation", ["connect", "disconnect"])+def test_partial_write_is_disconnected_and_connect_can_repair(+ home, monkeypatch, operation+):+ if operation == "disconnect":+ connect(home)+ original = dsh_files.write_yaml++ def fail(path, *args, **kwargs):+ if path == home / ".credentials.yaml":+ raise PermissionError("test failure")+ return original(path, *args, **kwargs)++ with monkeypatch.context() as scoped:+ scoped.setattr(dsh_files, "write_yaml", fail)+ with pytest.raises(PermissionError):+ connect(home) if operation == "connect" else desktop.disconnect(home)+ assert not status(home)["connected"]+ assert connect(home)["connected"]+ assert not desktop.disconnect(home)["connected"]+++def test_absent_home_status_disconnect_and_refresh_create_nothing(tmp_path):+ home = tmp_path / "absent"+ assert not status(home)["connected"]+ assert not desktop.disconnect(home)["connected"]+ assert not desktop.refresh_connected(+ home, URL, TOKEN, catalog(), provider_progress_timeout=600+ )+ assert not home.exists()+++def test_invalid_yaml_does_not_modify_files_or_expose_secrets(home):+ patch = home / "profiles/desktop/cordis.patch.yml"+ patch.write_text("secret: [private-token")+ before = patch.read_bytes()+ with pytest.raises(desktop.DshConfigError, match="Invalid YAML") as error:+ connect(home)+ assert "private-token" not in str(error.value)+ assert patch.read_bytes() == before+ assert not (home / ".credentials.yaml").exists()+++def test_connect_honors_native_profile_lock(home, monkeypatch):+ lock = home / "profiles/desktop/package.json.lock"+ lock.write_text("native writer")+ original = dsh_files.file_lock+ monkeypatch.setattr(+ dsh_files, "file_lock", lambda path, **kwargs: original(path, wait=0)+ )+ with pytest.raises(TimeoutError):+ connect(home)+ assert lock.read_text() == "native writer"+ assert not (home / ".credentials.yaml").exists()diff --git a/tests/harnesses/test_dsh_files.py b/tests/harnesses/test_dsh_files.pynew file mode 100644index 00000000..0fca02ce--- /dev/null+++ b/tests/harnesses/test_dsh_files.py@@ -0,0 +1,52 @@+"""DSH's cooperative file locks and YAML preservation are native contracts."""++import os++import pytest++from free_claude_code.harnesses import dsh_files+++def test_lock_uses_native_pid_bytes_and_is_released(tmp_path):+ path = tmp_path / "package.json.lock"+ with dsh_files.file_lock(path, wait=0):+ assert path.read_bytes() == f"{os.getpid()}\n".encode()+ assert not path.exists()+++def test_lock_does_not_steal_or_remove_an_existing_record(tmp_path):+ path = tmp_path / "package.json.lock"+ path.write_bytes(b"999999999\n")+ with pytest.raises(TimeoutError), dsh_files.file_lock(path, wait=0):+ pytest.fail("acquired another owner's lock")+ assert path.read_bytes() == b"999999999\n"+++def test_lock_release_does_not_remove_a_replacement(tmp_path):+ path = tmp_path / "package.json.lock"+ with dsh_files.file_lock(path, wait=0):+ path.write_bytes(b"another-owner\n")+ assert path.read_bytes() == b"another-owner\n"+++def test_yaml_errors_never_quote_credentials(tmp_path):+ path = tmp_path / ".credentials.yaml"+ path.write_text("refs: {KEY: super-secret, KEY: another-secret}")+ with pytest.raises(ValueError) as error:+ dsh_files.read_yaml(path)+ assert "secret" not in str(error.value)+++def test_untouched_tags_comments_and_anchors_survive(tmp_path):+ path = tmp_path / "cordis.patch.yml"+ path.write_text("""# native comment+other: &keep+ expr: !!js "ctx.get('native')"+copy: *keep+""")+ doc = dsh_files.read_yaml(path)+ dsh_files.write_yaml(path, doc)+ result = path.read_text()+ assert "# native comment" in result+ assert "&keep" in result and "*keep" in result+ assert "!!js" in resultdiff --git a/tests/runtime/test_dsh_desktop_sync.py b/tests/runtime/test_dsh_desktop_sync.pynew file mode 100644index 00000000..6b29233f--- /dev/null+++ b/tests/runtime/test_dsh_desktop_sync.py@@ -0,0 +1,230 @@+"""DSH models follow catalog publication without resurrecting disconnected state."""++import asyncio+import json+import threading+from unittest.mock import AsyncMock++import pytest+import pytest_asyncio+from ruamel.yaml import YAML++from free_claude_code.application.model_metadata import ProviderModelInfo+from free_claude_code.harnesses import dsh_desktop_integration as desktop+from tests.runtime.test_integration_startup import runtime as runtime+++def install():+ profile = desktop.config_home() / "profiles/desktop"+ profile.mkdir(parents=True)+ (profile / "package.json").write_text(+ json.dumps(+ {+ "dsh": {+ "profile": {+ "bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app"]+ }+ },+ }+ )+ )+++def route():+ rows = YAML().load(+ (desktop.config_home() / "profiles/desktop/cordis.patch.yml").read_text()+ )+ return next(+ row["config"]["providers"]["free-claude-code"]+ for row in rows+ if row["id"] == "llm-pi-ai"+ )+++async def settle(runtime):+ await runtime.provider_manager.wait_for_catalog()+ task = runtime._integrations._dsh_update.task+ if task:+ await asyncio.wait_for(asyncio.shield(task), 5)+++@pytest_asyncio.fixture+async def connected(runtime):+ install()+ await runtime.start()+ try:+ await runtime.connect_dsh_desktop()+ await settle(runtime)+ yield runtime+ finally:+ await runtime.close()+++async def test_late_catalog_updates_and_disconnect_remains_removed(connected):+ runtime = connected+ runtime.provider_manager.cache_model_infos(+ "nvidia_nim", (ProviderModelInfo("two"),)+ )+ await asyncio.gather(*runtime.provider_manager._publications)+ await settle(runtime)+ assert {model["id"] for model in route()["models"]} == {+ "nvidia_nim/one",+ "nvidia_nim/two",+ }+ await runtime.disconnect_dsh_desktop()+ runtime._integrations.catalog_changed()+ await settle(runtime)+ assert not desktop.has_provider(desktop.config_home())+ assert not (await runtime.dsh_desktop_status())["connected"]+++async def test_disconnect_during_catalog_wait_cannot_be_reconnected(+ connected, monkeypatch+):+ runtime = connected+ entered, release = asyncio.Event(), asyncio.Event()+ original = runtime.provider_manager.wait_for_catalog++ async def held():+ entered.set()+ await release.wait()+ return await original()++ monkeypatch.setattr(runtime.provider_manager, "wait_for_catalog", held)+ try:+ await runtime.refresh_dsh_desktop()+ await asyncio.wait_for(entered.wait(), 5)+ assert (await asyncio.wait_for(runtime.dsh_desktop_status(), 1))["connected"]+ assert not (await asyncio.wait_for(runtime.disconnect_dsh_desktop(), 1))[+ "connected"+ ]+ finally:+ release.set()+ await settle(runtime)+ assert not desktop.has_provider(desktop.config_home())+++async def test_status_and_disconnect_do_not_need_catalog(connected, monkeypatch):+ runtime = connected+ monkeypatch.setattr(+ runtime.provider_manager,+ "wait_for_catalog",+ AsyncMock(side_effect=AssertionError("must not wait")),+ )+ assert (await runtime.dsh_desktop_status())["connected"]+ assert not (await runtime.disconnect_dsh_desktop())["connected"]+++async def test_new_generation_replaces_old_url_and_credential(connected, monkeypatch):+ runtime = connected+ entered, release = asyncio.Event(), asyncio.Event()+ original = runtime.provider_manager.wait_for_catalog+ calls = 0++ async def held():+ nonlocal calls+ snapshot = await original()+ calls += 1+ if calls == 1:+ entered.set()+ await release.wait()+ return snapshot++ monkeypatch.setattr(runtime.provider_manager, "wait_for_catalog", held)+ try:+ await runtime.refresh_dsh_desktop()+ await asyncio.wait_for(entered.wait(), 5)+ await runtime.provider_manager.replace(+ runtime.settings.model_copy(+ update={"port": 12345, "proxy_auth_token": "rotated"}+ ),+ commit=AsyncMock(),+ reason="test",+ )+ finally:+ release.set()+ await settle(runtime)+ assert route()["baseURL"] == "http://127.0.0.1:12345/v1"+ credentials = YAML().load((desktop.config_home() / ".credentials.yaml").read_text())+ assert credentials["refs"][desktop.DSH_DESKTOP_API_KEY] == "rotated"+ assert (await runtime.dsh_desktop_status())["connected"]+++async def test_catalog_change_during_write_is_coalesced_without_loss(+ connected, monkeypatch+):+ runtime = connected+ entered, release = asyncio.Event(), threading.Event()+ loop = asyncio.get_running_loop()+ original = desktop.refresh_connected+ calls = 0++ def held(*args, **kwargs):+ nonlocal calls+ calls += 1+ if calls == 1:+ loop.call_soon_threadsafe(entered.set)+ assert release.wait(5)+ return original(*args, **kwargs)++ monkeypatch.setattr(desktop, "refresh_connected", held)+ try:+ runtime._integrations.catalog_changed()+ await asyncio.wait_for(entered.wait(), 5)+ runtime.provider_manager.cache_model_infos(+ "nvidia_nim", (ProviderModelInfo("late"),)+ )+ await asyncio.gather(*runtime.provider_manager._publications)+ finally:+ release.set()+ await settle(runtime)+ assert calls >= 2+ assert "nvidia_nim/late" in {model["id"] for model in route()["models"]}+++async def test_startup_without_connection_does_not_create_native_profile(runtime):+ try:+ await runtime.start()+ await settle(runtime)+ assert not desktop.config_home().exists()+ assert not desktop.has_provider(desktop.config_home())+ finally:+ await runtime.close()+++async def test_first_configure_waiting_for_catalog_is_superseded_by_disconnect(+ runtime, monkeypatch+):+ install()+ await runtime.start()+ await settle(runtime)+ entered, release = asyncio.Event(), asyncio.Event()+ original = runtime.provider_manager.wait_for_catalog++ async def held():+ entered.set()+ await release.wait()+ return await original()++ monkeypatch.setattr(runtime.provider_manager, "wait_for_catalog", held)+ task = asyncio.create_task(runtime.connect_dsh_desktop())+ try:+ await asyncio.wait_for(entered.wait(), 5)+ assert not (await asyncio.wait_for(runtime.disconnect_dsh_desktop(), 1))[+ "connected"+ ]+ release.set()+ await asyncio.wait_for(task, 5)+ assert not desktop.has_provider(desktop.config_home())+ assert not (await runtime.dsh_desktop_status())["connected"]+ finally:+ release.set()+ await asyncio.gather(task, return_exceptions=True)+ await runtime.close()diff --git a/tests/runtime/test_folder_picker.py b/tests/runtime/test_folder_picker.pyindex 6186f71e..8e48f462 100644--- a/tests/runtime/test_folder_picker.py+++ b/tests/runtime/test_folder_picker.py@@ -1,8 +1,11 @@import asyncioimport jsonimport os+import signalimport subprocessimport sys+from contextlib import suppress+from pathlib import Pathimport pytest@@ -10,6 +13,90 @@ from free_claude_code.application.errors import ApplicationUnavailableErrorfrom free_claude_code.runtime.folder_picker import NativeFolderPicker+async def _retained_handle_probe(directory, cancel):+ root = Path(directory)+ ready = root / "descendant.pid"+ child_script = (+ "import os, pathlib, threading; "+ f"pathlib.Path({str(ready)!r}).write_text(str(os.getpid())); "+ "threading.Event().wait()"+ )+ selection = str(root)+ payload = json.dumps({"path": selection}) if sys.platform == "win32" else selection+ script = (+ "import pathlib, subprocess, sys, time\n"+ f"subprocess.Popen([sys.executable, '-c', {child_script!r}], start_new_session=True)\n"+ f"while not pathlib.Path({str(ready)!r}).exists(): time.sleep(0.01)\n"+ + ("time.sleep(60)\n" if cancel else f"print({payload!r}, flush=True)\n")+ )+ picker = NativeFolderPicker()+ process = None++ async def spawn(+ _initial, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE+ ):+ nonlocal process+ process = await asyncio.create_subprocess_exec(+ sys.executable,+ "-u",+ "-c",+ script,+ stdout=stdout,+ stderr=stderr,+ start_new_session=sys.platform != "win32",+ creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,+ )+ (root / "helper.pid").write_text(str(process.pid))+ return process++ patcher = pytest.MonkeyPatch()+ patcher.setattr(picker, "_spawn", spawn)+ request = asyncio.create_task(picker.pick_folder(None))+ try:+ async with asyncio.timeout(5):+ while not ready.exists() or not ready.read_text():+ await asyncio.sleep(0.01)+ if cancel:+ request.cancel()+ done, _ = await asyncio.wait({request}, timeout=1)+ assert done, "Picker is waiting for output handles retained by a descendant"+ if cancel:+ with pytest.raises(asyncio.CancelledError):+ await request+ else:+ assert await request == selection+ assert process is not None and process.returncode is not None+ finally:+ if ready.exists():+ os.kill(int(ready.read_text()), signal.SIGTERM)+ ready.unlink()+ await picker.close()+ await asyncio.gather(request, return_exceptions=True)+ (root / "helper.pid").unlink(missing_ok=True)+ patcher.undo()++[email protected]("cancel", [False, True])+def test_picker_does_not_wait_for_inherited_output_handles(tmp_path, cancel):+ script = (+ "import asyncio, runpy, sys; "+ "probe = runpy.run_path(sys.argv[1])['_retained_handle_probe']; "+ "asyncio.run(probe(sys.argv[2], sys.argv[3] == 'True'))"+ )+ try:+ result = subprocess.run(+ [sys.executable, "-c", script, __file__, str(tmp_path), str(cancel)],+ capture_output=True,+ text=True,+ timeout=15,+ )+ finally:+ for path in tmp_path.glob("*.pid"):+ with suppress(ProcessLookupError):+ os.kill(int(path.read_text()), signal.SIGTERM)+ assert result.returncode == 0, result.stdout + result.stderr++class DialogProcess:"""A real child, with barriers around the return from subprocess creation."""@@ -19,47 +106,165 @@ class DialogProcess:self.return_spawn = asyncio.Event()self.return_spawn.set()self.process: asyncio.subprocess.Process+ self.captures = []- async def spawn(self, _initial_path):+ async def spawn(self, _initial_path, stdout, stderr):+ self.captures.extend((stdout, stderr))self.process = await asyncio.create_subprocess_exec(sys.executable,"-u","-c",- "print('ready', flush=True)\n" + self.script,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,+ self.script,+ stdout=stdout,+ stderr=stderr,creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,start_new_session=sys.platform != "win32",)- assert self.process.stdout is not None- assert (await self.process.stdout.readline()).rstrip(b"\r\n") == b"ready"self.started.set()await self.return_spawn.wait()return self.process+async def _exec_identity_probe(directory, after_exec):+ root = Path(directory)+ helper_ready, exec_ready, proceed = (+ root / name for name in ("helper.pid", "exec.pid", "proceed")+ )+ command = root / "native-picker"+ command.write_text(+ f"#!{sys.executable}\nimport os, pathlib, threading\n"+ f"pathlib.Path({str(exec_ready)!r}).write_text(str(os.getpid()))\n"+ "threading.Event().wait()\n",+ encoding="utf-8",+ )+ command.chmod(0o700)+ child = DialogProcess(+ "import os, pathlib, time\n"+ "from free_claude_code.runtime import native_folder_dialog as native\n"+ f"pathlib.Path({str(helper_ready)!r}).write_text(str(os.getpid()))\n"+ f"while not pathlib.Path({str(proceed)!r}).exists(): time.sleep(0.01)\n"+ f"native.shutil.which = lambda _: {str(command)!r}\n"+ "native._linux(None)\n"+ )+ picker = NativeFolderPicker()+ with pytest.MonkeyPatch.context() as patcher:+ patcher.setattr(picker, "_spawn", child.spawn)+ request = asyncio.create_task(picker.pick_folder(None))+ try:+ async with asyncio.timeout(5):+ while not helper_ready.exists() or not helper_ready.read_text():+ await asyncio.sleep(0.01)+ if after_exec:+ proceed.touch()+ while not exec_ready.exists() or not exec_ready.read_text():+ await asyncio.sleep(0.01)+ assert int(exec_ready.read_text()) == child.process.pid+ assert int(helper_ready.read_text()) == child.process.pid+ request.cancel()+ done, _ = await asyncio.wait({request}, timeout=1)+ assert done, "Picker cancellation did not reap its owned process"+ with pytest.raises(asyncio.CancelledError):+ await request+ assert child.process.returncode is not None+ finally:+ await picker.close()+ await asyncio.gather(request, return_exceptions=True)+ helper_ready.unlink(missing_ok=True)+ exec_ready.unlink(missing_ok=True)++[email protected](os.name == "nt", reason="POSIX exec replacement")[email protected]("after_exec", [False, True])+def test_posix_exec_preserves_owned_pid_and_cancellation(tmp_path, after_exec):+ script = (+ "import asyncio, runpy, sys; "+ "probe = runpy.run_path(sys.argv[1])['_exec_identity_probe']; "+ "asyncio.run(probe(sys.argv[2], sys.argv[3] == 'True'))"+ )+ try:+ result = subprocess.run(+ [sys.executable, "-c", script, __file__, str(tmp_path), str(after_exec)],+ capture_output=True,+ text=True,+ timeout=15,+ )+ finally:+ if (pid_file := tmp_path / "helper.pid").exists():+ with suppress(ProcessLookupError):+ os.kill(int(pid_file.read_text()), signal.SIGTERM)+ assert result.returncode == 0, result.stdout + result.stderr++@pytest.mark.asyncio@pytest.mark.parametrize("cancelled", [False, True])async def test_selection_and_cancellation_return_after_child_exit(monkeypatch, tmp_path, cancelled):path = None if cancelled else str(tmp_path / "project café with spaces")- child = DialogProcess(f"print({json.dumps({'path': path})!r})")+ if sys.platform.startswith("linux") and cancelled:+ script = "import sys; sys.exit(1)"+ else:+ output = json.dumps({"path": path}) if sys.platform == "win32" else path or ""+ script = f"print({output!r})"+ child = DialogProcess(script)picker = NativeFolderPicker()monkeypatch.setattr(picker, "_spawn", child.spawn)assert await picker.pick_folder(None) == path- assert child.process.returncode == 0+ assert child.process.returncode == (+ 1 if sys.platform.startswith("linux") and cancelled else 0+ )+ for capture in child.captures:+ with pytest.raises(OSError):+ os.fstat(capture)# Completion makes the next independent click available.assert await picker.pick_folder(None) == pathawait picker.close()[email protected]("spawn_fails", [False, True])+async def test_spawn_and_result_failures_close_captures_before_unregister(+ monkeypatch, spawn_fails+):+ from free_claude_code.runtime import folder_picker++ picker = NativeFolderPicker()+ child = DialogProcess("print('invalid result')")+ captures = []+ registrations = []++ async def spawn(initial, stdout, stderr):+ captures.extend((stdout, stderr))+ if spawn_fails:+ raise FileNotFoundError("Native executable disappeared")+ return await child.spawn(initial, stdout, stderr)++ def unregister(pid):+ assert child.process.returncode is not None+ for capture in captures:+ with pytest.raises(OSError):+ os.fstat(capture)+ registrations.remove(pid)++ monkeypatch.setattr(picker, "_spawn", spawn)+ monkeypatch.setattr(folder_picker, "register_pid", registrations.append)+ monkeypatch.setattr(folder_picker, "unregister_pid", unregister)+ with pytest.raises(ApplicationUnavailableError):+ await picker.pick_folder(None)+ assert not registrations+ for capture in captures:+ with pytest.raises(OSError):+ os.fstat(capture)+ assert picker._active is None+ await picker.close()++@pytest.mark.asyncioasync def test_selection_failure_racing_shutdown_is_reported_to_request(monkeypatch):picker = NativeFolderPicker()started = asyncio.Event()- async def spawn(_initial):+ async def spawn(_initial, stdout, stderr):started.set()await picker._stop.wait()raise FileNotFoundError("Native picker disappeared while shutdown started")@@ -144,22 +349,3 @@ async def test_interrupted_close_still_waits_for_child_cleanup(monkeypatch):await closingassert await request is Noneassert child.process.returncode is not None--[email protected](os.name == "nt", reason="POSIX process group ownership")-async def test_cancellation_reaps_a_helper_waiting_on_its_child(monkeypatch):- child = DialogProcess(- "import subprocess, sys\n"- "subprocess.run([sys.executable, '-c', 'import threading; threading.Event().wait()'])"- )- picker = NativeFolderPicker()- monkeypatch.setattr(picker, "_spawn", child.spawn)- request = asyncio.create_task(picker.pick_folder(None))- await child.started.wait()- request.cancel()- with pytest.raises(asyncio.CancelledError):- await request- # communicate() also waits for pipes inherited by descendants to close.- assert child.process.returncode is not None- await picker.close()diff --git a/tests/runtime/test_native_folder_dialog.py b/tests/runtime/test_native_folder_dialog.pyindex e1768a93..ba0205ff 100644--- a/tests/runtime/test_native_folder_dialog.py+++ b/tests/runtime/test_native_folder_dialog.py@@ -6,31 +6,52 @@ import pytestfrom free_claude_code.runtime import native_folder_dialog as native[email protected]("platform", ["macos", "linux"])+def test_posix_dialog_replaces_helper_without_spawning_child(monkeypatch, platform):+ calls = []++ def exec_command(path, arguments, *env):+ calls.append((path, arguments, env))+ raise SystemExit(0)++ def nested_child(*args, **kwargs):+ pytest.fail("Native dialog must replace the owned helper process")++ monkeypatch.setattr(native.os, "execv", exec_command)+ monkeypatch.setattr(native.os, "execve", exec_command)+ monkeypatch.setattr(subprocess, "run", nested_child)+ monkeypatch.setattr(native.shutil, "which", lambda _: "/usr/bin/zenity")+ with pytest.raises(SystemExit):+ getattr(native, "_" + platform)("/tmp/start")+ assert len(calls) == 1++@pytest.mark.parametrize(- ("status", "output", "diagnostic", "expected"),+ ("platform", "status", "output", "diagnostic", "expected"),[- (0, "/tmp/project café \n\n", "", "/tmp/project café \n"),- (1, "", "", None),- (1, "", "Gtk-WARNING: optional theme is missing", None),+ ("linux", 0, "/tmp/project café \n\n", "", "/tmp/project café \n"),+ ("linux", 1, "", "", None),+ ("linux", 1, "", "Gtk-WARNING: optional theme is missing", None),+ (+ "linux",+ 0,+ "/tmp/project\n",+ "optional component cannot open display",+ "/tmp/project",+ ),+ ("darwin", 0, "/tmp/project café \n\n", "", "/tmp/project café \n"),+ ("darwin", 0, "\n", "", None),],)-def test_linux_selection_preserves_paths_and_normal_cancel(- monkeypatch, status, output, diagnostic, expected+def test_native_selection_preserves_paths_and_normal_cancel(+ platform, status, output, diagnostic, expected):- monkeypatch.setattr(native.shutil, "which", lambda _tool: "/usr/bin/zenity")- monkeypatch.setenv("ZENITY_CANCEL", "42")- calls = []-- def run(command, **kwargs):- calls.append((command, kwargs))- return subprocess.CompletedProcess(- command, status, output.encode("utf-8"), diagnostic.encode("utf-8")+ assert (+ native.decode_result(+ output.encode(), diagnostic.encode(), status, platform=platform)-- monkeypatch.setattr(native.subprocess, "run", run)- assert native._linux("/tmp/start") == expected- assert "--filename=/tmp/start/" in calls[0][0]- assert "ZENITY_CANCEL" not in calls[0][1]["env"]+ == expected+ )@pytest.mark.parametrize(@@ -41,49 +62,71 @@ def test_linux_selection_preserves_paths_and_normal_cancel("Could not connect to display",],)-def test_linux_display_failure_is_not_user_cancellation(monkeypatch, diagnostic):- monkeypatch.setattr(native.shutil, "which", lambda _tool: "/usr/bin/zenity")- monkeypatch.setattr(- native.subprocess,- "run",- lambda *args, **kwargs: subprocess.CompletedProcess(- args, 1, b"", diagnostic.encode()- ),- )+def test_linux_display_failure_is_not_user_cancellation(diagnostic):with pytest.raises(RuntimeError, match=diagnostic):- native._linux(None)+ native.decode_result(b"", diagnostic.encode(), 1, platform="linux")-def test_linux_uses_installed_kdialog_or_reports_missing_tools(monkeypatch):+def test_linux_uses_installed_tool_arguments_and_environment(monkeypatch):+ calls = []+ monkeypatch.setenv("ZENITY_CANCEL", "42")+ monkeypatch.setattr(+ native.os,+ "execve",+ lambda path, command, env: calls.append((path, command, env)),+ )+ monkeypatch.setattr(native.shutil, "which", lambda _: "/usr/bin/zenity")+ native._linux("/tmp/start")+ assert calls[0][0] == "/usr/bin/zenity"+ assert "--filename=/tmp/start/" in calls[0][1]+ assert "ZENITY_CANCEL" not in calls[0][2]monkeypatch.setattr(native.shutil,"which",lambda tool: "/usr/bin/kdialog" if tool == "kdialog" else None,)- calls = []-- def run(command, **_kwargs):- calls.append(command)- return subprocess.CompletedProcess(command, 0, b"/tmp/project\n", b"")-- monkeypatch.setattr(native.subprocess, "run", run)- assert native._linux("/tmp") == "/tmp/project"- assert calls[0][-2:] == ["--getexistingdirectory", "/tmp"]- monkeypatch.setattr(native.shutil, "which", lambda _tool: None)+ native._linux("/tmp")+ assert calls[1][0] == "/usr/bin/kdialog"+ assert calls[1][1][-2:] == ["--getexistingdirectory", "/tmp"]+ monkeypatch.setattr(native.shutil, "which", lambda _: None)with pytest.raises(RuntimeError, match="No desktop folder picker"):native._linux(None)-def test_macos_passes_the_hint_as_data_and_preserves_path_characters(monkeypatch):+def test_macos_passes_the_hint_as_data(monkeypatch):hint = '/tmp/quotes " and spaces'+ calls = []+ monkeypatch.setattr(+ native.os, "execv", lambda path, command: calls.append((path, command))+ )+ native._macos(hint)+ assert calls[0][0] == "/usr/bin/osascript"+ assert calls[0][1][-1] == hint+ assert hint not in calls[0][1][-2]- def run(command, **_kwargs):- assert command[-1] == hint- assert hint not in command[-2]- return subprocess.CompletedProcess(command, 0, b"/tmp/project \n\n", b"")- monkeypatch.setattr(native.subprocess, "run", run)- assert native._macos(hint) == "/tmp/project \n"[email protected]("failure", ["missing_tool", "exec_error"])+def test_helper_setup_failure_cannot_be_mistaken_for_cancel(+ monkeypatch, capsys, failure+):+ monkeypatch.setattr(native.sys, "platform", "linux")+ monkeypatch.setattr(+ native.shutil,+ "which",+ lambda _: None if failure == "missing_tool" else "/missing/zenity",+ )++ def fail(*args):+ raise FileNotFoundError("Native executable disappeared")++ monkeypatch.setattr(native.os, "execve", fail)+ assert native.main() == 2+ captured = capsys.readouterr()+ assert captured.err+ with pytest.raises(RuntimeError):+ native.decode_result(+ captured.out.encode(), captured.err.encode(), 2, platform="linux"+ )@pytest.mark.parametrize("selection", ["", "C:/Projects/café"])diff --git a/tests/test_thread_diagnostics.py b/tests/test_thread_diagnostics.pyindex 90979235..9b45ccb3 100644--- a/tests/test_thread_diagnostics.py+++ b/tests/test_thread_diagnostics.py@@ -106,6 +106,7 @@ def test_slow_test_reports_stacks_without_interrupting_execution():@pytest.mark.parametrize("fails", [False, True])def test_completion_cancels_and_joins_pending_diagnostic(fails):output = DiagnosticOutput()+ existing_threads = set(threading.enumerate())try:with dump_threads_after(60, output, "completed-test"):if fails:@@ -113,4 +114,7 @@ def test_completion_cancels_and_joins_pending_diagnostic(fails):except RuntimeError as error:assert fails and str(error) == "original failure"assert output.getvalue() == ""- assert not any(t.name == "fcc-test-diagnostics" for t in threading.enumerate())+ assert not any(+ t.name == "fcc-test-diagnostics" and t not in existing_threads+ for t in threading.enumerate()+ )diff --git a/uv.lock b/uv.lockindex 794399ea..462e1b8b 100644--- a/uv.lock+++ b/uv.lock@@ -625,6 +625,7 @@ dependencies = [{ name = "python-dotenv" },{ name = "python-telegram-bot" },{ name = "requests", extra = ["socks"] },+ { name = "ruamel-yaml" },{ name = "simplejson" },{ name = "sqlalchemy" },{ name = "tiktoken" },@@ -680,6 +681,7 @@ requires-dist = [{ name = "python-dotenv", specifier = ">=1.2.2" },{ name = "python-telegram-bot", specifier = ">=22.8" },{ name = "requests", extras = ["socks"], specifier = ">=2.34.2" },+ { name = "ruamel-yaml", specifier = ">=0.19.1" },{ name = "simplejson", specifier = ">=4.1.2" },{ name = "sqlalchemy", specifier = ">=2.1.1" },{ name = "tiktoken", specifier = ">=0.13.0" },@@ -2247,6 +2249,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/2a/72/bfa4e61ab8e7dc1c8adf397e05e6cbdd4239357bd72b248d3de662f23915/rpds_py-2026.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:c93c629be4636cf54337bd5f06c104d55e42ced54d681f6fe21ae510a65116f6", size = 225422, upload-time = "2026-05-28T12:01:05.194Z" },]+[[package]]+name = "ruamel-yaml"+version = "0.19.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/c7/3b/ebda527b56beb90cb7652cb1c7e4f91f48649fbcd8d2eb2fb6e77cd3329b/ruamel_yaml-0.19.1.tar.gz", hash = "sha256:53eb66cd27849eff968ebf8f0bf61f46cdac2da1d1f3576dd4ccee9b25c31993", size = 142709, upload-time = "2026-01-02T16:50:31.84Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/b8/0c/51f6841f1d84f404f92463fc2b1ba0da357ca1e3db6b7fbda26956c3b82a/ruamel_yaml-0.19.1-py3-none-any.whl", hash = "sha256:27592957fedf6e0b62f281e96effd28043345e0e66001f97683aa9a40c667c93", size = 118102, upload-time = "2026-01-02T16:50:29.201Z" },+]+[[package]]name = "ruff"version = "0.16.8"