Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

Merge origin/master into codex-integrate-org-into-master

Max2883e3fe3d87
diff --cc skills/background-watch-hook/scripts/_github_wait_common.py
index 61000c321,52e0d48ff..ab9c3a380
--- a/skills/background-watch-hook/scripts/_github_wait_common.py
+++ b/skills/background-watch-hook/scripts/_github_wait_common.py
@@@ -3,6 -3,6 +3,7 @@@
from __future__ import annotations
++import http.client
import json
import math
import os
@@@ -52,6 -55,126 +56,133 @@@ NOT_MODIFIED_STATUS = 30
SINCE_REWIND_SECONDS = 2
_MISSING = object()
+ _T = TypeVar("_T")
+
+
+ class GitHubRequestError(RuntimeError):
+ """Base class for failures classified at the GitHub request boundary."""
+
+ retryable = False
+
+ def __init__(self, message: str, *, status_code: int | None = None) -> None:
+ super().__init__(message)
+ self.status_code = status_code
+
+
+ class GitHubTransientError(GitHubRequestError):
+ """A network or retryable HTTP failure that a bounded waiter may retry."""
+
+ retryable = True
+
+
+ class GitHubTerminalError(GitHubRequestError):
+ """A terminal GitHub failure that must stop the waiter."""
+
+
+ class GitHubProtocolError(GitHubTerminalError):
+ """A successful response that violates the expected GitHub contract."""
+
+
+ class InitialRequestRetriesExhausted(GitHubTerminalError):
+ """A bounded initial GitHub request exhausted its transient retries."""
+
+
+ class GitHubRequestResult(Generic[_T]):
+ """One classified request outcome; callers never catch request exceptions."""
+
+ __slots__ = ("error", "value")
+
+ def __init__(
+ self,
+ *,
+ value: _T | None = None,
+ error: GitHubRequestError | None = None,
+ ) -> None:
+ self.value = value
+ self.error = error
+
+ @property
+ def succeeded(self) -> bool:
+ return self.error is None
+
+
+ def _classify_github_exception(
+ err: Exception,
+ *,
+ unauthenticated: bool = False,
+ ) -> GitHubRequestError:
+ if isinstance(err, GitHubRequestError):
+ return err
+ if isinstance(err, urllib.error.HTTPError):
+ code = int(err.code)
+ reason = str(err.reason)
+ if unauthenticated and code in {403, 429}:
+ return GitHubTerminalError(
+ "GitHub unauthenticated polling hit a rate limit; authenticate with "
+ "'gh auth login' or GITHUB_TOKEN/GH_TOKEN",
+ status_code=code,
+ )
+ error_type = GitHubTransientError if code in RETRYABLE_HTTP_STATUS_CODES else GitHubTerminalError
+ return error_type(f"GitHub HTTP {code} {reason}", status_code=code)
+ if isinstance(err, (urllib.error.URLError, TimeoutError, ConnectionError, OSError)):
+ reason = str(getattr(err, "reason", err))
+ return GitHubTransientError(f"GitHub network failure: {reason}")
++ # `http.client` raises `HTTPException`, not `OSError`, when the transport
++ # breaks mid-body: a large PR truncated by the peer surfaces as
++ # `IncompleteRead`. It is a network failure like any other, and classifying it
++ # terminal killed managed waits on a connection glitch they should have
++ # simply re-polled through.
++ if isinstance(err, http.client.HTTPException):
++ return GitHubTransientError(f"GitHub network failure: {type(err).__name__}: {err}")
+ return GitHubTerminalError(
+ f"Unexpected GitHub request failure ({type(err).__name__}): {err}"
+ )
+
+
+ def github_request(
+ operation: Callable[[], _T],
+ *,
+ unauthenticated: bool = False,
+ ) -> GitHubRequestResult[_T]:
+ """Run one GitHub operation through the transient/terminal taxonomy."""
+
+ try:
+ return GitHubRequestResult(value=operation())
+ except Exception as err: # noqa: BLE001 - this is the classification boundary
+ return GitHubRequestResult(
+ error=_classify_github_exception(err, unauthenticated=unauthenticated)
+ )
+
+
+ def retry_initial_request(
+ operation: Callable[[], _T],
+ *,
+ description: str,
+ unauthenticated: bool = False,
+ ) -> GitHubRequestResult[_T]:
+ """Retry initial network and retryable HTTP failures with bounded backoff."""
+
+ for attempt in range(1, INITIAL_REQUEST_MAX_ATTEMPTS + 1):
+ result = github_request(operation, unauthenticated=unauthenticated)
+ if result.succeeded or result.error is None or not result.error.retryable:
+ return result
+ failure = str(result.error)
+
+ if attempt == INITIAL_REQUEST_MAX_ATTEMPTS:
+ return GitHubRequestResult(
+ error=InitialRequestRetriesExhausted(
+ f"{description} failed after {INITIAL_REQUEST_MAX_ATTEMPTS} attempts: {failure}"
+ )
+ )
+ delay = INITIAL_REQUEST_BACKOFF_SECONDS * (2 ** (attempt - 1))
+ print(
+ f"Transient {description} failure on attempt {attempt}/{INITIAL_REQUEST_MAX_ATTEMPTS}: "
+ f"{failure}; retrying in {delay:.1f}s",
+ file=sys.stderr,
+ )
+ time.sleep(delay)
+
+ return GitHubRequestResult(error=GitHubTerminalError("unreachable request state"))
def no_event(summary: str = "") -> int:
diff --cc skills/background-watch-hook/scripts/wait_pr.py
index 05e79ee42,fa018a808..1e4f54564
--- a/skills/background-watch-hook/scripts/wait_pr.py
+++ b/skills/background-watch-hook/scripts/wait_pr.py
@@@ -32,7 -31,8 +31,9 @@@ from _github_wait_common import ( # no
get_authenticated_login,
get_token,
github_get,
- is_retryable_http_error,
+ github_graphql,
+ github_request,
++ InitialRequestRetriesExhausted,
LAST_DELIVERY_ENV,
later_since,
list_paginated,
@@@ -40,7 -40,7 +41,8 @@@
max_id,
min_interval_for_unauthenticated,
REQUEST_TIMEOUT_SECONDS,
+ RETRY_EXIT_CODE,
+ retry_initial_request,
requests_per_poll,
ResponseCache,
squash,
@@@ -494,6 -850,6 +852,21 @@@ def _write_new_pr_cursor_output(path: s
json.dump({"pr_cursor": pr_cursor}, handle)
++def _startup_failure_exit_code(error: Any) -> int:
++ """How a failure *before* the first poll should end this run.
++
++ Nothing has been observed yet, so no activity is lost by ending the run early.
++ A transient failure that merely outlasted the bounded startup retries -- a
++ truncated body on a large PR, a blip in the network -- must therefore exit
++ ``RETRY_EXIT_CODE`` so a managed retry-capable watch can re-arm itself instead
++ of dying and leaving the PR unwatched until somebody notices. Genuinely
++ terminal failures (a bad token, a PR that does not exist) still exit 1:
++ retrying those would poll forever without ever succeeding.
++ """
++
++ return RETRY_EXIT_CODE if isinstance(error, InitialRequestRetriesExhausted) else 1
++
++
def _watch_identity(args: argparse.Namespace) -> str:
"""A stable digest of the options that decide what this watch reports.
@@@ -1191,13 -1665,91 +1682,91 @@@ def main() -> int
)
return 2
- watch_identity = _watch_identity(args)
- watch_id = _managed_watch_id()
- delivery_stamp = _last_delivery()
- # Only a managed run has a next cycle to promote staged cursors, and only it gets
- # told whether the report was queued. A manual run is one process whose stdout is
- # the delivery, so staging there would leave cursors nobody ever promotes.
- two_phase = watch_id is not None
+ token_fingerprint = _token_fingerprint(token)
+ viewer_login = None
+ if args.pr is not None and not args.include_self_comments:
+ # The stored login spares a /user request on every cycle of a forever watch,
+ # but only while the token still belongs to the account it was resolved for.
+ # A rotated or swapped credential would otherwise keep filtering out the old
+ # account's comments and let the new account's own comments wake the Agent.
+ if token_fingerprint is not None and _saved_str(saved, "token_fingerprint") == token_fingerprint:
+ viewer_login = _saved_str(saved, "viewer_login")
+ if viewer_login is None:
+ viewer_result = retry_initial_request(
+ lambda: get_authenticated_login(token, raise_on_error=True),
+ description="GitHub viewer lookup",
+ unauthenticated=token is None,
+ )
+ if viewer_result.error is not None:
+ print(f"GitHub viewer lookup failed: {viewer_result.error}", file=sys.stderr)
- return 1
++ return _startup_failure_exit_code(viewer_result.error)
+ viewer_login = viewer_result.value
+ if token is not None and not viewer_login:
+ print(
+ "Could not resolve the authenticated GitHub login; refusing to poll while self-comment filtering is enabled.",
+ file=sys.stderr,
+ )
+ return 1
+
+ base_interval = max(args.interval, 1.0)
+ effective_interval = base_interval
+ settle_seconds = max(args.settle, 0.0)
+
+ start = time.monotonic()
+
+ saved_pr_cursor = None if args.catch_up else _saved_int(saved, "pr_cursor")
+ since_pr_id = args.since_pr_id if args.since_pr_id is not None else saved_pr_cursor
+ initial_resume = all(_saved_int(saved, key) is not None for key in STATE_CURSOR_KEYS)
+ initial_review_comment_since = (
+ _saved_str(saved, "review_comment_since")
+ if initial_resume and args.since_review_comment_id is None
+ else None
+ )
+ initial_issue_comment_since = (
+ _saved_str(saved, "issue_comment_since")
+ if initial_resume and args.since_issue_comment_id is None
+ else None
+ )
+
+ def _fetch_initial_state() -> tuple[dict[str, Any], int]:
+ if args.pr is not None:
+ return _fetch_state(
+ args.repo,
+ args.pr,
+ token,
+ cache=cache,
+ review_comment_since=initial_review_comment_since,
+ issue_comment_since=initial_issue_comment_since,
+ )
+ initial_pr_stop_after_id = None
+ initial_pr_max_pages = None
+ if since_pr_id is not None and not args.catch_up:
+ initial_pr_stop_after_id = since_pr_id
+ elif not args.catch_up:
+ initial_pr_max_pages = 1
+ return _fetch_new_pr_state(
+ args.repo,
+ token,
+ stop_after_id=initial_pr_stop_after_id,
+ max_pages=initial_pr_max_pages,
+ cache=cache,
+ )
+
+ initial_request = retry_initial_request(
+ _fetch_initial_state,
+ description="initial GitHub PR state request",
+ unauthenticated=token is None,
+ )
+ if initial_request.error is not None:
+ print(f"Failed to fetch initial PR state: {initial_request.error}", file=sys.stderr)
- return 1
++ return _startup_failure_exit_code(initial_request.error)
+ if initial_request.value is None:
+ print("Initial GitHub PR state request completed without a result", file=sys.stderr)
+ return 1
+ state, requests_per_poll_count = initial_request.value
+
+ # The remote target is now proven valid. Only now may this run create or adopt
+ # its state path; a typo or inaccessible PR must leave no ownership claim.
_verify_state_file_writable(
args.state_file,
repo=args.repo,
diff --cc tests/test_github_wait_common.py
index a35e3756c,eb6ab5d69..e56354ed3
--- a/tests/test_github_wait_common.py
+++ b/tests/test_github_wait_common.py
@@@ -1,5 -1,5 +1,6 @@@
from __future__ import annotations
++import http.client
import importlib.util
import json
import urllib.error
@@@ -47,6 -47,78 +48,90 @@@ def _not_modified() -> urllib.error.HTT
)
+ def test_retry_initial_request_recovers_with_bounded_backoff() -> None:
+ module = _load_module()
+ attempts = 0
+
+ def _operation() -> str:
+ nonlocal attempts
+ attempts += 1
+ if attempts < 3:
+ raise urllib.error.URLError("temporary network failure")
+ return "ok"
+
+ with patch.object(module.time, "sleep", return_value=None) as sleep:
+ result = module.retry_initial_request(
+ _operation,
+ description="test request",
+ )
+
+ assert result.value == "ok"
+ assert result.error is None
+ assert attempts == 3
+ assert [call.args[0] for call in sleep.call_args_list] == [1.0, 2.0]
+
+
+ def test_retry_initial_request_does_not_retry_terminal_failure() -> None:
+ module = _load_module()
+ attempts = 0
+ error = urllib.error.HTTPError(
+ "https://api.github.com/example",
+ 404,
+ "Not Found",
+ hdrs=None,
+ fp=None,
+ )
+
+ def _operation() -> None:
+ nonlocal attempts
+ attempts += 1
+ raise error
+
+ with patch.object(module.time, "sleep", return_value=None) as sleep:
+ result = module.retry_initial_request(
+ _operation,
+ description="test request",
+ )
+
+ assert result.value is None
+ assert result.error is not None
+ assert result.error.retryable is False
+ assert attempts == 1
+ sleep.assert_not_called()
+
+
+ def test_unauthenticated_rate_limit_is_terminal() -> None:
+ module = _load_module()
+ error = urllib.error.HTTPError(
+ "https://api.github.com/example",
+ 429,
+ "Too Many Requests",
+ hdrs=None,
+ fp=None,
+ )
+
+ result = module.github_request(
+ lambda: (_ for _ in ()).throw(error),
+ unauthenticated=True,
+ )
+
+ assert result.error is not None
+ assert result.error.retryable is False
+ assert result.error.status_code == 429
+
+
++def test_http_incomplete_read_is_transient() -> None:
++ module = _load_module()
++
++ result = module.github_request(
++ lambda: (_ for _ in ()).throw(http.client.IncompleteRead(b"partial", 12))
++ )
++
++ assert result.error is not None
++ assert result.error.retryable is True
++ assert "IncompleteRead" in str(result.error)
++
++
def test_github_get_without_cache_sends_no_conditional_header() -> None:
module = _load_module()
requests: list[object] = []
diff --cc tests/test_wait_for_github_pr_activity.py
index a7dd818f6,0e6faa502..9e3920005
--- a/tests/test_wait_for_github_pr_activity.py
+++ b/tests/test_wait_for_github_pr_activity.py
@@@ -755,18 -915,162 +915,181 @@@ def test_main_stops_after_bounded_initi
err = urllib.error.URLError("temporary network failure")
with (
- patch.object(module, "_fetch_state", side_effect=err),
+ patch.object(module, "_fetch_state", side_effect=err) as fetch,
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value="tester"),
+ patch.object(module.time, "sleep", return_value=None),
+ patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
- assert rc == 1
++ assert rc == 75
+ assert fetch.call_count == 3
+ assert "failed after 3 attempts" in stderr.getvalue()
+
+
+ def test_main_recovers_from_retryable_pr_polling_failure() -> None:
+ module = _load_module()
+ updated = _pr_state()
+ updated["issue_comments"] = [
+ {
+ "id": 501,
+ "body": "New review result",
+ "html_url": "https://github.com/example/repo/pull/153#issuecomment-501",
+ "user": {"login": "reviewer"},
+ }
+ ]
+ error = urllib.error.URLError("temporary network failure")
+ stdout = io.StringIO()
+
+ with (
+ patch.object(module, "_fetch_state", side_effect=[(_pr_state(), 1), error, (updated, 1)]) as fetch,
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value="tester"),
+ patch.object(module.time, "sleep", return_value=None),
+ patch(
+ "sys.argv",
+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--interval", "1"],
+ ),
+ redirect_stdout(stdout),
+ ):
+ rc = module.main()
+
+ assert rc == 0
+ assert fetch.call_count == 3
+ assert "issue_comment #501" in stdout.getvalue()
+
+
+ def test_main_stops_on_a_terminal_polling_http_error() -> None:
+ module = _load_module()
+ error = urllib.error.HTTPError(
+ url="https://api.github.com/repos/example/repo/pulls/153",
+ code=404,
+ msg="Not Found",
+ hdrs=None,
+ fp=None,
+ )
+ stderr = io.StringIO()
+
+ with (
+ patch.object(module, "_fetch_state", side_effect=[(_pr_state(), 1), error]),
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(module, "get_authenticated_login", return_value="tester"),
+ patch.object(module.time, "sleep", return_value=None),
+ patch(
+ "sys.argv",
+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--interval", "1"],
+ ),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 1
+ assert "GitHub polling failed: GitHub HTTP 404 Not Found" in stderr.getvalue()
+
+
+ def test_new_pr_seed_does_not_resolve_viewer_login(tmp_path: Path) -> None:
+ module = _load_module()
+ state_file = tmp_path / "new-prs.json"
+
+ with (
+ patch.object(module, "_fetch_new_pr_state", return_value=({"pull_requests": []}, 1)),
+ patch.object(module, "get_token", return_value="app-token"),
+ patch.object(
+ module,
+ "get_authenticated_login",
+ side_effect=AssertionError("new-PR mode must not call /user"),
+ ),
+ patch(
+ "sys.argv",
+ [
+ "wait_pr.py",
+ "--repo",
+ "avibe-bot/avibe",
+ "--new-prs",
+ "--state-file",
+ str(state_file),
+ "--seed-state",
+ ],
+ ),
+ ):
+ rc = module.main()
+
+ assert rc == 0
+ assert state_file.is_file()
+
+
+ def test_main_fails_closed_when_authenticated_login_cannot_be_resolved() -> None:
+ module = _load_module()
+ stderr = io.StringIO()
+
+ with (
patch.object(module, "get_token", return_value="token"),
patch.object(module, "get_authenticated_login", return_value=None),
+ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll")),
+ patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 1
+ assert "refusing to poll" in stderr.getvalue()
+
+
+ def test_main_retries_transient_authenticated_login_failure() -> None:
+ module = _load_module()
+ state = _pr_state(
+ issue_comments=[
+ {
+ "id": 501,
+ "body": "Review result",
+ "html_url": "https://github.com/example/repo/pull/153#issuecomment-501",
+ "user": {"login": "reviewer"},
+ }
+ ]
+ )
+
+ with (
+ patch.object(module, "get_token", return_value="token"),
+ patch.object(
+ module,
+ "get_authenticated_login",
+ side_effect=[TimeoutError("temporary viewer timeout"), "tester"],
+ ) as lookup,
+ patch.object(module, "_fetch_state", return_value=(state, 1)),
+ patch.object(module.time, "sleep", return_value=None) as sleep,
+ patch(
+ "sys.argv",
+ ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153", "--catch-up"],
+ ),
+ ):
+ rc = module.main()
+
+ assert rc == 0
+ assert lookup.call_count == 2
+ assert [call.args[0] for call in sleep.call_args_list] == [1.0]
+
+
++def test_main_stops_after_bounded_viewer_lookup_retries_with_retryable_exit_code() -> None:
++ module = _load_module()
++ stderr = io.StringIO()
++
++ with (
++ patch.object(module, "get_token", return_value="token"),
++ patch.object(module, "get_authenticated_login", side_effect=TimeoutError("temporary viewer timeout")) as lookup,
++ patch.object(module, "_fetch_state", side_effect=AssertionError("must not poll before viewer login")),
++ patch.object(module.time, "sleep", return_value=None),
+ patch("sys.argv", ["wait_pr.py", "--repo", "avibe-bot/avibe", "--pr", "153"]),
+ patch("sys.stderr", stderr),
+ ):
+ rc = module.main()
+
+ assert rc == 75
- assert "GitHub network error: temporary network failure" in stderr.getvalue()
++ assert lookup.call_count == 3
++ assert "GitHub viewer lookup failed" in stderr.getvalue()
+
+
def test_render_activity_actionable_only_drops_bot_trigger_comment_but_advances_cursor() -> None:
module = _load_module()
state = {
diff --cc ui/src/components/workbench/ChatPage.tsx
index f85657ba1,cc17e4e95..2d84055ec
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@@ -1389,14 -1386,16 +1393,20 @@@ export const ChatPage: React.FC = () =
if (bootstrapIsCurrent()) {
setSession(bootstrap.session);
} else {
- // A newer turn-end/activity read won the row race. Keep its route-bearing
- // snapshot and repair a cold page if that read has not hydrated it yet.
+ // A newer turn-end/activity read won the row race. Preserve its row if
+ // it landed, but keep this successful bootstrap as the fallback while a
+ // cold-page recovery is pending or if both bounded attempts fail.
+ setSession((current) => sessionRowWithBootstrapFallback(
+ current,
+ sessionId,
+ bootstrap.session,
+ ));
void refreshSessionRow();
}
+ // Capability comes from the bootstrap payload, not the session-row race
+ // above — set it unconditionally so a lost row race can't strand the
+ // composer disabled for a member who can chat.
+ setSessionCanChat(Boolean(bootstrap.capabilities?.can_chat));
setAgents(bootstrap.agents);
setDefaultAgentName(bootstrap.default_agent_name);
setMessageFontSize(normalizeChatMessageFontSize(bootstrap.config?.ui?.chat_message_font_size));