Share the sync session in the Claude worker

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 21:47:47 +01:00
parent a936d07a7e
commit 801a0b4bab
5 changed files with 35 additions and 38 deletions

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go." description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none' publish_to: 'none'
version: 1.0.171+1 version: 1.0.172+1
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2

View File

@ -1,12 +1,14 @@
"""Connecting the relay worker to RTDB, signed in and unlocked. """Connecting the relay worker to RTDB, signed in and unlocked.
The database URL and API key come from crdt-sync's shared The database URL and API key come from crdt-sync's shared
``~/.config/crdt-sync/firebase.json``; the signed-in session is the worker's ``~/.config/crdt-sync/firebase.json``; the signed-in session is the sync's own,
own app, ``~/.config/diet_guard_claude/firebase_auth.json`` (seeded once with ``~/.config/diet_guard/firebase_auth.json``. Sharing it is safe: the worker's
crdt-sync's ``seed_session --app diet_guard_claude``). Never the gate's pull and publish already refresh it through the ordinary sync client,
``diet_guard`` session file: two processes refreshing one token file corrupt Firebase does not invalidate an older refresh token when one is reused, and
it. Never ``firebase_client_for``: without a session it falls back to the crdt-sync's ``FileCredentialStore`` writes atomically with a unique temp name
dead shared password and fails with a misleading error. for exactly this several-process case. Never ``firebase_client_for``: without
a session it falls back to the dead shared password and fails with a
misleading error.
:func:`connect_sealed` is the worker's only network entry point besides the :func:`connect_sealed` is the worker's only network entry point besides the
event stream it returns; ``conftest`` blocks it. event stream it returns; ``conftest`` blocks it.
@ -35,7 +37,7 @@ from diet_guard._claude_layout import E2E_LAYOUT, LAYOUT, ROOT
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Awaitable, Callable from collections.abc import Awaitable, Callable
APP: Final = "diet_guard_claude" APP: Final = "diet_guard"
class RelaySetupError(RuntimeError): class RelaySetupError(RuntimeError):
@ -65,8 +67,8 @@ def connect() -> Rtdb:
provider = FirebaseTokenProvider(config.api_key, credential_store_for(APP)) provider = FirebaseTokenProvider(config.api_key, credential_store_for(APP))
if not provider.has_session(): if not provider.has_session():
msg = ( msg = (
f"no signed-in session in ~/.config/{APP}/firebase_auth.json; seed it " f"no signed-in session in ~/.config/{APP}/firebase_auth.json; sign "
f"with crdt-sync: python3 -m tool.seed_session ... --app {APP}" "diet_guard's sync in first (the phone and the gate use the same one)"
) )
raise RelaySetupError(msg) raise RelaySetupError(msg)
return Rtdb(config.database_url, token_source(provider), root=ROOT) return Rtdb(config.database_url, token_source(provider), root=ROOT)

View File

@ -38,7 +38,7 @@ def _provider(*, session: bool = True, token: str | Exception = "tok") -> Mock:
# -- connect -------------------------------------------------------------------- # -- connect --------------------------------------------------------------------
def test_connect_builds_a_client_rooted_at_the_relay() -> None: def test_connect_builds_a_client_rooted_at_the_relay() -> None:
"""Config and the worker's own session give an Rtdb on the relay root.""" """Config and the sync's session give an Rtdb on the relay root."""
provider = _provider() provider = _provider()
with ( with (
patch.object(connect_mod.FirebaseConfig, "load", return_value=CONFIG), patch.object(connect_mod.FirebaseConfig, "load", return_value=CONFIG),
@ -46,7 +46,7 @@ def test_connect_builds_a_client_rooted_at_the_relay() -> None:
patch.object(connect_mod, "credential_store_for") as store, patch.object(connect_mod, "credential_store_for") as store,
): ):
rtdb = connect_mod.connect() rtdb = connect_mod.connect()
store.assert_called_once_with("diet_guard_claude") store.assert_called_once_with("diet_guard")
assert rtdb.root == ROOT assert rtdb.root == ROOT
assert rtdb.sealer is None assert rtdb.sealer is None
@ -62,8 +62,8 @@ def test_connect_without_firebase_config_is_a_setup_error() -> None:
connect_mod.connect() connect_mod.connect()
def test_connect_without_a_session_names_the_seed_command() -> None: def test_connect_without_a_session_names_the_session_file() -> None:
"""No signed-in session: the error says how to seed one for this app.""" """No signed-in session: the error says where the sync's session lives."""
with ( with (
patch.object(connect_mod.FirebaseConfig, "load", return_value=CONFIG), patch.object(connect_mod.FirebaseConfig, "load", return_value=CONFIG),
patch.object(connect_mod, "credential_store_for"), patch.object(connect_mod, "credential_store_for"),
@ -72,7 +72,7 @@ def test_connect_without_a_session_names_the_seed_command() -> None:
), ),
pytest.raises( pytest.raises(
connect_mod.RelaySetupError, connect_mod.RelaySetupError,
match=r"seed_session .* --app diet_guard_claude", match=r"~/.config/diet_guard/firebase_auth.json",
), ),
): ):
connect_mod.connect() connect_mod.connect()

