codee-agent 0.9.3__py3-none-any.whl → 0.9.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
codee/admin.py CHANGED
@@ -11,7 +11,7 @@ from pydantic import BaseModel
11
11
  from codee.admin_api import api_app
12
12
  from codee.admin_service import (
13
13
  AGENTS_FILE, TASKS_CHECKS, WORKFLOW_HIGHLIGHT_GROUPS, AdminService,
14
- SKILL_TYPES, WorkflowGeneration, normalize_work_items)
14
+ SKILL_TYPES, WorkflowGeneration, context_tier_label, normalize_work_items)
15
15
  from codee.workflow_graph import workflow_graph
16
16
  from codee_main_context.context import (
17
17
  DEFAULT_ISSUE_TYPES, TasksProvider, credential_field)
@@ -50,7 +50,8 @@ def _skill_summary(skill: dict[str, str]) -> SkillSummary:
50
50
  """One listing row, with its agent named the way the editor's picker does."""
51
51
  return SkillSummary(**{
52
52
  **skill,
53
- "agent": AGENT_NAMES.get(skill["agent"], DEFAULT_AGENT_OPTION)})
53
+ "agent": AGENT_NAMES.get(skill["agent"], DEFAULT_AGENT_OPTION),
54
+ "context_tier": context_tier_label(skill["context_tier"])})
54
55
 
55
56
 
56
57
  def _model_option(models: list["ModelOption"],
@@ -114,6 +115,9 @@ class SkillSummary(BaseModel):
114
115
  agent: str = ""
115
116
  model: str = ""
116
117
  effort: str = ""
118
+ # The skill's `x-codee-context-tier:` as a person reads it, empty for the
119
+ # model's default window.
120
+ context_tier: str = ""
117
121
  issue_status: str = ""
118
122
  issue_type: str = ""
119
123
 
@@ -466,6 +470,9 @@ class AdminState(rx.State):
466
470
  # slow loop of its own.
467
471
  claude_account_usage: list[ClaudeAccount] = []
468
472
  claude_usage_loading: bool = False
473
+ # The account a "Set current" click is switching to, or 0. One at a time:
474
+ # two switches racing would leave the CLI on whichever wrote last.
475
+ claude_switching_account: int = 0
469
476
 
470
477
  runs: list[RunRecord] = []
471
478
  runs_has_more: bool = False
@@ -1171,6 +1178,36 @@ class AdminState(rx.State):
1171
1178
  for account in measured]
1172
1179
  await asyncio.sleep(USAGE_POLL_INTERVAL)
1173
1180
 
1181
+ @rx.event(background=True)
1182
+ async def use_claude_code_account(self, account_id: int) -> Any:
1183
+ """Make one account current and sign Claude Code in as it.
1184
+
1185
+ In the background because it can be two network round trips — renewing
1186
+ the token, then reading the profile — and the dashboard redraws every
1187
+ second meanwhile. The usage rows are redrawn as soon as it lands, so
1188
+ the "in use" badge moves without waiting out the slow usage loop.
1189
+ """
1190
+ async with self:
1191
+ if self.claude_switching_account:
1192
+ return
1193
+ self.claude_switching_account = account_id
1194
+
1195
+ try:
1196
+ switched, message = await asyncio.to_thread(
1197
+ SERVICE.use_claude_code_account, account_id)
1198
+ measured = await asyncio.to_thread(
1199
+ SERVICE.claude_code_account_usage)
1200
+ except Exception as error: # noqa: BLE001 - never leave the row spinning
1201
+ switched, message = False, f"{type(error).__name__}: {error}"
1202
+ measured = None
1203
+
1204
+ async with self:
1205
+ self.claude_switching_account = 0
1206
+ if measured is not None:
1207
+ self.claude_account_usage = [_usage_row(account)
1208
+ for account in measured]
1209
+ yield rx.toast.success(message) if switched else rx.toast.error(message)
1210
+
1174
1211
  def _fetch_runs_page(self, offset: int,
1175
1212
  limit: int = RUNS_PAGE_SIZE) -> list[RunRecord]:
1176
1213
  """One page of runs. Reads one row past the page to learn whether more exist."""
@@ -2032,13 +2069,34 @@ SUBTLE_ICON = "var(--codee-subtle-icon)"
2032
2069
  RUNNING_BACKGROUND = "var(--codee-running-background)"
2033
2070
  RUNNING_GLOW = "var(--codee-running-glow)"
2034
2071
  MONO = "IBM Plex Mono, monospace"
