[Bug]CodeBuddy provider: /auth/start can permanently wedge the settings API + incompatibilities with WorkBuddy 5.9.3 desktop
Environment
- DeepTutor 1.7.0 (pip, Python 3.12.14, macOS 15, Apple M2 Pro)
- codebuddy-agent-sdk 0.3.299
- WorkBuddy desktop 5.9.3 running and signed in (same account system as CodeBuddy)
- Node.js 22.22.2
I ran DeepTutor on the same machine where the WorkBuddy desktop app is running. Four issues found, in decreasing severity. (Related prior art: the CodeBuddy provider was introduced in #773 / PR #780; I searched existing issues and none of the four bugs below has been reported — #1827 covers a different 401-retry path in the HTTP provider.)
Bug 1 (critical): /auth/start can permanently wedge the whole settings API
Repro: With WorkBuddy desktop running, trigger the CodeBuddy login from the web UI (or POST /api/settings/providers/codebuddy/auth/start).
The headless CLI fails to create a login session, but still reports result=success:
[Error] [ExternalLinkAuthenticationProvider] fetch auth state error: Error [ERR_SOCKET_CLOSED]: Socket is closed
[Error] [ExternalLinkAuthenticationProvider] createSession main logic error: Error [ERR_SOCKET_CLOSED]: Socket is closed
[Error] [AuthenticationManager] sign in error: Error [ERR_SOCKET_CLOSED]: Socket is closed
[Info] [StdioIO] send control_response id=auth_start result=success elapsedMs=10311
Because createSession fails, the returned flow has no usable auth_url and never resolves. In deeptutor/services/codebuddy_auth.py, start_login() then does:
flow = await _start_sdk_authenticate()
if not getattr(flow, "auth_url", ""):
result = await flow # <-- awaits forever while holding self._lock
That await holds the service lock indefinitely, so every subsequent GET /auth/status (which the frontend polls) hangs forever — the UI shows "checking login status" endlessly. Only a backend restart recovers.
Suggested fix: bound every flow await with a hard timeout and never await a flow while holding the lock. I patched it locally like this (works, verified):
async def _await_flow(awaitable, timeout):
# asyncio.wait() (not wait_for) so a flow that ignores cancellation
# can never hang the caller
task = asyncio.ensure_future(_resolve(awaitable))
done, _ = await asyncio.wait({task}, timeout=timeout)
if not done:
task.cancel()
raise TimeoutError(f"codebuddy auth flow timed out after {timeout:.0f}s")
return task.result()
Apply it in start_login() (45 s), _probe_locked() (45 s), and _wait_for_login() (300 s, matching the SDK's own timeout). Also, status() currently re-probes (spawning a headless process) on every frontend poll — a short TTL cache of the connected state (~30 s) removes that cost.
Bug 2: SDK probe cannot see an existing signed-in session
codebuddy_agent_sdk spawns headless with --setting-sources none by default (documented as "SDK default behavior: no filesystem settings loaded"), so the initialize response contains no account and the probe always falls back to browser login — even when the machine is already signed in via the WorkBuddy desktop app.
Additionally, the SDK's auth check requires both userId and token in the initialize response. WorkBuddy 5.9.3 no longer returns a token in that response (the token is encrypted at rest in workbuddy-desktop.info), so even with --setting-sources user the probe fails the and token check.
I verified with the bundled binary:
$ echo "$INIT_REQ" | codebuddy-headless --input-format=stream-json --output-format=stream-json --setting-sources user
-> response contains "account": { "userId": "015097a2-...", ... } # login visible
$ echo "$INIT_REQ" | codebuddy-headless ... --setting-sources none
-> no account field # login invisible
Suggested fix: probe with user settings sources enabled (or add an option), and treat userId alone as "already authenticated" since the headless binary manages tokens internally (model calls work without a Python-side token).
Bug 3: credential file lookup incompatible with WorkBuddy 5.9.3
deeptutor/services/codebuddy_credentials.py looks for Tencent-Cloud.coding-copilot.info (plaintext). WorkBuddy 5.9.3 writes:
- a different file name:
~/Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info - an encrypted token envelope:
{"access_token": "$wbEncrypted:..."}
So find_auth_file() returns None and the local (SDK-free) login path is always dead on current WorkBuddy installs.
Bug 4 (fatal for model calls): headless daemon port conflict with WorkBuddy desktop
The headless binary starts an internal daemon server on port 54006. The WorkBuddy desktop app's own processes already listen on 54006, so every agent run crashes with:
[Error] [ProcessExit] unhandledRejection | name=Error | message=Failed to start server. Is port 54006 in use? | code=EADDRINUSE
(reproduced 5/5 attempts). DeepTutor surfaces this as empty assistant responses (0 content chars) after retry rounds — deeptutor run chat burns tokens for 3 rounds and returns nothing. CODEBUDDY_DAEMON_CONFIGURED_PORT appears in the binary's strings but setting it in the environment did not change the behavior on 0.3.299 or 0.3.195.
Since the WorkBuddy desktop app and DeepTutor are meant to coexist on the same machine, the daemon port needs to be configurable or auto-fallback to a free port.
Minor
- The login-check UI has no timeout on the frontend either; a wedged backend produces an infinite "checking login status" spinner with no error state.
- If
deeptutor stopis issued after the launcher's parent was killed, orphan uvicorn/next-server processes keep ports 8001/3782 and the nextdeeptutor startfails silently (log says "ready" but nothing listens).
Happy to provide full logs (~/.codebuddy/logs/...) and my working local patch for Bug 1 if useful. Thanks for the great project!
I reproduced Bug 1 at the service boundary on current dev (60fb3bd, v1.7.2), with a controlled SDK-flow stand-in that has an empty auth_url and never resolves. Local credential lookup was bypassed; this did not use a WorkBuddy account or launch the real SDK.
Two details may help scope the fix/tests:
- A status request alone can trigger the same lockup.
status()holds the lock while_probe_locked()awaits the empty-URL flow, just asstart_login()does. Covering only/auth/startleaves that path open. - Cancel cannot recover it.
cancel_login()waits for the same lock. In both entry paths, the original request, a second status request, and cancellation all remain pending;_flowand_taskhave not been registered, so the normal background-login cleanup cannot own this flow.
Relevant code: start/status/cancel, status probe.
Offline reproduction of both entry paths
import asyncio
from unittest.mock import AsyncMock, patch
from deeptutor.services import codebuddy_auth
class Flow:
auth_url = ""
def __init__(self):
self.entered = asyncio.Event()
self.release = asyncio.Event()
def __await__(self):
return self.wait().__await__()
async def wait(self):
self.entered.set()
await self.release.wait()
async def main():
for entry in ("start_login", "status"):
service, flow = codebuddy_auth.CodeBuddyAuthService(), Flow()
tasks = []
with patch.object(service, "_probe_local_login", AsyncMock(return_value=False)), \
patch.object(codebuddy_auth, "_start_sdk_authenticate",
AsyncMock(return_value=flow)):
try:
tasks.append(asyncio.create_task(getattr(service, entry)()))
await asyncio.wait_for(flow.entered.wait(), 1)
tasks.extend([asyncio.create_task(service.status()),
asyncio.create_task(service.cancel_login())])
done, pending = await asyncio.wait(tasks, timeout=0.1)
print(entry, "completed:", len(done), "pending:", len(pending))
assert not done and len(pending) == 3
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
asyncio.run(main())
Both lines print completed: 0 pending: 3.
This confirms the CodeBuddy-auth request blockage; it does not establish that unrelated settings endpoints stop responding, or verify Bugs 2–4 against WorkBuddy 5.9.3. The existing tests/services/test_codebuddy_auth.py already has a controllable FakeFlow, so these cases can be added there. A timeout implementation also needs to retain ownership of timed-out flow tasks until cleanup finishes, and prevent a late completion from changing the state of a newer login.
Thanks @Taz33m — both points are correct, and they change the fix rather than just widen it.
I ran your script unchanged against a clean checkout of 60fb3bd: start_login completed: 0 pending: 3 and status completed: 0 pending: 3. So the bug is not specific to /auth/start; my report drew the boundary in the wrong place. status() holds self._lock across _probe_locked(), which awaits the same empty-URL flow at L138, and cancel_login() blocks on that lock at L65. Since the empty-URL path never registers _flow/_task, _wait_for_login never runs and cancel_login/logout have nothing to cancel — so the root cause is that a flow can be awaited with no owner. Timeouts alone would not have closed it: my earlier snippet would still have held the lock for the whole deadline, and every queued poll would have paid it again on its own fresh probe.
What I changed (Bug 1 only):
- The lock never spans an SDK await.
_probe_locked()is gone; the probe is now a_run_probe()task, and every SDK interaction runs inside a task the service spawns. The lock only guards in-memory state. - The attempt is registered before its first await.
start_login()publishes_login_task(and_flow, once acquired) before touching the SDK, sostatus()returns the in-flight snapshot instead of probing, andcancel_login()/logout()can always reach the flow. - Cancel is authoritative, not just fast. It bumps a generation counter under the lock and returns; every state write coming out of a flow is guarded by the generation it started under. A flow that resolves after a cancel — or after a newer login started — cannot overwrite current state.
- Timed-out flows stay owned. Everything spawned goes into
self._taskswith a done-callback, so a flow that refuses cancellation is still strongly referenced and still cancellable until it actually finishes, instead of being collected mid-flight. - The probe is single-flight and bounded. Concurrent
/statuspolls join one probe; a request waits at most_STATUS_PROBE_WAIT_S(20 s), then answers from state and backs off for 120 s, so a wedged SDK cannot spawn one headless process per poll. This also covers the case you flagged of a status request alone triggering the lockup.
Tests are added to tests/services/test_codebuddy_auth.py, reusing the existing FakeFlow plus a StuckFlow that enters, never resolves, and swallows cancellation (the case that makes ownership matter):
test_status_request_alone_cannot_wedge_the_service— bounded, reportslogin_timeout, later polls answer without respawningtest_start_status_and_cancel_all_settle_while_the_flow_hangs— your scenario; assertsnot pendingand that the cancel reached the flowtest_cancelled_login_does_not_block_the_next_attempttest_late_completion_of_an_abandoned_flow_cannot_overwrite_a_newer_logintest_timed_out_flow_stays_owned_until_it_finishestest_concurrent_status_polls_share_a_single_probe
On 60fb3bd, 5 of the 6 fail with TimeoutError (the late-completion one already passes there because the browser-flow path had an _flow is flow identity check — it is there to keep that guarantee under the generation mechanism). With the patch, all 13 pass in that file; tests/services/test_codebuddy_credentials.py, tests/cli/test_codebuddy_login.py and tests/api/test_settings_router.py are green too (134 passed), and ruff check/ruff format are clean. Your repro script's final assertion inverts as expected once the paths settle — with _STATUS_PROBE_WAIT_S monkeypatched to 0.05, both entry paths reach completed: 3, pending: 0, and cancel_login() returns in ~0.1 ms.
One residual, so it is not a surprise in review: the first /status poll on a wedged SDK still waits up to 20 s before answering (_START_WAIT_S is 25 s for /start). It is bounded, it no longer blocks other requests because no lock is held, and cancel is immediate — but it is a latency, not an O(1) answer. Making status O(1) needs a checking operation_state (return immediately, let the card poll), which touches web/lib/codebuddy-auth.ts and CodeBuddyAuthCard.tsx; I left it backend-only here.
On your last sentence: agreed, and I am not claiming otherwise. This patch is Bug 1 only. Bugs 2–4 need the real WorkBuddy 5.9.3 install (--setting-sources probe difference, the workbuddy-desktop.info envelope, and the 54006 EADDRINUSE); I have logs for all three and can attach them, or file them separately if that triages better.
The diff is 2 files (+492 / −82). Happy to open a PR, or paste it here first — whichever you prefer.
Thanks @ratelgogo for rerunning the reproduction and spelling out the ownership changes. Since #2582 is now open for this issue, could you share your existing two-file patch or a branch link in that PR's discussion so the approaches can be compared in one place?
I reviewed its current head and posted additional controlled reproductions: three simultaneous status polls start three unowned SDK-flow stand-ins, cancellation reaches none of them, and cancelling the caller leaves its child flow waiting. Its 21 auth/credential tests pass despite those gaps. Your proposed generation checks, shared probe and retained task ownership target the missing guarantees; the code will let us verify them directly.
Your Bug 1 scope is useful. The WorkBuddy 5.9.3 compatibility cases still need their own logs/fixtures and should be tracked separately from this service-lifecycle reproduction.
Verified fixed on the current local dev branch (85c91992c711), with regression checks.
will be fixed in the next releases!