View File

@ -182,13 +182,14 @@ unit lives at the repo root with the other two, `install.sh` installs it).
node, so requests that arrived while the PC was off are served in order. node, so requests that arrived while the PC was off are served in order.
- Waits are only for faults: the e2e unlock and a failed pre-pull retry - Waits are only for faults: the e2e unlock and a failed pre-pull retry
every 60 s / 30 s while something is pending. No idle timer. every 60 s / 30 s while something is pending. No idle timer.
- Session: the RTDB stream uses its own Firebase app name `diet_guard_claude` - Session: the worker shares the sync's own Firebase session,
(`~/.config/diet_guard_claude/firebase_auth.json`), so the stream never `~/.config/diet_guard/firebase_auth.json` (app name `diet_guard`); there is
shares a refresh token file with another process. Seed once, see "Deploy". no separate seed. Sharing is safe: the worker's pull and publish already go
The pull and publish go through the ordinary sync client, so the worker through the ordinary sync client and refresh that file, Firebase keeps an
also refreshes the gate's `~/.config/diet_guard/firebase_auth.json`, older refresh token valid after a refresh, and crdt-sync's
exactly as the CLI's own publish does. The database URL and API key come `FileCredentialStore` saves atomically under a unique temp name for exactly
from `~/.config/crdt-sync/firebase.json`; the passphrase from this several-process case. The database URL and API key come from
`~/.config/crdt-sync/firebase.json`; the passphrase from
`~/.config/crdt-sync/password`. `~/.config/crdt-sync/password`.
- One worker per PC. Claim leases last 300 s and renew every 60 s. - One worker per PC. Claim leases last 300 s and renew every 60 s.
- Dependencies (`rtdb_relay`, `httpx`, `claude_agent_sdk`) are imported only - Dependencies (`rtdb_relay`, `httpx`, `claude_agent_sdk`) are imported only
@ -233,9 +234,6 @@ model answer with a grilling round.
1. `/usr/bin/python3 -m pip install --user --break-system-packages -e .` 1. `/usr/bin/python3 -m pip install --user --break-system-packages -e .`
from `~/src/diet-guard` (new deps: `claude-agent-sdk`, `rtdb-relay`, from `~/src/diet-guard` (new deps: `claude-agent-sdk`, `rtdb-relay`,
`httpx`); verify `/usr/bin/python3 -c "import claude_agent_sdk, rtdb_relay, httpx"`. `httpx`); verify `/usr/bin/python3 -c "import claude_agent_sdk, rtdb_relay, httpx"`.
2. Seed the worker's session once (one Google consent): 2. `bash install.sh` (copies and enables `diet-guard-claude.service` once
`python3 -m tool.seed_session --client-id ... --client-secret ... --app diet_guard_claude` the sync session file exists; no Google consent needed).
in `~/src/utils/crdt-sync`. 3. Phone side: [DOCS-claude-relay-phone.md](DOCS-claude-relay-phone.md).
3. `bash install.sh` (copies and enables `diet-guard-claude.service` once
the session file exists).
4. Phone side: [DOCS-claude-relay-phone.md](DOCS-claude-relay-phone.md).