2035
- LOGO = "👨🏻‍💻"
2036
- # Inline SVG carrying the logo emoji, so the favicon needs no binary asset.
2072
+ # Corner brackets with an open palm and a spark; fills use currentColor so the
2073
+ # mark takes the colour of the badge it sits in.
2074
+ LOGO = (
2075
+ '<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" style="display:block" aria-hidden="true" fill="none" viewBox="6 6 36 36"><path fill="currentColor" d="M7.5 14.9V7.5H14.9V10.5H10.5V14.9Z"></path><path fill="currentColor" d="M40.5 14.9V7.5H33.1V10.5H37.5V14.9Z"></path><path fill="currentColor" d="M7.5 33.1V40.5H14.9V37.5H10.5V33.1Z"></path><path fill="currentColor" d="M40.5 33.1V40.5H33.1V37.5H37.5V33.1Z"></path><g fill="currentColor"><rect x="19.9" y="16.4" width="2.85" height="10" rx="1.425"></rect><rect x="23.3" y="14.75" width="2.85" height="11" rx="1.425"></rect><rect x="26.7" y="15.6" width="2.85" height="10.5" rx="1.425"></rect><rect x="30.1" y="17.9" width="2.85" height="9" rx="1.425"></rect><path d="M32.95 24.6V28C32.95 31 30.6 33.25 27.6 33.25H25.6C23 33.25 18.71 28.21 17.29 26.52Q16.2 25.22 15.11 23.92A1.425 1.425 0 0 1 17.29 22.08Q18.6 23.64 19.9 25.19V24.6Z"></path></g><path fill="currentColor" d="M16 15.3Q16.69 16.91 18.3 17.6Q16.69 18.29 16 19.9Q15.31 18.29 13.7 17.6Q15.31 16.91 16 15.3Z"></path></svg>'
2076
+ )
2077
+ # The logo on the accent-blue badge, inline so the favicon needs no binary asset.
2037
2078
  FAVICON = (
2038
2079
  "data:image/svg+xml;base64,"
2039
- "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMD"
2040
- "AgMTAwIj48dGV4dCB5PSIuOWVtIiBmb250LXNpemU9IjkwIj7wn5Go8J+Pu+KAjfCfkrs8L3Rl"
2041
- "eHQ+PC9zdmc+"
2080
+ "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAz"
2081
+ "MiAzMiI+PHJlY3Qgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIiByeD0iNiIgZmlsbD0iIzJmNmZk"
2082
+ "NiIvPjxzdmcgeD0iMyIgeT0iMyIgd2lkdGg9IjI2IiBoZWlnaHQ9IjI2IiB2aWV3Qm94PSI2"
2083
+ "IDYgMzYgMzYiPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik03LjUgMTQuOVY3LjVIMTQuOVYxMC41"
2084
+ "SDEwLjVWMTQuOVoiPjwvcGF0aD48cGF0aCBmaWxsPSIjZmZmIiBkPSJNNDAuNSAxNC45Vjcu"
2085
+ "NUgzMy4xVjEwLjVIMzcuNVYxNC45WiI+PC9wYXRoPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik03"
2086
+ "LjUgMzMuMVY0MC41SDE0LjlWMzcuNUgxMC41VjMzLjFaIj48L3BhdGg+PHBhdGggZmlsbD0i"
2087
+ "I2ZmZiIgZD0iTTQwLjUgMzMuMVY0MC41SDMzLjFWMzcuNUgzNy41VjMzLjFaIj48L3BhdGg+"
2088
+ "PGcgZmlsbD0iI2ZmZiI+PHJlY3QgeD0iMTkuOSIgeT0iMTYuNCIgd2lkdGg9IjIuODUiIGhl"
2089
+ "aWdodD0iMTAiIHJ4PSIxLjQyNSI+PC9yZWN0PjxyZWN0IHg9IjIzLjMiIHk9IjE0Ljc1IiB3"
2090
+ "aWR0aD0iMi44NSIgaGVpZ2h0PSIxMSIgcng9IjEuNDI1Ij48L3JlY3Q+PHJlY3QgeD0iMjYu"
2091
+ "NyIgeT0iMTUuNiIgd2lkdGg9IjIuODUiIGhlaWdodD0iMTAuNSIgcng9IjEuNDI1Ij48L3Jl"
2092
+ "Y3Q+PHJlY3QgeD0iMzAuMSIgeT0iMTcuOSIgd2lkdGg9IjIuODUiIGhlaWdodD0iOSIgcng9"
2093
+ "IjEuNDI1Ij48L3JlY3Q+PHBhdGggZD0iTTMyLjk1IDI0LjZWMjhDMzIuOTUgMzEgMzAuNiAz"
2094
+ "My4yNSAyNy42IDMzLjI1SDI1LjZDMjMgMzMuMjUgMTguNzEgMjguMjEgMTcuMjkgMjYuNTJR"
2095
+ "MTYuMiAyNS4yMiAxNS4xMSAyMy45MkExLjQyNSAxLjQyNSAwIDAgMSAxNy4yOSAyMi4wOFEx"
2096
+ "OC42IDIzLjY0IDE5LjkgMjUuMTlWMjQuNloiPjwvcGF0aD48L2c+PHBhdGggZmlsbD0iI2Zm"
2097
+ "ZiIgZD0iTTE2IDE1LjNRMTYuNjkgMTYuOTEgMTguMyAxNy42UTE2LjY5IDE4LjI5IDE2IDE5"
2098
+ "LjlRMTUuMzEgMTguMjkgMTMuNyAxNy42UTE1LjMxIDE2LjkxIDE2IDE1LjNaIj48L3BhdGg+"
2099
+ "PC9zdmc+PC9zdmc+"
2042
2100
  )
2043
2101
 
2044
2102
 
@@ -2063,13 +2121,35 @@ def nav_link(label: str, icon: str, href: str) -> rx.Component:
2063
2121
  )
2064
2122
 
2065
2123
 
2124
+ def footer_link(label: str, href: str) -> rx.Component:
2125
+ return rx.link(label, href=href, is_external=True, color=MUTED,
2126
+ text_decoration="underline", text_underline_offset="2px",
2127
+ _hover={"color": ACCENT})
2128
+
2129
+
2130
+ def footer() -> rx.Component:
2131
+ return rx.flex(
2132
+ rx.text("Codee is developed by ",
2133
+ footer_link("FuseBase", "https://thefusebase.com")),
2134
+ rx.text("·", aria_hidden="true"),
2135
+ footer_link("Source code on GitHub", "https://github.com/fusebase-dev/codee"),
2136
+ gap="0.5rem",
2137
+ wrap="wrap",
2138
+ align="center",
2139
+ color=MUTED,
2140
+ font_size="0.8rem",
2141
+ padding_top="1rem",
2142
+ border_top=BORDER,
2143
+ )
2144
+
2145
+
2066
2146
  def shell(content: rx.Component) -> rx.Component:
2067
2147
  return rx.box(
2068
2148
  rx.grid(
2069
2149
  rx.box(
2070
2150
  rx.vstack(
2071
2151
  rx.hstack(
2072
- rx.box(LOGO, color="white", background=ACCENT, width="2rem",
2152
+ rx.box(rx.html(LOGO), color="white", background=ACCENT, width="2rem",
2073
2153
  height="2rem", display="grid", place_items="center",
2074
2154
  border_radius="6px", font_weight="700",
2075
2155
  font_size="1.1rem", line_height="1"),
@@ -2116,7 +2196,9 @@ def shell(content: rx.Component) -> rx.Component:
2116
2196
  background=NAV_BACKGROUND,
2117
2197
  min_height=rx.breakpoints(initial="auto", lg="100vh"),
2118
2198
  ),
2119
- rx.box(content, padding=rx.breakpoints(initial="1.25rem", md="2rem", xl="3rem"),
2199
+ rx.box(rx.box(content, flex="1", width="100%"), footer(),
2200
+ padding=rx.breakpoints(initial="1.25rem", md="2rem", xl="3rem"),
2201
+ display="flex", flex_direction="column", gap="3rem",
2120
2202
  min_width="0", max_width="1440px", width="100%"),
2121
2203
  columns=rx.breakpoints(initial="1fr", lg="230px minmax(0, 1fr)"),
2122
2204
  min_height="100vh",
@@ -2515,6 +2597,20 @@ def claude_account_usage_row(account: ClaudeAccount) -> rx.Component:
2515
2597
  variant="soft", flex_shrink="0"),
2516
2598
  rx.fragment()),
2517
2599
  rx.spacer(),
2600
+ # Not on the live one, and not on one that cannot be signed in
2601
+ # with: there is nothing to switch to in either case.
2602
+ rx.cond(
2603
+ account.in_use | account.needs_reconnect,
2604
+ rx.fragment(),
2605
+ rx.button(
2606
+ "Set current", type="button", size="1", variant="soft",
2607
+ flex_shrink="0",
2608
+ loading=AdminState.claude_switching_account == account.id,
2609
+ disabled=AdminState.claude_switching_account != 0,
2610
+ title="Make this the account Claude Code runs on, and "
2611
+ "write its credentials into Claude Code's config",
2612
+ on_click=lambda: AdminState.use_claude_code_account(
2613
+ account.id))),
2518
2614
  spacing="2", align="center", width="100%",
2519
2615
  margin_bottom="0.6rem"),
2520
2616
  rx.cond(
@@ -2615,6 +2711,9 @@ def skill_card(skill: SkillSummary) -> rx.Component:
2615
2711
  rx.cond(skill.effort != "",
2616
2712
  rx.code(skill.effort, font_size="0.72rem",
2617
2713
  color_scheme="gray")),
2714
+ rx.cond(skill.context_tier != "",
2715
+ rx.code(skill.context_tier, font_size="0.72rem",
2716
+ color_scheme="gray", title="Context window")),
2618
2717
  spacing="2", align="center", width="100%",
2619
2718
  class_name="skill-card-meta"),
2620
2719
  rx.cond(
codee/admin_service.py CHANGED
@@ -20,8 +20,10 @@ from dotenv import load_dotenv
20
20
  from codee_database import claude_code_accounts, oauth_tokens
21
21
  from codee_tasks_azure_devops import oauth as azure_oauth
22
22
  from codee_agent_abstract.provider import AbstractCodingAgent, AgentModel
23
+ from codee_agent_claude_code import credentials as claude_credentials
23
24
  from codee_agent_claude_code import oauth as claude_oauth
24
- from codee_agent_claude_code.account import AccountUnavailable, fetch_account
25
+ from codee_agent_claude_code.account import (
26
+ AccountUnavailable, fetch_account, fetch_profile)
25
27
  from codee_agent_claude_code.provider import ClaudeCodeAgent
26
28
  from codee_agent_claude_code.usage import (
27
29
  SESSION_WINDOW, WEEKLY_WINDOW, UsageRateLimited, UsageUnavailable,
@@ -640,11 +642,29 @@ def _skill_run_summary(
640
642
  if skill.effort:
641
643
  lines.append(f"Effort: {skill.effort}")
642
644
  if skill.context_tier:
643
- lines.append(f"Context: {skill.context_tier}")
645
+ lines.append(f"Context: {context_tier_label(skill.context_tier)}")
644
646
  lines.append(f"Skill: {skill.name}")
645
647
  return lines
646
648
 
647
649
 
650
+ def context_tier_label(tier: str) -> str:
651
+ """A skill's ``x-codee-context-tier:`` as a person reads it.
652
+
653
+ The window's own size ("1M") is only known from the agent's model catalog,
654
+ which takes a CLI run to read, so places that list skills say the tier.
655
+ """
656
+ return tier.replace("_", " ")
657
+
658
+
659
+ def _skill_model_line(skill: IssueTriggeredSkill) -> str:
660
+ """The model a skill runs on, with its effort and context tier when set."""
661
+ return " \u00b7 ".join(filter(None, [
662
+ skill.model or WORKFLOW_DEFAULT_MODEL_LABEL,
663
+ skill.effort,
664
+ context_tier_label(skill.context_tier),
665
+ ]))
666
+
667
+
648
668
  def _with_agent_tooltips(
649
669
  workflow: dict[str, Any],
650
670
  skills: list[IssueTriggeredSkill],
@@ -696,10 +716,10 @@ def _node_with_agent_tooltip(
696
716
  if lines:
697
717
  lines.append("")
698
718
  lines.extend(_skill_run_summary(skill, default_agent))
699
- # The models named under the status name on the node itself. Skills sharing
700
- # an entry status often ask for the same one, so it is said once.
701
- models = list(dict.fromkeys(
702
- skill.model or WORKFLOW_DEFAULT_MODEL_LABEL for skill in handled))
719
+ # The models named under the status name on the node itself, each with its
720
+ # effort and context tier. Skills sharing an entry status often ask for the
721
+ # same one, so it is said once.
722
+ models = list(dict.fromkeys(_skill_model_line(skill) for skill in handled))
703
723
  return {
704
724
  **node,
705
725
  "className": " ".join(
@@ -2462,6 +2482,57 @@ class AdminService:
2462
2482
  claude_code_accounts.remove_account(account_id, self.context)
2463
2483
  self._reconcile_claude_code_account()
2464
2484
 
2485
+ def use_claude_code_account(self, account_id: int) -> tuple[bool, str]:
2486
+ """Make one account the one in use, and sign the CLI in as it now.
2487
+
2488
+ Returns whether it worked and a sentence to show either way. Both
2489
+ halves are done here rather than left to the next rotation check: the
2490
+ pointer alone would only take effect up to five minutes later, and only
2491
+ in a running executor.
2492
+
2493
+ The token is renewed first, because an account waiting its turn holds
2494
+ one that may have expired hours ago. Its profile goes into
2495
+ ``.claude.json`` too, so the CLI names the account it is now running
2496
+ as instead of the previous one. That part is best-effort: the
2497
+ credentials are what makes the switch, and a profile that could not be
2498
+ read is fetched by the CLI itself on its next run.
2499
+ """
2500
+ try:
2501
+ stored = {account.id: account for account
2502
+ in claude_code_accounts.accounts(self.context)}
2503
+ except Exception as error: # noqa: BLE001 - the UI must never see a traceback
2504
+ return False, f"Could not read the connected accounts: {error}"
2505
+ account = stored.get(account_id)
2506
+ if account is None:
2507
+ return False, "That account is no longer connected"
2508
+ name = account.label or f"account {account.id}"
2509
+ now = int(datetime.now(timezone.utc).timestamp() * 1000)
2510
+ if account.needs_reconnect(now):
2511
+ return False, f"{name} has to be connected again first"
2512
+
2513
+ try:
2514
+ account = ensure_fresh(account, self.context)
2515
+ # A renewal the API refused retires the account rather than
2516
+ # raising, so the only way to hear about it is to look again.
2517
+ renewed = {row.id: row for row
2518
+ in claude_code_accounts.accounts(self.context)}
2519
+ if renewed[account.id].needs_reconnect(now):
2520
+ return False, f"{name} has to be connected again first"
2521
+ claude_credentials.write_credentials(
2522
+ account.access_token, account.refresh_token,
2523
+ account.expires_at, account.scopes, account.subscription_type)
2524
+ claude_code_accounts.set_current_account(account.id, self.context)
2525
+ except Exception as error: # noqa: BLE001
2526
+ return False, f"Could not switch to {name}: {error}"
2527
+
2528
+ try:
2529
+ claude_credentials.write_oauth_account(
2530
+ fetch_profile(account.access_token))
2531
+ except Exception as error: # noqa: BLE001 - the switch itself landed
2532
+ print(f"[admin] Switched Claude Code to {name} but could not "
2533
+ f"record its profile: {error}")
2534
+ return True, f"Claude Code is now running as {name}"
2535
+
2465
2536
  def _reconcile_claude_code_account(self) -> None:
2466
2537
  """Point the current account at a connected one.
2467
2538
 
@@ -519,6 +519,84 @@ class AdminServiceClaudeCodeAccountsTest(unittest.TestCase):
519
519
  ["one@example.com"])
520
520
  self.assertTrue(accounts[0].in_use)
521
521
 
522
+ # A refresh window that will not have closed by the time the test runs.
523
+ NEVER_EXPIRES = 4102444800000 # 2100-01-01
524
+
525
+ def _claude_home(self) -> Path:
526
+ """Point the CLI's config at a temp dir, so nothing real is written."""
527
+ home = self.directory / "claude-home"
528
+ home.mkdir()
529
+ environment = patch.dict(os.environ, {"CLAUDE_CONFIG_DIR": str(home)})
530
+ environment.start()
531
+ self.addCleanup(environment.stop)
532
+ return home
533
+
534
+ def test_setting_an_account_current_signs_the_cli_in_as_it(self) -> None:
535
+ home = self._claude_home()
536
+ (home / ".claude.json").write_text(json.dumps(
537
+ {"oauthAccount": {"emailAddress": "one@example.com"}}))
538
+ self._connect("one@example.com")
539
+ second_tokens = claude_oauth.Tokens(
540
+ "access-2", "refresh-2", expires_at=1789300823639,
541
+ refresh_expires_at=self.NEVER_EXPIRES, scopes=("user:profile",),
542
+ subscription_type="pro")
543
+ self._connect("two@example.com", tokens=second_tokens)
544
+ second = self.service.claude_code_accounts()[1]
545
+
546
+ with patch("codee.admin_service.ensure_fresh",
547
+ side_effect=lambda a, c: a), \
548
+ patch("codee.admin_service.fetch_profile", return_value={
549
+ "account": {"uuid": "acc-2",
550
+ "email": "two@example.com"}}):
551
+ switched, message = self.service.use_claude_code_account(second.id)
552
+
553
+ self.assertTrue(switched, message)
554
+ self.assertTrue(self.service.claude_code_accounts()[1].in_use)
555
+ oauth = json.loads((home / ".credentials.json").read_text())[
556
+ "claudeAiOauth"]
557
+ self.assertEqual(oauth["accessToken"], "access-2")
558
+ self.assertEqual(oauth["refreshToken"], "refresh-2")
559
+ self.assertEqual(oauth["subscriptionType"], "pro")
560
+ self.assertEqual(
561
+ json.loads((home / ".claude.json").read_text())["oauthAccount"],
562
+ {"accountUuid": "acc-2", "emailAddress": "two@example.com"})
563
+
564
+ def test_an_unreadable_profile_does_not_undo_the_switch(self) -> None:
565
+ home = self._claude_home()
566
+ self._connect("one@example.com", tokens=claude_oauth.Tokens(
567
+ "access-1", "refresh-1", expires_at=1789300823639,
568
+ refresh_expires_at=self.NEVER_EXPIRES))
569
+
570
+ with patch("codee.admin_service.ensure_fresh",
571
+ side_effect=lambda a, c: a), \
572
+ patch("codee.admin_service.fetch_profile",
573
+ side_effect=AccountUnavailable("no route")):
574
+ switched, _ = self.service.use_claude_code_account(
575
+ self.service.claude_code_accounts()[0].id)
576
+
577
+ self.assertTrue(switched)
578
+ self.assertTrue((home / ".credentials.json").exists())
579
+
580
+ def test_an_account_that_needs_signing_in_again_is_not_switched_to(self) -> None:
581
+ home = self._claude_home()
582
+ expired = claude_oauth.Tokens(
583
+ "access-1", "refresh-1", expires_at=1, refresh_expires_at=1)
584
+ self._connect("one@example.com", tokens=expired)
585
+
586
+ switched, message = self.service.use_claude_code_account(
587
+ self.service.claude_code_accounts()[0].id)
588
+
589
+ self.assertFalse(switched)
590
+ self.assertIn("connected again", message)
591
+ self.assertFalse((home / ".credentials.json").exists())
592
+
593
+ def test_a_disconnected_account_is_not_switched_to(self) -> None:
594
+ self._claude_home()
595
+
596
+ switched, _ = self.service.use_claude_code_account(42)
597
+
598
+ self.assertFalse(switched)
599
+
522
600
  def test_disconnecting_an_account_forgets_its_tokens(self) -> None:
523
601
  self._connect()
524
602
  account = self.service.claude_code_accounts()[0]
@@ -2235,6 +2313,25 @@ class AdminServiceWorkflowAgentTest(unittest.TestCase):
2235
2313
  "'claude-opus-5'",
2236
2314
  )
2237
2315
 
2316
+ def test_the_effort_and_context_tier_follow_the_model_on_the_node(
2317
+ self) -> None:
2318
+ with tempfile.TemporaryDirectory() as temporary_directory:
2319
+ service = self._service(
2320
+ Path(temporary_directory),
2321
+ "model: claude-opus-5\neffort: high\n"
2322
+ "x-codee-context-tier: long_context\nx-codee-agent: codex\n")
2323
+
2324
+ nodes = self._story_nodes(service)
2325
+
2326
+ self.assertEqual(
2327
+ nodes["Ready"]["style"]["--codee-node-model"],
2328
+ "'claude-opus-5 \u00b7 high \u00b7 long context'",
2329
+ )
2330
+ self.assertIn(
2331
+ "Context: long context",
2332
+ nodes["Ready"]["style"]["--codee-agent-run"],
2333
+ )
2334
+
2238
2335
  def test_a_skill_that_names_neither_falls_back_to_what_runs_it(self) -> None:
2239
2336
  with tempfile.TemporaryDirectory() as temporary_directory:
2240
2337
  root = Path(temporary_directory)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: codee-agent
3
- Version: 0.9.3
3
+ Version: 0.9.4
4
4
  Summary: A virtual co-worker that picks up Jira and Azure DevOps tasks and solves them with coding agents.
5
5
  Keywords: ai,agent,jira,azure-devops,claude-code,github-copilot,codex,opencode,automation
6
6
  Author: Denis Kibalko
@@ -1,9 +1,9 @@
1
1
  codee/.gitignore,sha256=Fltsn5J90L9HwYTVg7Xlaoek3U0riZWmDTWmf0Ttfr8,15
2
2
  codee/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
- codee/admin.py,sha256=OzUEUpv4tMh4ks_GJxBsbmd3WNeN_7kdMIa0ZNAHjYA,200542
3
+ codee/admin.py,sha256=CHNBloc2YJ0PQwkG39BvOjRAZfK0okCufjtYR4dFbJY,206703
4
4
  codee/admin_api.py,sha256=q2S2H6neSXkcjrlhI3s190jJbOgenL0sqle5vnYmM5E,2503
5
5
  codee/admin_cli.py,sha256=8Hj9okvF1KMRsfm8IhGwl_E6OLqVAQ-wB2fjDKB9M4w,2871
6
- codee/admin_service.py,sha256=3S56yMad2gQb7FDz1qBAzt_FlUVYFE4QU8LtamZ13q8,125632
6
+ codee/admin_service.py,sha256=IuOeVp2NF4ZsH5M5VG6gF2KFzkRHXvXpmL5N9wnzgcw,129132
7
7
  codee/agent_cli.py,sha256=BNCMT4bIoAVmgbbU5QxAyktPmUXXWbB_I9cjg1vdBLg,2553
8
8
  codee/coding_agents.py,sha256=w7ofwl8b7CaPJzwBttxNpZyHUbm94P1XroKrRN5y2f8,3438
9
9
  codee/executor.py,sha256=FWUi_uMHqkt5552gAnxm5yN8mADYzzOdhvJEUUnpqiE,25222
@@ -45,7 +45,7 @@ codee/templates/skills/task-security-reviewer/SKILL.md,sha256=DY__ZKPGUeqveMZ0M3
45
45
  codee/test_admin.py,sha256=fyLX0BRoSMsIZDOw1M5bDFg2NKO71hzMRSESKXaY6GE,15648
46
46
  codee/test_admin_api.py,sha256=eT-ZCWw8giVU5V1xdqdctytVjuXV3wm3FKv4Nnp3gaU,2710
47
47
  codee/test_admin_cli.py,sha256=xMAdp8nBneNp6krZQo3SLtGM9rpjo19mnmmKqtM0QDw,3775
48
- codee/test_admin_service.py,sha256=fM3vjAJqZIWpxpdtILcjug9QSPuGfa9EJ87yBAu9HBw,179865
48
+ codee/test_admin_service.py,sha256=F1qfUS2z3Wuj6S6V7FoFgmQdV3JhThxfoMkDKQwJ-OQ,184159
49
49
  codee/test_agent_cli.py,sha256=JMRuG1lt5EgGr-YbvXEG8MSQdlQZwF4Yda8ZDLZVJTo,4363
50
50
  codee/test_coding_agents.py,sha256=8YPcEqVcyrvcQq6gpX3DmdHoP7z7fJ9kHl59Hre9Ruk,2700
51
51
  codee/test_executor.py,sha256=z8c71dhOcsjp9ILn79d7Tf0e3YC5TQMYYevOGU1AmpQ,28164
@@ -62,11 +62,11 @@ codee_agent_abstract/provider.py,sha256=ldBXT4WquuHXtX083y_zxGWScYJDktBX0zTJvn87
62
62
  codee_agent_abstract/test.py,sha256=x0qDiG907L5cFyDJmWEG6ZGTKdAQmIu9UK-qoDL0QoA,10729
63
63
  codee_agent_abstract/transcript.py,sha256=CuR-NQlHFL90FVtq4Y9zOV7wLSGuUkOld1sWcsFIPDQ,3854
64
64
  codee_agent_claude_code/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
65
- codee_agent_claude_code/account.py,sha256=Gv_9vGtMFROi9p2iNUqKKWmDoA3HZE_7n6wHVie9XJM,3068
66
- codee_agent_claude_code/credentials.py,sha256=sT9GasA5SjZIoNmlZlo1hRECYDFn6O3Tge7Tuw8D9J8,5320
65
+ codee_agent_claude_code/account.py,sha256=GaE6y0HwTLRXGUCNUj8W8QcDNL8iRLVUwGQuW_gcfzU,3510
66
+ codee_agent_claude_code/credentials.py,sha256=qLJl5skFrg58ubr5jOcSBeuP38ryADLlx75__O1JzXg,12313
67
67
  codee_agent_claude_code/oauth.py,sha256=kSr5cLuVcHUvny563DSXpwCV0tw8zySMsfqtdqDrGnI,10357
68
68
  codee_agent_claude_code/provider.py,sha256=CmUdds-ckq2a3yubIUYw-ntesdkTFFmv28sNQsDCJK0,10865
69
- codee_agent_claude_code/test.py,sha256=vE8tXFqcz0jiwWIhBy8SAOIsZBy3cDb6OBC-ddASrQM,30442
69
+ codee_agent_claude_code/test.py,sha256=c1fytWSG8Fyk3cpHfh5asuddeL8wJjPGcJ1VHYMuVvI,35540
70
70
  codee_agent_claude_code/usage.py,sha256=wSvJNDwAJmmQT7Syc-TF-DeW3yc8c2iJvZbbRwbJsqU,6202
71
71
  codee_agent_codex/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
72
72
  codee_agent_codex/provider.py,sha256=4QjFW-GAXPX90pUJCgmPRklIrpgYxdRGmOxD-PKVIfo,22038
@@ -95,8 +95,8 @@ codee_tasks_azure_devops/test.py,sha256=i9xDAM0sNw6Cr1s3BprECDnua4WQHkD1anD7kK_l
95
95
  codee_tasks_jira/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
96
96
  codee_tasks_jira/provider.py,sha256=N0llXpNzA4O6jD72hx_3_iksloFykar7wscZDcGfdb4,19053
97
97
  codee_tasks_jira/test.py,sha256=R0jOw8k_8uF6mYhANpGWZxQI8Dkya0M2Bk0oEK64iGo,27070
98
- codee_agent-0.9.3.dist-info/licenses/LICENSE,sha256=kXz80_Kc5IXrxIiweSCMx9Dv_AUeOcfwnQqCk2IDTmY,1075
99
- codee_agent-0.9.3.dist-info/WHEEL,sha256=a0ta4TK7UKMB0EbDesmi2mn0Djkly7aj_7Tu2R7SseE,81
100
- codee_agent-0.9.3.dist-info/entry_points.txt,sha256=Hr_8ZaN6g5DO1S94WbFpIwJzGAIeyhJrWIXl9BA0uIM,194
101
- codee_agent-0.9.3.dist-info/METADATA,sha256=NbCVqUAFkPCddQEYQxnTdvX3m-13MLel0zNgXA2Nq9E,2997
102
- codee_agent-0.9.3.dist-info/RECORD,,
98
+ codee_agent-0.9.4.dist-info/licenses/LICENSE,sha256=kXz80_Kc5IXrxIiweSCMx9Dv_AUeOcfwnQqCk2IDTmY,1075
99
+ codee_agent-0.9.4.dist-info/WHEEL,sha256=a0ta4TK7UKMB0EbDesmi2mn0Djkly7aj_7Tu2R7SseE,81
100
+ codee_agent-0.9.4.dist-info/entry_points.txt,sha256=Hr_8ZaN6g5DO1S94WbFpIwJzGAIeyhJrWIXl9BA0uIM,194
101
+ codee_agent-0.9.4.dist-info/METADATA,sha256=5NxXtM6SkhG8qspnw8otBntMTITGvgZKlK8Up5HKpAA,2997
102
+ codee_agent-0.9.4.dist-info/RECORD,,
@@ -31,6 +31,21 @@ def fetch_account(access_token: str) -> str:
31
31
 
32
32
  Raises :class:`AccountUnavailable` when there is no answer to show.
33
33
  """
34
+ label = read_account(fetch_profile(access_token))
35
+ if not label:
36
+ raise AccountUnavailable("the profile named no account")
37
+ return label
38
+
39
+
40
+ def fetch_profile(access_token: str) -> dict:
41
+ """The whole profile response for one key: the account and its organization.
42
+
43
+ What :func:`fetch_account` reads its label from, and what signing the CLI
44
+ in needs in full — it records the account's ids and organization next to
45
+ the token, not just the email.
46
+
47
+ Raises :class:`AccountUnavailable` when there is no answer to read.
48
+ """
34
49
  try:
35
50
  response = oauth.get(PROFILE_PATH, access_token)
36
51
  except oauth.OAuthApiError as error:
@@ -47,10 +62,7 @@ def fetch_account(access_token: str) -> str:
47
62
  if response.status_code in (401, 403)
48
63
  else f"HTTP {response.status_code}{detail}")
49
64
 
50
- label = read_account(response.payload)
51
- if not label:
52
- raise AccountUnavailable("the profile named no account")
53
- return label
65
+ return response.payload
54
66
 
55
67
 
56
68
  def read_account(payload: dict) -> str:
@@ -12,10 +12,18 @@ to be left holding the refresh token and the real expiry that let it renew the
12
12
  token mid-run. Writing an access token alone — under an expiry invented to stop
13
13
  the CLI trying to renew it — would strand a long run the moment it aged out.
14
14
  Anything else in the file is left exactly as it was found.
15
+
16
+ On macOS the CLI keeps the same JSON in the login Keychain instead, and reads
17
+ the Keychain before the file — so a file write alone would be ignored there.
18
+ Both are written on a Mac, and the Keychain is what is read back.
15
19
  """
20
+ import getpass
16
21
  import json
17
22
  import os
23
+ import shutil
18
24
  import stat
25
+ import subprocess
26
+ import sys
19
27
  from dataclasses import dataclass
20
28
  from pathlib import Path
21
29
 
@@ -29,6 +37,14 @@ log = get_logger(__name__)
29
37
  CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR"
30
38
  CREDENTIALS_NAME = ".credentials.json"
31
39
  OAUTH_SECTION = "claudeAiOauth"
40
+ # The CLI's global config, which names the account it is signed in as. It sits
41
+ # in the home directory by default, not in ``~/.claude``, and moves into the
42
+ # config directory when ``CLAUDE_CONFIG_DIR`` is set.
43
+ GLOBAL_CONFIG_NAME = ".claude.json"
44
+ OAUTH_ACCOUNT_SECTION = "oauthAccount"
45
+ # The Keychain item the CLI stores its credentials under on macOS.
46
+ KEYCHAIN_SERVICE = "Claude Code-credentials"
47
+ KEYCHAIN_TIMEOUT_SECONDS = 10
32
48
 
33
49
  # Credentials are readable by their owner and nobody else. The CLI writes them
34
50
  # that way and a rewrite has to keep it, including when this module is what
@@ -36,6 +52,14 @@ OAUTH_SECTION = "claudeAiOauth"
36
52
  _OWNER_ONLY = stat.S_IRUSR | stat.S_IWUSR
37
53
 
38
54
 
55
+ class CredentialsUnwritable(Exception):
56
+ """The Keychain item could not be written, so the CLI is not signed in.
57
+
58
+ Raised rather than logged: on macOS the Keychain is what the CLI reads, so
59
+ a sign-in that only reached the file has not happened.
60
+ """
61
+
62
+
39
63
  @dataclass(frozen=True)
40
64
  class StoredCredentials:
41
65
  """The ``claudeAiOauth`` section, as far as Codee reads it."""
@@ -57,6 +81,12 @@ def credentials_file() -> Path:
57
81
  return config_dir() / CREDENTIALS_NAME
58
82
 
59
83
 
84
+ def global_config_file() -> Path:
85
+ """Path to ``.claude.json``, honouring ``CLAUDE_CONFIG_DIR``."""
86
+ configured = os.environ.get(CONFIG_DIR_ENV, "").strip()
87
+ return (Path(configured) if configured else Path.home()) / GLOBAL_CONFIG_NAME
88
+
89
+
60
90
  def read_credentials() -> StoredCredentials:
61
91
  """What the CLI would authenticate with, or an empty set.
62
92
 
@@ -64,8 +94,13 @@ def read_credentials() -> StoredCredentials:
64
94
  half-written JSON, an installation signed in some other way. All of them
65
95
  mean the same thing to the caller: what is on disk is not something ours
66
96
  can be compared against, so write ours.
97
+
98
+ On macOS the Keychain is read first, because that is what the CLI reads
99
+ first; the file only counts when the Keychain holds nothing.
67
100
  """
68
- data = _read_file()
101
+ data = _read_keychain() if _uses_keychain() else {}
102
+ if not data:
103
+ data = _read_file()
69
104
  section = data.get(OAUTH_SECTION)
70
105
  if not isinstance(section, dict):
71
106
  return StoredCredentials()
@@ -91,8 +126,69 @@ def write_credentials(access_token: str, refresh_token: str = "",
91
126
  the CLI reads this file at the start of every run, and a torn read there
92
127
  would look like a signed-out installation to whichever agent run happened
93
128
  to land on it.
129
+
130
+ On macOS the Keychain item is written as well, with the same contents,
131
+ and :class:`CredentialsUnwritable` is raised when it cannot be.
94
132
  """
95
133
  data = _read_file()
134
+ _merge_oauth(data, access_token, refresh_token, expires_at, scopes,
135
+ subscription_type)
136
+ _write_json(credentials_file(), data)
137
+ log.debug("signed Claude Code in through %s", credentials_file())
138
+
139
+ if _uses_keychain():
140
+ keychain = _read_keychain()
141
+ _merge_oauth(keychain, access_token, refresh_token, expires_at, scopes,
142
+ subscription_type)
143
+ _write_keychain(keychain)
144
+
145
+
146
+ def write_oauth_account(profile: dict) -> bool:
147
+ """Record whose account the CLI is signed in as, from a profile response.
148
+
149
+ The CLI keeps this next to the token in ``.claude.json`` and shows it in
150
+ ``/status``; after a switch it would otherwise go on naming the previous
151
+ account. The section is replaced, not merged: a field the new profile does
152
+ not carry would otherwise keep describing the old account. The CLI fills
153
+ in the rest itself the next time it fetches the profile.
154
+
155
+ Only an existing file is touched — one that is not there belongs to a CLI
156
+ that has never run, and will be written by its own first run. Returns
157
+ whether the file was written.
158
+ """
159
+ path = global_config_file()
160
+ if not path.exists():
161
+ return False
162
+ data = _read_json(path)
163
+ account = profile.get("account")
164
+ account = account if isinstance(account, dict) else {}
165
+ organization = profile.get("organization")
166
+ organization = organization if isinstance(organization, dict) else {}
167
+ section = {}
168
+ for source, key, field in (
169
+ (account, "uuid", "accountUuid"),
170
+ (account, "email", "emailAddress"),
171
+ (account, "display_name", "displayName"),
172
+ (account, "full_name", "fullName"),
173
+ (account, "created_at", "accountCreatedAt"),
174
+ (organization, "uuid", "organizationUuid"),
175
+ (organization, "name", "organizationName"),
176
+ (organization, "organization_type", "organizationType"),
177
+ (organization, "billing_type", "billingType"),
178
+ (organization, "rate_limit_tier", "organizationRateLimitTier"),
179
+ (organization, "has_extra_usage_enabled", "hasExtraUsageEnabled"),
180
+ (organization, "subscription_created_at", "subscriptionCreatedAt")):
181
+ if source.get(key) is not None:
182
+ section[field] = source[key]
183
+ data[OAUTH_ACCOUNT_SECTION] = section
184
+ _write_json(path, data, mode=_mode_of(path))
185
+ log.debug("recorded the signed-in account in %s", path)
186
+ return True
187
+
188
+
189
+ def _merge_oauth(data: dict, access_token: str, refresh_token: str,
190
+ expires_at: int, scopes: str, subscription_type: str) -> None:
191
+ """Write one account into ``data``'s ``claudeAiOauth``, in place."""
96
192
  section = data.get(OAUTH_SECTION)
97
193
  section = dict(section) if isinstance(section, dict) else {}
98
194
  section["accessToken"] = access_token
@@ -106,15 +202,23 @@ def write_credentials(access_token: str, refresh_token: str = "",
106
202
  section["subscriptionType"] = subscription_type
107
203
  data[OAUTH_SECTION] = section
108
204
 
109
- path = credentials_file()
205
+
206
+ def _write_json(path: Path, data: dict, mode: int = _OWNER_ONLY) -> None:
207
+ """Replace ``path`` with ``data`` through a temp file and a rename."""
110
208
  path.parent.mkdir(parents=True, exist_ok=True)
111
209
  temp = path.with_name(path.name + ".codee.tmp")
112
210
  temp.write_text(json.dumps(data, indent=2) + "\n")
113
211
  # On the temp file, before the rename: a chmod after it would leave the
114
212
  # real credentials world-readable for as long as the two calls take.
115
- os.chmod(temp, _OWNER_ONLY)
213
+ os.chmod(temp, mode)
116
214
  os.replace(temp, path)
117
- log.debug("signed Claude Code in through %s", path)
215
+
216
+
217
+ def _mode_of(path: Path) -> int:
218
+ try:
219
+ return stat.S_IMODE(path.stat().st_mode)
220
+ except OSError:
221
+ return _OWNER_ONLY
118
222
 
119
223
 
120
224
  def _read_file() -> dict:
@@ -124,10 +228,73 @@ def _read_file() -> dict:
124
228
  nothing in it worth preserving — but one that simply isn't there yet is the
125
229
  ordinary case for a machine the CLI has never signed in on.
126
230
  """
127
- path = credentials_file()
231
+ return _read_json(credentials_file())
232
+
233
+
234
+ def _read_json(path: Path) -> dict:
128
235
  try:
129
236
  data = json.loads(path.read_text())
130
237
  except (OSError, json.JSONDecodeError) as error:
131
238
  log.debug("could not read %s: %s", path, error)
132
239
  return {}
133
240
  return data if isinstance(data, dict) else {}
241
+
242
+
243
+ def _uses_keychain() -> bool:
244
+ """Whether the CLI here keeps its credentials in the macOS Keychain.
245
+
246
+ Not when ``CLAUDE_CONFIG_DIR`` is set: the CLI then files them under a
247
+ Keychain item named after that directory, so the default item would be
248
+ the wrong one to write. The file is still written in that case.
249
+ """
250
+ return (sys.platform == "darwin"
251
+ and not os.environ.get(CONFIG_DIR_ENV, "").strip()
252
+ and shutil.which("security") is not None)
253
+
254
+
255
+ def _keychain_account() -> str:
256
+ return os.environ.get("USER") or getpass.getuser()
257
+
258
+
259
+ def _read_keychain() -> dict:
260
+ """The CLI's Keychain item as a dict, or an empty one when there is none."""
261
+ try:
262
+ result = subprocess.run(
263
+ ["security", "find-generic-password", "-a", _keychain_account(),
264
+ "-s", KEYCHAIN_SERVICE, "-w"],
265
+ capture_output=True, text=True, timeout=KEYCHAIN_TIMEOUT_SECONDS)
266
+ except (OSError, subprocess.SubprocessError) as error:
267
+ log.debug("could not read the Keychain: %s", error)
268
+ return {}
269
+ if result.returncode != 0:
270
+ return {}
271
+ try:
272
+ data = json.loads(result.stdout)
273
+ except json.JSONDecodeError as error:
274
+ log.debug("could not parse the Keychain item: %s", error)
275
+ return {}
276
+ return data if isinstance(data, dict) else {}
277
+
278
+
279
+ def _write_keychain(data: dict) -> None:
280
+ """Create or replace the CLI's Keychain item.
281
+
282
+ The secret goes in on stdin, hex-encoded, through ``security -i``, the
283
+ same way the CLI writes it: passed as an argument it would be readable by
284
+ anyone listing processes while the command runs.
285
+ """
286
+ secret = json.dumps(data).encode().hex()
287
+ command = (f'add-generic-password -U -a "{_keychain_account()}" '
288
+ f'-s "{KEYCHAIN_SERVICE}" -X "{secret}"\n')
289
+ try:
290
+ result = subprocess.run(["security", "-i"], input=command,
291
+ capture_output=True, text=True,
292
+ timeout=KEYCHAIN_TIMEOUT_SECONDS)
293
+ except (OSError, subprocess.SubprocessError) as error:
294
+ raise CredentialsUnwritable(
295
+ f"could not write the Claude Code Keychain item: {error}") from error
296
+ if result.returncode != 0:
297
+ raise CredentialsUnwritable(
298
+ "could not write the Claude Code Keychain item: "
299
+ f"{(result.stderr or result.stdout).strip()}")
300
+ log.debug("signed Claude Code in through the Keychain")
@@ -286,6 +286,109 @@ class ClaudeCodeCredentialsTest(unittest.TestCase):
286
286
  self.assertEqual([path.name for path in self.home.iterdir()],
287
287
  [credentials.CREDENTIALS_NAME])
288
288
 
289
+ PROFILE = {
290
+ "account": {"uuid": "acc-2", "email": "two@example.com",
291
+ "display_name": "Two"},
292
+ "organization": {"uuid": "org-2", "name": "Two Ltd",
293
+ "has_extra_usage_enabled": False},
294
+ }
295
+
296
+ def test_the_signed_in_account_is_named_in_the_global_config(self) -> None:
297
+ config = self.home / credentials.GLOBAL_CONFIG_NAME
298
+ config.write_text(json.dumps({
299
+ "numStartups": 4,
300
+ "oauthAccount": {"emailAddress": "one@example.com",
301
+ "organizationRole": "admin"}}))
302
+
303
+ self.assertTrue(credentials.write_oauth_account(self.PROFILE))
304
+
305
+ stored = json.loads(config.read_text())
306
+ self.assertEqual(stored["numStartups"], 4)
307
+ # Replaced, not merged: the old account's role must not describe
308
+ # the new one.
309
+ self.assertEqual(stored["oauthAccount"], {
310
+ "accountUuid": "acc-2", "emailAddress": "two@example.com",
311
+ "displayName": "Two", "organizationUuid": "org-2",
312
+ "organizationName": "Two Ltd", "hasExtraUsageEnabled": False})
313
+
314
+ def test_a_cli_that_never_ran_gets_no_global_config(self) -> None:
315
+ self.assertFalse(credentials.write_oauth_account(self.PROFILE))
316
+
317
+ self.assertFalse(
318
+ (self.home / credentials.GLOBAL_CONFIG_NAME).exists())
319
+
320
+
321
+ class ClaudeCodeKeychainTest(unittest.TestCase):
322
+ """On macOS the CLI reads its credentials from the Keychain first."""
323
+
324
+ def setUp(self) -> None:
325
+ self._temporary = tempfile.TemporaryDirectory()
326
+ self.addCleanup(self._temporary.cleanup)
327
+ home = Path(self._temporary.name)
328
+ self._uses_keychain = credentials._uses_keychain
329
+ # The file goes to a temp home; the Keychain is never really touched.
330
+ for patcher in (patch.object(Path, "home", return_value=home),
331
+ patch.object(credentials, "_uses_keychain",
332
+ return_value=True),
333
+ patch.dict(os.environ, {"USER": "someone"})):
334
+ patcher.start()
335
+ self.addCleanup(patcher.stop)
336
+ os.environ.pop(credentials.CONFIG_DIR_ENV, None)
337
+ self.path = home / ".claude" / credentials.CREDENTIALS_NAME
338
+
339
+ @staticmethod
340
+ def _found(payload: dict) -> subprocess.CompletedProcess:
341
+ return subprocess.CompletedProcess([], 0, json.dumps(payload), "")
342
+
343
+ def test_the_keychain_wins_over_the_file(self) -> None:
344
+ self.path.parent.mkdir(parents=True)
345
+ self.path.write_text(json.dumps(
346
+ {"claudeAiOauth": {"accessToken": "from-file"}}))
347
+ with patch("subprocess.run", return_value=self._found(
348
+ {"claudeAiOauth": {"accessToken": "from-keychain"}})):
349
+ self.assertEqual(credentials.read_access_token(), "from-keychain")
350
+
351
+ def test_signing_in_writes_the_keychain_and_the_file(self) -> None:
352
+ existing = {"claudeAiOauth": {"accessToken": "old",
353
+ "subscriptionType": "max"},
354
+ "mcpOAuth": {"kept": True}}
355
+ with patch("subprocess.run", side_effect=[
356
+ self._found(existing),
357
+ subprocess.CompletedProcess([], 0, "", "")]) as run:
358
+ credentials.write_credentials("token-2", "refresh-2", 2)
359
+
360
+ command = run.call_args_list[1]
361
+ self.assertEqual(command.args[0], ["security", "-i"])
362
+ # The secret goes in on stdin, never on the command line.
363
+ script = command.kwargs["input"]
364
+ self.assertIn('-a "someone" -s "Claude Code-credentials"', script)
365
+ written = json.loads(bytes.fromhex(
366
+ script.split('-X "')[1].split('"')[0]))
367
+ self.assertEqual(written["claudeAiOauth"]["accessToken"], "token-2")
368
+ self.assertEqual(written["claudeAiOauth"]["subscriptionType"], "max")
369
+ self.assertEqual(written["mcpOAuth"], {"kept": True})
370
+ self.assertEqual(json.loads(self.path.read_text())
371
+ ["claudeAiOauth"]["accessToken"], "token-2")
372
+
373
+ def test_a_keychain_that_refuses_the_write_is_an_error(self) -> None:
374
+ with patch("subprocess.run", side_effect=[
375
+ subprocess.CompletedProcess([], 44, "", "not found"),
376
+ subprocess.CompletedProcess([], 1, "", "denied")]), \
377
+ self.assertRaises(credentials.CredentialsUnwritable):
378
+ credentials.write_credentials("token-2", "refresh-2", 2)
379
+
380
+ def test_a_moved_config_dir_leaves_the_default_item_alone(self) -> None:
381
+ # The CLI files a moved config's credentials under another item name,
382
+ # so the default item would be the wrong one to write.
383
+ uses_keychain = self._uses_keychain
384
+ with patch.object(credentials.sys, "platform", "darwin"), \
385
+ patch.object(credentials.shutil, "which",
386
+ return_value="/usr/bin/security"):
387
+ self.assertTrue(uses_keychain())
388
+ with patch.dict(os.environ,
389
+ {credentials.CONFIG_DIR_ENV: "/elsewhere"}):
390
+ self.assertFalse(uses_keychain())
391
+
289
392
 
290
393
  class ClaudeCodeAccountTest(unittest.TestCase):
291
394
  """Reading which account an access key belongs to."""