-
Notifications
You must be signed in to change notification settings - Fork 4
fix: GPT session re-auth crash + cleaner ImplementAndJudge card #181
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
packages/pythinker-core/tests/test_openai_responses_auth.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| """Auth-boundary behavior for the OpenAI Responses chat provider. | ||
|
|
||
| Regression coverage for the mid-session credential blank: when an OAuth refresh | ||
| token is rejected server-side (e.g. it was rotated on another machine), the | ||
| Pythinker OAuth refresh path blanks the *live* OpenAI client's ``api_key`` to | ||
| ``""``. The OpenAI SDK then raises a bare ``TypeError`` from ``_validate_headers`` | ||
| at request-build time. That ``TypeError`` is neither ``OpenAIError`` nor | ||
| ``httpx.HTTPError``, so without conversion it escapes every handler as a fatal | ||
| "Unexpected error". The provider must convert it to a typed ``APIStatusError`` | ||
| (401) so the standard refresh -> ``/login`` recovery engages instead. | ||
| """ | ||
|
|
||
| import pytest | ||
|
|
||
| from pythinker_core.chat_provider import APIStatusError | ||
| from pythinker_core.contrib.chat_provider.openai_responses import OpenAIResponses | ||
| from pythinker_core.message import Message | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("stream", [True, False]) | ||
| async def test_blanked_credential_raises_typed_401(stream: bool) -> None: | ||
| # Construct with a valid key (the SDK enforces credentials at construction), | ||
| # then simulate the live blank applied by the OAuth refresh path. | ||
| provider = OpenAIResponses(model="gpt-5-codex", api_key="sk-valid-dummy", stream=stream) | ||
| # Mirror _apply_access_token(runtime, ref, "") blanking the live client. | ||
| provider._client.api_key = "" # pyright: ignore[reportPrivateUsage] | ||
|
|
||
| with pytest.raises(APIStatusError) as exc_info: | ||
| await provider.generate("You are helpful.", [], [Message(role="user", content="hi")]) | ||
|
|
||
| assert exc_info.value.status_code == 401 | ||
|
|
||
|
|
||
| async def test_typeerror_with_valid_key_propagates(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| # A TypeError that is NOT the missing-credential case must still propagate, | ||
| # so the conversion never becomes a bug-swallower. | ||
| provider = OpenAIResponses(model="gpt-5-codex", api_key="sk-valid-dummy", stream=True) | ||
|
|
||
| async def boom(*args: object, **kwargs: object) -> None: | ||
| raise TypeError("unrelated bug, not an auth failure") | ||
|
|
||
| monkeypatch.setattr(provider._client.responses, "create", boom) # pyright: ignore[reportPrivateUsage] | ||
|
|
||
| with pytest.raises(TypeError, match="unrelated bug"): | ||
| await provider.generate("You are helpful.", [], [Message(role="user", content="hi")]) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
114 changes: 114 additions & 0 deletions
114
src/pythinker_code/ui/shell/tool_renderers/implement_judge.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| """Pythinker renderer for the ``ImplementAndJudge`` chain tool. | ||
|
|
||
| The generic fallback renders this as ``ImplementAndJudge(4 args: acceptance, | ||
| base_prompt, brief, scope)`` — an unreadable arg dump. This dedicated renderer | ||
| shows the chain as ``⏺ Implement & Judge — <brief>`` so the card reads as a | ||
| single clear action instead of leaking the parameter names. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from rich.console import Group, RenderableType | ||
| from rich.text import Text | ||
|
|
||
| from pythinker_code.ui.shell.components.render_utils import sanitize_ansi | ||
| from pythinker_code.ui.shell.glyphs import TRANSCRIPT_ASSISTANT_MARKER | ||
| from pythinker_code.ui.shell.tool_renderers import ( | ||
| ToolRenderContext, | ||
| ToolRenderDefinition, | ||
| ToolResultPayload, | ||
| ) | ||
| from pythinker_code.ui.shell.tool_renderers._render_utils import ( | ||
| as_str, | ||
| fg, | ||
| format_lines_block, | ||
| missing_required_arg, | ||
| pending_tool_call_header, | ||
| running_spinner, | ||
| tool_title, | ||
| ) | ||
| from pythinker_code.ui.theme import tui_rich_style | ||
|
|
||
| # Internal tool name stays ``ImplementAndJudge`` (registry/config/tests); only | ||
| # the on-screen label is the friendlier form. Kept in sync with | ||
| # ``pythinker_code.tools.agent.IMPLEMENT_JUDGE_NAME`` by a focused test. | ||
| _TOOL_NAME = "ImplementAndJudge" | ||
| _DISPLAY_NAME = "Implement & Judge" | ||
| _BRIEF_MAX_CHARS = 80 | ||
| _COLLAPSED_LINES = 8 | ||
|
|
||
|
|
||
| def _compact(text: str, *, max_chars: int = _BRIEF_MAX_CHARS) -> str: | ||
| """Collapse whitespace and ellipsize a possibly multi-line brief.""" | ||
| compact = " ".join(text.split()) | ||
| if len(compact) <= max_chars: | ||
| return compact | ||
| if max_chars <= 1: | ||
| return "…" | ||
| return compact[: max_chars - 1].rstrip() + "…" | ||
|
|
||
|
|
||
| def _render_call(ctx: ToolRenderContext) -> RenderableType: | ||
| args = ctx.args or {} | ||
| brief = as_str(args.get("brief")) | ||
| style_token = "error" if ctx.is_error else "success" if ctx.has_result else "muted" | ||
|
|
||
| if brief is None: | ||
| # Streamed args still incomplete, or the required brief is missing. | ||
| if ctx.has_result: | ||
| header: RenderableType = Group( | ||
| _label_header(style_token), missing_required_arg("brief") | ||
| ) | ||
| else: | ||
| header = pending_tool_call_header(_DISPLAY_NAME) | ||
| return running_spinner( | ||
| header, | ||
| execution_started=ctx.execution_started, | ||
| has_result=ctx.has_result, | ||
| marker_style_token="muted", | ||
| ) | ||
|
|
||
| header = _label_header(style_token) | ||
| header.append(" — ", style=tui_rich_style("muted")) | ||
| header.append(sanitize_ansi(_compact(brief)), style=tui_rich_style("thinking_text")) | ||
| header.no_wrap = True | ||
| header.overflow = "ellipsis" | ||
| return running_spinner( | ||
| header, | ||
| execution_started=ctx.execution_started, | ||
| has_result=ctx.has_result, | ||
| marker_style_token="muted", | ||
| ) | ||
|
|
||
|
|
||
| def _label_header(style_token: str) -> Text: | ||
| marker = "✘" if style_token == "error" else TRANSCRIPT_ASSISTANT_MARKER | ||
| header = Text() | ||
| header.append(f"{marker} ", style=tui_rich_style(style_token)) | ||
| header.append_text(tool_title(_DISPLAY_NAME)) | ||
| return header | ||
|
|
||
|
|
||
| def _render_result(ctx: ToolRenderContext, result: ToolResultPayload) -> RenderableType | None: | ||
| text = sanitize_ansi(result.text or "").rstrip("\n") | ||
| if not text: | ||
| return None | ||
| body, remaining = format_lines_block( | ||
| text, | ||
| expanded=ctx.expanded, | ||
| collapsed_max_lines=_COLLAPSED_LINES, | ||
| style_token="error" if result.is_error else "tool_output", | ||
| ) | ||
| if remaining > 0: | ||
| ctx.state["__suppress_generic_expand_hint__"] = True | ||
| return Group(body, fg("muted", f"… ({remaining} more lines, ctrl+o to expand)")) | ||
| return body | ||
|
|
||
|
|
||
| IMPLEMENT_JUDGE_RENDERER = ToolRenderDefinition( | ||
| name=_TOOL_NAME, | ||
| label=_DISPLAY_NAME, | ||
| render_shell="default", | ||
| render_call=_render_call, | ||
| render_result=_render_result, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.