View File

@ -28,9 +28,8 @@ readonly SERVICE_SRC="$SCRIPT_DIR/diet-guard-gate.service"
readonly TIMER_SRC="$SCRIPT_DIR/diet-guard-gate.timer" readonly TIMER_SRC="$SCRIPT_DIR/diet-guard-gate.timer"
readonly SYNC_SERVICE_SRC="$SCRIPT_DIR/diet-guard-sync.service" readonly SYNC_SERVICE_SRC="$SCRIPT_DIR/diet-guard-sync.service"
readonly CLAUDE_SERVICE_SRC="$SCRIPT_DIR/diet-guard-claude.service" readonly CLAUDE_SERVICE_SRC="$SCRIPT_DIR/diet-guard-claude.service"
# The relay worker's own Firebase session (never the gate's: two processes # The relay worker shares the sync's Firebase session (docs/DOCS-claude-relay.md).
# refreshing one token file corrupt it). Seeded once, see the step below. readonly CLAUDE_SESSION_FILE="$HOME/.config/diet_guard/firebase_auth.json"
readonly CLAUDE_SESSION_FILE="$HOME/.config/diet_guard_claude/firebase_auth.json"
readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user" readonly SYSTEMD_USER_DIR="$HOME/.config/systemd/user"
readonly DATA_DIR="$HOME/.local/share/diet_guard" readonly DATA_DIR="$HOME/.local/share/diet_guard"
readonly BUDGET_FILE="$DATA_DIR/.budget" readonly BUDGET_FILE="$DATA_DIR/.budget"
@ -88,9 +87,9 @@ else
fi fi
# 4b. The "send to Claude" relay worker ------------------------------------ # 4b. The "send to Claude" relay worker ------------------------------------
# Serves the phone's meal requests (docs/DOCS-claude-relay.md). It needs its own # Serves the phone's meal requests (docs/DOCS-claude-relay.md). It needs the
# signed-in Firebase session, which only one Google consent can create, so the # sync's signed-in Firebase session, so the unit is installed always but
# unit is installed always but started only once the session file exists. # started only once the session file exists.
echo "[4b/5] Installing the Claude relay worker unit..." echo "[4b/5] Installing the Claude relay worker unit..."
cp "$CLAUDE_SERVICE_SRC" "$SYSTEMD_USER_DIR/diet-guard-claude.service" cp "$CLAUDE_SERVICE_SRC" "$SYSTEMD_USER_DIR/diet-guard-claude.service"
systemctl --user daemon-reload systemctl --user daemon-reload
@ -98,10 +97,8 @@ if [[ -f "$CLAUDE_SESSION_FILE" ]]; then
systemctl --user enable --now diet-guard-claude.service systemctl --user enable --now diet-guard-claude.service
echo " Relay worker enabled and started." echo " Relay worker enabled and started."
else else
echo " Not started: no session at $CLAUDE_SESSION_FILE. Seed it once (one" echo " Not started: no sync session at $CLAUDE_SESSION_FILE."
echo " Google consent) in ~/src/utils/crdt-sync:" echo " Sign diet_guard's sync in first, then re-run this installer."
echo " python3 -m tool.seed_session --client-id ... --client-secret ... --app diet_guard_claude"
echo " then re-run this installer."
fi fi
# 5. Set the initial daily budget --------------------------------------------- # 5. Set the initial daily budget ---------------------------------------------