Compare commits
50
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a97b71844 | ||
|
|
ae51ae3ab1 | ||
|
|
1bdcab8fc0 | ||
|
|
0c77d010fa | ||
|
|
dc18209c3c | ||
|
|
69347adb34 | ||
|
|
43a809e41a | ||
|
|
a5cc0104bf | ||
|
|
86a0bebc0d | ||
|
|
04d9421c74 | ||
|
|
14401aa3c3 | ||
|
|
99897274c6 | ||
|
|
20c5b690a8 | ||
|
|
dc86c043bc | ||
|
|
d5cce4e390 | ||
|
|
ae9b22a9e6 | ||
|
|
96a9e8077e | ||
|
|
a97e6a2b14 | ||
|
|
4317da85fd | ||
|
|
45fde0ad9a | ||
|
|
94565e9d6d | ||
|
|
56c2e6fa07 | ||
|
|
28629f3d93 | ||
|
|
c9a5c767c6 | ||
|
|
0d1faf47a0 | ||
|
|
00288a2b3b | ||
|
|
8f52feffba | ||
|
|
ee29e49361 | ||
|
|
e2073b7692 | ||
|
|
70b6d8ee5a | ||
|
|
1f5e50ccd7 | ||
|
|
5580c9d9bb | ||
|
|
2ebdf55501 | ||
|
|
ad107ea205 | ||
|
|
f5aeb27e5a | ||
|
|
fdaeb121d5 | ||
|
|
06c0df6304 | ||
|
|
71a2b3a7fb | ||
|
|
65e48084cb | ||
|
|
1074ecc24f | ||
|
|
f2a23e32aa | ||
|
|
630cc6d316 | ||
|
|
e16205d82a | ||
|
|
676c37e5ca | ||
|
|
9b6fed9bdd | ||
|
|
4d90eef3d8 | ||
|
|
478323893a | ||
|
|
fcddeeb810 | ||
|
|
49002b7141 | ||
|
|
326eb47df3 |
@@ -3,8 +3,11 @@
|
||||
function classifyCiPaths(paths) {
|
||||
const forceAll = paths.some((path) => [
|
||||
'.github/workflows/ci-required.yml',
|
||||
'.github/workflows/release-backmerge.yml',
|
||||
'.github/scripts/classify-ci-paths.cjs',
|
||||
'.github/scripts/classify-ci-paths.test.cjs',
|
||||
'scripts/plan_release_backmerge.py',
|
||||
'scripts/tests/plan_release_backmerge_test.py',
|
||||
].includes(path));
|
||||
const exact = (values) => paths.some((path) => values.includes(path));
|
||||
const under = (prefixes) => paths.some((path) => prefixes.some((prefix) => path.startsWith(prefix)));
|
||||
|
||||
@@ -30,5 +30,13 @@ assert.deepEqual(classifyCiPaths(['.github/workflows/ci-required.yml']), {
|
||||
contract: true,
|
||||
docs: true,
|
||||
});
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/release-backmerge.yml']), {
|
||||
android: true,
|
||||
desktop: true,
|
||||
plugin: true,
|
||||
dashboard: true,
|
||||
contract: true,
|
||||
docs: true,
|
||||
});
|
||||
|
||||
console.log('CI path classification tests passed.');
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
|
||||
name: CI — Upstream Contract
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
push:
|
||||
@@ -40,45 +43,64 @@ jobs:
|
||||
steps:
|
||||
- name: Checkout hermes-relay
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Resolve upstream ref
|
||||
id: ref
|
||||
env:
|
||||
REQUESTED_REF: ${{ github.event.inputs.upstream_ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# PR/push runs use a known-good NousResearch/hermes-agent commit so
|
||||
# normal CI is stable. The weekly schedule below intentionally tracks
|
||||
# main as the upstream-drift siren.
|
||||
DEFAULT_REF="ef4b897a1843cd32c4f141f55db60f0f0602cc98"
|
||||
if [ "${{ github.event_name }}" = "schedule" ]; then
|
||||
REF="main" # weekly drift siren
|
||||
elif [ -n "${{ github.event.inputs.upstream_ref }}" ]; then
|
||||
REF="${{ github.event.inputs.upstream_ref }}" # manual override
|
||||
elif [ -n "$REQUESTED_REF" ]; then
|
||||
REF="$REQUESTED_REF" # manual override
|
||||
else
|
||||
REF="$DEFAULT_REF"
|
||||
fi
|
||||
|
||||
# The ref is passed to git below, so reject option-like or malformed
|
||||
# values before it reaches that boundary. Full commit IDs and normal
|
||||
# branch/tag names remain supported for manual contract checks.
|
||||
if [[ "$REF" == -* ]] ||
|
||||
! git check-ref-format --allow-onelevel "$REF" >/dev/null; then
|
||||
echo "FAIL: invalid upstream branch or tag name." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "ref=$REF" >> "$GITHUB_OUTPUT"
|
||||
echo "Checking standard-path route contract against upstream ref: $REF"
|
||||
|
||||
- name: Checkout vanilla upstream (no plugin, no bootstrap)
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
repository: NousResearch/hermes-agent
|
||||
ref: ${{ steps.ref.outputs.ref }}
|
||||
path: _upstream
|
||||
fetch-depth: 1
|
||||
- name: Extract trusted upstream contract sources
|
||||
env:
|
||||
UPSTREAM_REF: ${{ steps.ref.outputs.ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
UPSTREAM_GIT="$RUNNER_TEMP/hermes-agent-contract.git"
|
||||
git init --bare "$UPSTREAM_GIT"
|
||||
git -C "$UPSTREAM_GIT" remote add origin \
|
||||
"https://github.com/NousResearch/hermes-agent.git"
|
||||
git -C "$UPSTREAM_GIT" fetch --no-tags --depth=1 origin -- "$UPSTREAM_REF"
|
||||
UPSTREAM_COMMIT="$(git -C "$UPSTREAM_GIT" rev-parse 'FETCH_HEAD^{commit}')"
|
||||
|
||||
mkdir -p _upstream/gateway/platforms _upstream/hermes_cli
|
||||
git -C "$UPSTREAM_GIT" show \
|
||||
"$UPSTREAM_COMMIT:gateway/platforms/api_server.py" \
|
||||
> _upstream/gateway/platforms/api_server.py
|
||||
git -C "$UPSTREAM_GIT" show \
|
||||
"$UPSTREAM_COMMIT:hermes_cli/web_server.py" \
|
||||
> _upstream/hermes_cli/web_server.py
|
||||
echo "Extracted contract sources from upstream commit: $UPSTREAM_COMMIT"
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
- name: Assert upstream checkout is vanilla (no relay bootstrap/plugin)
|
||||
run: |
|
||||
if [ -e "_upstream/hermes_relay_bootstrap" ] || \
|
||||
[ -e "_upstream/plugin/hermes_relay_bootstrap" ] || \
|
||||
find _upstream -name "hermes_relay_bootstrap.pth" 2>/dev/null | grep -q .; then
|
||||
echo "FAIL: upstream checkout contains a relay bootstrap — not vanilla."; exit 1
|
||||
fi
|
||||
echo "OK: upstream checkout carries no relay plugin/bootstrap."
|
||||
|
||||
- name: Run route-surface contract
|
||||
run: python scripts/check-upstream-route-contract.py "_upstream"
|
||||
|
||||
@@ -38,6 +38,10 @@ jobs:
|
||||
working-directory: plugin/dashboard
|
||||
run: npm run build
|
||||
|
||||
- name: Test dashboard source
|
||||
working-directory: plugin/dashboard
|
||||
run: npm test
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v7
|
||||
with:
|
||||
@@ -54,7 +58,11 @@ jobs:
|
||||
run: pip install -r relay_server/requirements.txt fastapi httpx requests
|
||||
|
||||
- name: Run dashboard API tests
|
||||
run: python -m unittest plugin.dashboard.test_plugin_api
|
||||
run: >-
|
||||
python -m unittest
|
||||
plugin.dashboard.test_plugin_api
|
||||
plugin.dashboard.test_git_api
|
||||
plugin.dashboard.test_mobile_plugin_api
|
||||
|
||||
- name: Verify dashboard bundle outputs
|
||||
run: |
|
||||
|
||||
@@ -106,4 +106,8 @@ jobs:
|
||||
plugin/tests/test_session_grants.py \
|
||||
plugin/tests/test_native_layout_imports.py \
|
||||
plugin/tests/test_profile_discovery.py \
|
||||
plugin/tests/test_profiles_updated_broadcast.py
|
||||
plugin/tests/test_profiles_updated_broadcast.py \
|
||||
plugin/tests/test_git_state.py \
|
||||
plugin/tests/test_git_state_write.py \
|
||||
plugin/tests/test_git_state_extras.py \
|
||||
plugin/tests/test_mobile_plugin_store.py
|
||||
|
||||
@@ -10,6 +10,16 @@ on:
|
||||
pull_request:
|
||||
branches: [main, dev]
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
base_sha:
|
||||
description: "Exact base commit for a trusted release-backmerge candidate"
|
||||
required: true
|
||||
type: string
|
||||
head_sha:
|
||||
description: "Exact candidate commit to check"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -31,22 +41,63 @@ jobs:
|
||||
contract: ${{ steps.filter.outputs.contract }}
|
||||
docs: ${{ steps.filter.outputs.docs }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
- name: Checkout pull request merge
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
- name: Checkout exact dispatched candidate
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ inputs.head_sha }}
|
||||
|
||||
- name: Test path classifier
|
||||
run: node .github/scripts/classify-ci-paths.test.cjs
|
||||
|
||||
- name: Classify changed files
|
||||
id: filter
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
DISPATCH_BASE_SHA: ${{ inputs.base_sha }}
|
||||
DISPATCH_HEAD_SHA: ${{ inputs.head_sha }}
|
||||
with:
|
||||
script: |
|
||||
let diffArgs;
|
||||
if (context.eventName === 'workflow_dispatch') {
|
||||
const base = process.env.DISPATCH_BASE_SHA || '';
|
||||
const head = process.env.DISPATCH_HEAD_SHA || '';
|
||||
const shaPattern = /^[0-9a-f]{40}$/;
|
||||
if (!shaPattern.test(base) || !shaPattern.test(head)) {
|
||||
core.setFailed('Exact-tree dispatch requires full 40-character base/head SHAs.');
|
||||
return;
|
||||
}
|
||||
const { stdout: checkedOut } = await exec.getExecOutput(
|
||||
'git',
|
||||
['rev-parse', 'HEAD'],
|
||||
);
|
||||
if (checkedOut.trim() !== head) {
|
||||
core.setFailed(`Checked out ${checkedOut.trim()}, expected ${head}.`);
|
||||
return;
|
||||
}
|
||||
const ancestry = await exec.exec(
|
||||
'git',
|
||||
['merge-base', '--is-ancestor', base, head],
|
||||
{ ignoreReturnCode: true },
|
||||
);
|
||||
if (ancestry !== 0) {
|
||||
core.setFailed(`Candidate ${head} does not descend from base ${base}.`);
|
||||
return;
|
||||
}
|
||||
diffArgs = ['diff', '--name-only', base, head];
|
||||
} else {
|
||||
diffArgs = ['diff', '--name-only', 'HEAD^1', 'HEAD^2'];
|
||||
}
|
||||
const { stdout } = await exec.getExecOutput(
|
||||
'git',
|
||||
['diff', '--name-only', 'HEAD^1', 'HEAD^2'],
|
||||
diffArgs,
|
||||
);
|
||||
const paths = stdout.split(/\r?\n/).filter(Boolean);
|
||||
const { classifyCiPaths } = require(
|
||||
|
||||
@@ -365,3 +365,22 @@ jobs:
|
||||
find app/build/outputs/apk -name '*.apk' -exec ls -la {} + >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
|
||||
find app/build/outputs/bundle -name '*.aab' -exec ls -la {} + >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
|
||||
echo '```' >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
request-backmerge:
|
||||
name: Request stable release backmerge
|
||||
needs: [validate, release]
|
||||
if: needs.validate.outputs.prerelease != 'true'
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch fail-closed release reconciliation
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: android-v${{ needs.validate.outputs.version }}
|
||||
run: |
|
||||
gh workflow run release-backmerge.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f release_tag="$RELEASE_TAG"
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
# Reconcile a completed stable hotfix into dev without adding a ceremonial PR
|
||||
# merge commit. Normal dev -> main releases are detected and intentionally no-op.
|
||||
# A conflicted merge, failed exact-tree CI, stale dev ref, or denied branch update
|
||||
# stops without mutating dev and falls back to the normal reconciliation PR path.
|
||||
|
||||
name: Release Backmerge
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Published stable tag to reconcile (android-v*, server-v*, or desktop-v*)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-backmerge-dev
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
name: Prepare exact backmerge candidate
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
outcome: ${{ steps.prepare.outputs.outcome }}
|
||||
base_dev_sha: ${{ steps.prepare.outputs.base_dev_sha }}
|
||||
candidate_branch: ${{ steps.prepare.outputs.candidate_branch }}
|
||||
candidate_sha: ${{ steps.prepare.outputs.candidate_sha }}
|
||||
release_commit: ${{ steps.prepare.outputs.release_commit }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: main
|
||||
|
||||
- name: Validate release and prepare merge commit
|
||||
id: prepare
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
if [[ ! "$RELEASE_TAG" =~ ^(android|server|desktop)-v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::error::Release Backmerge accepts stable SemVer production tags only; got $RELEASE_TAG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git fetch origin \
|
||||
"+refs/heads/main:refs/remotes/origin/main" \
|
||||
"+refs/heads/dev:refs/remotes/origin/dev" \
|
||||
"+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}"
|
||||
release_commit="$(git rev-parse "${RELEASE_TAG}^{commit}")"
|
||||
base_dev_sha="$(git rev-parse origin/dev)"
|
||||
echo "release_commit=$release_commit" >> "$GITHUB_OUTPUT"
|
||||
echo "base_dev_sha=$base_dev_sha" >> "$GITHUB_OUTPUT"
|
||||
|
||||
if ! git merge-base --is-ancestor "$release_commit" origin/main; then
|
||||
echo "::error::$RELEASE_TAG ($release_commit) is not contained in origin/main"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
read -r is_draft is_prerelease < <(
|
||||
gh release view "$RELEASE_TAG" --json isDraft,isPrerelease \
|
||||
--jq '[.isDraft, .isPrerelease] | @tsv'
|
||||
)
|
||||
if [ "$is_draft" != "false" ] || [ "$is_prerelease" != "false" ]; then
|
||||
echo "::error::$RELEASE_TAG is not a published stable GitHub release"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
plan="$(
|
||||
python3 scripts/plan_release_backmerge.py \
|
||||
--release-commit "$release_commit" \
|
||||
--dev-commit "$base_dev_sha"
|
||||
)"
|
||||
case "$plan" in
|
||||
already-contained)
|
||||
echo "outcome=noop" >> "$GITHUB_OUTPUT"
|
||||
echo "## Release backmerge not needed" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "\`$RELEASE_TAG\` is already contained in \`dev\`." >> "$GITHUB_STEP_SUMMARY"
|
||||
exit 0
|
||||
;;
|
||||
normal-release)
|
||||
echo "outcome=noop" >> "$GITHUB_OUTPUT"
|
||||
echo "## Normal release: no backmerge" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "The released merge's integration parent is already contained in \`dev\`." >> "$GITHUB_STEP_SUMMARY"
|
||||
exit 0
|
||||
;;
|
||||
hotfix) ;;
|
||||
*)
|
||||
echo "::error::Unknown release-backmerge plan: $plan"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
candidate_branch="chore/release-backmerge/${RELEASE_TAG}-${GITHUB_RUN_ID}"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git switch --detach "$base_dev_sha"
|
||||
|
||||
set +e
|
||||
git merge --no-ff -m "chore: back-merge ${RELEASE_TAG}" "$release_commit"
|
||||
merge_status=$?
|
||||
set -e
|
||||
if [ "$merge_status" -ne 0 ]; then
|
||||
conflicts="$(git diff --name-only --diff-filter=U | paste -sd ', ' -)"
|
||||
echo "outcome=conflict" >> "$GITHUB_OUTPUT"
|
||||
echo "::error::Automatic backmerge conflicts: ${conflicts:-unknown}. Open a reconciliation PR."
|
||||
echo "## Manual reconciliation PR required" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "\`$RELEASE_TAG\` conflicts with current \`dev\`: ${conflicts:-unknown}." >> "$GITHUB_STEP_SUMMARY"
|
||||
git merge --abort || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
candidate_sha="$(git rev-parse HEAD)"
|
||||
first_parent="$(git rev-parse HEAD^1)"
|
||||
second_parent="$(git rev-parse HEAD^2)"
|
||||
if [ "$first_parent" != "$base_dev_sha" ] || [ "$second_parent" != "$release_commit" ]; then
|
||||
echo "::error::Candidate parents do not match dev + release commit"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git push origin "$candidate_sha:refs/heads/$candidate_branch"
|
||||
echo "outcome=candidate" >> "$GITHUB_OUTPUT"
|
||||
echo "candidate_branch=$candidate_branch" >> "$GITHUB_OUTPUT"
|
||||
echo "candidate_sha=$candidate_sha" >> "$GITHUB_OUTPUT"
|
||||
|
||||
echo "## Backmerge candidate prepared" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Release: \`$RELEASE_TAG\` (\`$release_commit\`)" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Dev base: \`$base_dev_sha\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Candidate: \`$candidate_sha\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Temporary ref: \`$candidate_branch\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
gate:
|
||||
name: Run exact-tree required checks
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.outcome == 'candidate'
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
outputs:
|
||||
check_run_id: ${{ steps.gate.outputs.check_run_id }}
|
||||
steps:
|
||||
- name: Dispatch and await Required checks
|
||||
id: gate
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
BASE_DEV_SHA: ${{ needs.prepare.outputs.base_dev_sha }}
|
||||
CANDIDATE_BRANCH: ${{ needs.prepare.outputs.candidate_branch }}
|
||||
CANDIDATE_SHA: ${{ needs.prepare.outputs.candidate_sha }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh workflow run ci-required.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref "$CANDIDATE_BRANCH" \
|
||||
-f base_sha="$BASE_DEV_SHA" \
|
||||
-f head_sha="$CANDIDATE_SHA"
|
||||
|
||||
check_run_id=""
|
||||
for _ in {1..20}; do
|
||||
check_run_id="$(
|
||||
gh run list \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--workflow ci-required.yml \
|
||||
--branch "$CANDIDATE_BRANCH" \
|
||||
--event workflow_dispatch \
|
||||
--limit 20 \
|
||||
--json databaseId,headSha \
|
||||
--jq ".[] | select(.headSha == \"$CANDIDATE_SHA\") | .databaseId" \
|
||||
| head -n 1
|
||||
)"
|
||||
if [ -n "$check_run_id" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 3
|
||||
done
|
||||
if [ -z "$check_run_id" ]; then
|
||||
echo "::error::Required checks dispatch was not observed for $CANDIDATE_SHA"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "check_run_id=$check_run_id" >> "$GITHUB_OUTPUT"
|
||||
gh run watch "$check_run_id" --repo "$GITHUB_REPOSITORY" --exit-status
|
||||
|
||||
promote:
|
||||
name: Compare-and-swap dev
|
||||
needs: [prepare, gate]
|
||||
if: needs.prepare.outputs.outcome == 'candidate' && needs.gate.result == 'success'
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: main
|
||||
|
||||
- name: Fast-forward dev to the tested candidate
|
||||
env:
|
||||
BASE_DEV_SHA: ${{ needs.prepare.outputs.base_dev_sha }}
|
||||
CANDIDATE_BRANCH: ${{ needs.prepare.outputs.candidate_branch }}
|
||||
CANDIDATE_SHA: ${{ needs.prepare.outputs.candidate_sha }}
|
||||
RELEASE_COMMIT: ${{ needs.prepare.outputs.release_commit }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch origin --no-tags \
|
||||
"+refs/heads/dev:refs/remotes/origin/dev" \
|
||||
"+refs/heads/$CANDIDATE_BRANCH:refs/remotes/origin/$CANDIDATE_BRANCH"
|
||||
current_dev="$(git rev-parse origin/dev)"
|
||||
remote_candidate="$(git rev-parse "origin/$CANDIDATE_BRANCH")"
|
||||
|
||||
if [ "$current_dev" != "$BASE_DEV_SHA" ]; then
|
||||
echo "::error::dev moved from $BASE_DEV_SHA to $current_dev; rerun or open a reconciliation PR"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$remote_candidate" != "$CANDIDATE_SHA" ]; then
|
||||
echo "::error::Candidate ref moved from $CANDIDATE_SHA to $remote_candidate"
|
||||
exit 1
|
||||
fi
|
||||
if [ "$(git rev-parse "$CANDIDATE_SHA^1")" != "$BASE_DEV_SHA" ] || \
|
||||
[ "$(git rev-parse "$CANDIDATE_SHA^2")" != "$RELEASE_COMMIT" ]; then
|
||||
echo "::error::Candidate ancestry changed after verification"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The explicit lease is the atomic stale-base guard. The update is a
|
||||
# fast-forward from BASE_DEV_SHA; no unrelated history can be replaced.
|
||||
git push \
|
||||
--force-with-lease="refs/heads/dev:$BASE_DEV_SHA" \
|
||||
origin "$CANDIDATE_SHA:refs/heads/dev"
|
||||
|
||||
git push origin --delete "$CANDIDATE_BRANCH" || \
|
||||
echo "::warning::Could not remove temporary branch $CANDIDATE_BRANCH"
|
||||
|
||||
echo "## Release backmerge complete" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "Fast-forwarded \`dev\` from \`$BASE_DEV_SHA\` to tested merge \`$CANDIDATE_SHA\`." >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
fallback:
|
||||
name: Report PR fallback
|
||||
needs: [prepare, gate, promote]
|
||||
if: always() && needs.prepare.outputs.outcome == 'candidate' && needs.promote.result != 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Preserve safe fallback instructions
|
||||
env:
|
||||
CANDIDATE_BRANCH: ${{ needs.prepare.outputs.candidate_branch }}
|
||||
CANDIDATE_SHA: ${{ needs.prepare.outputs.candidate_sha }}
|
||||
CHECK_RUN_ID: ${{ needs.gate.outputs.check_run_id }}
|
||||
run: |
|
||||
echo "## Automatic backmerge stopped" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "\`dev\` was not updated. Open or refresh a reconciliation PR after addressing the failed/stale gate." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Candidate ref: \`${CANDIDATE_BRANCH:-not-created}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Candidate SHA: \`${CANDIDATE_SHA:-n/a}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Required-check run: \`${CHECK_RUN_ID:-n/a}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -539,3 +539,22 @@ jobs:
|
||||
release-assets/cli-binaries/hermes-relay-darwin-arm64
|
||||
release-assets/cli-windows-installer/hermes-relay-windows-x64-setup.exe
|
||||
release-assets/SHA256SUMS.txt
|
||||
|
||||
request-backmerge:
|
||||
name: Request stable release backmerge
|
||||
needs: [validate-release, publish-release]
|
||||
if: ${{ !contains(needs.validate-release.outputs.version, '-') }}
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch fail-closed release reconciliation
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: desktop-v${{ needs.validate-release.outputs.version }}
|
||||
run: |
|
||||
gh workflow run release-backmerge.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f release_tag="$RELEASE_TAG"
|
||||
|
||||
@@ -138,3 +138,22 @@ jobs:
|
||||
dist/*.whl
|
||||
dist/*.tar.gz
|
||||
dist/SHA256SUMS.txt
|
||||
|
||||
request-backmerge:
|
||||
name: Request stable release backmerge
|
||||
needs: [validate, package]
|
||||
if: ${{ !contains(needs.validate.outputs.version, '-') }}
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch fail-closed release reconciliation
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: server-v${{ needs.validate.outputs.version }}
|
||||
run: |
|
||||
gh workflow run release-backmerge.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f release_tag="$RELEASE_TAG"
|
||||
|
||||
@@ -28,7 +28,7 @@ not redefine the branch, release, or hotfix policy here and in `RELEASE.md`.
|
||||
| Staging source | An exact tested `dev` SHA or release-candidate tag; staging is an environment, never a branch |
|
||||
| Production source | Immutable `android-v*`, `server-v*`, or `desktop-v*` tags, selected by surface |
|
||||
| Hotfix base | The immutable production tag for the affected surface |
|
||||
| Back-merge target | `dev`; merge `main` back immediately after every hotfix |
|
||||
| Back-merge target | `dev`; stable hotfixes reconcile automatically when the exact tested merge is conflict-free, otherwise through a PR |
|
||||
|
||||
Feature completion means merged and verified on `dev`; it does not mean
|
||||
released. A release train is separate work owned by a Forge release
|
||||
@@ -37,6 +37,14 @@ open the `dev` → `main` release PR, tag the resulting `main` tip, publish the
|
||||
surface artifacts, deploy or roll out, and verify the live result. Never create
|
||||
a staging branch.
|
||||
|
||||
A normal `dev` → `main` release needs no back-merge: the released integration
|
||||
parent is already in `dev`. A production-tag hotfix is different. After its
|
||||
stable release succeeds, `Release Backmerge` prepares a `dev`-first merge
|
||||
commit, runs the same path-aware required checks on that exact SHA, verifies
|
||||
that `dev` has not moved, and fast-forwards `dev`. Conflicts, failed checks,
|
||||
stale refs, or denied branch updates fail closed and require a reconciliation
|
||||
PR; never resolve those cases by choosing a side automatically.
|
||||
|
||||
### Local integration discipline
|
||||
|
||||
- Fetch `origin/dev` before creating a task branch or worktree; do not base new
|
||||
|
||||
@@ -6,6 +6,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **Android presents Relay Git as a first-class native workspace.** A compact optional Chat rail opens repository status, line totals, filters, diffs, branches, staging, commits, and remotes; the full workspace remains available from Settings when Chat controls are hidden.
|
||||
- **Hermes-Relay Plugin provides a bounded Git workspace API for authenticated Dashboard clients.** Configured repository roots, path validation, tracked line totals, scoped write grants, and explicit confirmation protect repository reads and mutations.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The visible Android Sphere keeps its smooth procedural motion across startup and chat.** Backgrounded and motion-disabled surfaces remain still without reducing foreground animation to a stepped ambient pulse.
|
||||
|
||||
## [Android 1.13.2] - 2026-08-25
|
||||
|
||||
### Added
|
||||
|
||||
- **Android Supervised Mode presents a parent-controlled, profile-pinned chat surface.** Parents can limit attachments, Standard voice, generated media, conversation history, actions, and technical metadata while device authentication protects full settings. Hermes-Relay can identify and revoke a paired supervised client without becoming the policy enforcement boundary.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android session rows stay neutral when optional live activity is unavailable or still loading.** Directory refreshes no longer restore a persistent Checking state, and full-row activity borders are reserved for actual Starting or Working turns.
|
||||
- **Returning from parent settings keeps Supervised Chat rendered.** Parent access now relocks without rebuilding the active navigation graph, and full Settings keeps a prominent shortcut back to Supervised Mode controls.
|
||||
|
||||
## [Android 1.13.1] - 2026-08-25
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -159,6 +159,11 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p align="center">
|
||||
<img src="assets/screenshots/supplemental/15_git_workspace.png" alt="Native Git workspace showing repository changes, an inline diff, and staging controls" width="260"><br>
|
||||
<sub><b>Native Git workspace</b> — optional Hermes-Relay plugin</sub>
|
||||
</p>
|
||||
|
||||
### Simplified Chinese
|
||||
|
||||
<table>
|
||||
|
||||
+32
-10
@@ -200,6 +200,11 @@ never create a staging branch. Stable production tags are cut only from the new
|
||||
10. Build and publish that surface's artifacts, roll out or deploy from the
|
||||
immutable tag, and verify the release and live environment.
|
||||
|
||||
Do not back-merge a normal release. The `main` release merge already has the
|
||||
released `dev` tip as its integration parent, so merging it back only adds
|
||||
history noise. The release-backmerge workflow detects this topology and exits
|
||||
successfully without changing `dev`.
|
||||
|
||||
### Branch names
|
||||
|
||||
| Prefix | When | Example |
|
||||
@@ -258,7 +263,9 @@ The intended settings are:
|
||||
- **`main`** — PRs required; `Required checks` required and current; force push
|
||||
and deletion blocked. Normal work does not target this branch.
|
||||
- **`dev`** — PRs and `Required checks` required; force push and deletion
|
||||
blocked. This is the normal contribution target.
|
||||
blocked. This is the normal contribution target. The release-backmerge
|
||||
workflow is the sole exception: its automation identity may compare-and-swap
|
||||
`dev` to an exact checked merge commit after a stable hotfix release.
|
||||
- **Merge policy** — merge commits allowed; squash and rebase merges disabled so
|
||||
the no-ff contract cannot be bypassed in the GitHub UI.
|
||||
- **Default branch** — `main`, which remains the release-history branch and the
|
||||
@@ -922,8 +929,23 @@ When production has a bug, use the same invariant for every surface:
|
||||
4. Open the focused hotfix PR into `main` and merge with a merge commit/no-ff.
|
||||
5. Tag the new `main` tip with the affected surface's patch tag.
|
||||
6. Verify the artifacts and production rollout or deployment.
|
||||
7. Merge `main` back into `dev` immediately so integration inherits the fix and
|
||||
version history.
|
||||
7. Let the stable release workflow dispatch `Release Backmerge`. A
|
||||
conflict-free candidate runs the same path-aware `Required checks` against
|
||||
its exact SHA, then compare-and-swaps `dev` only if the base ref is unchanged.
|
||||
Conflicts, failed checks, stale refs, or a denied update require a normal
|
||||
reconciliation PR.
|
||||
|
||||
`Release Backmerge` accepts only published stable `android-v*`, `server-v*`, or
|
||||
`desktop-v*` SemVer tags contained in `main`. It exits without mutation for a
|
||||
normal release whose integration parent is already in `dev`. For a selective
|
||||
hotfix, it pushes a temporary merge ref, dispatches `Required checks` with full
|
||||
base/head SHAs, and updates `dev` with an explicit force-with-lease only after
|
||||
that exact candidate passes. The lease is a compare-and-swap guard, not
|
||||
permission to rewrite history: the candidate's first parent must be the
|
||||
unchanged `dev` tip and its second parent the released commit. The repository
|
||||
ruleset must allow this workflow's automation identity to perform that one
|
||||
checked branch update; if it does not, the workflow fails closed and the
|
||||
reconciliation uses a PR.
|
||||
|
||||
For an Android app hotfix:
|
||||
|
||||
@@ -938,21 +960,21 @@ For an Android app hotfix:
|
||||
6. `git tag android-v0.6.2` from the new `main` tip and `git push origin android-v0.6.2`
|
||||
so Android release CI builds and publishes.
|
||||
7. Verify the automated Play submission, GitHub artifacts, and rollout.
|
||||
8. Merge `main` back into `dev` (`git checkout dev && git merge --no-ff main`)
|
||||
so `dev` picks up the hotfix and the versionCode bump. Without this,
|
||||
`dev`'s `appVersionCode` lags behind `main` and the next app release
|
||||
bump collides.
|
||||
8. Verify the automated release backmerge completed. If it stopped, open a
|
||||
reconciliation PR so `dev` picks up the hotfix and versionCode bump. Without
|
||||
reconciliation, `dev`'s `appVersionCode` lags behind `main` and the next app
|
||||
release bump collides.
|
||||
|
||||
For a Plugin hotfix, branch from the affected `server-v*` tag, apply
|
||||
the fix, run `bash scripts/bump-plugin-version.sh <next-version>`, merge to
|
||||
`main`, tag `server-v<next-version>`, verify the package/deployment, and merge
|
||||
`main` back to `dev`. Do not touch
|
||||
`main`, tag `server-v<next-version>`, verify the package/deployment, and verify
|
||||
the automated release backmerge. Do not touch
|
||||
`gradle/libs.versions.toml` unless an Android app release is also shipping.
|
||||
|
||||
For a CLI+UI hotfix, branch from the affected `desktop-v*` tag, update only
|
||||
`desktop/package.json` and its generated lock/runtime/tray metadata, merge to
|
||||
`main`, tag `desktop-v<next-version>`, verify all binaries and the installer,
|
||||
then merge `main` back to `dev`.
|
||||
then verify the automated release backmerge or use the PR fallback.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
+10
-7
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay Android v1.13.1
|
||||
# Hermes-Relay Android v1.13.2
|
||||
|
||||
**Release Date:** August 25, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.13.1-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
> Installing on your phone? Download `hermes-relay-1.13.2-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,17 +12,20 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This patch makes Android session activity follow live Hermes runtime state instead of a five-minute recency estimate. It keeps Working, Starting, Needs input, Idle, Checking, Unavailable, and Background work accurate while preserving stale state until a complete, unambiguous snapshot can safely replace it.
|
||||
This release adds a parent-configured Supervised Mode and improves its return from full settings. It also keeps session rows neutral until live activity is confirmed.
|
||||
|
||||
## Added
|
||||
|
||||
- Use a profile-pinned Supervised Mode with parent-controlled attachments, Standard voice, generated media, history, actions, and technical details. Device authentication protects full settings; this remains a client-side restricted view rather than a server-enforced account boundary.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Derive session activity from the authoritative live runtime snapshot rather than Dashboard recency.
|
||||
- Preserve prior activity when a refresh is incomplete, unsupported, or ambiguously scoped.
|
||||
- Keep session drawer labels, timestamps, and active-turn ownership aligned with the exact profile and session.
|
||||
- Keep session rows neutral while optional live activity is unavailable or still loading, and reserve full-row activity borders for actual Starting or Working turns.
|
||||
- Keep Supervised Chat rendered when parent access relocks after visiting full settings.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.13.1** (versionCode **50**).
|
||||
- App version: **1.13.2** (versionCode **51**).
|
||||
- Standard Chat, sessions, Manage, sharing, profile switching, and Vanilla Hermes voice continue to work against unmodified upstream Hermes.
|
||||
- Granular Device Control remains sideload-only; the Google Play build continues to ship Hermes Bridge Core without AccessibilityService Device Control.
|
||||
- The optional Relay plugin remains unnecessary for standard Android chat, sessions, Manage, and Vanilla Hermes voice.
|
||||
|
||||
@@ -1 +1 @@
|
||||
Session activity now follows live Hermes runtime state instead of a recent-activity estimate. Working, Starting, Needs input, Idle, Checking, Unavailable, and Background work stay accurate, and stale state clears only after a complete, unambiguous update.
|
||||
Supervised Mode adds a parent-configured, profile-pinned chat view with device-authenticated settings. Parents can limit attachments, Standard voice, generated media, history, actions, and technical details. Session rows stay neutral while live activity is unavailable, and returning from parent settings no longer blanks Supervised Chat.
|
||||
|
||||
@@ -1 +1 @@
|
||||
会话活动现在依据 Hermes 的实时运行状态,而不是最近活动时间估算。工作中、启动中、需要输入、空闲、检查中、不可用和后台工作等状态会保持准确;只有完整且明确的更新才会清除旧状态。
|
||||
新增监督模式:家长可配置并固定到指定配置文件,设置受设备身份验证保护。家长可限制附件、标准语音、生成媒体、历史记录、操作和技术详情。实时活动不可用时会话行保持中性显示,从家长设置返回时监督聊天也不再空白。
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
{
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.13.2",
|
||||
"title": "Supervised Mode and clearer activity",
|
||||
"date": "2026-08-25",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Use a supervised chat",
|
||||
"bullets": [
|
||||
"Configure a profile-pinned restricted chat with parent-controlled attachments, voice, media, history, actions, and technical details.",
|
||||
"Protect full settings with device authentication and keep Supervised Chat visible when parent access relocks."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Show only confirmed activity",
|
||||
"bullets": [
|
||||
"Keep session rows neutral while optional live activity is unavailable or still loading.",
|
||||
"Show full-row activity borders only during actual Starting or Working turns."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.13.1",
|
||||
"title": "Accurate session activity",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
v1.13.1 - Accurate session activity
|
||||
v1.13.2 - Supervised Mode and clearer activity
|
||||
|
||||
* Follow live Hermes runtime state for Working, Starting, Needs input, and Idle.
|
||||
* Keep stale activity visible until a complete, unambiguous snapshot clears it.
|
||||
* Distinguish Checking, Unavailable, and Background work in the session drawer.
|
||||
* Configure a profile-pinned Supervised Mode with device-authenticated parent settings.
|
||||
* Keep Supervised Chat visible when parent access relocks after full settings.
|
||||
* Keep uncertain session activity neutral until live work is confirmed.
|
||||
|
||||
@@ -11,6 +11,7 @@ import com.hermesandroid.relay.data.replaceHermesReachCredential
|
||||
import com.hermesandroid.relay.data.sameBrokerAuthority
|
||||
import com.hermesandroid.relay.data.PairingPreferences
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.isSafeProfileUiMeta
|
||||
import com.hermesandroid.relay.network.relay.ChannelMultiplexer
|
||||
import com.hermesandroid.relay.network.relay.models.Envelope
|
||||
@@ -18,6 +19,8 @@ import com.hermesandroid.relay.network.shared.InvalidCredentialException
|
||||
import com.hermesandroid.relay.network.shared.normalizeCredentialForHeader
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
@@ -53,6 +56,39 @@ sealed class AuthState {
|
||||
data class Failed(val reason: String) : AuthState()
|
||||
}
|
||||
|
||||
internal fun relaySupervisedModePayload(policy: SupervisedModePolicy): JsonObject {
|
||||
if (!policy.isActive) return buildJsonObject { put("active", false) }
|
||||
val capabilities = buildList {
|
||||
add("text_chat")
|
||||
if (policy.capabilities.newChat) add("new_chat")
|
||||
if (policy.capabilities.cancelResponse) add("cancel")
|
||||
if (policy.capabilities.steerResponse) add("steer")
|
||||
if (policy.capabilities.attachments) add("attachments")
|
||||
if (policy.capabilities.voice) add("voice")
|
||||
if (policy.capabilities.generatedImages) add("generated_images")
|
||||
if (policy.capabilities.shareGeneratedImages) add("share_images")
|
||||
if (policy.capabilities.copyResponses) add("copy")
|
||||
if (policy.capabilities.retryResponse) add("retry")
|
||||
if (policy.capabilities.quoteReplies) add("quote_reply")
|
||||
if (policy.visibility.resolved().showTimestamps) add("timestamps")
|
||||
}.take(12)
|
||||
return buildJsonObject {
|
||||
put("active", true)
|
||||
put("profile_label", policy.pinnedProfileName.orEmpty().take(80))
|
||||
put("capabilities", JsonArray(capabilities.map(::JsonPrimitive)))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun relaySupervisedModeUpdateEnvelope(
|
||||
policy: SupervisedModePolicy,
|
||||
): Envelope = Envelope(
|
||||
channel = "system",
|
||||
type = "supervised.update",
|
||||
payload = buildJsonObject {
|
||||
put("supervised_mode", relaySupervisedModePayload(policy))
|
||||
},
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ConnectionAuthSecrets(
|
||||
val sessionToken: String? = null,
|
||||
@@ -120,6 +156,60 @@ class AuthManager(
|
||||
private val eagerHydrate: Boolean = true,
|
||||
) : ChannelMultiplexer.ChannelHandler {
|
||||
|
||||
@Volatile
|
||||
private var supervisedMode: SupervisedModePolicy = SupervisedModePolicy()
|
||||
|
||||
@Volatile
|
||||
private var supervisedMetadataReconnectFallback: (() -> Unit)? = null
|
||||
private var pendingSupervisedUpdateId: String? = null
|
||||
private var supervisedUpdateFallbackJob: Job? = null
|
||||
|
||||
/**
|
||||
* Update the public client-mode tag sent on Relay auth. This does not grant
|
||||
* authority: Relay labels enforcement_owner=android_client and the Android
|
||||
* policy remains the enforcing surface.
|
||||
*/
|
||||
fun updateSupervisedMode(policy: SupervisedModePolicy) {
|
||||
if (supervisedMode == policy) return
|
||||
supervisedMode = policy
|
||||
if (_authState.value is AuthState.Paired) sendSupervisedModeUpdate()
|
||||
}
|
||||
|
||||
/**
|
||||
* Install the narrow compatibility path used when an older Relay ignores
|
||||
* `system/supervised.update`. Reopening the authenticated socket causes
|
||||
* the current policy to travel through the legacy `system/auth` payload.
|
||||
*/
|
||||
fun setSupervisedMetadataReconnectFallback(callback: () -> Unit) {
|
||||
supervisedMetadataReconnectFallback = callback
|
||||
}
|
||||
|
||||
private fun sendSupervisedModeUpdate() {
|
||||
val envelope = relaySupervisedModeUpdateEnvelope(supervisedMode)
|
||||
pendingSupervisedUpdateId = envelope.id
|
||||
supervisedUpdateFallbackJob?.cancel()
|
||||
multiplexer.send(envelope)
|
||||
supervisedUpdateFallbackJob = scope.launch {
|
||||
delay(SUPERVISED_UPDATE_ACK_TIMEOUT_MS)
|
||||
if (pendingSupervisedUpdateId == envelope.id) {
|
||||
pendingSupervisedUpdateId = null
|
||||
Log.i(TAG, "supervised.update unsupported or unacknowledged; refreshing Relay socket")
|
||||
supervisedMetadataReconnectFallback?.invoke()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun settleSupervisedModeUpdate(envelope: Envelope, unsupported: Boolean) {
|
||||
if (envelope.id != pendingSupervisedUpdateId) return
|
||||
pendingSupervisedUpdateId = null
|
||||
supervisedUpdateFallbackJob?.cancel()
|
||||
supervisedUpdateFallbackJob = null
|
||||
if (unsupported) {
|
||||
Log.i(TAG, "supervised.update rejected; refreshing Relay socket for compatibility")
|
||||
supervisedMetadataReconnectFallback?.invoke()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AuthManager"
|
||||
private const val KEY_SESSION_TOKEN = "session_token"
|
||||
@@ -134,6 +224,7 @@ class AuthManager(
|
||||
// migration has run, so we never rebuild the legacy keyset to re-check.
|
||||
private const val KEY_LEGACY_MIGRATED = "legacy_migrated"
|
||||
private const val PAIRING_CODE_LENGTH = 6
|
||||
private const val SUPERVISED_UPDATE_ACK_TIMEOUT_MS = 2_000L
|
||||
private val PAIRING_CODE_CHARS = ('A'..'Z') + ('0'..'9')
|
||||
|
||||
/**
|
||||
@@ -835,6 +926,10 @@ class AuthManager(
|
||||
put("device_form_factor", "phone")
|
||||
}
|
||||
|
||||
private fun JsonObjectBuilder.putSupervisedMode() {
|
||||
put("supervised_mode", relaySupervisedModePayload(supervisedMode))
|
||||
}
|
||||
|
||||
private fun relayDeviceName(): String {
|
||||
val configured = runCatching {
|
||||
Settings.Global.getString(context.contentResolver, "device_name")
|
||||
@@ -890,6 +985,7 @@ class AuthManager(
|
||||
put("device_id", deviceId)
|
||||
putRelayDeviceIdentity()
|
||||
putRelayClientSupports()
|
||||
putSupervisedMode()
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
@@ -906,6 +1002,7 @@ class AuthManager(
|
||||
put("device_id", deviceId)
|
||||
putRelayDeviceIdentity()
|
||||
putRelayClientSupports()
|
||||
putSupervisedMode()
|
||||
pendingTtlSeconds?.let { put("ttl_seconds", it) }
|
||||
pendingGrants?.let { grants ->
|
||||
val obj = buildJsonObject {
|
||||
@@ -985,6 +1082,8 @@ class AuthManager(
|
||||
when (envelope.type) {
|
||||
"auth.ok" -> handleAuthOk(envelope)
|
||||
"auth.fail" -> handleAuthFail(envelope)
|
||||
"supervised.updated" -> settleSupervisedModeUpdate(envelope, unsupported = false)
|
||||
"error" -> settleSupervisedModeUpdate(envelope, unsupported = true)
|
||||
// `profiles.updated` push — sent by the v0.7.1+ relay on
|
||||
// the "pairing" channel whenever its in-memory profile
|
||||
// snapshot changes (file-watcher, SIGHUP, or a manual
|
||||
@@ -1129,6 +1228,11 @@ class AuthManager(
|
||||
get() = _authState.value is AuthState.Paired
|
||||
|
||||
private fun handleAuthOk(envelope: Envelope) {
|
||||
// A successful auth always carries the latest client report, including
|
||||
// after the compatibility reconnect used for older Relay versions.
|
||||
pendingSupervisedUpdateId = null
|
||||
supervisedUpdateFallbackJob?.cancel()
|
||||
supervisedUpdateFallbackJob = null
|
||||
scope.launch {
|
||||
try {
|
||||
val payload = envelope.payload
|
||||
|
||||
@@ -33,6 +33,8 @@ class ChatInputPreferencesRepository(
|
||||
stringPreferencesKey("physical_keyboard_enter_behavior")
|
||||
internal val KEY_CONVERT_LARGE_PASTES =
|
||||
booleanPreferencesKey("convert_large_pastes_to_attachments")
|
||||
internal val KEY_SHOW_GIT_WORKSPACE_IN_CHAT =
|
||||
booleanPreferencesKey("show_git_workspace_in_chat")
|
||||
}
|
||||
|
||||
val physicalKeyboardEnterBehavior: Flow<PhysicalKeyboardEnterBehavior> = dataStore.data
|
||||
@@ -47,6 +49,10 @@ class ChatInputPreferencesRepository(
|
||||
.map { preferences -> preferences[KEY_CONVERT_LARGE_PASTES] ?: true }
|
||||
.distinctUntilChanged()
|
||||
|
||||
val showGitWorkspaceInChat: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[KEY_SHOW_GIT_WORKSPACE_IN_CHAT] ?: true }
|
||||
.distinctUntilChanged()
|
||||
|
||||
suspend fun setPhysicalKeyboardEnterBehavior(behavior: PhysicalKeyboardEnterBehavior) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[KEY_PHYSICAL_KEYBOARD_ENTER] = behavior.storedValue
|
||||
@@ -58,4 +64,10 @@ class ChatInputPreferencesRepository(
|
||||
preferences[KEY_CONVERT_LARGE_PASTES] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setShowGitWorkspaceInChat(enabled: Boolean) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[KEY_SHOW_GIT_WORKSPACE_IN_CHAT] = enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.plugins.runtime.ScopedPluginApiClient
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
// Read + write client for the Hermes-Relay Git State endpoints.
|
||||
// All requests are confined to the ``hermes-relay`` plugin namespace and the
|
||||
// ``git/*`` sub-path via ScopedPluginApiClient, which rejects traversal and
|
||||
// encodes query values.
|
||||
|
||||
private fun pathsArray(paths: List<String>) = buildJsonArray { paths.forEach { add(JsonPrimitive(it)) } }
|
||||
|
||||
class GitStateApiClient(
|
||||
dashboard: DashboardApiClient,
|
||||
) {
|
||||
private val scoped = ScopedPluginApiClient("hermes-relay", dashboard)
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
suspend fun repos(): Result<List<GitRepo>> = scoped
|
||||
.get("git/repos")
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<ReposResponse>(element).repos
|
||||
}
|
||||
|
||||
suspend fun status(repo: String): Result<GitStatus> = scoped
|
||||
.get("git/status", mapOf("repo" to repo))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitStatus>(element) }
|
||||
|
||||
suspend fun branches(repo: String): Result<List<GitBranch>> = scoped
|
||||
.get("git/branches", mapOf("repo" to repo))
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<BranchesResponse>(element).branches
|
||||
}
|
||||
|
||||
suspend fun diff(repo: String, path: String, kind: String): Result<GitDiff> = scoped
|
||||
.get("git/diff", mapOf("repo" to repo, "path" to path, "kind" to kind))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitDiff>(element) }
|
||||
|
||||
suspend fun file(repo: String, path: String): Result<GitFile> = scoped
|
||||
.get("git/file", mapOf("repo" to repo, "path" to path))
|
||||
.mapCatching { element -> json.decodeFromJsonElement<GitFile>(element) }
|
||||
|
||||
// ── Write operations ───────────────────────────────────────────────────
|
||||
// Every write requires the plugin.api.write grant, which the app enforces
|
||||
// (see GitStateViewModel: a POST is never sent without the grant). The
|
||||
// server additionally enforces per-use confirmation strings for destructive
|
||||
// ops (discard/push/dirty-checkout) — the caller passes the echoed token.
|
||||
|
||||
suspend fun stage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
scoped.post("git/stage", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
suspend fun unstage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
scoped.post("git/unstage", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
suspend fun discard(
|
||||
repo: String,
|
||||
paths: List<String>,
|
||||
confirmation: String,
|
||||
deleteUntracked: Boolean = false,
|
||||
): Result<GitMutationResult> = scoped.post("git/discard", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("paths", pathsArray(paths))
|
||||
put("confirmation", confirmation)
|
||||
put("delete_untracked", deleteUntracked)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
suspend fun commit(repo: String, message: String): Result<GitMutationResult> =
|
||||
scoped.post("git/commit", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("message", message)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
suspend fun commitSelected(
|
||||
repo: String,
|
||||
message: String,
|
||||
paths: List<String>,
|
||||
): Result<GitMutationResult> = scoped.post("git/commit_selected", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("message", message)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
suspend fun fetch(repo: String, remote: String = "origin"): Result<GitMutationResult> =
|
||||
scoped.post("git/fetch", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("remote", remote)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
suspend fun pull(repo: String, remote: String = "origin", branch: String = ""): Result<GitMutationResult> =
|
||||
scoped.post("git/pull", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
suspend fun push(
|
||||
repo: String,
|
||||
confirmation: String,
|
||||
remote: String = "origin",
|
||||
branch: String = "",
|
||||
): Result<GitMutationResult> = scoped.post("git/push", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
put("confirmation", confirmation)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
suspend fun checkout(
|
||||
repo: String,
|
||||
ref: String,
|
||||
confirmation: String? = null,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitMutationResult> = scoped.post("git/checkout", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("ref", ref)
|
||||
if (confirmation != null) put("confirmation", confirmation)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
// ── Phase 3 extras ─────────────────────────────────────────────────────
|
||||
|
||||
/** Generate a commit-message suggestion from the staged diff. */
|
||||
suspend fun commitMessage(repo: String): Result<GitCommitMessage> =
|
||||
scoped.post("git/commit_message", buildJsonObject {
|
||||
put("repo", repo)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
|
||||
/** Generate a commit-message suggestion from the given paths' staged diff. */
|
||||
suspend fun commitMessageSelected(
|
||||
repo: String,
|
||||
paths: List<String>,
|
||||
): Result<GitCommitMessage> = scoped.post("git/commit_message_selected", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
|
||||
/** Checkout that auto-stashes a dirty tree first. */
|
||||
suspend fun stashCheckout(
|
||||
repo: String,
|
||||
ref: String,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitStashCheckoutResult> = scoped.post("git/stash_checkout", buildJsonObject {
|
||||
put("repo", repo)
|
||||
put("ref", ref)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitStashCheckoutResult>(it) }
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/** A repository discovered by the plugin's /git/repos endpoint. */
|
||||
@Serializable
|
||||
data class GitRepo(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val root: String,
|
||||
@SerialName("current_branch") val currentBranch: String? = null,
|
||||
val dirty: Boolean = false,
|
||||
)
|
||||
|
||||
/** Working-tree status from /git/status. */
|
||||
@Serializable
|
||||
data class GitStatus(
|
||||
val counts: GitStatusCounts = GitStatusCounts(),
|
||||
val staged: List<GitStatusEntry> = emptyList(),
|
||||
val modified: List<GitStatusEntry> = emptyList(),
|
||||
val untracked: List<GitStatusEntry> = emptyList(),
|
||||
val truncated: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class GitStatusCounts(
|
||||
val staged: Int = 0,
|
||||
val modified: Int = 0,
|
||||
val untracked: Int = 0,
|
||||
/** Unique changed paths. -1 means an older plugin did not provide it. */
|
||||
val changes: Int = -1,
|
||||
val additions: Int = 0,
|
||||
val deletions: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class GitStatusEntry(
|
||||
val path: String,
|
||||
val additions: Int? = null,
|
||||
val deletions: Int? = null,
|
||||
)
|
||||
|
||||
/** A branch from /git/branches. */
|
||||
@Serializable
|
||||
data class GitBranch(
|
||||
val name: String,
|
||||
val upstream: String? = null,
|
||||
val ahead: Int = 0,
|
||||
val behind: Int = 0,
|
||||
@SerialName("is_current") val isCurrent: Boolean = false,
|
||||
)
|
||||
|
||||
/** A per-file diff from /git/diff. */
|
||||
@Serializable
|
||||
data class GitDiff(
|
||||
val path: String,
|
||||
val kind: String,
|
||||
val diff: String,
|
||||
val truncated: Boolean = false,
|
||||
)
|
||||
|
||||
/** A tracked-file read from /git/file. */
|
||||
@Serializable
|
||||
data class GitFile(
|
||||
val path: String,
|
||||
val content: String,
|
||||
val truncated: Boolean = false,
|
||||
)
|
||||
|
||||
/** Wrapper for /git/repos response. */
|
||||
@Serializable
|
||||
internal data class ReposResponse(
|
||||
val repos: List<GitRepo> = emptyList(),
|
||||
val notice: String? = null,
|
||||
)
|
||||
|
||||
/** Wrapper for /git/branches response. */
|
||||
@Serializable
|
||||
internal data class BranchesResponse(
|
||||
val branches: List<GitBranch> = emptyList(),
|
||||
)
|
||||
|
||||
/** A mutation response: fresh HEAD oid + working-tree status (+ branches). */
|
||||
@Serializable
|
||||
data class GitMutationResult(
|
||||
val head: String = "",
|
||||
val status: GitStatus = GitStatus(),
|
||||
val branches: List<GitBranch> = emptyList(),
|
||||
)
|
||||
|
||||
/** A /git/commit_message suggestion: generated message + optional notice. */
|
||||
@Serializable
|
||||
data class GitCommitMessage(
|
||||
val message: String = "",
|
||||
val notice: String = "",
|
||||
)
|
||||
|
||||
/** A /git/stash_checkout result: standard mutation shape + stash flag/message. */
|
||||
@Serializable
|
||||
data class GitStashCheckoutResult(
|
||||
val head: String = "",
|
||||
val status: GitStatus = GitStatus(),
|
||||
val branches: List<GitBranch> = emptyList(),
|
||||
val stashed: Boolean = false,
|
||||
@SerialName("stash_message") val stashMessage: String = "",
|
||||
)
|
||||
@@ -90,10 +90,10 @@ data class SessionActivityRecord(
|
||||
}
|
||||
}
|
||||
|
||||
/** Presentation projection that never labels uncertain or background activity as Working. */
|
||||
/** Presentation projection that never labels missing optional runtime data as session state. */
|
||||
fun presentationState(nowMillis: Long = Long.MIN_VALUE): SessionActivityState? = when (freshness) {
|
||||
SessionActivityFreshness.Revalidating -> SessionActivityState.Checking
|
||||
SessionActivityFreshness.Unavailable -> SessionActivityState.Unavailable
|
||||
SessionActivityFreshness.Revalidating -> null
|
||||
SessionActivityFreshness.Unavailable -> null
|
||||
SessionActivityFreshness.Confirmed -> when (phase(nowMillis)) {
|
||||
SessionActivityPhase.Starting -> SessionActivityState.Starting
|
||||
SessionActivityPhase.Working -> SessionActivityState.Working
|
||||
@@ -294,7 +294,9 @@ data class SessionActivityRegistry(
|
||||
|
||||
private fun observeOwner(update: SessionActivityUpdate.ObserveOwner): SessionActivityRegistry {
|
||||
val existing = records[update.owner]
|
||||
if (existing?.freshness == SessionActivityFreshness.Confirmed) return this
|
||||
// Directory rows establish ownership only. They are not live evidence and must not
|
||||
// turn an unsupported/failed active-list probe back into a permanent Checking row.
|
||||
if (existing != null) return this
|
||||
val observed = SessionActivityRecord(
|
||||
owner = update.owner,
|
||||
turnPhase = SessionActivityPhase.Idle,
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import com.hermesandroid.relay.ui.theme.AppThemes
|
||||
|
||||
/**
|
||||
* Parent-configured restrictions for the official Android client.
|
||||
*
|
||||
* This policy deliberately describes a client presentation mode, not a server
|
||||
* authorization boundary. The pinned profile is expected to have already been
|
||||
* configured with the appropriate server-side tool and content restrictions.
|
||||
*/
|
||||
@Serializable
|
||||
data class SupervisedModePolicy(
|
||||
val enabled: Boolean = false,
|
||||
val pinnedProfileName: String? = null,
|
||||
val capabilities: SupervisedCapabilities = SupervisedCapabilities(),
|
||||
val appearance: SupervisedAppearance = SupervisedAppearance(),
|
||||
val visibility: SupervisedVisibility = SupervisedVisibility(),
|
||||
val parentAccess: SupervisedParentAccess = SupervisedParentAccess(),
|
||||
) {
|
||||
/** A saved policy is usable only when it names a concrete Hermes profile. */
|
||||
val isConfigured: Boolean
|
||||
get() = !pinnedProfileName.isNullOrBlank()
|
||||
|
||||
/** Consumers should use this instead of treating [enabled] alone as sufficient. */
|
||||
val isActive: Boolean
|
||||
get() = enabled && isConfigured
|
||||
|
||||
internal fun normalized(): SupervisedModePolicy = copy(
|
||||
pinnedProfileName = pinnedProfileName?.trim()?.takeIf { it.isNotEmpty() },
|
||||
capabilities = capabilities.normalized(),
|
||||
appearance = appearance.normalized(),
|
||||
parentAccess = parentAccess.normalized(),
|
||||
)
|
||||
}
|
||||
|
||||
/** Actions and content types the supervised chat surface may expose. */
|
||||
@Serializable
|
||||
data class SupervisedCapabilities(
|
||||
val attachments: Boolean = false,
|
||||
val voice: Boolean = false,
|
||||
val generatedImages: Boolean = true,
|
||||
val conversationHistory: Boolean = false,
|
||||
val newChat: Boolean = true,
|
||||
val cancelResponse: Boolean = true,
|
||||
val steerResponse: Boolean = true,
|
||||
val retryResponse: Boolean = true,
|
||||
val copyResponses: Boolean = true,
|
||||
val quoteReplies: Boolean = true,
|
||||
val editAndResend: Boolean = false,
|
||||
val shareGeneratedImages: Boolean = false,
|
||||
val sessionActions: SupervisedSessionActions = SupervisedSessionActions(),
|
||||
val attachmentMaxCount: Int = DEFAULT_ATTACHMENT_MAX_COUNT,
|
||||
val attachmentMaxFileMb: Int = DEFAULT_ATTACHMENT_MAX_FILE_MB,
|
||||
val attachmentCategories: Set<SupervisedAttachmentCategory> = setOf(
|
||||
SupervisedAttachmentCategory.Images,
|
||||
),
|
||||
) {
|
||||
internal fun normalized(): SupervisedCapabilities = copy(
|
||||
attachmentMaxCount = attachmentMaxCount.coerceIn(1, MAX_ATTACHMENT_COUNT),
|
||||
attachmentMaxFileMb = attachmentMaxFileMb.coerceIn(1, MAX_ATTACHMENT_FILE_MB),
|
||||
attachmentCategories = attachmentCategories.ifEmpty {
|
||||
setOf(SupervisedAttachmentCategory.Images)
|
||||
},
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_ATTACHMENT_MAX_COUNT = 4
|
||||
const val DEFAULT_ATTACHMENT_MAX_FILE_MB = 10
|
||||
const val MAX_ATTACHMENT_COUNT = 10
|
||||
const val MAX_ATTACHMENT_FILE_MB = 100
|
||||
}
|
||||
}
|
||||
|
||||
/** Appearance applied only while the supervised root is locked. */
|
||||
@Serializable
|
||||
data class SupervisedAppearance(
|
||||
val appThemeId: String = AppThemes.DEFAULT_ID,
|
||||
val themePreference: String = "auto",
|
||||
val showPet: Boolean = false,
|
||||
val allowProfileIconChanges: Boolean = false,
|
||||
val allowBackgroundChanges: Boolean = false,
|
||||
) {
|
||||
internal fun normalized(): SupervisedAppearance = copy(
|
||||
appThemeId = AppThemes.byId(appThemeId).id,
|
||||
themePreference = themePreference.takeIf { it in VALID_THEME_PREFERENCES } ?: "auto",
|
||||
)
|
||||
|
||||
private companion object {
|
||||
val VALID_THEME_PREFERENCES = setOf("auto", "light", "dark")
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutable operations available from a supervised conversation-history row. */
|
||||
@Serializable
|
||||
data class SupervisedSessionActions(
|
||||
val pin: Boolean = false,
|
||||
val rename: Boolean = false,
|
||||
val archive: Boolean = false,
|
||||
val delete: Boolean = false,
|
||||
val shareTranscript: Boolean = false,
|
||||
) {
|
||||
val enabledCount: Int
|
||||
get() = listOf(pin, rename, archive, delete, shareTranscript).count { it }
|
||||
|
||||
val allEnabled: Boolean
|
||||
get() = enabledCount == TOTAL
|
||||
|
||||
val noneEnabled: Boolean
|
||||
get() = enabledCount == 0
|
||||
|
||||
fun withAll(enabled: Boolean): SupervisedSessionActions = SupervisedSessionActions(
|
||||
pin = enabled,
|
||||
rename = enabled,
|
||||
archive = enabled,
|
||||
delete = enabled,
|
||||
shareTranscript = enabled,
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val TOTAL = 5
|
||||
}
|
||||
}
|
||||
|
||||
enum class SupervisedSessionAction {
|
||||
Pin,
|
||||
Rename,
|
||||
Archive,
|
||||
Delete,
|
||||
ShareTranscript,
|
||||
}
|
||||
|
||||
fun SupervisedModePolicy.allowsSessionAction(action: SupervisedSessionAction): Boolean {
|
||||
if (!enabled) return true
|
||||
if (!capabilities.conversationHistory) return false
|
||||
return when (action) {
|
||||
SupervisedSessionAction.Pin -> capabilities.sessionActions.pin
|
||||
SupervisedSessionAction.Rename -> capabilities.sessionActions.rename
|
||||
SupervisedSessionAction.Archive -> capabilities.sessionActions.archive
|
||||
SupervisedSessionAction.Delete -> capabilities.sessionActions.delete
|
||||
SupervisedSessionAction.ShareTranscript -> capabilities.sessionActions.shareTranscript
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
enum class SupervisedAttachmentCategory {
|
||||
@SerialName("images")
|
||||
Images,
|
||||
|
||||
@SerialName("documents")
|
||||
Documents,
|
||||
|
||||
@SerialName("audio")
|
||||
Audio,
|
||||
|
||||
@SerialName("video")
|
||||
Video,
|
||||
}
|
||||
|
||||
/**
|
||||
* Controls which metadata and conversation affordances are rendered.
|
||||
*
|
||||
* [Simple] is the quiet default. [Transparent] is a useful preset for older or
|
||||
* technical users, while [Custom] tells the UI to honor every stored toggle.
|
||||
*/
|
||||
@Serializable
|
||||
data class SupervisedVisibility(
|
||||
val preset: SupervisedVisibilityPreset = SupervisedVisibilityPreset.Simple,
|
||||
val showAgentIdentity: Boolean = true,
|
||||
val showModelName: Boolean = false,
|
||||
val showProfileName: Boolean = false,
|
||||
val showConnectionStatus: Boolean = true,
|
||||
val showTechnicalRoute: Boolean = false,
|
||||
val showTimestamps: Boolean = true,
|
||||
val showToolNames: Boolean = false,
|
||||
val showToolDetails: Boolean = false,
|
||||
val showWorkingStatus: Boolean = true,
|
||||
val showReasoning: Boolean = false,
|
||||
val showUsage: Boolean = false,
|
||||
) {
|
||||
/** Resolve presets to the concrete flags consumed by chat presentation. */
|
||||
fun resolved(): SupervisedVisibility = when (preset) {
|
||||
SupervisedVisibilityPreset.Simple -> SIMPLE
|
||||
SupervisedVisibilityPreset.Transparent -> TRANSPARENT
|
||||
SupervisedVisibilityPreset.Custom -> this
|
||||
}
|
||||
|
||||
companion object {
|
||||
val SIMPLE = SupervisedVisibility(preset = SupervisedVisibilityPreset.Simple)
|
||||
|
||||
val TRANSPARENT = SupervisedVisibility(
|
||||
preset = SupervisedVisibilityPreset.Transparent,
|
||||
showModelName = true,
|
||||
showProfileName = true,
|
||||
showTechnicalRoute = true,
|
||||
showToolNames = true,
|
||||
showUsage = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
enum class SupervisedVisibilityPreset {
|
||||
@SerialName("simple")
|
||||
Simple,
|
||||
|
||||
@SerialName("transparent")
|
||||
Transparent,
|
||||
|
||||
@SerialName("custom")
|
||||
Custom,
|
||||
}
|
||||
|
||||
/** Device-authentication and automatic relock behavior for parent access. */
|
||||
@Serializable
|
||||
data class SupervisedParentAccess(
|
||||
/** Reserved for forward-compatible persistence; normalization never permits an auth bypass. */
|
||||
val requireDeviceAuthentication: Boolean = true,
|
||||
val relockOnBackground: Boolean = true,
|
||||
val timeoutMinutes: Int = DEFAULT_TIMEOUT_MINUTES,
|
||||
) {
|
||||
internal fun normalized(): SupervisedParentAccess = copy(
|
||||
requireDeviceAuthentication = true,
|
||||
timeoutMinutes = timeoutMinutes.coerceIn(MIN_TIMEOUT_MINUTES, MAX_TIMEOUT_MINUTES),
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_TIMEOUT_MINUTES = 5
|
||||
const val MIN_TIMEOUT_MINUTES = 1
|
||||
const val MAX_TIMEOUT_MINUTES = 60
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.serialization.builtins.MapSerializer
|
||||
import kotlinx.serialization.builtins.serializer
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
/** Persists one independent [SupervisedModePolicy] per Hermes connection. */
|
||||
class SupervisedModeStore private constructor(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
constructor(context: Context) : this(context.relayDataStore)
|
||||
|
||||
private val json = Json {
|
||||
encodeDefaults = true
|
||||
ignoreUnknownKeys = true
|
||||
}
|
||||
private val serializer = MapSerializer(String.serializer(), SupervisedModePolicy.serializer())
|
||||
|
||||
fun policyFlow(connectionId: String): Flow<SupervisedModePolicy> =
|
||||
dataStore.data.map { preferences ->
|
||||
val decoded = decode(preferences[KEY_POLICIES])
|
||||
if (decoded.corrupt) {
|
||||
// A malformed persisted policy must never silently reopen the
|
||||
// unrestricted app. Enabled + unconfigured renders the
|
||||
// supervised recovery surface until an authenticated user
|
||||
// repairs or clears the policy.
|
||||
SupervisedModePolicy(enabled = true)
|
||||
} else {
|
||||
decoded.policies[connectionId]?.normalized() ?: SupervisedModePolicy()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setPolicy(connectionId: String, policy: SupervisedModePolicy) {
|
||||
require(connectionId.isNotBlank()) { "connectionId must not be blank" }
|
||||
dataStore.edit { preferences ->
|
||||
val policies = decode(preferences[KEY_POLICIES]).policies.toMutableMap()
|
||||
policies[connectionId] = policy.normalized()
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, policies)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun updatePolicy(
|
||||
connectionId: String,
|
||||
transform: (SupervisedModePolicy) -> SupervisedModePolicy,
|
||||
) {
|
||||
require(connectionId.isNotBlank()) { "connectionId must not be blank" }
|
||||
dataStore.edit { preferences ->
|
||||
val policies = decode(preferences[KEY_POLICIES]).policies.toMutableMap()
|
||||
val current = policies[connectionId]?.normalized() ?: SupervisedModePolicy()
|
||||
policies[connectionId] = transform(current).normalized()
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, policies)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setEnabled(connectionId: String, enabled: Boolean) {
|
||||
updatePolicy(connectionId) { it.copy(enabled = enabled) }
|
||||
}
|
||||
|
||||
suspend fun clear(connectionId: String) {
|
||||
dataStore.edit { preferences ->
|
||||
val policies = decode(preferences[KEY_POLICIES]).policies.toMutableMap()
|
||||
policies.remove(connectionId)
|
||||
if (policies.isEmpty()) {
|
||||
preferences.remove(KEY_POLICIES)
|
||||
} else {
|
||||
preferences[KEY_POLICIES] = json.encodeToString(serializer, policies)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Clear supervised policies without disturbing unrelated app settings. */
|
||||
suspend fun clearAll() {
|
||||
dataStore.edit { preferences -> preferences.remove(KEY_POLICIES) }
|
||||
}
|
||||
|
||||
private fun decode(raw: String?): DecodeResult {
|
||||
if (raw.isNullOrBlank()) return DecodeResult(emptyMap(), corrupt = false)
|
||||
return try {
|
||||
DecodeResult(json.decodeFromString(serializer, raw), corrupt = false)
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Unable to decode supervised-mode policies; failing closed", error)
|
||||
DecodeResult(emptyMap(), corrupt = true)
|
||||
}
|
||||
}
|
||||
|
||||
private data class DecodeResult(
|
||||
val policies: Map<String, SupervisedModePolicy>,
|
||||
val corrupt: Boolean,
|
||||
)
|
||||
|
||||
internal companion object {
|
||||
private const val TAG = "SupervisedModeStore"
|
||||
private val KEY_POLICIES = stringPreferencesKey("supervised_mode_policies_v1")
|
||||
|
||||
fun forTesting(dataStore: DataStore<Preferences>): SupervisedModeStore =
|
||||
SupervisedModeStore(dataStore)
|
||||
}
|
||||
}
|
||||
@@ -153,7 +153,7 @@ class ChannelMultiplexer {
|
||||
)
|
||||
send(pong)
|
||||
}
|
||||
"auth.ok", "auth.fail" -> {
|
||||
"auth.ok", "auth.fail", "supervised.updated", "error" -> {
|
||||
// Delegate to system handler if registered
|
||||
handlers["system"]?.onMessage(envelope)
|
||||
}
|
||||
|
||||
@@ -442,6 +442,35 @@ class ConnectionManager(
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Reopen the current authenticated Relay socket without discarding pair
|
||||
* state. Used only as a compatibility fallback when an older Relay does
|
||||
* not acknowledge a post-auth metadata update; the replacement socket's
|
||||
* normal `system/auth` frame carries the latest metadata.
|
||||
*/
|
||||
fun reconnectForAuthenticatedMetadataUpdate(): Boolean {
|
||||
val targetUrl = serverUrl?.takeIf { it.isNotBlank() } ?: return false
|
||||
if (isRelayRateLimitBackoffActive(
|
||||
rateLimitBackoffUntilMs,
|
||||
SystemClock.elapsedRealtime(),
|
||||
)
|
||||
) {
|
||||
Log.i(TAG, "metadata reconnect: preserving active rate-limit backoff")
|
||||
return false
|
||||
}
|
||||
val previousSocket = webSocket
|
||||
if (previousSocket == null) {
|
||||
connect(targetUrl)
|
||||
} else {
|
||||
doConnect(
|
||||
targetUrl,
|
||||
previousSocketToClose = previousSocket,
|
||||
replaceReason = "Relay metadata compatibility refresh",
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as [connect] but bypasses the resolver — used by the network-
|
||||
* change callback when we've already picked a winner and just want to
|
||||
|
||||
@@ -48,6 +48,9 @@ interface VoiceAudioClient {
|
||||
val effectiveRoute: VoiceAudioRoute
|
||||
get() = route
|
||||
|
||||
/** Temporary client-policy override; the shared router honors it before user prefs. */
|
||||
fun setRouteOverride(route: VoiceAudioRoute?) = Unit
|
||||
|
||||
suspend fun transcribe(audioFile: File): Result<String>
|
||||
suspend fun synthesize(text: String): Result<File>
|
||||
|
||||
@@ -82,8 +85,15 @@ class AutoVoiceAudioClient(
|
||||
private val standardReadyProvider: () -> Boolean,
|
||||
private val relayReadyProvider: () -> Boolean,
|
||||
) : VoiceAudioClient {
|
||||
@Volatile
|
||||
private var routeOverride: VoiceAudioRoute? = null
|
||||
|
||||
override fun setRouteOverride(route: VoiceAudioRoute?) {
|
||||
routeOverride = route
|
||||
}
|
||||
|
||||
override val route: VoiceAudioRoute
|
||||
get() = routeProvider()
|
||||
get() = routeOverride ?: routeProvider()
|
||||
|
||||
/**
|
||||
* Resolve the configured preference to the backend a call would land on:
|
||||
@@ -92,7 +102,7 @@ class AutoVoiceAudioClient(
|
||||
* decide whether standard-only limitations (global TTS) currently apply.
|
||||
*/
|
||||
override val effectiveRoute: VoiceAudioRoute
|
||||
get() = when (routeProvider()) {
|
||||
get() = when (route) {
|
||||
VoiceAudioRoute.Standard -> VoiceAudioRoute.Standard
|
||||
VoiceAudioRoute.Relay -> VoiceAudioRoute.Relay
|
||||
VoiceAudioRoute.Auto ->
|
||||
@@ -114,7 +124,7 @@ class AutoVoiceAudioClient(
|
||||
private suspend fun <T> runWithSelectedRoute(
|
||||
block: suspend (VoiceAudioClient) -> Result<T>,
|
||||
): Result<T> {
|
||||
return when (routeProvider()) {
|
||||
return when (route) {
|
||||
VoiceAudioRoute.Standard -> {
|
||||
if (!standardReadyProvider()) {
|
||||
Result.failure(
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import com.hermesandroid.relay.data.GitRepo
|
||||
import com.hermesandroid.relay.ui.components.ChatGitWorkspaceSummary
|
||||
import com.hermesandroid.relay.viewmodel.GitRepoDetailState
|
||||
|
||||
internal fun selectGitRepoForWorkspace(
|
||||
repos: List<GitRepo>,
|
||||
selectedRepoId: String?,
|
||||
sessionRepoRoot: String?,
|
||||
sessionWorkingDirectory: String?,
|
||||
): GitRepo? {
|
||||
if (repos.isEmpty()) return null
|
||||
|
||||
fun normalized(path: String): String =
|
||||
path.trim().replace('\\', '/').trimEnd('/')
|
||||
|
||||
val exactRoot = sessionRepoRoot?.let(::normalized).orEmpty()
|
||||
val workingDirectory = sessionWorkingDirectory?.let(::normalized).orEmpty()
|
||||
val matched = exactRoot.takeIf { it.isNotBlank() }?.let { root ->
|
||||
repos.firstOrNull { normalized(it.root).equals(root, ignoreCase = true) }
|
||||
} ?: workingDirectory.takeIf { it.isNotBlank() }?.let { cwd ->
|
||||
repos.filter { repo ->
|
||||
val root = normalized(repo.root)
|
||||
cwd.equals(root, ignoreCase = true) ||
|
||||
cwd.startsWith("$root/", ignoreCase = true)
|
||||
}.maxByOrNull { normalized(it.root).length }
|
||||
}
|
||||
if (matched != null) return matched
|
||||
if (repos.any { it.id == selectedRepoId }) return null
|
||||
return repos.singleOrNull()
|
||||
}
|
||||
|
||||
internal fun buildChatGitWorkspaceSummary(
|
||||
repo: GitRepo?,
|
||||
detail: GitRepoDetailState,
|
||||
): ChatGitWorkspaceSummary? {
|
||||
val ready = detail as? GitRepoDetailState.Ready ?: return null
|
||||
repo ?: return null
|
||||
val status = ready.status
|
||||
val changedPaths = buildSet {
|
||||
status.staged.forEach { add(it.path) }
|
||||
status.modified.forEach { add(it.path) }
|
||||
status.untracked.forEach { add(it.path) }
|
||||
}
|
||||
val branch = ready.branches.firstOrNull { it.isCurrent }?.name
|
||||
?: repo.currentBranch.orEmpty()
|
||||
if (branch.isBlank()) return null
|
||||
return ChatGitWorkspaceSummary(
|
||||
branch = branch,
|
||||
changeCount = status.counts.changes.takeIf { it >= 0 } ?: changedPaths.size,
|
||||
additions = status.counts.additions,
|
||||
deletions = status.counts.deletions,
|
||||
)
|
||||
}
|
||||
@@ -54,6 +54,7 @@ import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
@@ -133,6 +134,8 @@ import com.hermesandroid.relay.data.CandidateBuild
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.FeatureFlags
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.SupervisedModeStore
|
||||
import com.hermesandroid.relay.data.VoicePresentationMode
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
@@ -144,6 +147,7 @@ import com.hermesandroid.relay.util.HumanError
|
||||
import kotlinx.coroutines.delay
|
||||
import com.hermesandroid.relay.ui.onboarding.OnboardingScreen
|
||||
import com.hermesandroid.relay.ui.screens.AboutScreen
|
||||
import com.hermesandroid.relay.ui.screens.AdvancedSettingsScreen
|
||||
import com.hermesandroid.relay.ui.screens.AnalyticsScreen
|
||||
import com.hermesandroid.relay.ui.screens.AppearanceSettingsScreen
|
||||
import com.hermesandroid.relay.ui.screens.CustomThemeScreen
|
||||
@@ -170,9 +174,14 @@ import com.hermesandroid.relay.ui.screens.PermissionsStatusScreen
|
||||
import com.hermesandroid.relay.ui.screens.ProfileInspectorScreen
|
||||
import com.hermesandroid.relay.ui.screens.RealtimeVoiceTestScreen
|
||||
import com.hermesandroid.relay.ui.screens.SettingsScreen
|
||||
import com.hermesandroid.relay.ui.screens.SupervisedControlsScreen
|
||||
import com.hermesandroid.relay.ui.screens.SupervisedAppearanceSettingsScreen
|
||||
import com.hermesandroid.relay.ui.screens.UsageLimitsScreen
|
||||
import com.hermesandroid.relay.ui.screens.PluginsScreen
|
||||
import com.hermesandroid.relay.ui.screens.PluginPageScreen
|
||||
import com.hermesandroid.relay.ui.screens.GitStateScreen
|
||||
import com.hermesandroid.relay.viewmodel.GitStateViewModel
|
||||
import com.hermesandroid.relay.viewmodel.GitStateUiState
|
||||
import com.hermesandroid.relay.ui.screens.TerminalScreen
|
||||
import com.hermesandroid.relay.ui.screens.NotificationCompanionSettingsScreen
|
||||
import com.hermesandroid.relay.ui.screens.ProactiveSettingsScreen
|
||||
@@ -192,7 +201,9 @@ import com.hermesandroid.relay.viewmodel.ChatTransportPath
|
||||
import com.hermesandroid.relay.viewmodel.ChatTransportReadiness
|
||||
import com.hermesandroid.relay.viewmodel.ChatViewModel
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import com.hermesandroid.relay.plugins.runtime.PLUGIN_API_WRITE_CAPABILITY
|
||||
import com.hermesandroid.relay.viewmodel.PluginsViewModel
|
||||
import com.hermesandroid.relay.viewmodel.PluginsHubState
|
||||
import com.hermesandroid.relay.viewmodel.ProfileInspectorViewModel
|
||||
import com.hermesandroid.relay.viewmodel.TerminalViewModel
|
||||
import com.hermesandroid.relay.viewmodel.VoiceViewModel
|
||||
@@ -440,6 +451,7 @@ sealed class Screen(
|
||||
}
|
||||
data object Settings : Screen("settings", "Settings", Icons.Filled.Settings)
|
||||
data object Plugins : Screen("plugins", "Plugins", Icons.Filled.Extension)
|
||||
data object GitState : Screen("git_state", "Git", Icons.Filled.Code)
|
||||
data object PluginPage : Screen(
|
||||
"plugins/{pluginId}/pages/{pageId}",
|
||||
"Plugin",
|
||||
@@ -531,6 +543,17 @@ sealed class Screen(
|
||||
// the plural `ConnectionsSettings` subpage. See `ConnectionsSettings`
|
||||
// above for the surviving route.)
|
||||
data object ChatSettings : Screen("settings/chat", "Chat", Icons.Filled.Settings)
|
||||
data object AdvancedSettings : Screen("settings/advanced", "Advanced", Icons.Filled.Settings)
|
||||
data object SupervisedAppearanceSettings : Screen(
|
||||
"settings/supervised/appearance",
|
||||
"Appearance",
|
||||
Icons.Filled.Settings,
|
||||
)
|
||||
data object SupervisedControls : Screen(
|
||||
"settings/supervised",
|
||||
"Supervised mode",
|
||||
Icons.Filled.Settings,
|
||||
)
|
||||
data object ProviderUsage : Screen("settings/usage", "Usage & limits", Icons.Filled.Settings)
|
||||
data object MediaSettings : Screen("settings/media", "Media", Icons.Filled.Settings)
|
||||
data object AppearanceSettings : Screen("settings/appearance", "Appearance", Icons.Filled.Settings)
|
||||
@@ -589,6 +612,24 @@ sealed class Screen(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SupervisedStartupLoadingScreen() {
|
||||
HermesRelayTheme(themePreference = "dark") {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = "Loading protected settings…",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RelayApp() {
|
||||
val applicationContext = LocalContext.current.applicationContext
|
||||
@@ -597,13 +638,17 @@ fun RelayApp() {
|
||||
val chatViewModel: ChatViewModel = processRuntime.chatViewModel
|
||||
val terminalViewModel: TerminalViewModel = viewModel()
|
||||
val pluginsViewModel: PluginsViewModel = viewModel()
|
||||
val gitStateViewModel: GitStateViewModel = viewModel()
|
||||
val voiceViewModel: VoiceViewModel = processRuntime.voiceViewModel
|
||||
val runtimeInitializationState by processRuntime.initializationState.collectAsState()
|
||||
|
||||
LaunchedEffect(processRuntime) {
|
||||
processRuntime.ensureInitialized()
|
||||
}
|
||||
if (runtimeInitializationState != HermesRuntimeInitializationState.Ready) return
|
||||
if (runtimeInitializationState != HermesRuntimeInitializationState.Ready) {
|
||||
SupervisedStartupLoadingScreen()
|
||||
return
|
||||
}
|
||||
|
||||
val voiceClient: RelayVoiceClient = processRuntime.relayVoiceClient
|
||||
val voicePreferences = processRuntime.voicePreferences
|
||||
@@ -700,6 +745,72 @@ fun RelayApp() {
|
||||
val profileSelectionSettled by connectionViewModel.profileSelectionSettled.collectAsState()
|
||||
val agentProfiles by connectionViewModel.agentProfiles.collectAsState()
|
||||
val activeConnectionId by connectionViewModel.activeConnectionId.collectAsState()
|
||||
val connectionStoreHydrated by
|
||||
connectionViewModel.connectionStore.isHydrated.collectAsState()
|
||||
val supervisedModeStore = remember(applicationContext) {
|
||||
SupervisedModeStore(applicationContext)
|
||||
}
|
||||
val supervisedPolicyState = produceState<Pair<String?, SupervisedModePolicy>?>(
|
||||
initialValue = null,
|
||||
key1 = activeConnectionId,
|
||||
key2 = supervisedModeStore,
|
||||
) {
|
||||
val connectionId = activeConnectionId
|
||||
if (connectionId == null) {
|
||||
value = null to SupervisedModePolicy()
|
||||
} else {
|
||||
supervisedModeStore.policyFlow(connectionId).collect { policy ->
|
||||
value = connectionId to policy
|
||||
}
|
||||
}
|
||||
}
|
||||
val ownedSupervisedPolicyState = supervisedPolicyState.value
|
||||
?.takeIf { (ownerConnectionId, _) -> ownerConnectionId == activeConnectionId }
|
||||
// Fail closed across process restoration. activeConnectionId starts as
|
||||
// null while ConnectionStore reads DataStore, so null alone cannot prove
|
||||
// this is a fresh install with no supervised policy to restore.
|
||||
if (!isRelayNavigationHydrated(
|
||||
connectionStoreHydrated = connectionStoreHydrated,
|
||||
activeConnectionId = activeConnectionId,
|
||||
supervisedPolicyHydrated = ownedSupervisedPolicyState != null,
|
||||
)
|
||||
) {
|
||||
SupervisedStartupLoadingScreen()
|
||||
return
|
||||
}
|
||||
val supervisedPolicy = ownedSupervisedPolicyState?.second ?: SupervisedModePolicy()
|
||||
val supervisedPinnedProfile = supervisedPolicy.pinnedProfileName?.let { name ->
|
||||
agentProfiles.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
||||
}
|
||||
val supervisedProfileConfirmed = !supervisedPolicy.enabled || (
|
||||
profileSelectionSettled &&
|
||||
supervisedPinnedProfile != null &&
|
||||
selectedProfile?.name.equals(supervisedPinnedProfile.name, ignoreCase = true)
|
||||
)
|
||||
val chatSupervisedPolicy = if (supervisedPolicy.enabled && !supervisedProfileConfirmed) {
|
||||
supervisedPolicy.copy(pinnedProfileName = null)
|
||||
} else supervisedPolicy
|
||||
var parentAccessUnlocked by remember(activeConnectionId) { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(
|
||||
activeConnectionId,
|
||||
supervisedPolicy,
|
||||
agentProfiles,
|
||||
selectedProfile,
|
||||
profileSelectionSettled,
|
||||
) {
|
||||
chatViewModel.updateSupervisedModePolicy(chatSupervisedPolicy)
|
||||
connectionViewModel.authManager.updateSupervisedMode(chatSupervisedPolicy)
|
||||
if (!supervisedPolicy.enabled) {
|
||||
parentAccessUnlocked = false
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val pinned = supervisedPinnedProfile ?: return@LaunchedEffect
|
||||
if (!selectedProfile?.name.equals(pinned.name, ignoreCase = true)) {
|
||||
connectionViewModel.selectProfile(pinned)
|
||||
chatViewModel.activateGatewayProfile(pinned)
|
||||
}
|
||||
}
|
||||
val connections by connectionViewModel.connections.collectAsState()
|
||||
|
||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||
@@ -746,6 +857,11 @@ fun RelayApp() {
|
||||
val serverCapabilities by connectionViewModel.serverCapabilities.collectAsState()
|
||||
val gatewayAvailability by connectionViewModel.gatewayAvailability.collectAsState()
|
||||
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
||||
val gitOwnerKey = activeConnectionId?.takeIf { it.isNotBlank() }?.let { connectionId ->
|
||||
effectiveDashboardUrl.takeIf { it.isNotBlank() }?.let { dashboardUrl ->
|
||||
"$connectionId\u0000${effectiveSessionProfileName.orEmpty()}\u0000$dashboardUrl"
|
||||
}
|
||||
}
|
||||
LaunchedEffect(
|
||||
activeConnectionId,
|
||||
effectiveDashboardUrl,
|
||||
@@ -760,6 +876,64 @@ fun RelayApp() {
|
||||
sessionId = currentChatSessionId,
|
||||
)
|
||||
}
|
||||
LaunchedEffect(gitOwnerKey) {
|
||||
val dashboard = effectiveDashboardUrl
|
||||
.takeIf { it.isNotBlank() }
|
||||
?.let { connectionViewModel.dashboardClientForActive(it) }
|
||||
gitStateViewModel.configure(dashboard, gitOwnerKey)
|
||||
}
|
||||
|
||||
// Mirror the plugin.api.write grant into the Git view model so write
|
||||
// mutations are refused client-side until the user grants write access
|
||||
// (matches the plug-in's grant gating in PluginsViewModel).
|
||||
val pluginsHubState by pluginsViewModel.hubState.collectAsState()
|
||||
LaunchedEffect(pluginsHubState, gitOwnerKey) {
|
||||
val ready = pluginsHubState as? PluginsHubState.Ready
|
||||
val granted = ready
|
||||
?.takeIf { it.ownerKey == gitOwnerKey }
|
||||
?.plugins
|
||||
?.firstOrNull { it.catalog.id == "hermes-relay" }
|
||||
?.preferences
|
||||
?.grants
|
||||
?.contains(PLUGIN_API_WRITE_CAPABILITY) == true
|
||||
gitStateViewModel.setWriteGrant(gitOwnerKey, granted)
|
||||
}
|
||||
|
||||
val gitReposState by gitStateViewModel.repos.collectAsState()
|
||||
val gitDetailState by gitStateViewModel.detail.collectAsState()
|
||||
val selectedGitRepoId by gitStateViewModel.selectedRepoId.collectAsState()
|
||||
val chatSessions by chatViewModel.sessions.collectAsState()
|
||||
val activeChatSession = remember(chatSessions, currentChatSessionId) {
|
||||
chatSessions.firstOrNull { it.sessionId == currentChatSessionId }
|
||||
}
|
||||
|
||||
// Bind Git to the active coding session when upstream supplies its exact
|
||||
// workspace metadata. CWD fallback only matches a path-segment descendant;
|
||||
// an ambiguous multi-repo catalog stays unselected until the user chooses.
|
||||
LaunchedEffect(gitReposState, activeChatSession, selectedGitRepoId) {
|
||||
val repos = (gitReposState as? GitStateUiState.Ready)?.repos.orEmpty()
|
||||
val target = selectGitRepoForWorkspace(
|
||||
repos = repos,
|
||||
selectedRepoId = selectedGitRepoId,
|
||||
sessionRepoRoot = activeChatSession?.gitRepoRoot,
|
||||
sessionWorkingDirectory = activeChatSession?.workingDirectory,
|
||||
)
|
||||
if (target != null && target.id != selectedGitRepoId) {
|
||||
gitStateViewModel.selectRepo(target.id)
|
||||
}
|
||||
}
|
||||
|
||||
val gitWorkspaceAvailable = gitReposState is GitStateUiState.Ready
|
||||
val gitWorkspaceSummary = remember(
|
||||
gitReposState,
|
||||
gitDetailState,
|
||||
selectedGitRepoId,
|
||||
) {
|
||||
val repo = (gitReposState as? GitStateUiState.Ready)
|
||||
?.repos
|
||||
?.firstOrNull { it.id == selectedGitRepoId }
|
||||
buildChatGitWorkspaceSummary(repo, gitDetailState)
|
||||
}
|
||||
|
||||
// What's New auto-show
|
||||
val showWhatsNew by connectionViewModel.showWhatsNew.collectAsState()
|
||||
@@ -784,6 +958,22 @@ fun RelayApp() {
|
||||
val appearanceAccent by connectionViewModel.appearanceAccent.collectAsState()
|
||||
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
|
||||
val activeCustomTheme by connectionViewModel.activeCustomTheme.collectAsState()
|
||||
val navController = rememberNavController()
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = navBackStackEntry?.destination?.route
|
||||
val parentAccessForCurrentRoute = parentAccessUnlocked &&
|
||||
!shouldRelockParentAccess(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessUnlocked,
|
||||
route = currentRoute,
|
||||
)
|
||||
val resolvedTheme = resolveSupervisedTheme(
|
||||
policy = supervisedPolicy,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
globalAppThemeId = appThemeId,
|
||||
globalThemePreference = themePreference,
|
||||
)
|
||||
val supervisedAppearanceLocked = supervisedPolicy.enabled && !parentAccessForCurrentRoute
|
||||
|
||||
// Resolve the active sphere skin (built-in / adaptive / user-loaded) and
|
||||
// publish it + the full available set so every MorphingSphere picks it up
|
||||
@@ -800,10 +990,10 @@ fun RelayApp() {
|
||||
value = SphereRegistry.builtIns +
|
||||
withContext(Dispatchers.IO) { SphereSkinLoader.loadUserSkins(sphereContext) }
|
||||
}
|
||||
val activeSphereSkin = remember(sphereSkinId, appThemeId, availableSphereSkins) {
|
||||
val activeSphereSkin = remember(sphereSkinId, resolvedTheme.appThemeId, availableSphereSkins) {
|
||||
SphereRegistry.resolve(
|
||||
selectedId = sphereSkinId,
|
||||
themeDefaultSkinId = AppThemes.byId(appThemeId).defaultSphereSkinId,
|
||||
themeDefaultSkinId = AppThemes.byId(resolvedTheme.appThemeId).defaultSphereSkinId,
|
||||
available = availableSphereSkins,
|
||||
)
|
||||
}
|
||||
@@ -938,37 +1128,19 @@ fun RelayApp() {
|
||||
),
|
||||
)
|
||||
HermesRelayTheme(
|
||||
appThemeId = appThemeId,
|
||||
themePreference = themePreference,
|
||||
appThemeId = resolvedTheme.appThemeId,
|
||||
themePreference = resolvedTheme.themePreference,
|
||||
fontScale = fontScale,
|
||||
appFontId = appFontId,
|
||||
accentHex = appearanceAccent,
|
||||
accentHex = appearanceAccent.takeIf { resolvedTheme.useGlobalCustomTheme },
|
||||
shapeId = appearanceShape,
|
||||
customTheme = activeCustomTheme,
|
||||
customTheme = activeCustomTheme.takeIf { resolvedTheme.useGlobalCustomTheme },
|
||||
) {
|
||||
// Surface a crash report from a previous session, if any. Renders a
|
||||
// platform Dialog (own window) so tree position is z-order-agnostic;
|
||||
// it just needs to be inside the theme for Material colors.
|
||||
CrashReportGate()
|
||||
|
||||
val navController = rememberNavController()
|
||||
|
||||
// === PHASE3-safety-rails-followup: cross-layer deep-link nav ===
|
||||
// Collect navigation requests posted by external launchers (e.g., the
|
||||
// BridgeForegroundService notification's "Settings" action). The
|
||||
// service sets EXTRA_NAV_ROUTE on its launch intent → MainActivity's
|
||||
// onCreate / onNewIntent reads it and pumps it onto NavRouteRequest →
|
||||
// we forward each emission to the NavController. Single observer at
|
||||
// the app root so every screen benefits.
|
||||
LaunchedEffect(navController) {
|
||||
com.hermesandroid.relay.util.NavRouteRequest.requests.collect { route ->
|
||||
navController.navigate(route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
}
|
||||
// === END PHASE3-safety-rails-followup ===
|
||||
|
||||
// Wire the proactive "session" surfacing once: a message with
|
||||
// surfacing="session" is injected into the active chat conversation.
|
||||
// ChatViewModel isn't available where ConnectionViewModel builds the
|
||||
@@ -1039,8 +1211,74 @@ fun RelayApp() {
|
||||
// restart cleanly lands back in setup.
|
||||
val isDemoMode by connectionViewModel.isDemoMode.collectAsState()
|
||||
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = navBackStackEntry?.destination?.route
|
||||
// The unlock remains useful while moving between parent-only settings,
|
||||
// but never follows an enrolled device user back into supervised chat.
|
||||
// Cross-layer requests (notifications, services, deep links) use the
|
||||
// route-scoped unlock. As soon as Chat is current, the parent grant is
|
||||
// ineffective even before the state-clearing effect runs.
|
||||
LaunchedEffect(
|
||||
navController,
|
||||
supervisedPolicy.enabled,
|
||||
parentAccessForCurrentRoute,
|
||||
) {
|
||||
com.hermesandroid.relay.util.NavRouteRequest.requests.collect { route ->
|
||||
if (
|
||||
supervisedPolicy.enabled &&
|
||||
!isSupervisedRouteAllowed(route, parentAccessForCurrentRoute)
|
||||
) return@collect
|
||||
navController.navigate(route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(
|
||||
supervisedPolicy.enabled,
|
||||
parentAccessForCurrentRoute,
|
||||
currentRoute,
|
||||
) {
|
||||
val redirect = shouldRedirectSupervisedRoute(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
currentRoute = currentRoute,
|
||||
)
|
||||
if (redirect) {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(navController.graph.findStartDestination().id) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(supervisedPolicy.enabled, parentAccessUnlocked, currentRoute) {
|
||||
if (shouldRelockParentAccess(supervisedPolicy.enabled, parentAccessUnlocked, currentRoute)) {
|
||||
// Route-scoped authority is already false on Chat. Let Navigation
|
||||
// finish committing the new destination before clearing the raw
|
||||
// parent grant, otherwise the same-frame root recomposition can
|
||||
// leave a themed but contentless surface.
|
||||
withFrameNanos { }
|
||||
withFrameNanos { }
|
||||
parentAccessUnlocked = false
|
||||
}
|
||||
}
|
||||
LaunchedEffect(parentAccessUnlocked, supervisedPolicy.parentAccess.timeoutMinutes) {
|
||||
if (parentAccessUnlocked) {
|
||||
delay(supervisedPolicy.parentAccess.timeoutMinutes * 60_000L)
|
||||
parentAccessUnlocked = false
|
||||
}
|
||||
}
|
||||
DisposableEffect(lifecycleOwner, supervisedPolicy.enabled, parentAccessUnlocked) {
|
||||
val relockObserver = LifecycleEventObserver { _, event ->
|
||||
if (
|
||||
event == Lifecycle.Event.ON_PAUSE &&
|
||||
supervisedPolicy.enabled &&
|
||||
parentAccessUnlocked &&
|
||||
supervisedPolicy.parentAccess.relockOnBackground
|
||||
) {
|
||||
parentAccessUnlocked = false
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(relockObserver)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(relockObserver) }
|
||||
}
|
||||
val suppressGlobalChrome = shouldSuppressGlobalChrome(
|
||||
onboardingCompleted = onboardingCompleted,
|
||||
isDemoMode = isDemoMode,
|
||||
@@ -1719,6 +1957,8 @@ fun RelayApp() {
|
||||
!suppressGlobalChrome &&
|
||||
!isKeyboardVisible &&
|
||||
!showStartupSphere &&
|
||||
(!supervisedPolicy.enabled ||
|
||||
supervisedPolicy.visibility.resolved().showTechnicalRoute) &&
|
||||
shouldShowConnectionFooter(voiceUiState.voiceMode, voicePresentationMode)
|
||||
) {
|
||||
val footerRoute = resolveFooterRouteCandidate(
|
||||
@@ -1793,12 +2033,16 @@ fun RelayApp() {
|
||||
.fillMaxSize()
|
||||
.padding(innerPadding),
|
||||
) {
|
||||
val routeContentAllowed = isSupervisedRouteContentAllowed(
|
||||
supervisedEnabled = supervisedPolicy.enabled,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
currentRoute = currentRoute,
|
||||
)
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
NavHost(
|
||||
navController = navController,
|
||||
startDestination = startDestination,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
composable(Screen.Onboarding.route) {
|
||||
// The wizard inside OnboardingScreen now owns credential
|
||||
@@ -1885,15 +2129,43 @@ fun RelayApp() {
|
||||
// sheet.
|
||||
val openAgentSheetArg = backStackEntry.arguments
|
||||
?.getBoolean(Screen.Chat.ARG_OPEN_AGENT_SHEET, false) == true
|
||||
val requestedSessionId = backStackEntry.arguments
|
||||
val rawRequestedSessionId = backStackEntry.arguments
|
||||
?.getString(Screen.Chat.ARG_SESSION_ID)
|
||||
?.takeIf { it.isNotBlank() }
|
||||
val requestedProfileRoute = backStackEntry.arguments
|
||||
val rawRequestedProfileRoute = backStackEntry.arguments
|
||||
?.getString(Screen.Chat.ARG_PROFILE)
|
||||
?.takeIf { it.isNotBlank() }
|
||||
val requestedProactiveChatId = backStackEntry.arguments
|
||||
val rawRequestedProactiveChatId = backStackEntry.arguments
|
||||
?.getString(Screen.Chat.ARG_PROACTIVE_CHAT_ID)
|
||||
?.takeIf { it.isNotBlank() }
|
||||
// Nav/deep-link arguments are not ownership evidence. The
|
||||
// supervised drawer uses profile-scoped session rows
|
||||
// directly; external args stay discarded until an
|
||||
// owner-aware source can explicitly prove the binding.
|
||||
val sanitizedRouteArgs = sanitizeSupervisedChatRouteArgs(
|
||||
policy = supervisedPolicy,
|
||||
args = SupervisedChatRouteArgs(
|
||||
sessionId = rawRequestedSessionId,
|
||||
profile = rawRequestedProfileRoute,
|
||||
proactiveChatId = rawRequestedProactiveChatId,
|
||||
),
|
||||
pinnedProfileOwnershipProven = false,
|
||||
)
|
||||
val requestedSessionId = sanitizedRouteArgs.sessionId
|
||||
val requestedProfileRoute = sanitizedRouteArgs.profile
|
||||
val requestedProactiveChatId = sanitizedRouteArgs.proactiveChatId
|
||||
LaunchedEffect(
|
||||
supervisedPolicy.enabled,
|
||||
rawRequestedSessionId,
|
||||
rawRequestedProfileRoute,
|
||||
rawRequestedProactiveChatId,
|
||||
) {
|
||||
if (supervisedPolicy.enabled) {
|
||||
backStackEntry.arguments?.putString(Screen.Chat.ARG_SESSION_ID, null)
|
||||
backStackEntry.arguments?.putString(Screen.Chat.ARG_PROFILE, null)
|
||||
backStackEntry.arguments?.putString(Screen.Chat.ARG_PROACTIVE_CHAT_ID, null)
|
||||
}
|
||||
}
|
||||
val proactiveInboxEntries by connectionViewModel.inboxMessages.collectAsState()
|
||||
val phoneThreadChatIds by connectionViewModel.phoneThreadChatIds.collectAsState()
|
||||
LaunchedEffect(
|
||||
@@ -2056,9 +2328,15 @@ fun RelayApp() {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
supervisedPolicy = chatSupervisedPolicy,
|
||||
onNavigateToBotMode = {
|
||||
navController.navigate(Screen.BotMode.route) { launchSingleTop = true }
|
||||
},
|
||||
gitWorkspaceAvailable = gitWorkspaceAvailable,
|
||||
gitWorkspaceSummary = gitWorkspaceSummary,
|
||||
onNavigateToGitWorkspace = {
|
||||
navController.navigate(Screen.GitState.route) { launchSingleTop = true }
|
||||
},
|
||||
)
|
||||
}
|
||||
composable(Screen.BotMode.route) {
|
||||
@@ -2376,6 +2654,25 @@ fun RelayApp() {
|
||||
SettingsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
chatViewModel = chatViewModel,
|
||||
supervisedPolicy = supervisedPolicy,
|
||||
parentAccessUnlocked = parentAccessForCurrentRoute,
|
||||
onRequestParentAccess = { parentAccessUnlocked = true },
|
||||
onUpdateSupervisedPolicy = { policy ->
|
||||
activeConnectionId?.let { connectionId ->
|
||||
connectionSwitchScope.launch {
|
||||
supervisedModeStore.setPolicy(connectionId, policy)
|
||||
}
|
||||
}
|
||||
},
|
||||
onNavigateToAdvancedSettings = {
|
||||
navController.navigate(Screen.AdvancedSettings.route)
|
||||
},
|
||||
onNavigateToSupervisedAppearance = {
|
||||
navController.navigate(Screen.SupervisedAppearanceSettings.route)
|
||||
},
|
||||
onNavigateToSupervisedControls = {
|
||||
navController.navigate(Screen.SupervisedControls.route)
|
||||
},
|
||||
onBack = { navController.popBackStack() },
|
||||
// (The `onNavigateToChatWithAgentSheet` callback that
|
||||
// used to live here was removed 2026-04-21. Tapping
|
||||
@@ -2395,6 +2692,9 @@ fun RelayApp() {
|
||||
onNavigateToPlugins = {
|
||||
navController.navigate(Screen.Plugins.route)
|
||||
},
|
||||
onNavigateToGitWorkspace = {
|
||||
navController.navigate(Screen.GitState.route)
|
||||
},
|
||||
onNavigateToChatSettings = {
|
||||
navController.navigate(Screen.ChatSettings.route)
|
||||
},
|
||||
@@ -2450,6 +2750,62 @@ fun RelayApp() {
|
||||
},
|
||||
)
|
||||
}
|
||||
composable(Screen.AdvancedSettings.route) {
|
||||
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
} else {
|
||||
AdvancedSettingsScreen(
|
||||
supervisedPolicy = supervisedPolicy,
|
||||
onNavigateToSupervisedControls = {
|
||||
navController.navigate(Screen.SupervisedControls.route)
|
||||
},
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
}
|
||||
composable(Screen.SupervisedAppearanceSettings.route) {
|
||||
if (!supervisedPolicy.enabled && !parentAccessForCurrentRoute) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
} else {
|
||||
SupervisedAppearanceSettingsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
policy = supervisedPolicy,
|
||||
onPolicyChange = { policy ->
|
||||
activeConnectionId?.let { connectionId ->
|
||||
connectionSwitchScope.launch {
|
||||
supervisedModeStore.setPolicy(connectionId, policy)
|
||||
}
|
||||
}
|
||||
},
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
}
|
||||
composable(Screen.SupervisedControls.route) {
|
||||
if (!parentAccessForCurrentRoute && supervisedPolicy.enabled) {
|
||||
LaunchedEffect(Unit) { navController.popBackStack() }
|
||||
} else {
|
||||
SupervisedControlsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
policy = supervisedPolicy,
|
||||
profiles = agentProfiles.filterNot { it.isDefault },
|
||||
onPolicyChange = { policy ->
|
||||
activeConnectionId?.let { connectionId ->
|
||||
connectionSwitchScope.launch {
|
||||
supervisedModeStore.setPolicy(connectionId, policy)
|
||||
}
|
||||
}
|
||||
},
|
||||
onBack = { navController.popBackStack() },
|
||||
onReturnToSupervisedView = {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(Screen.Chat.route) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
composable(Screen.ProviderUsage.route) {
|
||||
UsageLimitsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
@@ -2462,10 +2818,20 @@ fun RelayApp() {
|
||||
viewModel = pluginsViewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
onOpenPage = { pluginId, pageId ->
|
||||
navController.navigate(Screen.PluginPage.route(pluginId, pageId))
|
||||
if (pluginId == "hermes-relay" && pageId == "git") {
|
||||
navController.navigate(Screen.GitState.route)
|
||||
} else {
|
||||
navController.navigate(Screen.PluginPage.route(pluginId, pageId))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
composable(Screen.GitState.route) {
|
||||
GitStateScreen(
|
||||
viewModel = gitStateViewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(
|
||||
route = Screen.PluginPage.route,
|
||||
arguments = listOf(
|
||||
@@ -2927,7 +3293,8 @@ fun RelayApp() {
|
||||
composable(Screen.About.route) {
|
||||
AboutScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onBack = { navController.popBackStack() }
|
||||
onBack = { navController.popBackStack() },
|
||||
allowDeveloperUnlock = !supervisedPolicy.enabled || parentAccessForCurrentRoute,
|
||||
)
|
||||
}
|
||||
composable(
|
||||
@@ -3030,6 +3397,12 @@ fun RelayApp() {
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!routeContentAllowed) {
|
||||
// Keep the graph mounted so the redirect can complete, but
|
||||
// cover restored parent-only content with an opaque fail-closed surface.
|
||||
SupervisedStartupLoadingScreen()
|
||||
}
|
||||
}
|
||||
} // end bridge-return wrapper column
|
||||
} // end CompositionLocalProvider
|
||||
}
|
||||
@@ -3042,6 +3415,7 @@ fun RelayApp() {
|
||||
val petSurfaceOwner = petSurfaceOwnerForRoute(currentRoute)
|
||||
val petActivity = petCompanionCoordinator.activityFor(petSurfaceOwner)
|
||||
val showFloatingPet = activeFloatingPet != null &&
|
||||
shouldShowPetInSupervisedMode(supervisedPolicy, parentAccessForCurrentRoute) &&
|
||||
floatingPetAllowedOnRoute(currentRoute) &&
|
||||
!petActivity.hidden &&
|
||||
!suppressGlobalChrome &&
|
||||
@@ -3072,6 +3446,7 @@ fun RelayApp() {
|
||||
),
|
||||
animationEnabled = animationEnabled,
|
||||
appForeground = appIsForeground,
|
||||
interactive = !supervisedAppearanceLocked,
|
||||
route = roamingRoute,
|
||||
visitRequest = petCompanionCoordinator.pendingVisitRequest,
|
||||
onVisitRequestConsumed = petCompanionCoordinator::clearVisitRequest,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
|
||||
internal data class ResolvedSupervisedTheme(
|
||||
val appThemeId: String,
|
||||
val themePreference: String,
|
||||
val useGlobalCustomTheme: Boolean,
|
||||
)
|
||||
|
||||
/** Keep the supervised palette isolated from the parent's ordinary app theme. */
|
||||
internal fun resolveSupervisedTheme(
|
||||
policy: SupervisedModePolicy,
|
||||
parentAccessUnlocked: Boolean,
|
||||
globalAppThemeId: String,
|
||||
globalThemePreference: String,
|
||||
): ResolvedSupervisedTheme = if (policy.enabled && !parentAccessUnlocked) {
|
||||
ResolvedSupervisedTheme(
|
||||
appThemeId = policy.appearance.appThemeId,
|
||||
themePreference = policy.appearance.themePreference,
|
||||
useGlobalCustomTheme = false,
|
||||
)
|
||||
} else {
|
||||
ResolvedSupervisedTheme(
|
||||
appThemeId = globalAppThemeId,
|
||||
themePreference = globalThemePreference,
|
||||
useGlobalCustomTheme = true,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun shouldShowPetInSupervisedMode(
|
||||
policy: SupervisedModePolicy,
|
||||
parentAccessUnlocked: Boolean,
|
||||
): Boolean = !policy.enabled || parentAccessUnlocked || policy.appearance.showPet
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import com.hermesandroid.relay.data.ConnectionStore
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
|
||||
/** Allowlist applied to external, deep-link, and programmatic navigation. */
|
||||
internal fun isSupervisedRouteAllowed(route: String?, parentAccessUnlocked: Boolean): Boolean {
|
||||
if (parentAccessUnlocked) return true
|
||||
val normalized = route?.substringBefore('?') ?: return false
|
||||
return normalized == "chat" ||
|
||||
normalized == Screen.Settings.route ||
|
||||
normalized == Screen.SupervisedAppearanceSettings.route
|
||||
}
|
||||
|
||||
/** Do not inspect or mutate a NavController until its first destination exists. */
|
||||
internal fun shouldRedirectSupervisedRoute(
|
||||
supervisedEnabled: Boolean,
|
||||
parentAccessUnlocked: Boolean,
|
||||
currentRoute: String?,
|
||||
): Boolean = currentRoute != null &&
|
||||
supervisedEnabled &&
|
||||
!isSupervisedRouteAllowed(currentRoute, parentAccessUnlocked)
|
||||
|
||||
/** A null route is Navigation's pre-graph bootstrap state, not a forbidden destination. */
|
||||
internal fun isSupervisedRouteContentAllowed(
|
||||
supervisedEnabled: Boolean,
|
||||
parentAccessUnlocked: Boolean,
|
||||
currentRoute: String?,
|
||||
): Boolean = currentRoute == null ||
|
||||
!supervisedEnabled ||
|
||||
isSupervisedRouteAllowed(currentRoute, parentAccessUnlocked)
|
||||
|
||||
/**
|
||||
* Cold-start gate for the app navigation graph.
|
||||
*
|
||||
* A null active connection is also the seed value used while [ConnectionStore]
|
||||
* is reading DataStore. Callers must therefore wait for the store's explicit
|
||||
* hydration signal before treating null as "no connection" and composing the
|
||||
* unrestricted onboarding/settings graph.
|
||||
*/
|
||||
internal fun isRelayNavigationHydrated(
|
||||
connectionStoreHydrated: Boolean,
|
||||
activeConnectionId: String?,
|
||||
supervisedPolicyHydrated: Boolean,
|
||||
): Boolean = connectionStoreHydrated &&
|
||||
(activeConnectionId == null || supervisedPolicyHydrated)
|
||||
|
||||
/** A parent unlock never follows the user back into the supervised chat root. */
|
||||
internal fun shouldRelockParentAccess(
|
||||
supervisedEnabled: Boolean,
|
||||
parentAccessUnlocked: Boolean,
|
||||
route: String?,
|
||||
): Boolean = supervisedEnabled &&
|
||||
parentAccessUnlocked &&
|
||||
route?.substringBefore('?') == "chat"
|
||||
|
||||
/**
|
||||
* External chat route arguments are untrusted. A session may be restored only
|
||||
* after an owner-aware source has proved that it belongs to the pinned profile.
|
||||
*/
|
||||
internal fun mayRestoreSupervisedSessionRoute(
|
||||
policy: SupervisedModePolicy,
|
||||
requestedSessionId: String?,
|
||||
requestedProfile: String?,
|
||||
pinnedProfileOwnershipProven: Boolean,
|
||||
): Boolean = policy.isActive &&
|
||||
policy.capabilities.conversationHistory &&
|
||||
pinnedProfileOwnershipProven &&
|
||||
!requestedSessionId.isNullOrBlank() &&
|
||||
!requestedProfile.isNullOrBlank() &&
|
||||
requestedProfile.equals(policy.pinnedProfileName, ignoreCase = true)
|
||||
|
||||
internal data class SupervisedChatRouteArgs(
|
||||
val sessionId: String? = null,
|
||||
val profile: String? = null,
|
||||
val proactiveChatId: String? = null,
|
||||
)
|
||||
|
||||
/** Strip external chat targeting before any destination effect can dispatch it. */
|
||||
internal fun sanitizeSupervisedChatRouteArgs(
|
||||
policy: SupervisedModePolicy,
|
||||
args: SupervisedChatRouteArgs,
|
||||
pinnedProfileOwnershipProven: Boolean,
|
||||
): SupervisedChatRouteArgs {
|
||||
if (!policy.enabled) return args
|
||||
val allowSession = mayRestoreSupervisedSessionRoute(
|
||||
policy = policy,
|
||||
requestedSessionId = args.sessionId,
|
||||
requestedProfile = args.profile,
|
||||
pinnedProfileOwnershipProven = pinnedProfileOwnershipProven,
|
||||
)
|
||||
return if (allowSession) {
|
||||
args.copy(proactiveChatId = null)
|
||||
} else {
|
||||
SupervisedChatRouteArgs()
|
||||
}
|
||||
}
|
||||
|
||||
/** A disabled policy may become active only after an enrolled credential succeeds. */
|
||||
internal fun mayEnableSupervisedMode(
|
||||
policy: SupervisedModePolicy,
|
||||
deviceSecure: Boolean,
|
||||
deviceCredentialConfirmed: Boolean,
|
||||
): Boolean = !policy.enabled &&
|
||||
policy.isConfigured &&
|
||||
deviceSecure &&
|
||||
deviceCredentialConfirmed
|
||||
@@ -125,6 +125,7 @@ fun AttachmentGallery(
|
||||
if (attachments.size < 2) return
|
||||
|
||||
val context = LocalContext.current
|
||||
val exportAllowed = LocalImageExportAllowed.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val blurMode = LocalMediaBlurMode.current
|
||||
val revealed = remember { mutableStateMapOf<String, Boolean>() }
|
||||
@@ -189,7 +190,7 @@ fun AttachmentGallery(
|
||||
)
|
||||
}
|
||||
|
||||
if (!blurred) {
|
||||
if (!blurred && exportAllowed) {
|
||||
SaveOverlayButton(
|
||||
onClick = {
|
||||
scope.launch { saveAttachment(context, attachment) }
|
||||
@@ -201,7 +202,7 @@ fun AttachmentGallery(
|
||||
}
|
||||
|
||||
AttachmentActionsMenu(
|
||||
expanded = menuExpanded,
|
||||
expanded = menuExpanded && exportAllowed,
|
||||
onDismiss = { menuExpanded = false },
|
||||
context = context,
|
||||
scope = scope,
|
||||
|
||||
@@ -312,6 +312,8 @@ fun AttachmentViewer(
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val exportAllowed = LocalImageExportAllowed.current ||
|
||||
attachment.renderMode != AttachmentRenderMode.IMAGE
|
||||
AllowDeviceRotation()
|
||||
val scope = rememberCoroutineScope()
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
@@ -405,6 +407,7 @@ fun AttachmentViewer(
|
||||
title = title,
|
||||
busy = busy,
|
||||
actionsEnabled = !blurred,
|
||||
exportAllowed = exportAllowed,
|
||||
onShare = onShare,
|
||||
onSave = onSave,
|
||||
onOpenExternal = onOpenExternal,
|
||||
@@ -448,6 +451,7 @@ internal fun AttachmentGalleryViewer(
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val exportAllowed = LocalImageExportAllowed.current
|
||||
AllowDeviceRotation()
|
||||
val scope = rememberCoroutineScope()
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
@@ -584,6 +588,7 @@ internal fun AttachmentGalleryViewer(
|
||||
title = toolbarTitle,
|
||||
busy = busy,
|
||||
actionsEnabled = !currentBlurred,
|
||||
exportAllowed = exportAllowed,
|
||||
onShare = onShare,
|
||||
onSave = onSave,
|
||||
onOpenExternal = onOpenExternal,
|
||||
@@ -613,6 +618,7 @@ private fun MediaViewerToolbar(
|
||||
title: String,
|
||||
busy: Boolean,
|
||||
actionsEnabled: Boolean = true,
|
||||
exportAllowed: Boolean = true,
|
||||
onShare: () -> Unit,
|
||||
onSave: () -> Unit,
|
||||
onOpenExternal: () -> Unit,
|
||||
@@ -653,11 +659,13 @@ private fun MediaViewerToolbar(
|
||||
) {
|
||||
Icon(Icons.Filled.OpenInNew, contentDescription = stringResource(R.string.attachment_open_externally_a11y))
|
||||
}
|
||||
IconButton(onClick = onShare, enabled = actionsEnabled && !busy, colors = tint) {
|
||||
Icon(Icons.Filled.Share, contentDescription = stringResource(R.string.attachment_share_a11y))
|
||||
}
|
||||
IconButton(onClick = onSave, enabled = actionsEnabled && !busy, colors = tint) {
|
||||
Icon(Icons.Filled.Download, contentDescription = stringResource(R.string.attachment_save_a11y))
|
||||
if (exportAllowed) {
|
||||
IconButton(onClick = onShare, enabled = actionsEnabled && !busy, colors = tint) {
|
||||
Icon(Icons.Filled.Share, contentDescription = stringResource(R.string.attachment_share_a11y))
|
||||
}
|
||||
IconButton(onClick = onSave, enabled = actionsEnabled && !busy, colors = tint) {
|
||||
Icon(Icons.Filled.Download, contentDescription = stringResource(R.string.attachment_save_a11y))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ fun ChatFailurePanel(
|
||||
onDetails: () -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
showDetails: Boolean = true,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Surface(
|
||||
@@ -72,8 +73,10 @@ fun ChatFailurePanel(
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = onDetails) {
|
||||
Text(stringResource(R.string.chat_failure_details))
|
||||
if (showDetails) {
|
||||
TextButton(onClick = onDetails) {
|
||||
Text(stringResource(R.string.chat_failure_details))
|
||||
}
|
||||
}
|
||||
if (failure.recoverable) {
|
||||
TextButton(onClick = onRetry) {
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
|
||||
|
||||
/** Small, read-only Git projection supplied by the native workspace owner. */
|
||||
data class ChatGitWorkspaceSummary(
|
||||
val branch: String,
|
||||
val changeCount: Int,
|
||||
val additions: Int? = null,
|
||||
val deletions: Int? = null,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun ChatGitContextButton(
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Box(modifier = modifier) {
|
||||
RelayChromeIconButton(
|
||||
icon = Icons.Filled.AccountTree,
|
||||
contentDescription = stringResource(R.string.chat_git_open_workspace),
|
||||
onClick = onClick,
|
||||
)
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.size(9.dp)
|
||||
.align(Alignment.TopEnd),
|
||||
shape = CircleShape,
|
||||
color = RelayRefresh.Green,
|
||||
border = BorderStroke(1.5.dp, RelayRefresh.Background),
|
||||
content = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ChatGitWorkspaceRail(
|
||||
summary: ChatGitWorkspaceSummary,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val branch = summary.branch.trim()
|
||||
val changeCount = summary.changeCount.coerceAtLeast(0)
|
||||
val changeLabel = pluralStringResource(
|
||||
R.plurals.chat_git_change_count,
|
||||
changeCount,
|
||||
changeCount,
|
||||
)
|
||||
val additions = summary.additions?.coerceAtLeast(0)
|
||||
val deletions = summary.deletions?.coerceAtLeast(0)
|
||||
val a11yLabel = buildList {
|
||||
add(stringResource(R.string.chat_git_branch, branch))
|
||||
add(changeLabel)
|
||||
additions?.let { add(stringResource(R.string.chat_git_additions, it)) }
|
||||
deletions?.let { add(stringResource(R.string.chat_git_deletions, it)) }
|
||||
add(stringResource(R.string.chat_git_open_workspace))
|
||||
}.joinToString(". ")
|
||||
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.height(38.dp)
|
||||
.clearAndSetSemantics { contentDescription = a11yLabel },
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
color = RelayRefresh.Background.copy(alpha = 0.72f),
|
||||
border = BorderStroke(1.dp, RelayRefresh.LineStrong),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 11.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.AccountTree,
|
||||
contentDescription = null,
|
||||
tint = RelayRefresh.Cyan,
|
||||
modifier = Modifier.size(17.dp),
|
||||
)
|
||||
Text(
|
||||
text = branch,
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Paper,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.widthIn(max = 92.dp),
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.width(1.dp)
|
||||
.height(16.dp)
|
||||
.background(RelayRefresh.LineStrong),
|
||||
)
|
||||
Text(
|
||||
text = changeLabel,
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
)
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
additions?.let {
|
||||
Text(
|
||||
text = "+$it",
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Green,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
deletions?.let {
|
||||
Text(
|
||||
text = "-$it",
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Danger,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = RelayRefresh.Muted,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
@@ -42,6 +43,9 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.util.MediaSaver
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Whether the current conversation policy permits copying image bytes out of the app. */
|
||||
val LocalImageExportAllowed = staticCompositionLocalOf { true }
|
||||
|
||||
/**
|
||||
* What the [ChatImageViewer] displays and how it obtains bytes for Save/Share.
|
||||
*
|
||||
@@ -104,6 +108,7 @@ fun ChatImageViewer(
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val exportAllowed = LocalImageExportAllowed.current
|
||||
AllowDeviceRotation()
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
@@ -156,60 +161,72 @@ fun ChatImageViewer(
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
val tint = IconButtonDefaults.iconButtonColors(contentColor = Color.White)
|
||||
val cdShare = stringResource(R.string.cd_share)
|
||||
val cdSave = stringResource(R.string.cd_save)
|
||||
val cdClose = stringResource(R.string.cd_close_viewer)
|
||||
val errorMsg = context.getString(R.string.image_viewer_error)
|
||||
IconButton(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
busy = true
|
||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
||||
busy = false
|
||||
if (bytes == null) {
|
||||
toast(context, errorMsg)
|
||||
return@launch
|
||||
}
|
||||
val uri = MediaSaver.stageForShare(context, bytes, source.displayName, source.mime)
|
||||
MediaSaver.share(context, uri, source.mime)
|
||||
}
|
||||
},
|
||||
colors = tint,
|
||||
) {
|
||||
Icon(Icons.Filled.Share, contentDescription = cdShare)
|
||||
}
|
||||
val savedFmt = context.getString(R.string.image_viewer_saved)
|
||||
val failedFmt = context.getString(R.string.image_viewer_failed)
|
||||
IconButton(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
busy = true
|
||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
||||
if (bytes == null) {
|
||||
if (exportAllowed) {
|
||||
val cdShare = stringResource(R.string.cd_share)
|
||||
val cdSave = stringResource(R.string.cd_save)
|
||||
IconButton(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
busy = true
|
||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
||||
busy = false
|
||||
toast(context, errorMsg)
|
||||
return@launch
|
||||
if (bytes == null) {
|
||||
toast(context, errorMsg)
|
||||
return@launch
|
||||
}
|
||||
val uri = MediaSaver.stageForShare(
|
||||
context,
|
||||
bytes,
|
||||
source.displayName,
|
||||
source.mime,
|
||||
)
|
||||
MediaSaver.share(context, uri, source.mime)
|
||||
}
|
||||
when (val result = MediaSaver.saveImage(context, bytes, source.displayName, source.mime)) {
|
||||
is MediaSaver.SaveResult.Saved -> {
|
||||
},
|
||||
colors = tint,
|
||||
) {
|
||||
Icon(Icons.Filled.Share, contentDescription = cdShare)
|
||||
}
|
||||
val savedFmt = context.getString(R.string.image_viewer_saved)
|
||||
val failedFmt = context.getString(R.string.image_viewer_failed)
|
||||
IconButton(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
busy = true
|
||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
||||
if (bytes == null) {
|
||||
busy = false
|
||||
toast(context, savedFmt.format(result.location))
|
||||
toast(context, errorMsg)
|
||||
return@launch
|
||||
}
|
||||
MediaSaver.SaveResult.UseShareInstead -> {
|
||||
busy = false
|
||||
val uri = MediaSaver.stageForShare(context, bytes, source.displayName, source.mime)
|
||||
MediaSaver.share(context, uri, source.mime)
|
||||
}
|
||||
is MediaSaver.SaveResult.Failed -> {
|
||||
busy = false
|
||||
toast(context, failedFmt.format(result.message))
|
||||
when (val result = MediaSaver.saveImage(context, bytes, source.displayName, source.mime)) {
|
||||
is MediaSaver.SaveResult.Saved -> {
|
||||
busy = false
|
||||
toast(context, savedFmt.format(result.location))
|
||||
}
|
||||
MediaSaver.SaveResult.UseShareInstead -> {
|
||||
busy = false
|
||||
val uri = MediaSaver.stageForShare(
|
||||
context,
|
||||
bytes,
|
||||
source.displayName,
|
||||
source.mime,
|
||||
)
|
||||
MediaSaver.share(context, uri, source.mime)
|
||||
}
|
||||
is MediaSaver.SaveResult.Failed -> {
|
||||
busy = false
|
||||
toast(context, failedFmt.format(result.message))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
colors = tint,
|
||||
) {
|
||||
Icon(Icons.Filled.Download, contentDescription = cdSave)
|
||||
},
|
||||
colors = tint,
|
||||
) {
|
||||
Icon(Icons.Filled.Download, contentDescription = cdSave)
|
||||
}
|
||||
}
|
||||
IconButton(onClick = onDismiss, colors = tint) {
|
||||
Icon(Icons.Filled.Close, contentDescription = cdClose)
|
||||
|
||||
@@ -483,6 +483,7 @@ fun FloatingPetCompanion(
|
||||
compact: Boolean,
|
||||
animationEnabled: Boolean,
|
||||
appForeground: Boolean,
|
||||
interactive: Boolean = true,
|
||||
route: String?,
|
||||
visitRequest: PetVisitRequest?,
|
||||
onVisitRequestConsumed: (String) -> Unit,
|
||||
@@ -2318,13 +2319,14 @@ fun FloatingPetCompanion(
|
||||
}
|
||||
.pointerInput(
|
||||
pet.id,
|
||||
interactive,
|
||||
safeBounds,
|
||||
roamingRails,
|
||||
settledHabitat,
|
||||
positioned,
|
||||
surfaceScrolling,
|
||||
) {
|
||||
if (!floatingPetAcceptsPointerInput(positioned, surfaceScrolling)) {
|
||||
if (!interactive || !floatingPetAcceptsPointerInput(positioned, surfaceScrolling)) {
|
||||
return@pointerInput
|
||||
}
|
||||
detectDragGesturesAfterLongPress(
|
||||
@@ -2399,16 +2401,16 @@ fun FloatingPetCompanion(
|
||||
)
|
||||
}
|
||||
.clickable(
|
||||
enabled = floatingPetAcceptsPointerInput(positioned, surfaceScrolling),
|
||||
enabled = interactive && floatingPetAcceptsPointerInput(positioned, surfaceScrolling),
|
||||
) {
|
||||
tapReactionNonce += 1
|
||||
setMenuExpanded(true)
|
||||
}
|
||||
.semantics(mergeDescendants = true) {
|
||||
role = Role.Button
|
||||
if (interactive) role = Role.Button
|
||||
contentDescription = companionDescription
|
||||
stateDescription = stateLabel
|
||||
customActions = buildList {
|
||||
customActions = if (interactive) buildList {
|
||||
add(CustomAccessibilityAction(moveStartLabel) {
|
||||
onPlacementChanged(placement.copy(edge = PetLogicalEdge.Start)); true
|
||||
})
|
||||
@@ -2438,7 +2440,7 @@ fun FloatingPetCompanion(
|
||||
add(CustomAccessibilityAction(resetLabel) { onResetPlacement(); true })
|
||||
add(CustomAccessibilityAction(appearanceLabel) { onOpenAppearance(); true })
|
||||
add(CustomAccessibilityAction(hideLabel) { onHide(); true })
|
||||
}
|
||||
} else emptyList()
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
@@ -2482,7 +2484,7 @@ fun FloatingPetCompanion(
|
||||
}
|
||||
|
||||
DropdownMenu(
|
||||
expanded = menuExpanded,
|
||||
expanded = interactive && menuExpanded,
|
||||
onDismissRequest = { setMenuExpanded(false) },
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
|
||||
+18
-13
@@ -270,6 +270,7 @@ private fun ImageRender(
|
||||
maxWidth: Dp
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val exportAllowed = LocalImageExportAllowed.current
|
||||
val scope = rememberCoroutineScope()
|
||||
// Decode OFF the main thread — a large inbound image would otherwise block
|
||||
// composition. Null while decoding (placeholder); decodeFailed → file card.
|
||||
@@ -356,14 +357,14 @@ private fun ImageRender(
|
||||
}
|
||||
// One-tap save overlay — hidden while the blur cover is up so it
|
||||
// doesn't sit over the "tap to reveal" prompt.
|
||||
if (!blurred) {
|
||||
if (!blurred && exportAllowed) {
|
||||
SaveOverlayButton(
|
||||
onClick = { scope.launch { saveAttachment(context, attachment) } },
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(6.dp),
|
||||
)
|
||||
}
|
||||
AttachmentActionsMenu(
|
||||
expanded = menuExpanded,
|
||||
expanded = menuExpanded && exportAllowed,
|
||||
onDismiss = { menuExpanded = false },
|
||||
context = context,
|
||||
scope = scope,
|
||||
@@ -380,6 +381,8 @@ private fun FileCardRender(
|
||||
maxWidth: Dp
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val exportAllowed = LocalImageExportAllowed.current ||
|
||||
attachment.renderMode != AttachmentRenderMode.IMAGE
|
||||
val scope = rememberCoroutineScope()
|
||||
val (emoji, typeLabel) = emojiAndLabelFor(attachment.renderMode, attachment.contentType)
|
||||
var menuExpanded by remember { mutableStateOf(false) }
|
||||
@@ -463,21 +466,23 @@ private fun FileCardRender(
|
||||
}
|
||||
}
|
||||
// Visible one-tap save affordance (B2).
|
||||
IconButton(
|
||||
onClick = { scope.launch { saveAttachment(context, attachment) } },
|
||||
modifier = Modifier.size(32.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Download,
|
||||
contentDescription = stringResource(R.string.inbound_attach_cd_save),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
if (exportAllowed) {
|
||||
IconButton(
|
||||
onClick = { scope.launch { saveAttachment(context, attachment) } },
|
||||
modifier = Modifier.size(32.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Download,
|
||||
contentDescription = stringResource(R.string.inbound_attach_cd_save),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AttachmentActionsMenu(
|
||||
expanded = menuExpanded,
|
||||
expanded = menuExpanded && exportAllowed,
|
||||
onDismiss = { menuExpanded = false },
|
||||
context = context,
|
||||
scope = scope,
|
||||
|
||||
@@ -94,6 +94,14 @@ import java.util.Date
|
||||
internal const val CHAT_PET_IDENTITY_OBSTACLE_PREFIX = "chat-message-identity:"
|
||||
private val MESSAGE_REACTIONS = listOf("❤️", "👍", "👎", "😂", "‼️", "❓")
|
||||
|
||||
internal fun assistantImageContent(
|
||||
content: String,
|
||||
showImages: Boolean,
|
||||
): Pair<String, List<ChatInlineImage>> {
|
||||
val (body, images) = extractChatInlineImages(content)
|
||||
return body to if (showImages) images else emptyList()
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun MessageBubble(
|
||||
@@ -101,6 +109,13 @@ fun MessageBubble(
|
||||
modifier: Modifier = Modifier,
|
||||
maxBubbleWidth: Dp = 300.dp,
|
||||
showThinking: Boolean = true,
|
||||
showAgentIdentity: Boolean = true,
|
||||
showTimestamps: Boolean = true,
|
||||
showWorkingStatus: Boolean = true,
|
||||
showUsage: Boolean = true,
|
||||
showTechnicalBadges: Boolean = true,
|
||||
showAssistantImages: Boolean = true,
|
||||
allowAssistantImageExport: Boolean = true,
|
||||
isFirstInGroup: Boolean = true,
|
||||
isLastInGroup: Boolean = true,
|
||||
onCopyMessage: (String) -> Unit = {},
|
||||
@@ -238,18 +253,24 @@ fun MessageBubble(
|
||||
// content so they render as real images (remote URLs via Coil) or a
|
||||
// graceful inline notice — not the blank element the markdown renderer
|
||||
// emits for an image link. User/system bubbles keep their raw content.
|
||||
val (markdownBody, inlineImages) = remember(visibleMessageContent, isUser, isSystem) {
|
||||
val (markdownBody, inlineImages) = remember(
|
||||
visibleMessageContent,
|
||||
isUser,
|
||||
isSystem,
|
||||
showAssistantImages,
|
||||
) {
|
||||
if (isUser || isSystem) {
|
||||
visibleMessageContent to emptyList()
|
||||
} else {
|
||||
extractChatInlineImages(visibleMessageContent)
|
||||
assistantImageContent(visibleMessageContent, showAssistantImages)
|
||||
}
|
||||
}
|
||||
val showImageGeneration = shouldShowImageGenerationPlaceholder(
|
||||
val showImageGeneration = showAssistantImages && showWorkingStatus && shouldShowImageGenerationPlaceholder(
|
||||
toolCalls = message.toolCalls,
|
||||
isStreaming = message.isStreaming,
|
||||
hasMediaResult = message.attachments.isNotEmpty() || inlineImages.isNotEmpty(),
|
||||
)
|
||||
val actionContent = if (!isUser && !isSystem) markdownBody else visibleMessageContent
|
||||
val streamingStatusLabel = if (
|
||||
!isUser &&
|
||||
!isSystem &&
|
||||
@@ -297,7 +318,10 @@ fun MessageBubble(
|
||||
val blurRepo = remember(context) { MediaSettingsRepository(context.applicationContext) }
|
||||
val blurMode by blurRepo.blurMode.collectAsState(initial = BlurMode.FLAGGED)
|
||||
|
||||
CompositionLocalProvider(LocalMediaBlurMode provides blurMode) {
|
||||
CompositionLocalProvider(
|
||||
LocalMediaBlurMode provides blurMode,
|
||||
LocalImageExportAllowed provides allowAssistantImageExport,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
horizontalAlignment = alignment,
|
||||
@@ -305,7 +329,7 @@ fun MessageBubble(
|
||||
// Keep sender identity in the first-message label rather than a
|
||||
// persistent leading column. Long responses and every follow-up in the
|
||||
// group therefore retain the full bubble-width allowance.
|
||||
if (!isUser && !isSystem && isFirstInGroup && !message.agentName.isNullOrBlank()) {
|
||||
if (showAgentIdentity && !isUser && !isSystem && isFirstInGroup && !message.agentName.isNullOrBlank()) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
@@ -336,7 +360,7 @@ fun MessageBubble(
|
||||
}
|
||||
}
|
||||
|
||||
if (!isUser && !isSystem && message.badges.isNotEmpty()) {
|
||||
if (showTechnicalBadges && !isUser && !isSystem && message.badges.isNotEmpty()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.widthIn(max = maxBubbleWidth)
|
||||
@@ -415,7 +439,7 @@ fun MessageBubble(
|
||||
// is rendered directly in the conversation
|
||||
// lane below, without an opaque bubble. Cards and attachments still own
|
||||
// a normal bubble even when response prose has not arrived yet.
|
||||
streamingStatusLabel?.let { streamingStatus ->
|
||||
streamingStatusLabel?.takeIf { showWorkingStatus }?.let { streamingStatus ->
|
||||
StandaloneStreamingStatus(
|
||||
status = streamingStatus,
|
||||
accessibilityDescription = a11yDescription,
|
||||
@@ -508,7 +532,7 @@ fun MessageBubble(
|
||||
text = { Text(stringResource(R.string.msg_bubble_copy)) },
|
||||
onClick = {
|
||||
showMessageActions = false
|
||||
onCopyMessage(visibleMessageContent)
|
||||
onCopyMessage(actionContent)
|
||||
},
|
||||
)
|
||||
if (onQuoteMessage != null) {
|
||||
@@ -516,7 +540,7 @@ fun MessageBubble(
|
||||
text = { Text(stringResource(R.string.msg_bubble_quote)) },
|
||||
onClick = {
|
||||
showMessageActions = false
|
||||
onQuoteMessage(message.copy(content = visibleMessageContent))
|
||||
onQuoteMessage(message.copy(content = actionContent))
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -531,7 +555,7 @@ fun MessageBubble(
|
||||
},
|
||||
onClick = {
|
||||
showMessageActions = false
|
||||
onSpeakMessage?.invoke(visibleMessageContent)
|
||||
onSpeakMessage?.invoke(actionContent)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -601,7 +625,7 @@ fun MessageBubble(
|
||||
) {
|
||||
showMessageActions = true
|
||||
} else {
|
||||
onCopyMessage(visibleMessageContent)
|
||||
onCopyMessage(actionContent)
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -798,7 +822,7 @@ fun MessageBubble(
|
||||
}
|
||||
}
|
||||
|
||||
val hasTokenUsage = !isUser &&
|
||||
val hasTokenUsage = showUsage && !isUser &&
|
||||
(message.inputTokens != null || message.outputTokens != null)
|
||||
|
||||
// Timestamp — only on the LAST bubble of a same-author run so a
|
||||
@@ -808,13 +832,13 @@ fun MessageBubble(
|
||||
// This row is reserved from the first streaming frame. Completion
|
||||
// can reveal both timestamp and token usage without adding a new
|
||||
// footer line or changing the bubble's measured height.
|
||||
if (isLastInGroup) {
|
||||
if (isLastInGroup && (showTimestamps || hasTokenUsage)) {
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
if (showTimestamps) Text(
|
||||
text = timeFormat.format(Date(message.timestamp)),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = textColor.copy(alpha = if (message.isStreaming) 0f else 0.6f),
|
||||
@@ -883,15 +907,15 @@ fun MessageBubble(
|
||||
showEdit = showEditAction,
|
||||
onCopy = {
|
||||
showInlineActions = false
|
||||
onCopyMessage(visibleMessageContent)
|
||||
onCopyMessage(actionContent)
|
||||
},
|
||||
onQuote = {
|
||||
showInlineActions = false
|
||||
onQuoteMessage?.invoke(message.copy(content = visibleMessageContent))
|
||||
onQuoteMessage?.invoke(message.copy(content = actionContent))
|
||||
},
|
||||
onSpeak = {
|
||||
showInlineActions = false
|
||||
onSpeakMessage?.invoke(visibleMessageContent)
|
||||
onSpeakMessage?.invoke(actionContent)
|
||||
},
|
||||
onStopSpeaking = {
|
||||
showInlineActions = false
|
||||
|
||||
@@ -14,7 +14,6 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
@@ -26,8 +25,6 @@ import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.ui.theme.LocalBrand
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlin.math.sin
|
||||
|
||||
/**
|
||||
* ASCII morphing sphere — the visual embodiment of the AI agent.
|
||||
@@ -56,19 +53,13 @@ import kotlin.math.sin
|
||||
private const val SPHERE_TIME_UNITS_PER_SEC = 1f
|
||||
private const val SPHERE_TWO_PI = 6.2832f
|
||||
private const val SPHERE_COLOR_RADIANS_PER_SEC = 0.7854f
|
||||
private const val SPHERE_IDLE_BREATH_RADIANS_PER_SEC = 0.72f
|
||||
private const val SPHERE_IDLE_BREATH_SCALE = 0.012f
|
||||
private const val SPHERE_IDLE_LAYER_FRAME_INTERVAL_MS = 184L
|
||||
|
||||
internal enum class SphereMotionMode {
|
||||
Still,
|
||||
AmbientLayer,
|
||||
Procedural,
|
||||
}
|
||||
|
||||
internal fun sphereMotionMode(
|
||||
state: SphereState,
|
||||
voiceMode: Boolean,
|
||||
motionVisible: Boolean,
|
||||
fixedTime: Float?,
|
||||
fixedColorPhase: Float?,
|
||||
@@ -76,11 +67,7 @@ internal fun sphereMotionMode(
|
||||
if (!motionVisible || fixedTime != null || fixedColorPhase != null) {
|
||||
return SphereMotionMode.Still
|
||||
}
|
||||
return if (state == SphereState.Idle && !voiceMode) {
|
||||
SphereMotionMode.AmbientLayer
|
||||
} else {
|
||||
SphereMotionMode.Procedural
|
||||
}
|
||||
return SphereMotionMode.Procedural
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -134,15 +121,12 @@ fun MorphingSphere(
|
||||
val cg2 by animateFloatAsState(targetC.g2, spec, label = "cg2")
|
||||
val cb2 by animateFloatAsState(targetC.b2, spec, label = "cb2")
|
||||
|
||||
// Active states retain the full procedural animation. Visible Idle uses a
|
||||
// lightweight graphics-layer breath: redrawing the 58x34 glyph grid just
|
||||
// for ambient drift was the measured screen-on hotspot, while transforming
|
||||
// its cached layer preserves the intended living Sphere at far lower cost.
|
||||
// Every visible Sphere uses the same display-synced procedural loop so
|
||||
// startup, chat, and voice all feel equally smooth. Backgrounded and
|
||||
// explicitly paused/reduced-motion renderers still pin a static frame.
|
||||
val animatedTime = remember { mutableFloatStateOf(0f) }
|
||||
val animatedColorPhase = remember { mutableFloatStateOf(0f) }
|
||||
val motionMode = sphereMotionMode(
|
||||
state = state,
|
||||
voiceMode = effVoiceMode,
|
||||
motionVisible = motionVisible,
|
||||
fixedTime = fixedTime,
|
||||
fixedColorPhase = fixedColorPhase,
|
||||
@@ -162,25 +146,6 @@ fun MorphingSphere(
|
||||
}
|
||||
}
|
||||
}
|
||||
val idleBreathPhase = remember { mutableFloatStateOf(0f) }
|
||||
LaunchedEffect(motionMode) {
|
||||
if (motionMode != SphereMotionMode.AmbientLayer) {
|
||||
idleBreathPhase.floatValue = 0f
|
||||
return@LaunchedEffect
|
||||
}
|
||||
var lastNanos = withFrameNanos { it }
|
||||
while (true) {
|
||||
val now = withFrameNanos { it }
|
||||
val dtSec = (now - lastNanos).coerceAtLeast(0L) / 1_000_000_000f
|
||||
lastNanos = now
|
||||
idleBreathPhase.floatValue =
|
||||
(idleBreathPhase.floatValue + dtSec * SPHERE_IDLE_BREATH_RADIANS_PER_SEC) %
|
||||
SPHERE_TWO_PI
|
||||
// The frame wait plus this delay caps the gentle layer-only pulse
|
||||
// near 5fps while active procedural states retain display-rate motion.
|
||||
delay(SPHERE_IDLE_LAYER_FRAME_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
val time = fixedTime ?: animatedTime.floatValue
|
||||
val colorPhase = fixedColorPhase ?: animatedColorPhase.floatValue
|
||||
@@ -192,18 +157,7 @@ fun MorphingSphere(
|
||||
val textMeasurer = rememberTextMeasurer(cacheSize = 64)
|
||||
val glyphStrings = remember { HashMap<Char, String>(32) }
|
||||
|
||||
Canvas(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.graphicsLayer {
|
||||
if (motionMode == SphereMotionMode.AmbientLayer) {
|
||||
val scale = 1f + sin(idleBreathPhase.floatValue) * SPHERE_IDLE_BREATH_SCALE
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
}
|
||||
}
|
||||
.clipToBounds(),
|
||||
) {
|
||||
Canvas(modifier = modifier.fillMaxSize().clipToBounds()) {
|
||||
val canvasW = size.width
|
||||
val canvasH = size.height
|
||||
val cellW = canvasW / cols
|
||||
|
||||
@@ -109,6 +109,7 @@ import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.ChatSession
|
||||
import com.hermesandroid.relay.data.SessionActivityState
|
||||
import com.hermesandroid.relay.data.SupervisedSessionActions
|
||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.ui.theme.ProfileAccentSwatches
|
||||
@@ -208,6 +209,8 @@ fun SessionDrawerContent(
|
||||
animationEnabled: Boolean = true,
|
||||
autoTitlesSupported: Boolean = true,
|
||||
archiveSupported: Boolean = true,
|
||||
supervisedSessionActions: SupervisedSessionActions? = null,
|
||||
newChatEnabled: Boolean = true,
|
||||
onRefresh: (() -> Unit)? = null,
|
||||
/** Opens the separate Bot Mode messenger workspace; never changes drawer filters. */
|
||||
onOpenBotMode: (() -> Unit)? = null,
|
||||
@@ -288,8 +291,10 @@ fun SessionDrawerContent(
|
||||
allowBareSessionIds = !showAllProfiles,
|
||||
)
|
||||
val sourceSessions = sourceRows.map { it.session }
|
||||
val showThreads = threadsCapabilityActive || sourceSessions.any { isThreadSource(it.source) }
|
||||
val activeFilter = resolveSessionDrawerFilter(filter, showThreads, archiveSupported)
|
||||
val showThreads = supervisedSessionActions == null &&
|
||||
(threadsCapabilityActive || sourceSessions.any { isThreadSource(it.source) })
|
||||
val effectiveArchiveSupported = archiveSupported && supervisedSessionActions?.archive != false
|
||||
val activeFilter = resolveSessionDrawerFilter(filter, showThreads, effectiveArchiveSupported)
|
||||
// External gateway sources present (discord/telegram/cron/…) for the source
|
||||
// filter dropdown. Own chats (tui/api_server) + phone Threads aren't listed.
|
||||
val presentSources = sourceSessions
|
||||
@@ -405,7 +410,7 @@ fun SessionDrawerContent(
|
||||
)
|
||||
// Source filter — show/hide gateway sources (default hides the
|
||||
// noisy cron+webhook). Only when external sources are present.
|
||||
if (onToggleSourceHidden != null && presentSources.isNotEmpty()) {
|
||||
if (supervisedSessionActions == null && onToggleSourceHidden != null && presentSources.isNotEmpty()) {
|
||||
Box {
|
||||
IconButton(
|
||||
onClick = { sourceFilterOpen = true },
|
||||
@@ -466,7 +471,7 @@ fun SessionDrawerContent(
|
||||
// Threads affordance — a clean thread-spool that toggles the Threads
|
||||
// filter. Shown only when the Threads capability is active (or a Thread is
|
||||
// already present), so an ordinary no-relay drawer is visually unchanged.
|
||||
if (showThreads) {
|
||||
if (supervisedSessionActions == null && showThreads) {
|
||||
IconButton(
|
||||
onClick = {
|
||||
filter = if (filter == SessionDrawerFilter.Threads) {
|
||||
@@ -537,7 +542,8 @@ fun SessionDrawerContent(
|
||||
onNewChat()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
enabled = newChatEnabled,
|
||||
) {
|
||||
Icon(Icons.Filled.Add, contentDescription = null)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
@@ -602,8 +608,10 @@ fun SessionDrawerContent(
|
||||
}
|
||||
SessionDrawerFilter.entries
|
||||
.filter { item ->
|
||||
(item != SessionDrawerFilter.Threads || showThreads) &&
|
||||
(item != SessionDrawerFilter.Archive || archiveSupported)
|
||||
(item != SessionDrawerFilter.Threads ||
|
||||
(supervisedSessionActions == null && showThreads)) &&
|
||||
(item != SessionDrawerFilter.Archive ||
|
||||
effectiveArchiveSupported)
|
||||
}
|
||||
.forEach { item ->
|
||||
FilterChip(
|
||||
@@ -635,17 +643,19 @@ fun SessionDrawerContent(
|
||||
)
|
||||
}
|
||||
}
|
||||
TextButton(
|
||||
onClick = { customizeOpen = true },
|
||||
modifier = Modifier.align(Alignment.Start),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.FilterList,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(stringResource(R.string.drawer_customize_sessions))
|
||||
if (supervisedSessionActions == null) {
|
||||
TextButton(
|
||||
onClick = { customizeOpen = true },
|
||||
modifier = Modifier.align(Alignment.Start),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.FilterList,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(stringResource(R.string.drawer_customize_sessions))
|
||||
}
|
||||
}
|
||||
// "+ New Thread" — Discord-style user-created thread, shown when the
|
||||
// Threads filter is active. The first message opens the conversation.
|
||||
@@ -779,13 +789,20 @@ fun SessionDrawerContent(
|
||||
showTokens = viewOptions.showTokens,
|
||||
showCost = viewOptions.showCost,
|
||||
nowMillis = drawerNowMillis,
|
||||
actionsEnabled = !provisional,
|
||||
actionsEnabled = !provisional && (
|
||||
supervisedSessionActions == null ||
|
||||
supervisedSessionActions.pin ||
|
||||
supervisedSessionActions.rename ||
|
||||
supervisedSessionActions.delete ||
|
||||
(supervisedSessionActions.archive && archiveSupported)
|
||||
),
|
||||
isActive = !showAllProfiles && session.sessionId == currentSessionId,
|
||||
activityState = activityState,
|
||||
animationEnabled = animationEnabled && isOpen,
|
||||
pinned = session.pinned,
|
||||
archived = session.archived,
|
||||
archiveSupported = archiveSupported,
|
||||
supervisedSessionActions = supervisedSessionActions,
|
||||
onClick = {
|
||||
if (showAllProfiles) {
|
||||
onSelectProfileSession?.invoke(row.profile, session.sessionId)
|
||||
@@ -1347,6 +1364,7 @@ private fun SessionItem(
|
||||
pinned: Boolean,
|
||||
archived: Boolean,
|
||||
archiveSupported: Boolean,
|
||||
supervisedSessionActions: SupervisedSessionActions?,
|
||||
onClick: () -> Unit,
|
||||
onTogglePinned: () -> Unit,
|
||||
onToggleArchived: () -> Unit,
|
||||
@@ -1510,7 +1528,7 @@ private fun SessionItem(
|
||||
expanded = menuOpen,
|
||||
onDismissRequest = { menuOpen = false },
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
if (supervisedSessionActions?.pin != false) DropdownMenuItem(
|
||||
text = {
|
||||
Text(
|
||||
if (pinned) {
|
||||
@@ -1536,7 +1554,7 @@ private fun SessionItem(
|
||||
onTogglePinned()
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
if (supervisedSessionActions == null) DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.chat_copy_session_id)) },
|
||||
leadingIcon = {
|
||||
Icon(Icons.Filled.ContentCopy, contentDescription = null)
|
||||
@@ -1546,7 +1564,7 @@ private fun SessionItem(
|
||||
onCopySessionId()
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
if (supervisedSessionActions?.rename != false) DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.drawer_rename)) },
|
||||
leadingIcon = {
|
||||
Icon(Icons.Filled.Edit, contentDescription = null)
|
||||
@@ -1556,7 +1574,7 @@ private fun SessionItem(
|
||||
onRename()
|
||||
},
|
||||
)
|
||||
if (archiveSupported) {
|
||||
if (archiveSupported && supervisedSessionActions?.archive != false) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(if (archived) stringResource(R.string.drawer_restore) else stringResource(R.string.drawer_archive)) },
|
||||
leadingIcon = {
|
||||
@@ -1576,7 +1594,7 @@ private fun SessionItem(
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenuItem(
|
||||
if (supervisedSessionActions?.delete != false) DropdownMenuItem(
|
||||
text = {
|
||||
Text(
|
||||
text = stringResource(R.string.drawer_delete),
|
||||
@@ -1752,19 +1770,9 @@ private fun Modifier.sessionActivityBorder(
|
||||
state: SessionActivityState?,
|
||||
animated: Boolean,
|
||||
): Modifier {
|
||||
if (state == null) return this
|
||||
val color = when (state) {
|
||||
SessionActivityState.Starting,
|
||||
SessionActivityState.Working -> RelayRefresh.Relay
|
||||
SessionActivityState.NeedsInput -> RelayRefresh.Amber
|
||||
SessionActivityState.BackgroundWork,
|
||||
SessionActivityState.Checking,
|
||||
SessionActivityState.Unavailable,
|
||||
-> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
val shouldRotate = animated && (
|
||||
state == SessionActivityState.Starting || state == SessionActivityState.Working
|
||||
)
|
||||
if (!sessionActivityShowsRowBorder(state)) return this
|
||||
val color = RelayRefresh.Relay
|
||||
val shouldRotate = animated
|
||||
val phase = if (shouldRotate) {
|
||||
val transition = rememberInfiniteTransition(label = "session-activity")
|
||||
transition.animateFloat(
|
||||
|
||||
@@ -84,6 +84,10 @@ internal fun sessionDrawerStatus(
|
||||
null -> SessionDrawerStatus.Idle
|
||||
}
|
||||
|
||||
/** Desktop-style row emphasis is reserved for an actual foreground turn. */
|
||||
internal fun sessionActivityShowsRowBorder(state: SessionActivityState?): Boolean =
|
||||
state == SessionActivityState.Starting || state == SessionActivityState.Working
|
||||
|
||||
/**
|
||||
* Normalizes live activity to the drawer's profile-scoped row identity.
|
||||
*
|
||||
|
||||
@@ -87,6 +87,8 @@ fun AboutScreen(
|
||||
connectionViewModel: ConnectionViewModel,
|
||||
onBack: () -> Unit,
|
||||
onUnlockDeveloperOptions: () -> Unit = {},
|
||||
/** Supervised clients may read About without gaining a settings mutation backdoor. */
|
||||
allowDeveloperUnlock: Boolean = true,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
@@ -218,7 +220,7 @@ fun AboutScreen(
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
.clickable(enabled = allowDeveloperUnlock) {
|
||||
if (devOptionsUnlocked) return@clickable
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - lastTapTime > 2000) {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Security
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.ui.theme.LocalBrand
|
||||
|
||||
/** Optional and specialized features kept off the primary Settings surface. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AdvancedSettingsScreen(
|
||||
supervisedPolicy: SupervisedModePolicy,
|
||||
onNavigateToSupervisedControls: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = stringResource(R.string.settings_back),
|
||||
)
|
||||
}
|
||||
},
|
||||
title = { Text(stringResource(R.string.settings_advanced)) },
|
||||
colors = TopAppBarDefaults.topAppBarColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
),
|
||||
)
|
||||
},
|
||||
) { innerPadding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(innerPadding)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp, vertical = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_advanced_intro),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Security,
|
||||
title = stringResource(R.string.settings_supervised_mode),
|
||||
subtitle = when {
|
||||
supervisedPolicy.isActive -> stringResource(
|
||||
R.string.settings_supervised_on_profile,
|
||||
supervisedPolicy.pinnedProfileName.orEmpty(),
|
||||
)
|
||||
supervisedPolicy.isConfigured -> stringResource(
|
||||
R.string.settings_supervised_ready_profile,
|
||||
supervisedPolicy.pinnedProfileName.orEmpty(),
|
||||
)
|
||||
else -> stringResource(R.string.settings_supervised_desc)
|
||||
},
|
||||
badge = supervisedPolicy.takeIf { it.isActive }?.let {
|
||||
SettingsStatusPillModel(
|
||||
label = stringResource(R.string.settings_supervised_on),
|
||||
tone = SettingsStatusTone.Good,
|
||||
)
|
||||
},
|
||||
onClick = onNavigateToSupervisedControls,
|
||||
isDarkTheme = isDarkTheme,
|
||||
petPerchKey = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
-18
@@ -1487,26 +1487,27 @@ private fun AppearanceSummaryRow(
|
||||
|
||||
/** Representative, theme-live chat sample so presets are judged in context. */
|
||||
@Composable
|
||||
private fun AppearanceLivePreview(
|
||||
internal fun AppearanceLivePreview(
|
||||
palette: BrandPalette,
|
||||
shapeScale: AppearanceShapeScale,
|
||||
restricted: Boolean = false,
|
||||
) {
|
||||
CompositionLocalProvider(
|
||||
LocalBrand provides palette,
|
||||
LocalAppearanceShapeScale provides shapeScale,
|
||||
) {
|
||||
MaterialTheme(colorScheme = palette.toColorScheme(), shapes = shapeScale.asMaterialShapes()) {
|
||||
AppearanceLivePreviewContent()
|
||||
AppearanceLivePreviewContent(restricted = restricted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AppearanceLivePreviewContent() {
|
||||
private fun AppearanceLivePreviewContent(restricted: Boolean) {
|
||||
val backgroundEnabled = LocalBackgroundVisualizationEnabled.current
|
||||
val backgroundAvatar = LocalAgentAvatar.current
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth().height(294.dp),
|
||||
modifier = Modifier.fillMaxWidth().height(if (restricted) 258.dp else 294.dp),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow),
|
||||
border = androidx.compose.foundation.BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
@@ -1648,14 +1649,16 @@ private fun AppearanceLivePreviewContent() {
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontSize = 8.sp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(6.dp).clip(CircleShape).background(LocalBrand.current.green))
|
||||
Text(
|
||||
text = stringResource(R.string.appearance_preview_tool_meta),
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp),
|
||||
color = LocalBrand.current.green,
|
||||
modifier = Modifier.padding(start = 5.dp),
|
||||
)
|
||||
if (!restricted) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(6.dp).clip(CircleShape).background(LocalBrand.current.green))
|
||||
Text(
|
||||
text = stringResource(R.string.appearance_preview_tool_meta),
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp),
|
||||
color = LocalBrand.current.green,
|
||||
modifier = Modifier.padding(start = 5.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Box(modifier = Modifier.padding(start = 6.dp).size(38.dp), contentAlignment = Alignment.Center) {
|
||||
@@ -1678,10 +1681,12 @@ private fun AppearanceLivePreviewContent() {
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(Icons.Filled.Add, null, Modifier.size(18.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text("gpt-5.6-sol", style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp))
|
||||
Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(14.dp))
|
||||
Text("High", style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp))
|
||||
Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(14.dp))
|
||||
if (!restricted) {
|
||||
Text("gpt-5.6-sol", style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp))
|
||||
Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(14.dp))
|
||||
Text("High", style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp))
|
||||
Icon(Icons.Filled.KeyboardArrowDown, null, Modifier.size(14.dp))
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.appearance_preview_message_placeholder),
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontSize = 9.sp),
|
||||
@@ -1691,7 +1696,7 @@ private fun AppearanceLivePreviewContent() {
|
||||
Icon(Icons.Filled.GraphicEq, null, Modifier.size(18.dp), tint = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
if (!restricted) Surface(
|
||||
modifier = Modifier.align(Alignment.CenterHorizontally),
|
||||
shape = appearanceRoundedCornerShape(16.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
@@ -1785,7 +1790,7 @@ private fun FontOptionRow(
|
||||
* are added.
|
||||
*/
|
||||
@Composable
|
||||
private fun ThemeSwatchChip(
|
||||
internal fun ThemeSwatchChip(
|
||||
appTheme: AppTheme,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
|
||||
@@ -50,6 +50,7 @@ import androidx.compose.material.icons.filled.Code
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.Menu
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
@@ -147,6 +148,7 @@ import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material3.SmallFloatingActionButton
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.SnackbarDuration
|
||||
import androidx.compose.material3.SnackbarResult
|
||||
@@ -179,6 +181,11 @@ import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.PhysicalKeyboardEnterBehavior
|
||||
import com.hermesandroid.relay.data.ProfilePresentationPolicy
|
||||
import com.hermesandroid.relay.data.ProactiveInboxEntry
|
||||
import com.hermesandroid.relay.data.SessionActivityState
|
||||
import com.hermesandroid.relay.data.SupervisedAttachmentCategory
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.SupervisedSessionAction
|
||||
import com.hermesandroid.relay.data.allowsSessionAction
|
||||
import com.hermesandroid.relay.data.VoicePresentationMode
|
||||
import com.hermesandroid.relay.data.hermesProcessNotificationOrNull
|
||||
import com.hermesandroid.relay.ui.components.AgentInfoSheet
|
||||
@@ -186,6 +193,9 @@ import com.hermesandroid.relay.ui.components.BackgroundTaskCard
|
||||
import com.hermesandroid.relay.ui.components.LocalRelayServerImageResolver
|
||||
import com.hermesandroid.relay.ui.components.RelayServerImageResolver
|
||||
import com.hermesandroid.relay.ui.components.ChatInputBar
|
||||
import com.hermesandroid.relay.ui.components.ChatGitContextButton
|
||||
import com.hermesandroid.relay.ui.components.ChatGitWorkspaceRail
|
||||
import com.hermesandroid.relay.ui.components.ChatGitWorkspaceSummary
|
||||
import com.hermesandroid.relay.ui.components.ChatFailureDetailsDialog
|
||||
import com.hermesandroid.relay.ui.components.ChatFailurePanel
|
||||
import com.hermesandroid.relay.viewmodel.ChatFailureRoute
|
||||
@@ -710,8 +720,43 @@ fun ChatScreen(
|
||||
// existing test/preview call sites keep compiling.
|
||||
onNavigateToVoiceSettings: () -> Unit = {},
|
||||
onNavigateToProfileInspector: (String) -> Unit = {},
|
||||
supervisedPolicy: SupervisedModePolicy = SupervisedModePolicy(),
|
||||
onNavigateToBotMode: () -> Unit = {},
|
||||
gitWorkspaceSummary: ChatGitWorkspaceSummary? = null,
|
||||
gitWorkspaceAvailable: Boolean = gitWorkspaceSummary != null,
|
||||
onNavigateToGitWorkspace: () -> Unit = {},
|
||||
) {
|
||||
val supervised = supervisedPolicy.enabled
|
||||
val supervisedVisibility = supervisedPolicy.visibility.resolved()
|
||||
LaunchedEffect(supervisedPolicy) {
|
||||
voiceViewModel.updateSupervisedModePolicy(supervisedPolicy)
|
||||
}
|
||||
if (supervised && !supervisedPolicy.isActive) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Supervised chat unavailable") },
|
||||
actions = {
|
||||
IconButton(onClick = onNavigateToSettings) {
|
||||
Icon(Icons.Filled.Settings, contentDescription = "Settings")
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize().padding(padding).padding(24.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
"The supervised profile is unavailable. Parent access is required to update this connection.",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
val voiceUiState by voiceViewModel.uiState.collectAsState()
|
||||
val responseSpeechActive by voiceViewModel.responseSpeechActive.collectAsState()
|
||||
val isDemoMode by connectionViewModel.isDemoMode.collectAsState()
|
||||
@@ -734,7 +779,6 @@ fun ChatScreen(
|
||||
LaunchedEffect(voiceUiState.voiceMode) {
|
||||
if (!voiceUiState.voiceMode) voicePresentationOverride = null
|
||||
}
|
||||
|
||||
// Route classified chat errors (media cache, streaming failures, …) to
|
||||
// the app-wide snackbar. Same pattern every VM-bound screen uses.
|
||||
val snackbarHost = LocalSnackbarHost.current
|
||||
@@ -796,7 +840,22 @@ fun ChatScreen(
|
||||
}
|
||||
|
||||
|
||||
val messages by chatViewModel.messages.collectAsState()
|
||||
val rawMessages by chatViewModel.messages.collectAsState()
|
||||
val messages = remember(rawMessages, supervised, supervisedPolicy.capabilities.generatedImages) {
|
||||
if (!supervised) rawMessages
|
||||
else rawMessages.map { message ->
|
||||
if (message.role == MessageRole.ASSISTANT) {
|
||||
message.copy(
|
||||
attachments = if (supervisedPolicy.capabilities.generatedImages) {
|
||||
message.attachments.filter { it.isImage }
|
||||
} else {
|
||||
emptyList()
|
||||
},
|
||||
cards = emptyList(),
|
||||
)
|
||||
} else message
|
||||
}
|
||||
}
|
||||
val messageReactionsSupported by chatViewModel.messageReactionsSupported.collectAsState()
|
||||
val newestReactableMessageKeys = remember(messages) {
|
||||
setOfNotNull(
|
||||
@@ -823,10 +882,17 @@ fun ChatScreen(
|
||||
// Stable voice can use the standard Hermes dashboard audio routes or the
|
||||
// optional Relay voice routes. Gate the mic on either route being usable;
|
||||
// availability picks the actionable toast when neither is.
|
||||
val voiceReady by connectionViewModel.voiceReady.collectAsState()
|
||||
val connectionVoiceReady by connectionViewModel.voiceReady.collectAsState()
|
||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||
val voiceReady = if (supervised) {
|
||||
supervisedPolicy.capabilities.voice &&
|
||||
standardVoiceAvailability ==
|
||||
com.hermesandroid.relay.viewmodel.StandardVoiceAvailability.Ready
|
||||
} else {
|
||||
connectionVoiceReady
|
||||
}
|
||||
val chatSpeakResponseActionsEnabled =
|
||||
shouldOfferChatSpeakAction(voiceReady, voiceUiState.state)
|
||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||
val standardVoiceSignInRouteHint by
|
||||
connectionViewModel.standardVoiceSignInRouteHint.collectAsState()
|
||||
val dashboardRouteMovedHint by connectionViewModel.dashboardRouteMovedHint.collectAsState()
|
||||
@@ -990,8 +1056,15 @@ fun ChatScreen(
|
||||
?: sessionModelState.pickerModel?.let { model ->
|
||||
modelProviders.singleOrNull { model in it.models }?.slug
|
||||
}
|
||||
val showThinking by connectionViewModel.showThinking.collectAsState()
|
||||
val toolDisplay by connectionViewModel.toolDisplay.collectAsState()
|
||||
val configuredShowThinking by connectionViewModel.showThinking.collectAsState()
|
||||
val configuredToolDisplay by connectionViewModel.toolDisplay.collectAsState()
|
||||
val showThinking = configuredShowThinking &&
|
||||
(!supervised || supervisedVisibility.showReasoning)
|
||||
val toolDisplay = if (!supervised) configuredToolDisplay else when {
|
||||
supervisedVisibility.showToolDetails -> "detailed"
|
||||
supervisedVisibility.showToolNames -> "compact"
|
||||
else -> "off"
|
||||
}
|
||||
val smoothAutoScroll by connectionViewModel.smoothAutoScroll.collectAsState()
|
||||
val closeDrawerOnSend by connectionViewModel.closeDrawerOnSend.collectAsState()
|
||||
val keepComposerFocusedOnSend by
|
||||
@@ -1000,6 +1073,13 @@ fun ChatScreen(
|
||||
connectionViewModel.physicalKeyboardEnterBehavior.collectAsState()
|
||||
val convertLargePastesToAttachments by
|
||||
connectionViewModel.convertLargePastesToAttachments.collectAsState()
|
||||
val showGitWorkspaceInChat by
|
||||
connectionViewModel.showGitWorkspaceInChat.collectAsState()
|
||||
val visibleGitWorkspaceSummary = gitWorkspaceSummary?.takeIf {
|
||||
!supervised && showGitWorkspaceInChat && it.branch.isNotBlank()
|
||||
}
|
||||
val showGitWorkspaceContextEntry =
|
||||
!supervised && showGitWorkspaceInChat && gitWorkspaceAvailable
|
||||
|
||||
val availableSkills by chatViewModel.availableSkills.collectAsState()
|
||||
val queuedMessages by chatViewModel.queuedMessages.collectAsState()
|
||||
@@ -1010,7 +1090,10 @@ fun ChatScreen(
|
||||
// marker so the user knows approvals are off without opening the agent drawer.
|
||||
val yoloEnabled by chatViewModel.yoloEnabled.collectAsState()
|
||||
val pendingAttachments by chatViewModel.pendingAttachments.collectAsState()
|
||||
val maxAttachmentMb by connectionViewModel.maxAttachmentMb.collectAsState()
|
||||
val configuredMaxAttachmentMb by connectionViewModel.maxAttachmentMb.collectAsState()
|
||||
val maxAttachmentMb = if (supervised) {
|
||||
minOf(configuredMaxAttachmentMb, supervisedPolicy.capabilities.attachmentMaxFileMb)
|
||||
} else configuredMaxAttachmentMb
|
||||
val charLimit by connectionViewModel.maxMessageLength.collectAsState()
|
||||
|
||||
// === Gateway desktop-parity state ===
|
||||
@@ -1019,6 +1102,9 @@ fun ChatScreen(
|
||||
val contextWindow by chatViewModel.contextWindow.collectAsState()
|
||||
// Injected-context audit sheet (opened by tapping the context meter).
|
||||
var showContextSheet by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(supervised) {
|
||||
if (supervised) showContextSheet = false
|
||||
}
|
||||
val steerableTurn by chatViewModel.steerableTurn.collectAsState()
|
||||
val steerNotice by chatViewModel.steerNotice.collectAsState()
|
||||
val voiceHintSeen by connectionViewModel.voiceHintSeen.collectAsState()
|
||||
@@ -2020,9 +2106,9 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
val showAutocomplete by remember(filteredCommands, inputText) {
|
||||
val showAutocomplete by remember(filteredCommands, inputText, supervised) {
|
||||
derivedStateOf {
|
||||
inputText.startsWith("/") && filteredCommands.isNotEmpty()
|
||||
!supervised && inputText.startsWith("/") && filteredCommands.isNotEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2295,7 +2381,7 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
val selectedProfileKey = AgentDisplay.profileSessionKey(selectedProfile?.name)
|
||||
val profileShelfAvailable = ProfilePresentationPolicy.shouldShowShelf(
|
||||
val profileShelfAvailable = !supervised && ProfilePresentationPolicy.shouldShowShelf(
|
||||
profiles = agentProfiles,
|
||||
presentation = profilePresentation,
|
||||
selectedKey = selectedProfileKey,
|
||||
@@ -2322,7 +2408,7 @@ fun ChatScreen(
|
||||
// Material routes scrim taps through the drawer's gesture handler.
|
||||
// Keep it enabled so tapping outside always dismisses the drawer; the
|
||||
// voice overlay already owns input while voice mode is visible.
|
||||
gesturesEnabled = true,
|
||||
gesturesEnabled = !supervised || supervisedPolicy.capabilities.conversationHistory,
|
||||
drawerContent = {
|
||||
val drawerProfileName = explicitBindingProfileName ?: effectiveProfile?.name
|
||||
val drawerTitle = if (drawerProfileName != null) {
|
||||
@@ -2366,7 +2452,9 @@ fun ChatScreen(
|
||||
}
|
||||
|
||||
SessionDrawerContent(
|
||||
sessions = sessions,
|
||||
sessions = if (
|
||||
supervised && !supervisedPolicy.capabilities.conversationHistory
|
||||
) emptyList() else sessions,
|
||||
currentSessionId = currentSessionId,
|
||||
scopeTitle = drawerTitle,
|
||||
scopeSubtitle = drawerSubtitle,
|
||||
@@ -2377,14 +2465,19 @@ fun ChatScreen(
|
||||
animationEnabled = animationEnabled,
|
||||
autoTitlesSupported = serverAutoTitles,
|
||||
archiveSupported = sessionArchivingSupported,
|
||||
supervisedSessionActions = supervisedPolicy.capabilities.sessionActions
|
||||
.takeIf { supervised },
|
||||
newChatEnabled = !supervised || supervisedPolicy.capabilities.newChat,
|
||||
onRefresh = { chatViewModel.refreshSessions() },
|
||||
onOpenBotMode = {
|
||||
scope.launch { drawerState.close() }
|
||||
onNavigateToBotMode()
|
||||
},
|
||||
onNewChat = {
|
||||
chatViewModel.createNewChat()
|
||||
scope.launch { drawerState.close() }
|
||||
if (!supervised || supervisedPolicy.capabilities.newChat) {
|
||||
chatViewModel.createNewChat()
|
||||
scope.launch { drawerState.close() }
|
||||
}
|
||||
},
|
||||
onNewDefaultChat = {
|
||||
if (isProfileLocked) return@SessionDrawerContent
|
||||
@@ -2410,6 +2503,9 @@ fun ChatScreen(
|
||||
scope.launch { drawerState.close() }
|
||||
},
|
||||
onDeleteSession = { sessionId ->
|
||||
if (supervised && !supervisedPolicy.allowsSessionAction(SupervisedSessionAction.Delete)) {
|
||||
return@SessionDrawerContent
|
||||
}
|
||||
val connectionId = activeConnection?.id
|
||||
val profileId = explicitBindingProfileName ?: selectedProfile?.name
|
||||
chatViewModel.deleteSession(sessionId) {
|
||||
@@ -2423,10 +2519,21 @@ fun ChatScreen(
|
||||
}
|
||||
},
|
||||
onRenameSession = { sessionId, title ->
|
||||
if (supervised && !supervisedPolicy.allowsSessionAction(SupervisedSessionAction.Rename)) {
|
||||
return@SessionDrawerContent
|
||||
}
|
||||
chatViewModel.renameSession(sessionId, title)
|
||||
},
|
||||
onSetSessionPinned = chatViewModel::setSessionPinned,
|
||||
onSetSessionArchived = chatViewModel::setSessionArchived,
|
||||
onSetSessionPinned = { sessionId, pinned ->
|
||||
if (!supervised || supervisedPolicy.allowsSessionAction(SupervisedSessionAction.Pin)) {
|
||||
chatViewModel.setSessionPinned(sessionId, pinned)
|
||||
}
|
||||
},
|
||||
onSetSessionArchived = { sessionId, archived ->
|
||||
if (!supervised || supervisedPolicy.allowsSessionAction(SupervisedSessionAction.Archive)) {
|
||||
chatViewModel.setSessionArchived(sessionId, archived)
|
||||
}
|
||||
},
|
||||
onCopySessionId = { sessionId ->
|
||||
scope.launch {
|
||||
clipboard.setClipEntry(
|
||||
@@ -2456,7 +2563,7 @@ fun ChatScreen(
|
||||
onToggleSourceHidden = { source, hidden ->
|
||||
connectionViewModel.setSourceHidden(source, hidden)
|
||||
},
|
||||
allProfilesSupported = !isProfileLocked &&
|
||||
allProfilesSupported = !supervised && !isProfileLocked &&
|
||||
!activeConnection?.resolvedDashboardUrl.isNullOrBlank(),
|
||||
allProfileSessions = allProfileSessions,
|
||||
allProfileSessionsLoading = allProfileSessionsLoading,
|
||||
@@ -2577,8 +2684,14 @@ fun ChatScreen(
|
||||
// Top bar — messaging app style with avatar, name, model subtitle
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { scope.launch { drawerState.open() } }) {
|
||||
Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.cd_sessions))
|
||||
if (!supervised || supervisedPolicy.capabilities.conversationHistory) {
|
||||
IconButton(onClick = { scope.launch { drawerState.open() } }) {
|
||||
Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.cd_sessions))
|
||||
}
|
||||
} else if (supervisedPolicy.capabilities.newChat) {
|
||||
IconButton(onClick = { chatViewModel.createNewChat() }) {
|
||||
Icon(Icons.Filled.Edit, contentDescription = "New chat")
|
||||
}
|
||||
}
|
||||
},
|
||||
title = {
|
||||
@@ -2610,8 +2723,10 @@ fun ChatScreen(
|
||||
// style subtitle status.
|
||||
var everConnected by remember { mutableStateOf(false) }
|
||||
if (headerChatReady) everConnected = true
|
||||
val showStreamingState = isStreaming &&
|
||||
(!supervised || supervisedVisibility.showWorkingStatus)
|
||||
val statusText = when {
|
||||
headerChatReady -> if (isStreaming) {
|
||||
headerChatReady -> if (showStreamingState) {
|
||||
stringResource(R.string.chat_streaming)
|
||||
} else {
|
||||
stringResource(R.string.chat_connected_label)
|
||||
@@ -2661,6 +2776,14 @@ fun ChatScreen(
|
||||
// personality label.
|
||||
val subtitleText = if (!headerChatReady) {
|
||||
statusText
|
||||
} else if (supervised) {
|
||||
buildList {
|
||||
if (supervisedVisibility.showProfileName) {
|
||||
conversationProfile?.name?.takeIf { it.isNotBlank() }?.let(::add)
|
||||
}
|
||||
if (supervisedVisibility.showModelName && !modelName.isNullOrBlank()) add(modelName)
|
||||
if (isEmpty() && supervisedVisibility.showConnectionStatus) add(statusText)
|
||||
}.joinToString(" · ")
|
||||
} else {
|
||||
resolveChatHeaderSubtitle(
|
||||
isStreaming = isStreaming,
|
||||
@@ -2679,7 +2802,7 @@ fun ChatScreen(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier
|
||||
.clickable {
|
||||
.clickable(enabled = !supervised) {
|
||||
if (profileShelfAvailable) {
|
||||
showProfileShelf = !showProfileShelf
|
||||
} else {
|
||||
@@ -2703,7 +2826,7 @@ fun ChatScreen(
|
||||
// Avatar — a plain 40dp circle whose letter swaps to the
|
||||
// active agent (profile or personality). No overlay ring:
|
||||
// the letter itself is the indicator.
|
||||
Box(modifier = Modifier.size(40.dp)) {
|
||||
if (!supervised || supervisedVisibility.showAgentIdentity) Box(modifier = Modifier.size(40.dp)) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
@@ -2753,14 +2876,16 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
ConnectionStatusBadge(
|
||||
isConnected = headerChatReady,
|
||||
isConnecting = isConnecting,
|
||||
modifier = Modifier
|
||||
.size(10.dp)
|
||||
.align(Alignment.BottomEnd),
|
||||
size = 10.dp
|
||||
)
|
||||
if (!supervised || supervisedVisibility.showConnectionStatus) {
|
||||
ConnectionStatusBadge(
|
||||
isConnected = headerChatReady,
|
||||
isConnecting = isConnecting,
|
||||
modifier = Modifier
|
||||
.size(10.dp)
|
||||
.align(Alignment.BottomEnd),
|
||||
size = 10.dp,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Name + single-line subtitle.
|
||||
@@ -2801,7 +2926,13 @@ fun ChatScreen(
|
||||
} else {
|
||||
Column {
|
||||
Text(
|
||||
text = if (agentDisplayName.isNotBlank()) agentDisplayName else stringResource(R.string.chat_agent_default),
|
||||
text = if (supervised && !supervisedVisibility.showAgentIdentity) {
|
||||
stringResource(R.string.screen_chat_label)
|
||||
} else if (agentDisplayName.isNotBlank()) {
|
||||
agentDisplayName
|
||||
} else {
|
||||
stringResource(R.string.chat_agent_default)
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
@@ -2838,7 +2969,7 @@ fun ChatScreen(
|
||||
maxLines = 1,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
)
|
||||
if (isStreaming && animationEnabled) {
|
||||
if (showStreamingState && animationEnabled) {
|
||||
StreamingDots(
|
||||
color = subtitleColor,
|
||||
modifier = Modifier.clearAndSetSemantics { },
|
||||
@@ -2859,7 +2990,7 @@ fun ChatScreen(
|
||||
// full explanation (global mode / --yolo / per-session)
|
||||
// lives. Keeps the risk visible without eating subtitle
|
||||
// width on every turn.
|
||||
if (yoloEnabled == true) {
|
||||
if (!supervised && yoloEnabled == true) {
|
||||
RelayChromeIconButton(
|
||||
icon = Icons.Filled.Bolt,
|
||||
contentDescription = stringResource(R.string.cd_approvals_off),
|
||||
@@ -2877,12 +3008,20 @@ fun ChatScreen(
|
||||
// tappable → Connections, so the affordance moved with the
|
||||
// info. Dropping it here declutters the actions row and frees
|
||||
// width for the title subtitle.)
|
||||
RelayChromeIconButton(
|
||||
icon = Icons.Filled.Code,
|
||||
contentDescription = stringResource(R.string.cd_terminal),
|
||||
onClick = onNavigateToTerminal,
|
||||
modifier = Modifier.padding(end = 4.dp),
|
||||
)
|
||||
if (!supervised) {
|
||||
if (showGitWorkspaceContextEntry) {
|
||||
ChatGitContextButton(
|
||||
onClick = onNavigateToGitWorkspace,
|
||||
modifier = Modifier.padding(end = 4.dp),
|
||||
)
|
||||
}
|
||||
RelayChromeIconButton(
|
||||
icon = Icons.Filled.Code,
|
||||
contentDescription = stringResource(R.string.cd_terminal),
|
||||
onClick = onNavigateToTerminal,
|
||||
modifier = Modifier.padding(end = 4.dp),
|
||||
)
|
||||
}
|
||||
RelayChromeIconButton(
|
||||
icon = Icons.Filled.Tune,
|
||||
contentDescription = stringResource(R.string.cd_settings),
|
||||
@@ -2895,7 +3034,11 @@ fun ChatScreen(
|
||||
// Settings — which is what was squeezing the title subtitle.
|
||||
// Session identity is useful before the first message; sharing only appears
|
||||
// once the conversation has content.
|
||||
if (messages.isNotEmpty() || !currentSessionId.isNullOrBlank()) {
|
||||
if (
|
||||
(!supervised && (messages.isNotEmpty() || !currentSessionId.isNullOrBlank())) ||
|
||||
(supervised && messages.isNotEmpty() &&
|
||||
supervisedPolicy.allowsSessionAction(SupervisedSessionAction.ShareTranscript))
|
||||
) {
|
||||
var showOverflowMenu by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
RelayChromeIconButton(
|
||||
@@ -2908,7 +3051,7 @@ fun ChatScreen(
|
||||
expanded = showOverflowMenu,
|
||||
onDismissRequest = { showOverflowMenu = false },
|
||||
) {
|
||||
currentSessionId?.takeIf { it.isNotBlank() }?.let { sessionId ->
|
||||
currentSessionId?.takeIf { !supervised && it.isNotBlank() }?.let { sessionId ->
|
||||
DropdownMenuItem(
|
||||
text = { Text(copySessionIdLabel) },
|
||||
leadingIcon = {
|
||||
@@ -2933,7 +3076,7 @@ fun ChatScreen(
|
||||
},
|
||||
)
|
||||
}
|
||||
if (messages.isNotEmpty()) {
|
||||
if (!supervised && messages.isNotEmpty()) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.chat_search_conversation)) },
|
||||
leadingIcon = {
|
||||
@@ -2957,6 +3100,22 @@ fun ChatScreen(
|
||||
shareConversation(context, messages)
|
||||
},
|
||||
)
|
||||
} else if (
|
||||
messages.isNotEmpty() &&
|
||||
supervisedPolicy.allowsSessionAction(
|
||||
SupervisedSessionAction.ShareTranscript,
|
||||
)
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.chat_share_conversation)) },
|
||||
leadingIcon = {
|
||||
Icon(Icons.Filled.Share, contentDescription = null)
|
||||
},
|
||||
onClick = {
|
||||
showOverflowMenu = false
|
||||
shareConversation(context, messages)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2998,13 +3157,15 @@ fun ChatScreen(
|
||||
// and the mode strip — slim bar + `NN% · used/max` token readout,
|
||||
// color-graded by fullness. Composes to nothing until the server
|
||||
// reports a context_max for the session.
|
||||
ContextMeterBar(
|
||||
usedFraction = contextUsage,
|
||||
usedTokens = contextWindow?.usedTokens,
|
||||
maxTokens = contextWindow?.maxTokens,
|
||||
onClick = { showContextSheet = true },
|
||||
)
|
||||
if (showContextSheet) {
|
||||
if (!supervised || supervisedVisibility.showUsage) {
|
||||
ContextMeterBar(
|
||||
usedFraction = contextUsage,
|
||||
usedTokens = contextWindow?.usedTokens,
|
||||
maxTokens = contextWindow?.maxTokens,
|
||||
onClick = if (supervised) null else ({ showContextSheet = true }),
|
||||
)
|
||||
}
|
||||
if (!supervised && showContextSheet) {
|
||||
// Live audit of the exact extra context the agent will be
|
||||
// injected with on the next turn (transparency / auditability).
|
||||
InjectedContextSheet(
|
||||
@@ -3065,7 +3226,31 @@ fun ChatScreen(
|
||||
},
|
||||
label = "chatEmptyStatePhaseTransition",
|
||||
) { targetConnectState ->
|
||||
if (targetConnectState == ChatConnectState.Connecting) {
|
||||
if (supervised && targetConnectState != ChatConnectState.Ready) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (supervisedVisibility.showConnectionStatus) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (targetConnectState == ChatConnectState.Connecting) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
Text(
|
||||
text = if (targetConnectState == ChatConnectState.Connecting) {
|
||||
stringResource(R.string.chat_connecting_dots)
|
||||
} else {
|
||||
stringResource(R.string.chat_disconnected_label)
|
||||
},
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (targetConnectState == ChatConnectState.Connecting) {
|
||||
ChatColdStartLoadingState(
|
||||
animationEnabled = animationEnabled,
|
||||
streamingIntensity = streamingIntensity,
|
||||
@@ -3105,7 +3290,10 @@ fun ChatScreen(
|
||||
Spacer(modifier = Modifier.weight(0.15f))
|
||||
|
||||
// ASCII sphere (constrained to square aspect)
|
||||
if (LocalBackgroundVisualizationEnabled.current) {
|
||||
if (
|
||||
LocalBackgroundVisualizationEnabled.current &&
|
||||
(!supervised || supervisedVisibility.showAgentIdentity)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -3133,7 +3321,10 @@ fun ChatScreen(
|
||||
// thread itself (not just the header) -
|
||||
// the desktop's intro.
|
||||
ChatConnectState.Ready ->
|
||||
if (effectiveProfile != null) {
|
||||
if (
|
||||
effectiveProfile != null &&
|
||||
(!supervised || supervisedVisibility.showAgentIdentity)
|
||||
) {
|
||||
stringResource(R.string.chat_prompt_chat_with, agentDisplayName)
|
||||
} else {
|
||||
stringResource(R.string.chat_start_conversation)
|
||||
@@ -3151,7 +3342,11 @@ fun ChatScreen(
|
||||
val profileBlurb = effectiveProfile?.description
|
||||
?.trim()
|
||||
?.takeIf { it.isNotBlank() && !it.equals(agentDisplayName, ignoreCase = true) }
|
||||
if (targetConnectState == ChatConnectState.Ready && profileBlurb != null) {
|
||||
if (
|
||||
targetConnectState == ChatConnectState.Ready &&
|
||||
profileBlurb != null &&
|
||||
(!supervised || supervisedVisibility.showAgentIdentity)
|
||||
) {
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
Text(
|
||||
text = profileBlurb,
|
||||
@@ -3268,6 +3463,7 @@ fun ChatScreen(
|
||||
// Ambient avatar behind messages
|
||||
if (
|
||||
LocalBackgroundVisualizationEnabled.current &&
|
||||
(!supervised || supervisedVisibility.showAgentIdentity) &&
|
||||
animationBehindChat &&
|
||||
!ambientMode
|
||||
) {
|
||||
@@ -3289,8 +3485,13 @@ fun ChatScreen(
|
||||
// /media/by-path route when a relay session is paired,
|
||||
// instead of degrading to the "image is on the server"
|
||||
// notice. Null when no relay (standard no-plugin) → notice.
|
||||
val relayServerImageResolver = remember(chatViewModel) {
|
||||
RelayServerImageResolver { path -> chatViewModel.resolveServerImage(path) }
|
||||
val relayServerImageResolver = remember(
|
||||
chatViewModel,
|
||||
supervised,
|
||||
supervisedPolicy.capabilities.generatedImages,
|
||||
) {
|
||||
if (supervised && !supervisedPolicy.capabilities.generatedImages) null
|
||||
else RelayServerImageResolver { path -> chatViewModel.resolveServerImage(path) }
|
||||
}
|
||||
val thinkingIndicatorConfig = remember(
|
||||
thinkingIndicatorStyle,
|
||||
@@ -3345,6 +3546,7 @@ fun ChatScreen(
|
||||
items(messages.size, key = { messages[it].uiKey }) { index ->
|
||||
val message = messages[index]
|
||||
val processNotification = message.hermesProcessNotificationOrNull()
|
||||
?.takeIf { !supervised || supervisedVisibility.showToolNames }
|
||||
|
||||
// Skip empty bubbles (content stripped by annotation parser, no tool calls,
|
||||
// no attachments). Attachments keep the bubble alive for inbound media;
|
||||
@@ -3369,7 +3571,10 @@ fun ChatScreen(
|
||||
messages[index + 1].timestamp - message.timestamp > GROUP_GAP_MS
|
||||
|
||||
// Date separator
|
||||
if (index == 0 || !isSameDay(messages[index - 1].timestamp, message.timestamp)) {
|
||||
if (
|
||||
(!supervised || supervisedVisibility.showTimestamps) &&
|
||||
(index == 0 || !isSameDay(messages[index - 1].timestamp, message.timestamp))
|
||||
) {
|
||||
DateSeparator(timestamp = message.timestamp)
|
||||
}
|
||||
|
||||
@@ -3381,7 +3586,9 @@ fun ChatScreen(
|
||||
message.attachments.isNotEmpty() ||
|
||||
message.cards.isNotEmpty()
|
||||
|
||||
message.backgroundTask?.let { task ->
|
||||
message.backgroundTask
|
||||
?.takeIf { !supervised || supervisedVisibility.showWorkingStatus }
|
||||
?.let { task ->
|
||||
val taskModifier = Modifier.padding(
|
||||
top = if (isFirstInGroup) 6.dp else 2.dp,
|
||||
bottom = if (shouldRenderBubble) 3.dp else 0.dp,
|
||||
@@ -3439,6 +3646,14 @@ fun ChatScreen(
|
||||
},
|
||||
maxBubbleWidth = maxBubbleWidth,
|
||||
showThinking = showThinking,
|
||||
showAgentIdentity = !supervised || supervisedVisibility.showAgentIdentity,
|
||||
showTimestamps = !supervised || supervisedVisibility.showTimestamps,
|
||||
showWorkingStatus = !supervised || supervisedVisibility.showWorkingStatus,
|
||||
showUsage = !supervised || supervisedVisibility.showUsage,
|
||||
showTechnicalBadges = !supervised || supervisedVisibility.showTechnicalRoute,
|
||||
showAssistantImages = !supervised || supervisedPolicy.capabilities.generatedImages,
|
||||
allowAssistantImageExport = !supervised ||
|
||||
supervisedPolicy.capabilities.shareGeneratedImages,
|
||||
isFirstInGroup = isFirstInGroup,
|
||||
isLastInGroup = isLastInGroup,
|
||||
recoveringAnswer = recoveringAnswer,
|
||||
@@ -3451,9 +3666,9 @@ fun ChatScreen(
|
||||
onAttachmentManualFetch = { msgId, idx ->
|
||||
chatViewModel.manualFetchAttachment(msgId, idx)
|
||||
},
|
||||
onCardAction = handleCardAction,
|
||||
onCardInput = handleCardInput,
|
||||
onSessionReference = { reference ->
|
||||
onCardAction = if (supervised) ({ _, _, _ -> }) else handleCardAction,
|
||||
onCardInput = if (supervised) ({ _, _, _ -> }) else handleCardInput,
|
||||
onSessionReference = if (supervised) null else { reference ->
|
||||
val target = agentProfiles.firstOrNull {
|
||||
it.name.equals(reference.profile, ignoreCase = true)
|
||||
}
|
||||
@@ -3471,6 +3686,7 @@ fun ChatScreen(
|
||||
}
|
||||
},
|
||||
onReact = if (
|
||||
!supervised &&
|
||||
isGatewayTransport &&
|
||||
messageReactionsSupported &&
|
||||
!message.isStreaming &&
|
||||
@@ -3484,6 +3700,7 @@ fun ChatScreen(
|
||||
null
|
||||
},
|
||||
onEditMessage = if (
|
||||
(!supervised || supervisedPolicy.capabilities.editAndResend) &&
|
||||
isGatewayTransport &&
|
||||
!isStreaming &&
|
||||
message.role == MessageRole.USER &&
|
||||
@@ -3502,10 +3719,14 @@ fun ChatScreen(
|
||||
null
|
||||
},
|
||||
animationEnabled = animationEnabled,
|
||||
onQuoteMessage = { quoted ->
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
quotedMessage = quoted
|
||||
},
|
||||
onQuoteMessage = if (
|
||||
!supervised || supervisedPolicy.capabilities.quoteReplies
|
||||
) {
|
||||
{ quoted ->
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
quotedMessage = quoted
|
||||
}
|
||||
} else null,
|
||||
onNavigateToMessage = { messageId ->
|
||||
val targetIndex = messages.indexOfFirst { it.id == messageId }
|
||||
if (targetIndex >= 0) {
|
||||
@@ -3516,7 +3737,10 @@ fun ChatScreen(
|
||||
scope.launch { listState.animateScrollToItem(targetIndex + 1) }
|
||||
}
|
||||
},
|
||||
onSpeakMessage = if (chatSpeakResponseActionsEnabled) {
|
||||
onSpeakMessage = if (
|
||||
chatSpeakResponseActionsEnabled &&
|
||||
(!supervised || supervisedPolicy.capabilities.voice)
|
||||
) {
|
||||
{ text -> voiceViewModel.speakResponse(text) }
|
||||
} else {
|
||||
null
|
||||
@@ -3527,6 +3751,9 @@ fun ChatScreen(
|
||||
null
|
||||
},
|
||||
onCopyMessage = { text ->
|
||||
if (supervised && !supervisedPolicy.capabilities.copyResponses) {
|
||||
return@MessageBubble
|
||||
}
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
// The new Clipboard API is suspend-based, so the
|
||||
// setClipEntry call has to live inside a coroutine.
|
||||
@@ -3995,7 +4222,8 @@ fun ChatScreen(
|
||||
// Gateway redirect is text-only. Attachment-bearing follow-ups must
|
||||
// retain their files in the session-owned queue instead of showing
|
||||
// a correction action that cannot carry them.
|
||||
val canSteerCurrentMessage = steerableTurn && pendingAttachments.isEmpty()
|
||||
val canSteerCurrentMessage = steerableTurn && pendingAttachments.isEmpty() &&
|
||||
(!supervised || supervisedPolicy.capabilities.steerResponse)
|
||||
val trailing = when {
|
||||
!isStreaming && hasContent -> ChatInputTrailing.SEND
|
||||
!isStreaming -> ChatInputTrailing.VOICE
|
||||
@@ -4128,7 +4356,7 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
val modelControl = modelPickerOptions.takeIf { it.isNotEmpty() }?.let {
|
||||
val modelControl = modelPickerOptions.takeIf { !supervised && it.isNotEmpty() }?.let {
|
||||
ChatInputPickerControl(
|
||||
value = compactModelChipLabel(currentModelForInput, modelDefaultLabel),
|
||||
contentDescription = stringResource(R.string.cd_select_model),
|
||||
@@ -4179,6 +4407,7 @@ fun ChatScreen(
|
||||
// is definitively unreachable (SSE-only) — the agent sheet carries the
|
||||
// disabled-with-reason version there.
|
||||
val effortControl = if (
|
||||
!supervised &&
|
||||
chatGatewayAvailability != GatewayAvailability.Unreachable &&
|
||||
effortAvailability.supported != false &&
|
||||
effortPickerOptions.isNotEmpty()
|
||||
@@ -4195,7 +4424,13 @@ fun ChatScreen(
|
||||
}
|
||||
|
||||
visibleChatFailure?.let { failure ->
|
||||
val failureRouteLabel = when (failure.route) {
|
||||
val displayFailure = if (!supervised) failure else failure.copy(
|
||||
model = failure.model.takeIf { supervisedVisibility.showModelName },
|
||||
provider = failure.provider.takeIf { supervisedVisibility.showTechnicalRoute },
|
||||
)
|
||||
val failureRouteLabel = if (
|
||||
supervised && !supervisedVisibility.showTechnicalRoute
|
||||
) "" else when (failure.route) {
|
||||
ChatFailureRoute.GATEWAY ->
|
||||
stringResource(R.string.chat_failure_route_gateway)
|
||||
ChatFailureRoute.API_FALLBACK ->
|
||||
@@ -4203,23 +4438,28 @@ fun ChatScreen(
|
||||
null -> ""
|
||||
}
|
||||
ChatFailurePanel(
|
||||
failure = failure,
|
||||
failure = displayFailure,
|
||||
routeLabel = failureRouteLabel,
|
||||
onDetails = { showChatFailureDetails = true },
|
||||
onRetry = { chatViewModel.retryLastMessage() },
|
||||
onRetry = {
|
||||
if (!supervised || supervisedPolicy.capabilities.retryResponse) {
|
||||
chatViewModel.retryLastMessage()
|
||||
}
|
||||
},
|
||||
onDismiss = chatViewModel::dismissChatFailure,
|
||||
showDetails = !supervised || supervisedVisibility.showTechnicalRoute,
|
||||
)
|
||||
if (showChatFailureDetails) {
|
||||
ChatFailureDetailsDialog(
|
||||
failure = failure,
|
||||
failure = displayFailure,
|
||||
routeLabel = failureRouteLabel,
|
||||
onCopy = {
|
||||
val details = buildString {
|
||||
append(failureRouteLabel)
|
||||
failure.provider?.takeIf { it.isNotBlank() }?.let { append(" · $it") }
|
||||
failure.model?.takeIf { it.isNotBlank() }?.let { append(" · $it") }
|
||||
displayFailure.provider?.takeIf { it.isNotBlank() }?.let { append(" · $it") }
|
||||
displayFailure.model?.takeIf { it.isNotBlank() }?.let { append(" · $it") }
|
||||
append("\n\n")
|
||||
append(failure.rawError)
|
||||
append(displayFailure.rawError)
|
||||
}
|
||||
scope.launch {
|
||||
clipboard.setClipEntry(
|
||||
@@ -4236,6 +4476,14 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
visibleGitWorkspaceSummary?.let { summary ->
|
||||
ChatGitWorkspaceRail(
|
||||
summary = summary,
|
||||
onClick = onNavigateToGitWorkspace,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
ChatInputBar(
|
||||
value = inputText,
|
||||
onValueChange = { inputText = it },
|
||||
@@ -4301,6 +4549,9 @@ fun ChatScreen(
|
||||
)
|
||||
},
|
||||
onStop = {
|
||||
if (supervised && !supervisedPolicy.capabilities.cancelResponse) {
|
||||
return@ChatInputBar
|
||||
}
|
||||
chatViewModel.cancelStream()
|
||||
// Firm haptic (LongPress — TextHandleMove was near-
|
||||
// imperceptible) plus a "Stopped" badge stamped on the turn
|
||||
@@ -4316,14 +4567,44 @@ fun ChatScreen(
|
||||
}
|
||||
},
|
||||
onAttachPhotos = {
|
||||
photoPickerLauncher.launch(
|
||||
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
|
||||
)
|
||||
val allowed = !supervised || (
|
||||
supervisedPolicy.capabilities.attachments &&
|
||||
SupervisedAttachmentCategory.Images in
|
||||
supervisedPolicy.capabilities.attachmentCategories &&
|
||||
pendingAttachments.size < supervisedPolicy.capabilities.attachmentMaxCount
|
||||
)
|
||||
if (allowed) {
|
||||
photoPickerLauncher.launch(
|
||||
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
|
||||
)
|
||||
}
|
||||
},
|
||||
onAttachFiles = { filePickerLauncher.launch(arrayOf("*/*")) },
|
||||
onAttachCamera = requestCameraCapture,
|
||||
onPasteImage = pasteImageFromClipboard,
|
||||
onLongPressAttach = { showCommandPalette = true },
|
||||
onAttachFiles = {
|
||||
if (!supervised || supervisedPolicy.capabilities.attachments) {
|
||||
val mimeTypes = if (!supervised) arrayOf("*/*") else buildList {
|
||||
val categories = supervisedPolicy.capabilities.attachmentCategories
|
||||
if (SupervisedAttachmentCategory.Images in categories) add("image/*")
|
||||
if (SupervisedAttachmentCategory.Audio in categories) add("audio/*")
|
||||
if (SupervisedAttachmentCategory.Video in categories) add("video/*")
|
||||
if (SupervisedAttachmentCategory.Documents in categories) {
|
||||
add("text/*")
|
||||
add("application/pdf")
|
||||
}
|
||||
}.toTypedArray()
|
||||
if (mimeTypes.isNotEmpty()) filePickerLauncher.launch(mimeTypes)
|
||||
}
|
||||
},
|
||||
onAttachCamera = if (!supervised || (
|
||||
supervisedPolicy.capabilities.attachments &&
|
||||
SupervisedAttachmentCategory.Images in
|
||||
supervisedPolicy.capabilities.attachmentCategories
|
||||
)) requestCameraCapture else ({ }),
|
||||
onPasteImage = if (!supervised || (
|
||||
supervisedPolicy.capabilities.attachments &&
|
||||
SupervisedAttachmentCategory.Images in
|
||||
supervisedPolicy.capabilities.attachmentCategories
|
||||
)) pasteImageFromClipboard else ({ }),
|
||||
onLongPressAttach = { if (!supervised) showCommandPalette = true },
|
||||
charLimit = charLimit,
|
||||
caption = turnStatus ?: inputCaption,
|
||||
voiceReady = voiceReady,
|
||||
@@ -4335,8 +4616,13 @@ fun ChatScreen(
|
||||
submitEnabled = pendingAttachments.none {
|
||||
it.state == com.hermesandroid.relay.data.AttachmentState.LOADING
|
||||
},
|
||||
largePasteThreshold = LARGE_PASTE_THRESHOLD_CHARS
|
||||
.takeIf { convertLargePastesToAttachments },
|
||||
largePasteThreshold = LARGE_PASTE_THRESHOLD_CHARS.takeIf {
|
||||
convertLargePastesToAttachments && (!supervised || (
|
||||
supervisedPolicy.capabilities.attachments &&
|
||||
SupervisedAttachmentCategory.Documents in
|
||||
supervisedPolicy.capabilities.attachmentCategories
|
||||
))
|
||||
},
|
||||
onLargePaste = { pastedText ->
|
||||
val owner = activeComposerDraftKey ?: composerDraftKey
|
||||
val sizeBytes = pastedText.toByteArray(Charsets.UTF_8).size.toLong()
|
||||
@@ -4654,7 +4940,7 @@ fun ChatScreen(
|
||||
}
|
||||
|
||||
// Command palette bottom sheet
|
||||
if (showCommandPalette) {
|
||||
if (showCommandPalette && !supervised) {
|
||||
CommandPalette(
|
||||
commands = allCommands,
|
||||
onSelect = { cmd ->
|
||||
@@ -4682,7 +4968,7 @@ fun ChatScreen(
|
||||
// personality, connection summary). Replaces the old AlertDialog and the
|
||||
// two top-bar chips (ProfilePicker + PersonalityPicker). Tap target is
|
||||
// the title Row in the TopAppBar above.
|
||||
if (showAgentInfo) {
|
||||
if (showAgentInfo && !supervised) {
|
||||
AgentInfoSheet(
|
||||
connectionViewModel = connectionViewModel,
|
||||
chatViewModel = chatViewModel,
|
||||
|
||||
@@ -391,6 +391,32 @@ fun ChatSettingsScreen(
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
val showGitWorkspaceInChat by
|
||||
connectionViewModel.showGitWorkspaceInChat.collectAsState()
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.chat_settings_show_git_workspace),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.chat_settings_show_git_workspace_desc),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = showGitWorkspaceInChat,
|
||||
onCheckedChange = connectionViewModel::setShowGitWorkspaceInChat,
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
val recentPromptsEnabled by
|
||||
connectionViewModel.chatRecentPromptsEnabled.collectAsState()
|
||||
Row(
|
||||
|
||||
@@ -0,0 +1,846 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.AutoAwesome
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.FileUpload
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.GitBranch
|
||||
import com.hermesandroid.relay.data.GitRepo
|
||||
import com.hermesandroid.relay.data.GitStatus
|
||||
import com.hermesandroid.relay.viewmodel.GitConfirmationStrings
|
||||
import com.hermesandroid.relay.viewmodel.GitContentViewState
|
||||
import com.hermesandroid.relay.viewmodel.GitMessageGenerationState
|
||||
import com.hermesandroid.relay.viewmodel.GitMutationState
|
||||
import com.hermesandroid.relay.viewmodel.GitRepoDetailState
|
||||
import com.hermesandroid.relay.viewmodel.GitStateUiState
|
||||
import com.hermesandroid.relay.viewmodel.GitStateViewModel
|
||||
import com.hermesandroid.relay.viewmodel.GitTarget
|
||||
|
||||
private enum class FileFilter { All, Staged, Modified, Untracked }
|
||||
private enum class ContentMode { Diff, File }
|
||||
private data class DisplayFile(
|
||||
val path: String,
|
||||
val filter: FileFilter,
|
||||
val additions: Int?,
|
||||
val deletions: Int?,
|
||||
)
|
||||
|
||||
/** First-class native Git workspace backed by the optional Relay contribution. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GitStateScreen(viewModel: GitStateViewModel, onBack: () -> Unit) {
|
||||
val reposState by viewModel.repos.collectAsState()
|
||||
val detailState by viewModel.detail.collectAsState()
|
||||
val contentState by viewModel.content.collectAsState()
|
||||
val mutation by viewModel.mutation.collectAsState()
|
||||
val messageGeneration by viewModel.messageGeneration.collectAsState()
|
||||
val stashNotice by viewModel.stashNotice.collectAsState()
|
||||
val hasGrant by viewModel.writeGrant.collectAsState()
|
||||
val selectedRepoId by viewModel.selectedRepoId.collectAsState()
|
||||
|
||||
// A path can be staged and modified at the same time. Keep the category in
|
||||
// the selection identity so selecting one row never silently selects the
|
||||
// other layer or disables its correct action.
|
||||
var selection by remember { mutableStateOf(setOf<DisplayFile>()) }
|
||||
var filter by rememberSaveable { mutableStateOf(FileFilter.All) }
|
||||
var expandedPath by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var contentMode by rememberSaveable { mutableStateOf(ContentMode.Diff) }
|
||||
var showRepos by rememberSaveable { mutableStateOf(false) }
|
||||
var showBranches by rememberSaveable { mutableStateOf(false) }
|
||||
var showCommit by rememberSaveable { mutableStateOf(false) }
|
||||
var showOverflow by rememberSaveable { mutableStateOf(false) }
|
||||
var pushAfter by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingConfirm by remember { mutableStateOf<ConfirmationRequest?>(null) }
|
||||
|
||||
val repos = (reposState as? GitStateUiState.Ready)?.repos.orEmpty()
|
||||
val selectedRepo = repos.firstOrNull { it.id == selectedRepoId }
|
||||
val detail = detailState as? GitRepoDetailState.Ready
|
||||
val currentBranch = detail?.branches?.firstOrNull { it.isCurrent }
|
||||
val changeCount = detail?.status?.uniqueChangeCount() ?: 0
|
||||
val stageSelection: () -> Unit = {
|
||||
val unstaged = selection.filter { it.filter != FileFilter.Staged }.map { it.path }
|
||||
if (unstaged.isEmpty()) {
|
||||
viewModel.unstage(selection.map { it.path }.distinct())
|
||||
} else {
|
||||
viewModel.stage(unstaged.distinct())
|
||||
}
|
||||
selection = emptySet()
|
||||
}
|
||||
val discardSelection: () -> Unit = {
|
||||
viewModel.currentTarget()?.let { target ->
|
||||
val discardable = selection.filter { it.filter != FileFilter.Staged }
|
||||
if (discardable.isNotEmpty()) {
|
||||
pendingConfirm = ConfirmationRequest.Discard(
|
||||
paths = discardable.map { it.path }.distinct(),
|
||||
deleteUntracked = discardable.any { it.filter == FileFilter.Untracked },
|
||||
target = target,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(repos, selectedRepoId) {
|
||||
if (repos.size == 1 && selectedRepoId == null) viewModel.selectRepo(repos.single().id)
|
||||
}
|
||||
LaunchedEffect(selectedRepoId) {
|
||||
selection = emptySet()
|
||||
expandedPath = null
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.git_state_back))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Surface(
|
||||
onClick = { showRepos = true },
|
||||
enabled = repos.isNotEmpty(),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = Color.Transparent,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
) {
|
||||
Column(Modifier.padding(horizontal = 10.dp, vertical = 5.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
selectedRepo?.name ?: stringResource(R.string.git_state_title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (repos.isNotEmpty()) Icon(Icons.Filled.ExpandMore, "Choose repository", Modifier.size(20.dp))
|
||||
}
|
||||
selectedRepo?.let {
|
||||
Text(branchSummary(it, currentBranch), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
IconButton(onClick = { selectedRepo?.let { viewModel.selectRepo(it.id) } ?: viewModel.loadRepos() }) {
|
||||
Icon(Icons.Filled.Refresh, "Refresh Git workspace")
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { showOverflow = true }) { Icon(Icons.Filled.MoreVert, "More Git actions") }
|
||||
DropdownMenu(expanded = showOverflow, onDismissRequest = { showOverflow = false }) {
|
||||
DropdownMenuItem(text = { Text("Choose repository") }, onClick = { showOverflow = false; showRepos = true })
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.git_state_branches)) }, enabled = detail != null, onClick = { showOverflow = false; showBranches = true })
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (detail != null) {
|
||||
Surface(shadowElevation = 8.dp, tonalElevation = 2.dp) {
|
||||
Column {
|
||||
if (selection.isNotEmpty()) {
|
||||
SelectionRail(
|
||||
count = selection.size,
|
||||
canWrite = hasGrant,
|
||||
allStaged = selection.all { it.filter == FileFilter.Staged },
|
||||
onStage = stageSelection,
|
||||
onDiscard = discardSelection,
|
||||
)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
OutlinedButton(onClick = { showBranches = true }, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.AccountTree, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.git_state_branches))
|
||||
}
|
||||
Button(onClick = { showCommit = true }, enabled = hasGrant && detail.status.counts.staged > 0, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.AutoAwesome, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.git_state_commit))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
when (val state = reposState) {
|
||||
GitStateUiState.Loading -> FullState(Modifier.padding(padding), true, "Finding repositories")
|
||||
is GitStateUiState.Unavailable -> UnavailableState(Modifier.padding(padding), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Error -> UnavailableState(Modifier.padding(padding), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Ready -> when {
|
||||
state.repos.isEmpty() -> FullState(Modifier.padding(padding), false, "No Git repositories found", "Add a repository to the host's configured Git roots, then refresh.")
|
||||
selectedRepo == null -> RepositoryPrompt(Modifier.padding(padding), state.repos, viewModel::selectRepo)
|
||||
else -> WorkspaceBody(
|
||||
modifier = Modifier.padding(padding),
|
||||
repo = selectedRepo,
|
||||
reposNotice = state.notice,
|
||||
detailState = detailState,
|
||||
mutation = mutation,
|
||||
stashNotice = stashNotice,
|
||||
hasGrant = hasGrant,
|
||||
filter = filter,
|
||||
onFilter = { filter = it },
|
||||
selection = selection,
|
||||
onToggleSelected = { file ->
|
||||
selection = if (file in selection) selection - file else selection + file
|
||||
},
|
||||
expandedPath = expandedPath,
|
||||
contentMode = contentMode,
|
||||
contentState = contentState,
|
||||
onOpen = { file, mode ->
|
||||
if (file.filter != FileFilter.Untracked) {
|
||||
val opening = expandedPath != file.path || contentMode != mode
|
||||
expandedPath = if (opening) file.path else null
|
||||
contentMode = mode
|
||||
if (opening) {
|
||||
if (mode == ContentMode.File) viewModel.loadFile(file.path)
|
||||
else viewModel.loadDiff(file.path, if (file.filter == FileFilter.Staged) "staged" else "unstaged")
|
||||
}
|
||||
}
|
||||
},
|
||||
onFetch = viewModel::fetch,
|
||||
onPull = viewModel::pull,
|
||||
onPush = { viewModel.currentTarget()?.let { pendingConfirm = ConfirmationRequest.Push(it) } },
|
||||
onClearMutation = viewModel::clearMutationError,
|
||||
onRetry = { viewModel.selectRepo(selectedRepo.id) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showRepos) RepositorySheet(repos, selectedRepo?.id, { showRepos = false }) { showRepos = false; viewModel.selectRepo(it) }
|
||||
if (showBranches && detail != null) {
|
||||
BranchSheet(
|
||||
branches = detail.branches,
|
||||
hasGrant = hasGrant,
|
||||
dirty = changeCount > 0,
|
||||
onDismiss = { showBranches = false },
|
||||
onSwitch = { ref ->
|
||||
showBranches = false
|
||||
if (changeCount > 0) viewModel.currentTarget()?.let { pendingConfirm = ConfirmationRequest.DirtyCheckout(ref, it) } else viewModel.checkout(ref)
|
||||
},
|
||||
onStashSwitch = { showBranches = false; viewModel.stashCheckout(it) },
|
||||
onCreate = { name, track -> showBranches = false; viewModel.checkout("", newBranch = name, track = track) },
|
||||
)
|
||||
}
|
||||
if (showCommit && detail != null) {
|
||||
val stagedPaths = detail.status.staged.map { it.path }
|
||||
CommitDialog(
|
||||
hasStaged = stagedPaths.isNotEmpty(),
|
||||
generating = messageGeneration is GitMessageGenerationState.Loading,
|
||||
generatedMessage = (messageGeneration as? GitMessageGenerationState.Ready)?.message.orEmpty(),
|
||||
generationNotice = (messageGeneration as? GitMessageGenerationState.Ready)?.notice,
|
||||
pushAfter = pushAfter,
|
||||
onPushAfterChange = { pushAfter = it },
|
||||
onGenerate = { viewModel.generateCommitMessage(stagedPaths) },
|
||||
onDismiss = { showCommit = false },
|
||||
onCommit = { message ->
|
||||
showCommit = false
|
||||
viewModel.commit(message) { target -> if (pushAfter) pendingConfirm = ConfirmationRequest.Push(target) }
|
||||
},
|
||||
)
|
||||
}
|
||||
pendingConfirm?.let { request ->
|
||||
ConfirmationDialog(
|
||||
request,
|
||||
onDismiss = { pendingConfirm = null },
|
||||
onDiscard = { paths, deleteUntracked, target -> pendingConfirm = null; viewModel.discard(paths, GitConfirmationStrings.DISCARD, deleteUntracked, target) },
|
||||
onPush = { target -> pendingConfirm = null; viewModel.push(GitConfirmationStrings.PUSH, expectedTarget = target) },
|
||||
onCheckout = { ref, target -> pendingConfirm = null; viewModel.checkout(ref, GitConfirmationStrings.DIRTY_CHECKOUT, expectedTarget = target) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WorkspaceBody(
|
||||
modifier: Modifier,
|
||||
repo: GitRepo,
|
||||
reposNotice: String?,
|
||||
detailState: GitRepoDetailState,
|
||||
mutation: GitMutationState,
|
||||
stashNotice: String?,
|
||||
hasGrant: Boolean,
|
||||
filter: FileFilter,
|
||||
onFilter: (FileFilter) -> Unit,
|
||||
selection: Set<DisplayFile>,
|
||||
onToggleSelected: (DisplayFile) -> Unit,
|
||||
expandedPath: String?,
|
||||
contentMode: ContentMode,
|
||||
contentState: GitContentViewState,
|
||||
onOpen: (DisplayFile, ContentMode) -> Unit,
|
||||
onFetch: () -> Unit,
|
||||
onPull: () -> Unit,
|
||||
onPush: () -> Unit,
|
||||
onClearMutation: () -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
) {
|
||||
when (detailState) {
|
||||
GitRepoDetailState.Idle, GitRepoDetailState.Loading -> FullState(modifier, true, "Loading workspace")
|
||||
is GitRepoDetailState.Error -> UnavailableState(modifier, detailState.message, onRetry)
|
||||
is GitRepoDetailState.Ready -> {
|
||||
val status = detailState.status
|
||||
val allFiles = buildList {
|
||||
status.staged.forEach { add(DisplayFile(it.path, FileFilter.Staged, it.additions, it.deletions)) }
|
||||
status.modified.forEach { add(DisplayFile(it.path, FileFilter.Modified, it.additions, it.deletions)) }
|
||||
status.untracked.forEach { add(DisplayFile(it.path, FileFilter.Untracked, it.additions, it.deletions)) }
|
||||
}
|
||||
val visible = allFiles.filter { filter == FileFilter.All || it.filter == filter }
|
||||
LazyColumn(modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 18.dp)) {
|
||||
item {
|
||||
SummaryRail(repo, detailState)
|
||||
RemoteActions(hasGrant, status, onFetch, onPull, onPush)
|
||||
reposNotice?.let { NoticeCard(it) }
|
||||
if (!hasGrant) WriteGrantNotice()
|
||||
MutationBanner(mutation, onClearMutation)
|
||||
stashNotice?.let { NoticeCard(it) }
|
||||
if (status.truncated) NoticeCard(stringResource(R.string.git_state_truncated), error = true)
|
||||
FilterRow(filter, status, onFilter)
|
||||
}
|
||||
if (visible.isEmpty()) item { EmptyFilterState(filter) }
|
||||
FileFilter.entries.filter { it != FileFilter.All }.forEach { group ->
|
||||
val files = visible.filter { it.filter == group }
|
||||
if (files.isNotEmpty()) {
|
||||
item { GroupHeader(group.name, files.size) }
|
||||
items(files, key = { "${group.name}:${it.path}" }) { file ->
|
||||
FileRow(
|
||||
file = file,
|
||||
selected = file in selection,
|
||||
expanded = expandedPath == file.path,
|
||||
mode = contentMode,
|
||||
contentState = contentState,
|
||||
onToggleSelected = { onToggleSelected(file) },
|
||||
onOpen = { onOpen(file, it) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SummaryRail(repo: GitRepo, detail: GitRepoDetailState.Ready) {
|
||||
val count = detail.status.uniqueChangeCount()
|
||||
val current = detail.branches.firstOrNull { it.isCurrent }
|
||||
Surface(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
) {
|
||||
Row(Modifier.padding(horizontal = 14.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("$count changes", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
|
||||
VerticalDivider()
|
||||
Text("+${detail.status.counts.additions}", color = Color(0xFF2E7D32), style = MaterialTheme.typography.labelLarge)
|
||||
VerticalDivider()
|
||||
Text("−${detail.status.counts.deletions}", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.labelLarge)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Surface(
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
color = Color.Transparent,
|
||||
) {
|
||||
Row(Modifier.padding(horizontal = 9.dp, vertical = 5.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.AccountTree, null, Modifier.size(16.dp)); Spacer(Modifier.width(5.dp))
|
||||
Text(current?.name ?: repo.currentBranch ?: "Detached", style = MaterialTheme.typography.labelLarge, maxLines = 1)
|
||||
if (repo.dirty || count > 0) { Spacer(Modifier.width(7.dp)); Box(Modifier.size(7.dp).background(MaterialTheme.colorScheme.tertiary, CircleShape)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VerticalDivider() {
|
||||
Box(
|
||||
Modifier.padding(horizontal = 10.dp).width(1.dp).height(22.dp)
|
||||
.background(MaterialTheme.colorScheme.outlineVariant),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RemoteActions(hasGrant: Boolean, status: GitStatus, onFetch: () -> Unit, onPull: () -> Unit, onPush: () -> Unit) {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
TextButton(onClick = onFetch, enabled = hasGrant && status.counts.untracked == 0, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.Refresh, null, Modifier.size(18.dp)); Spacer(Modifier.width(6.dp)); Text(stringResource(R.string.git_state_fetch))
|
||||
}
|
||||
VerticalDivider()
|
||||
TextButton(onClick = onPull, enabled = hasGrant, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.Download, null, Modifier.size(18.dp)); Spacer(Modifier.width(6.dp)); Text(stringResource(R.string.git_state_pull))
|
||||
}
|
||||
VerticalDivider()
|
||||
TextButton(onClick = onPush, enabled = hasGrant && status.counts.staged == 0, modifier = Modifier.weight(1f)) {
|
||||
Icon(Icons.Filled.FileUpload, null, Modifier.size(18.dp)); Spacer(Modifier.width(6.dp)); Text(stringResource(R.string.git_state_push))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FilterRow(selected: FileFilter, status: GitStatus, onSelect: (FileFilter) -> Unit) {
|
||||
val counts = mapOf(
|
||||
FileFilter.All to status.uniqueChangeCount(),
|
||||
FileFilter.Staged to status.counts.staged,
|
||||
FileFilter.Modified to status.counts.modified,
|
||||
FileFilter.Untracked to status.counts.untracked,
|
||||
)
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
FileFilter.entries.forEach { item ->
|
||||
val isSelected = selected == item
|
||||
Surface(
|
||||
onClick = { onSelect(item) },
|
||||
modifier = Modifier.weight(1f),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = if (isSelected) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent,
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant,
|
||||
),
|
||||
) {
|
||||
Box(Modifier.padding(horizontal = 3.dp, vertical = 9.dp), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"${item.name} ${counts.getValue(item)}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun GitStatus.uniqueChangeCount(): Int = counts.changes.takeIf { it >= 0 } ?: buildSet {
|
||||
staged.forEach { add(it.path) }
|
||||
modified.forEach { add(it.path) }
|
||||
untracked.forEach { add(it.path) }
|
||||
}.size
|
||||
|
||||
@Composable
|
||||
private fun FileRow(
|
||||
file: DisplayFile,
|
||||
selected: Boolean,
|
||||
expanded: Boolean,
|
||||
mode: ContentMode,
|
||||
contentState: GitContentViewState,
|
||||
onToggleSelected: () -> Unit,
|
||||
onOpen: (ContentMode) -> Unit,
|
||||
) {
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth()
|
||||
.then(
|
||||
if (file.filter == FileFilter.Untracked) Modifier
|
||||
else Modifier.clickable { onOpen(ContentMode.Diff) },
|
||||
)
|
||||
.padding(horizontal = 12.dp, vertical = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(
|
||||
checked = selected,
|
||||
onCheckedChange = { onToggleSelected() },
|
||||
modifier = Modifier.semantics {
|
||||
contentDescription = "Select ${file.path}"
|
||||
},
|
||||
)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(file.path.substringAfterLast('/'), style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
file.path.substringBeforeLast('/', "").takeIf { it.isNotEmpty() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (file.filter == FileFilter.Untracked) {
|
||||
Text("Preview unavailable until staged", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
file.additions?.let { additions ->
|
||||
Text("+$additions", color = Color(0xFF2E7D32), style = MaterialTheme.typography.labelSmall)
|
||||
Spacer(Modifier.width(5.dp))
|
||||
}
|
||||
file.deletions?.let { deletions ->
|
||||
Text("−$deletions", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.labelSmall)
|
||||
Spacer(Modifier.width(5.dp))
|
||||
}
|
||||
StatusBadge(file.filter)
|
||||
if (file.filter != FileFilter.Untracked) {
|
||||
Icon(if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, if (expanded) "Collapse" else "Expand")
|
||||
}
|
||||
}
|
||||
if (expanded && file.filter != FileFilter.Untracked) {
|
||||
Row(Modifier.padding(start = 56.dp, end = 16.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
if (file.filter != FileFilter.Untracked) FilterChip(mode == ContentMode.Diff, { onOpen(ContentMode.Diff) }, label = { Text("Diff") })
|
||||
FilterChip(mode == ContentMode.File, { onOpen(ContentMode.File) }, label = { Text("File") })
|
||||
}
|
||||
InlineContent(contentState, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 10.dp))
|
||||
}
|
||||
HorizontalDivider(Modifier.padding(start = 56.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusBadge(filter: FileFilter) {
|
||||
val label = when (filter) { FileFilter.Staged -> "S"; FileFilter.Modified -> "M"; FileFilter.Untracked -> "U"; else -> "" }
|
||||
val color = when (filter) { FileFilter.Staged -> MaterialTheme.colorScheme.primary; FileFilter.Modified -> MaterialTheme.colorScheme.tertiary; else -> MaterialTheme.colorScheme.secondary }
|
||||
Surface(shape = CircleShape, color = color.copy(alpha = 0.14f), modifier = Modifier.padding(horizontal = 8.dp)) {
|
||||
Text(label, color = color, style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold, modifier = Modifier.padding(horizontal = 7.dp, vertical = 3.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun InlineContent(state: GitContentViewState, modifier: Modifier) {
|
||||
Surface(modifier.fillMaxWidth(), shape = RoundedCornerShape(10.dp), color = MaterialTheme.colorScheme.surfaceContainerLow) {
|
||||
when (state) {
|
||||
GitContentViewState.Idle, GitContentViewState.Loading -> Box(Modifier.fillMaxWidth().height(100.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 2.dp) }
|
||||
is GitContentViewState.Error -> Text(state.message, Modifier.padding(12.dp), color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
is GitContentViewState.Diff -> MonospaceContent(state.diff.diff.ifEmpty { stringResource(R.string.git_state_no_changes) }, state.diff.truncated)
|
||||
is GitContentViewState.File -> MonospaceContent(state.file.content, state.file.truncated)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MonospaceContent(text: String, truncated: Boolean) {
|
||||
Column(Modifier.padding(12.dp)) {
|
||||
if (truncated) Text(stringResource(R.string.git_state_truncated), color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.labelSmall)
|
||||
Text(text, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace, modifier = Modifier.fillMaxWidth().height(220.dp).verticalScroll(rememberScrollState()))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SelectionRail(count: Int, canWrite: Boolean, allStaged: Boolean, onStage: () -> Unit, onDiscard: () -> Unit) {
|
||||
val canDiscard = canWrite && !allStaged
|
||||
Surface(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
shadowElevation = 6.dp,
|
||||
) {
|
||||
Row(Modifier.padding(horizontal = 14.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("$count selected", Modifier.weight(1f), style = MaterialTheme.typography.labelLarge)
|
||||
TextButton(onClick = onStage, enabled = canWrite) {
|
||||
Text(
|
||||
if (allStaged) "Unstage" else "Stage",
|
||||
color = if (canWrite) Color(0xFF4CAF50) else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onDiscard, enabled = canDiscard) {
|
||||
Text(
|
||||
stringResource(R.string.git_state_discard),
|
||||
color = if (canDiscard) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RepositoryPrompt(modifier: Modifier, repos: List<GitRepo>, onSelect: (String) -> Unit) {
|
||||
Column(modifier.fillMaxSize().padding(24.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text("Choose a repository", style = MaterialTheme.typography.headlineSmall)
|
||||
Text("Git actions stay scoped to the repository you select.", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
repos.forEach { repo -> RepositoryRow(repo, false) { onSelect(repo.id) } }
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun RepositorySheet(repos: List<GitRepo>, selectedId: String?, onDismiss: () -> Unit, onSelect: (String) -> Unit) {
|
||||
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp).padding(bottom = 28.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("Repositories", style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(8.dp))
|
||||
repos.forEach { repo -> RepositoryRow(repo, repo.id == selectedId) { onSelect(repo.id) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RepositoryRow(repo: GitRepo, selected: Boolean, onClick: () -> Unit) {
|
||||
Surface(Modifier.fillMaxWidth().clickable(onClick = onClick), color = if (selected) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent, shape = RoundedCornerShape(12.dp)) {
|
||||
Row(Modifier.padding(14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.AccountTree, null); Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(repo.name, style = MaterialTheme.typography.titleSmall)
|
||||
Text(repo.currentBranch ?: repo.root, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (repo.dirty) Box(Modifier.size(8.dp).background(MaterialTheme.colorScheme.tertiary, CircleShape))
|
||||
if (selected) { Spacer(Modifier.width(8.dp)); Icon(Icons.Filled.Check, "Selected") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun BranchSheet(
|
||||
branches: List<GitBranch>,
|
||||
hasGrant: Boolean,
|
||||
dirty: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onSwitch: (String) -> Unit,
|
||||
onStashSwitch: (String) -> Unit,
|
||||
onCreate: (String, Boolean) -> Unit,
|
||||
) {
|
||||
var newBranch by rememberSaveable { mutableStateOf("") }
|
||||
var track by rememberSaveable { mutableStateOf(false) }
|
||||
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||
Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp).padding(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Text(stringResource(R.string.git_state_branches), style = MaterialTheme.typography.titleLarge)
|
||||
branches.forEach { branch ->
|
||||
Surface(shape = RoundedCornerShape(12.dp), color = if (branch.isCurrent) MaterialTheme.colorScheme.secondaryContainer else Color.Transparent) {
|
||||
Row(Modifier.fillMaxWidth().padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(branch.name, fontFamily = FontFamily.Monospace, style = MaterialTheme.typography.bodyMedium)
|
||||
branch.upstream?.let { Text("$it · ahead ${branch.ahead} · behind ${branch.behind}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) }
|
||||
}
|
||||
if (branch.isCurrent) Text(stringResource(R.string.git_state_current), color = MaterialTheme.colorScheme.primary)
|
||||
else {
|
||||
TextButton(onClick = { onSwitch(branch.name) }, enabled = hasGrant) { Text(stringResource(R.string.git_state_switch)) }
|
||||
if (dirty) TextButton(onClick = { onStashSwitch(branch.name) }, enabled = hasGrant) { Text(stringResource(R.string.git_state_switch_stash)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider(); Text("Create branch", style = MaterialTheme.typography.titleMedium)
|
||||
OutlinedTextField(newBranch, { newBranch = it }, Modifier.fillMaxWidth(), label = { Text(stringResource(R.string.git_state_new_branch_hint)) }, singleLine = true)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) { Checkbox(track, { track = it }, enabled = hasGrant); Text(stringResource(R.string.git_state_track_remote)) }
|
||||
Button(onClick = { onCreate(newBranch.trim(), track) }, enabled = hasGrant && newBranch.isNotBlank(), modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.git_state_create_branch)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CommitDialog(
|
||||
hasStaged: Boolean,
|
||||
generating: Boolean,
|
||||
generatedMessage: String,
|
||||
generationNotice: String?,
|
||||
pushAfter: Boolean,
|
||||
onPushAfterChange: (Boolean) -> Unit,
|
||||
onGenerate: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
onCommit: (String) -> Unit,
|
||||
) {
|
||||
var message by rememberSaveable { mutableStateOf("") }
|
||||
LaunchedEffect(generatedMessage) { if (generatedMessage.isNotBlank()) message = generatedMessage }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.git_state_commit_title)) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedTextField(
|
||||
message, { message = it }, Modifier.fillMaxWidth(),
|
||||
label = { Text(stringResource(R.string.git_state_commit_message_hint)) }, minLines = 3,
|
||||
trailingIcon = {
|
||||
IconButton(onClick = onGenerate, enabled = hasStaged && !generating) {
|
||||
if (generating) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else Icon(Icons.Filled.AutoAwesome, stringResource(R.string.git_state_generate_message))
|
||||
}
|
||||
},
|
||||
)
|
||||
generationNotice?.takeIf { it.isNotBlank() }?.let { Text(it, color = MaterialTheme.colorScheme.tertiary, style = MaterialTheme.typography.bodySmall) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically) { Checkbox(pushAfter, onPushAfterChange); Text(stringResource(R.string.git_state_push_after_commit)) }
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { onCommit(message.trim()) }, enabled = hasStaged && message.isNotBlank()) { Text(stringResource(R.string.git_state_commit_confirm)) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.git_state_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
private sealed interface ConfirmationRequest {
|
||||
data class Discard(val paths: List<String>, val deleteUntracked: Boolean, val target: GitTarget) : ConfirmationRequest
|
||||
data class Push(val target: GitTarget) : ConfirmationRequest
|
||||
data class DirtyCheckout(val ref: String, val target: GitTarget) : ConfirmationRequest
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConfirmationDialog(
|
||||
request: ConfirmationRequest,
|
||||
onDismiss: () -> Unit,
|
||||
onDiscard: (List<String>, Boolean, GitTarget) -> Unit,
|
||||
onPush: (GitTarget) -> Unit,
|
||||
onCheckout: (String, GitTarget) -> Unit,
|
||||
) {
|
||||
val title = stringResource(when (request) {
|
||||
is ConfirmationRequest.Discard -> R.string.git_state_confirm_discard_title
|
||||
is ConfirmationRequest.Push -> R.string.git_state_confirm_push_title
|
||||
is ConfirmationRequest.DirtyCheckout -> R.string.git_state_confirm_checkout_dirty_title
|
||||
})
|
||||
val text = stringResource(when (request) {
|
||||
is ConfirmationRequest.Discard -> R.string.git_state_confirm_discard_text
|
||||
is ConfirmationRequest.Push -> R.string.git_state_confirm_push_text
|
||||
is ConfirmationRequest.DirtyCheckout -> R.string.git_state_confirm_checkout_dirty_text
|
||||
})
|
||||
val confirm = stringResource(when (request) {
|
||||
is ConfirmationRequest.Discard -> R.string.git_state_confirm_discard_confirm
|
||||
is ConfirmationRequest.Push -> R.string.git_state_confirm_push_confirm
|
||||
is ConfirmationRequest.DirtyCheckout -> R.string.git_state_confirm_checkout_confirm
|
||||
})
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(title) }, text = { Text(text) },
|
||||
confirmButton = { TextButton(onClick = {
|
||||
when (request) {
|
||||
is ConfirmationRequest.Discard -> onDiscard(request.paths, request.deleteUntracked, request.target)
|
||||
is ConfirmationRequest.Push -> onPush(request.target)
|
||||
is ConfirmationRequest.DirtyCheckout -> onCheckout(request.ref, request.target)
|
||||
}
|
||||
}) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.git_state_cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MutationBanner(mutation: GitMutationState, onClear: () -> Unit) {
|
||||
when (mutation) {
|
||||
GitMutationState.Idle -> Unit
|
||||
is GitMutationState.InProgress -> NoticeCard("${mutation.label} in progress…", loading = true)
|
||||
is GitMutationState.Success -> NoticeCard("${displayLabel(mutation.label)} completed · ${mutation.head.take(8)}")
|
||||
is GitMutationState.Error -> Card(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
|
||||
) {
|
||||
Row(Modifier.padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"${displayLabel(mutation.label)} failed: ${mutation.message}",
|
||||
modifier = Modifier.weight(1f),
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
IconButton(onClick = onClear) { Icon(Icons.Filled.Close, "Dismiss error") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun NoticeCard(message: String, error: Boolean = false, loading: Boolean = false) {
|
||||
Card(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = if (error) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.surfaceContainer),
|
||||
) {
|
||||
Row(Modifier.padding(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (loading) { CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp); Spacer(Modifier.width(10.dp)) }
|
||||
Text(message, color = if (error) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable private fun WriteGrantNotice() = NoticeCard(stringResource(R.string.git_state_write_grant_required))
|
||||
|
||||
@Composable
|
||||
private fun GroupHeader(label: String, count: Int) {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(label, style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.SemiBold); Spacer(Modifier.width(6.dp))
|
||||
Text(count.toString(), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmptyFilterState(filter: FileFilter) {
|
||||
Box(Modifier.fillMaxWidth().padding(48.dp), contentAlignment = Alignment.Center) {
|
||||
Text(if (filter == FileFilter.All) "Working tree clean" else "No ${filter.name.lowercase()} files", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FullState(modifier: Modifier, loading: Boolean, title: String, detail: String? = null) {
|
||||
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(Modifier.padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
if (loading) CircularProgressIndicator(); Text(title, style = MaterialTheme.typography.titleMedium)
|
||||
detail?.let { Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun UnavailableState(modifier: Modifier, message: String, onRetry: () -> Unit) {
|
||||
val missingRoute = message.contains("404") || message.contains("No such API endpoint", true)
|
||||
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(Modifier.padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Icon(Icons.Filled.Close, null, tint = MaterialTheme.colorScheme.error, modifier = Modifier.size(32.dp))
|
||||
Text(if (missingRoute) "Git isn't available on this host yet" else "Git workspace unavailable", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
if (missingRoute) "The host advertised Git, but its API route is not currently reachable. Restart or update the Dashboard, then retry." else message.ifBlank { "The Git service did not return a usable response." },
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Button(onClick = onRetry) { Icon(Icons.Filled.Refresh, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text("Retry") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun branchSummary(repo: GitRepo, branch: GitBranch?): String {
|
||||
val name = branch?.name ?: repo.currentBranch ?: "Detached HEAD"
|
||||
val tracking = buildList {
|
||||
if ((branch?.ahead ?: 0) > 0) add("ahead ${branch?.ahead}")
|
||||
if ((branch?.behind ?: 0) > 0) add("behind ${branch?.behind}")
|
||||
}
|
||||
return if (tracking.isEmpty()) name else "$name · ${tracking.joinToString(" · ")}"
|
||||
}
|
||||
|
||||
private fun displayLabel(label: String): String = label.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
|
||||
@@ -34,6 +34,7 @@ import androidx.compose.material.icons.automirrored.filled.Chat
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.automirrored.filled.Message
|
||||
import androidx.compose.material.icons.filled.Analytics
|
||||
import androidx.compose.material.icons.filled.AccountTree
|
||||
import androidx.compose.material.icons.filled.Code
|
||||
import androidx.compose.material.icons.filled.Devices
|
||||
import androidx.compose.material.icons.filled.Extension
|
||||
@@ -101,6 +102,7 @@ import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.ProviderUsageLandingMode
|
||||
import com.hermesandroid.relay.data.ProviderUsagePreferences
|
||||
import com.hermesandroid.relay.data.ProviderUsagePreferencesRepository
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.network.usage.ProviderUsageRepository
|
||||
import com.hermesandroid.relay.network.usage.ProviderUsageResponse
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
@@ -157,6 +159,14 @@ fun SettingsScreen(
|
||||
connectionViewModel: ConnectionViewModel,
|
||||
/** Header back affordance — Settings is a pushed destination, not a tab. */
|
||||
onBack: (() -> Unit)? = null,
|
||||
supervisedPolicy: SupervisedModePolicy? = null,
|
||||
parentAccessUnlocked: Boolean = false,
|
||||
/** Called only after the restricted surface completes device authentication. */
|
||||
onRequestParentAccess: () -> Unit = {},
|
||||
onUpdateSupervisedPolicy: (SupervisedModePolicy) -> Unit = {},
|
||||
onNavigateToAdvancedSettings: () -> Unit = {},
|
||||
onNavigateToSupervisedAppearance: () -> Unit = {},
|
||||
onNavigateToSupervisedControls: () -> Unit = {},
|
||||
// Needed by the Active Agent summary card at the top of the screen — it
|
||||
// reads the current personality pick so the subtitle can render
|
||||
// `connection · model · personality` without re-reading ChatViewModel
|
||||
@@ -181,6 +191,7 @@ fun SettingsScreen(
|
||||
onNavigateToManage: () -> Unit,
|
||||
onNavigateToProviderUsage: () -> Unit,
|
||||
onNavigateToPlugins: () -> Unit,
|
||||
onNavigateToGitWorkspace: () -> Unit,
|
||||
onNavigateToChatSettings: () -> Unit,
|
||||
onNavigateToTerminal: () -> Unit,
|
||||
onNavigateToBridge: () -> Unit,
|
||||
@@ -206,6 +217,21 @@ fun SettingsScreen(
|
||||
// discoverable before a pair-and-pick happens.
|
||||
onNavigateToProfileInspector: (profileName: String) -> Unit,
|
||||
) {
|
||||
// Keep the restricted root when an enabled policy becomes temporarily
|
||||
// unusable (for example, its profile was renamed). Parent authentication,
|
||||
// not a configuration error, is what unlocks the full settings surface.
|
||||
if (supervisedPolicy?.enabled == true && !parentAccessUnlocked) {
|
||||
SupervisedSettingsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
policy = supervisedPolicy,
|
||||
onPolicyChange = onUpdateSupervisedPolicy,
|
||||
onBack = onBack,
|
||||
onNavigateToAppearance = onNavigateToSupervisedAppearance,
|
||||
onParentAccessGranted = onRequestParentAccess,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
val context = LocalContext.current
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
|
||||
@@ -432,6 +458,20 @@ fun SettingsScreen(
|
||||
.padding(horizontal = 16.dp, vertical = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (supervisedPolicy?.enabled == true && parentAccessUnlocked) {
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Security,
|
||||
title = "Supervised mode",
|
||||
subtitle = "On · ${supervisedPolicy.pinnedProfileName.orEmpty()}",
|
||||
badge = SettingsStatusPillModel(
|
||||
label = "On",
|
||||
tone = SettingsStatusTone.Good,
|
||||
),
|
||||
onClick = onNavigateToSupervisedControls,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
}
|
||||
|
||||
// ── Active Agent summary ───────────────────────────────────
|
||||
// Mirrors the ChatScreen TopAppBar title block (avatar + name
|
||||
// + one-line `connection · model · personality` subtitle).
|
||||
@@ -497,6 +537,7 @@ fun SettingsScreen(
|
||||
modifier = Modifier.settingsPetSurface("settings-card:profile-lock"),
|
||||
)
|
||||
|
||||
|
||||
// ── Quick Controls ─────────────────────────────────────────
|
||||
// The switches flipped most often, pinned to the top-level Settings
|
||||
// landing instead of buried in a sub-screen. Persistent connection is
|
||||
@@ -564,6 +605,14 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.AccountTree,
|
||||
title = stringResource(R.string.settings_git_workspace),
|
||||
subtitle = stringResource(R.string.settings_git_workspace_desc),
|
||||
onClick = onNavigateToGitWorkspace,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.AutoMirrored.Filled.Chat,
|
||||
title = stringResource(R.string.settings_chat),
|
||||
@@ -666,6 +715,24 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Security,
|
||||
title = stringResource(R.string.settings_advanced),
|
||||
subtitle = when {
|
||||
supervisedPolicy?.isActive == true -> "On · ${supervisedPolicy.pinnedProfileName}"
|
||||
supervisedPolicy?.isConfigured == true -> "Ready · ${supervisedPolicy.pinnedProfileName}"
|
||||
else -> stringResource(R.string.settings_advanced_desc)
|
||||
},
|
||||
badge = supervisedPolicy?.takeIf { it.isActive }?.let {
|
||||
SettingsStatusPillModel(
|
||||
label = "On",
|
||||
tone = SettingsStatusTone.Good,
|
||||
)
|
||||
},
|
||||
onClick = onNavigateToAdvancedSettings,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Analytics,
|
||||
title = stringResource(R.string.settings_analytics),
|
||||
@@ -1280,12 +1347,12 @@ private fun ProfileLockOptionRow(
|
||||
}
|
||||
}
|
||||
|
||||
private data class SettingsStatusPillModel(
|
||||
internal data class SettingsStatusPillModel(
|
||||
val label: String,
|
||||
val tone: SettingsStatusTone = SettingsStatusTone.Neutral,
|
||||
)
|
||||
|
||||
private enum class SettingsStatusTone {
|
||||
internal enum class SettingsStatusTone {
|
||||
Neutral,
|
||||
Good,
|
||||
Info,
|
||||
@@ -1483,18 +1550,22 @@ private fun SettingsSectionHeader(
|
||||
* mega-SettingsScreen.
|
||||
*/
|
||||
@Composable
|
||||
private fun SettingsCategoryRow(
|
||||
internal fun SettingsCategoryRow(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
isDarkTheme: Boolean,
|
||||
badge: SettingsStatusPillModel? = null,
|
||||
petPerchKey: String = title,
|
||||
petPerchKey: String? = title,
|
||||
) {
|
||||
val surfaceModifier = if (petPerchKey != null) {
|
||||
Modifier.settingsPetSurface("settings-category:$petPerchKey")
|
||||
} else {
|
||||
Modifier
|
||||
}
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.settingsPetSurface("settings-category:$petPerchKey")
|
||||
modifier = surfaceModifier
|
||||
.fillMaxWidth()
|
||||
.gradientBorder(
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -49,6 +49,10 @@ import com.hermesandroid.relay.data.SessionActivityScope
|
||||
import com.hermesandroid.relay.data.SessionActivityUpdate
|
||||
import com.hermesandroid.relay.data.SessionLiveRuntime
|
||||
import com.hermesandroid.relay.data.SessionLiveStatus
|
||||
import com.hermesandroid.relay.data.SupervisedAttachmentCategory
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.SupervisedSessionAction
|
||||
import com.hermesandroid.relay.data.allowsSessionAction
|
||||
import com.hermesandroid.relay.data.ToolCallEvent
|
||||
import com.hermesandroid.relay.data.VoiceIntentTrace
|
||||
import com.hermesandroid.relay.data.HermesCard
|
||||
@@ -336,6 +340,24 @@ internal fun voiceTurnTransportRejection(
|
||||
}
|
||||
|
||||
class ChatViewModel : ViewModel() {
|
||||
/**
|
||||
* Active Android-only supervision policy. RelayApp replaces this snapshot
|
||||
* whenever the active connection changes. Enforcement belongs here as well
|
||||
* as in Compose so alternate UI entry points cannot bypass the restrictions.
|
||||
*/
|
||||
@Volatile
|
||||
private var supervisedModePolicy: SupervisedModePolicy = SupervisedModePolicy()
|
||||
|
||||
fun updateSupervisedModePolicy(policy: SupervisedModePolicy) {
|
||||
supervisedModePolicy = policy
|
||||
if (policy.enabled) {
|
||||
_pendingAttachments.update { attachments ->
|
||||
attachments.filterIndexed { index, attachment ->
|
||||
isAttachmentAllowedBySupervision(attachment, index)
|
||||
}.take(policy.capabilities.attachmentMaxCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var apiClient: HermesApiClient? = null
|
||||
private var chatHandler: ChatHandler? = null
|
||||
@@ -828,7 +850,10 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
fun addAttachment(attachment: Attachment) {
|
||||
_pendingAttachments.update { it + attachment }
|
||||
_pendingAttachments.update { current ->
|
||||
if (!isAttachmentAllowedBySupervision(attachment, current.size)) current
|
||||
else current + attachment
|
||||
}
|
||||
}
|
||||
|
||||
fun removeAttachment(index: Int) {
|
||||
@@ -838,11 +863,20 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
fun replacePendingAttachments(attachments: List<Attachment>) {
|
||||
_pendingAttachments.value = attachments.toList()
|
||||
val policy = supervisedModePolicy
|
||||
_pendingAttachments.value = if (!policy.enabled) {
|
||||
attachments.toList()
|
||||
} else {
|
||||
attachments.filter { isAttachmentAllowedBySupervision(it, 0) }
|
||||
.take(policy.capabilities.attachmentMaxCount)
|
||||
}
|
||||
}
|
||||
|
||||
fun replaceAttachment(composerId: String, attachment: Attachment) {
|
||||
_pendingAttachments.update { attachments ->
|
||||
if (!isAttachmentAllowedBySupervision(attachment, (attachments.size - 1).coerceAtLeast(0))) {
|
||||
return@update attachments.filterNot { it.composerId == composerId }
|
||||
}
|
||||
var replaced = false
|
||||
val updated = attachments.map { current ->
|
||||
if (current.composerId == composerId) {
|
||||
@@ -872,6 +906,23 @@ class ChatViewModel : ViewModel() {
|
||||
_pendingAttachments.value = emptyList()
|
||||
}
|
||||
|
||||
private fun isAttachmentAllowedBySupervision(attachment: Attachment, existingCount: Int): Boolean {
|
||||
val policy = supervisedModePolicy
|
||||
if (!policy.enabled) return true
|
||||
val capabilities = policy.capabilities
|
||||
if (!policy.isActive || !capabilities.attachments) return false
|
||||
if (existingCount >= capabilities.attachmentMaxCount) return false
|
||||
val maxBytes = capabilities.attachmentMaxFileMb.toLong() * 1024L * 1024L
|
||||
if ((attachment.fileSize ?: 0L) > maxBytes) return false
|
||||
val category = when {
|
||||
attachment.contentType.startsWith("image/") -> SupervisedAttachmentCategory.Images
|
||||
attachment.contentType.startsWith("audio/") -> SupervisedAttachmentCategory.Audio
|
||||
attachment.contentType.startsWith("video/") -> SupervisedAttachmentCategory.Video
|
||||
else -> SupervisedAttachmentCategory.Documents
|
||||
}
|
||||
return category in capabilities.attachmentCategories
|
||||
}
|
||||
|
||||
// Server-side personality selection
|
||||
private val _selectedPersonality = MutableStateFlow("default")
|
||||
val selectedPersonality: StateFlow<String> = _selectedPersonality.asStateFlow()
|
||||
@@ -4624,6 +4675,7 @@ class ChatViewModel : ViewModel() {
|
||||
onReady: ((String?) -> Unit)? = null,
|
||||
onFailure: (() -> Unit)? = null,
|
||||
) {
|
||||
if (supervisedModePolicy.enabled && !supervisedModePolicy.capabilities.newChat) return
|
||||
val handler = chatHandler ?: return
|
||||
recordPreResetEvidence(handler, "new_chat")
|
||||
clearOpenedSessionOwner()
|
||||
@@ -4956,6 +5008,7 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
fun deleteSession(sessionId: String, onDeleted: () -> Unit = {}) {
|
||||
if (!supervisedModePolicy.allowsSessionAction(SupervisedSessionAction.Delete)) return
|
||||
val handler = chatHandler ?: return
|
||||
val client = apiClient
|
||||
if (streamingEndpoint != "gateway" && client == null) return
|
||||
@@ -5020,6 +5073,7 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
fun renameSession(sessionId: String, newTitle: String) {
|
||||
if (!supervisedModePolicy.allowsSessionAction(SupervisedSessionAction.Rename)) return
|
||||
val handler = chatHandler ?: return
|
||||
val client = apiClient
|
||||
if (streamingEndpoint != "gateway" && client == null) return
|
||||
@@ -5064,6 +5118,7 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
fun setSessionPinned(sessionId: String, pinned: Boolean) {
|
||||
if (!supervisedModePolicy.allowsSessionAction(SupervisedSessionAction.Pin)) return
|
||||
val expectedContextKey = activeProfileContextKey
|
||||
val profileName = currentSessionProfileName()
|
||||
mutateSessionFlag(
|
||||
@@ -5082,6 +5137,7 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
fun setSessionArchived(sessionId: String, archived: Boolean) {
|
||||
if (!supervisedModePolicy.allowsSessionAction(SupervisedSessionAction.Archive)) return
|
||||
if (!_sessionArchivingSupported.value) {
|
||||
emitError(
|
||||
UnsupportedOperationException("Archive and restore require Dashboard sessions"),
|
||||
@@ -5150,6 +5206,22 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
fun sendMessage(text: String) {
|
||||
if (text.isBlank()) return
|
||||
supervisedMessageBlockReason(supervisedModePolicy, text)?.let { reason ->
|
||||
chatHandler?.addSystemNotice(reason)
|
||||
return
|
||||
}
|
||||
if (supervisedModePolicy.enabled) {
|
||||
val attachments = _pendingAttachments.value
|
||||
if (attachments.any { attachment ->
|
||||
!isAttachmentAllowedBySupervision(attachment, attachments.indexOf(attachment))
|
||||
}
|
||||
) {
|
||||
chatHandler?.addSystemNotice(
|
||||
"One or more attachments are unavailable under the supervised policy.",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
recordRecentPrompt(text)
|
||||
|
||||
// Demo / Explore mode: there is no server, but a silently dead Send
|
||||
@@ -5418,6 +5490,10 @@ class ChatViewModel : ViewModel() {
|
||||
action: com.hermesandroid.relay.data.HermesCardAction,
|
||||
) {
|
||||
val handler = chatHandler ?: return
|
||||
if (supervisedModePolicy.enabled) {
|
||||
handler.addSystemNotice("This action is unavailable in supervised mode.")
|
||||
return
|
||||
}
|
||||
// Ask answers route straight to the gateway respond RPCs —
|
||||
// answerAsk records its own (sanitized) dispatch stamp, so don't
|
||||
// double-stamp here.
|
||||
@@ -5456,6 +5532,10 @@ class ChatViewModel : ViewModel() {
|
||||
ask: GatewayAsk,
|
||||
restored: ChatTurnAskCheckpoint? = null,
|
||||
) {
|
||||
if (supervisedModePolicy.enabled) {
|
||||
denySupervisedInteraction(handler, ask)
|
||||
return
|
||||
}
|
||||
val sessionId = handler.currentSessionId.value
|
||||
val contextKey = activeProfileContextKey
|
||||
val existing = _pendingAsk.value
|
||||
@@ -5584,6 +5664,33 @@ class ChatViewModel : ViewModel() {
|
||||
sessionId?.let { maybeNotifyInteraction(it, ask) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Supervised Chat never exposes approval, clarification, sudo, or secret
|
||||
* inputs. Settle the upstream interaction immediately with its safest
|
||||
* negative/empty response; if that cannot be confirmed, interrupt the turn
|
||||
* so a hidden card cannot leave the session waiting indefinitely.
|
||||
*/
|
||||
private fun denySupervisedInteraction(handler: ChatHandler, ask: GatewayAsk) {
|
||||
val gateway = gatewayClient
|
||||
if (gateway == null) {
|
||||
handler.addSystemNotice("An interactive request was blocked by supervised mode.")
|
||||
cancelStream()
|
||||
return
|
||||
}
|
||||
viewModelScope.launch {
|
||||
val response: Result<GatewayAskResponse>? = when (ask.kind) {
|
||||
GatewayAsk.Kind.APPROVAL -> gateway.respondApproval(choice = "deny")
|
||||
GatewayAsk.Kind.CLARIFY -> ask.requestId?.let {
|
||||
gateway.respondClarify(it, "This supervised client cannot answer interactive requests.")
|
||||
}
|
||||
GatewayAsk.Kind.SUDO -> ask.requestId?.let { gateway.respondSudo(it, "") }
|
||||
GatewayAsk.Kind.SECRET -> ask.requestId?.let { gateway.respondSecret(it, "") }
|
||||
}
|
||||
handler.addSystemNotice("An interactive request was denied by supervised mode.")
|
||||
if (response == null || response.isFailure) cancelStream()
|
||||
}
|
||||
}
|
||||
|
||||
/** Render only upstream-supported approval values; old servers retain Approve/Deny. */
|
||||
private fun approvalActions(ask: GatewayAsk): List<HermesCardAction> {
|
||||
val advertised = ask.choices.orEmpty()
|
||||
@@ -9404,6 +9511,9 @@ class ChatViewModel : ViewModel() {
|
||||
* so we shouldn't see duplicate calls here.
|
||||
*/
|
||||
fun onMediaAttachmentRequested(messageId: String, token: String) {
|
||||
if (supervisedModePolicy.enabled &&
|
||||
!supervisedModePolicy.capabilities.generatedImages
|
||||
) return
|
||||
val handler = chatHandler ?: return
|
||||
val relay = relayHttpClient
|
||||
val repo = mediaSettingsRepo
|
||||
@@ -9461,6 +9571,9 @@ class ChatViewModel : ViewModel() {
|
||||
* token and uses [RelayHttpClient.fetchMedia].
|
||||
*/
|
||||
fun manualFetchAttachment(messageId: String, attachmentIndex: Int) {
|
||||
if (supervisedModePolicy.enabled &&
|
||||
!supervisedModePolicy.capabilities.generatedImages
|
||||
) return
|
||||
val handler = chatHandler ?: return
|
||||
val relay = relayHttpClient ?: return
|
||||
val repo = mediaSettingsRepo ?: return
|
||||
@@ -9534,6 +9647,9 @@ class ChatViewModel : ViewModel() {
|
||||
* it into the markdown-image renderer, which previously ignored the relay.
|
||||
*/
|
||||
suspend fun resolveServerImage(serverPath: String): ServerImageResult {
|
||||
if (supervisedModePolicy.enabled &&
|
||||
!supervisedModePolicy.capabilities.generatedImages
|
||||
) return ServerImageResult.Failure("Generated images are disabled in supervised mode")
|
||||
val relay = relayHttpClient
|
||||
?: return ServerImageResult.Failure("Relay not configured on this connection")
|
||||
// fetchMediaByPath returns Result<MediaBytes>; fold it ONCE, right here,
|
||||
@@ -9576,6 +9692,11 @@ class ChatViewModel : ViewModel() {
|
||||
expectedRole: MessageRole,
|
||||
unavailableMessage: String,
|
||||
) {
|
||||
if (
|
||||
expectedRole == MessageRole.ASSISTANT &&
|
||||
supervisedModePolicy.enabled &&
|
||||
!supervisedModePolicy.capabilities.generatedImages
|
||||
) return
|
||||
val handler = chatHandler ?: return
|
||||
val relay = relayHttpClient
|
||||
val repo = mediaSettingsRepo
|
||||
|
||||
@@ -2412,6 +2412,16 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
}
|
||||
|
||||
val showGitWorkspaceInChat: StateFlow<Boolean> =
|
||||
chatInputPreferencesRepository.showGitWorkspaceInChat
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, true)
|
||||
|
||||
fun setShowGitWorkspaceInChat(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
chatInputPreferencesRepository.setShowGitWorkspaceInChat(enabled)
|
||||
}
|
||||
}
|
||||
|
||||
// Turn-complete notification (default ON). RelayApp mirrors this into
|
||||
// ChatViewModel.notifyOnTurnComplete; ChatSettingsScreen owns the toggle
|
||||
// + the POST_NOTIFICATIONS runtime request on first enable.
|
||||
@@ -2749,6 +2759,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
private fun installAuthManager(am: AuthManager) {
|
||||
am.setActiveEndpointProvider { connectionManager.activeRelayEndpoint.value }
|
||||
am.setSupervisedMetadataReconnectFallback {
|
||||
connectionManager.reconnectForAuthenticatedMetadataUpdate()
|
||||
}
|
||||
authManager = am
|
||||
// Push into the flow so the flatMapLatest chains on authState /
|
||||
// pairingCode / currentPairedSession repoint to the new manager.
|
||||
@@ -3591,6 +3604,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
// ConnectionStore's EncryptedSharedPrefs.
|
||||
profileController.profileSelectionStore.clear(connectionId)
|
||||
profileController.profileLockStore.clear(connectionId)
|
||||
com.hermesandroid.relay.data.SupervisedModeStore(getApplication<Application>())
|
||||
.clear(connectionId)
|
||||
profileController.profilePresentationStore.clear(connectionId)
|
||||
profileController.profileSessionStore.clearConnection(connectionId)
|
||||
profileController.profileDisplayAliasStore.clearConnection(connectionId)
|
||||
@@ -3630,6 +3645,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
|
||||
init {
|
||||
authManager.setSupervisedMetadataReconnectFallback {
|
||||
connectionManager.reconnectForAuthenticatedMetadataUpdate()
|
||||
}
|
||||
// Wire multiplexer to connection manager (for relay/bridge/terminal)
|
||||
multiplexer.setSendCallback { envelope ->
|
||||
connectionManager.send(envelope)
|
||||
@@ -4096,6 +4114,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
connectionStore.removeConnection(duplicate.id)
|
||||
profileController.profileSelectionStore.clear(duplicate.id)
|
||||
profileController.profileLockStore.clear(duplicate.id)
|
||||
com.hermesandroid.relay.data.SupervisedModeStore(getApplication<Application>())
|
||||
.clear(duplicate.id)
|
||||
profileController.profilePresentationStore.clear(duplicate.id)
|
||||
profileController.profileSessionStore.clearConnection(duplicate.id)
|
||||
}
|
||||
@@ -7190,6 +7210,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
check(dataManager.resetAppData()) { "App data store reset failed" }
|
||||
profileController.profileSelectionStore.clearAll()
|
||||
profileController.profileLockStore.clearAll()
|
||||
com.hermesandroid.relay.data.SupervisedModeStore(getApplication<Application>())
|
||||
.clearAll()
|
||||
profileController.profilePresentationStore.clearAll()
|
||||
profileController.profileSessionStore.clearAll()
|
||||
_apiServerUrl.value = ""
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.hermesandroid.relay.data.GitBranch
|
||||
import com.hermesandroid.relay.data.GitDiff
|
||||
import com.hermesandroid.relay.data.GitFile
|
||||
import com.hermesandroid.relay.data.GitRepo
|
||||
import com.hermesandroid.relay.data.GitStateApiClient
|
||||
import com.hermesandroid.relay.data.GitStatus
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
sealed interface GitStateUiState {
|
||||
data object Loading : GitStateUiState
|
||||
data class Unavailable(val message: String) : GitStateUiState
|
||||
data class Error(val message: String) : GitStateUiState
|
||||
data class Ready(val repos: List<GitRepo>, val notice: String?) : GitStateUiState
|
||||
}
|
||||
|
||||
sealed interface GitRepoDetailState {
|
||||
data object Idle : GitRepoDetailState
|
||||
data object Loading : GitRepoDetailState
|
||||
data class Error(val message: String) : GitRepoDetailState
|
||||
data class Ready(
|
||||
val status: GitStatus,
|
||||
val branches: List<GitBranch>,
|
||||
) : GitRepoDetailState
|
||||
}
|
||||
|
||||
sealed interface GitContentViewState {
|
||||
data object Idle : GitContentViewState
|
||||
data object Loading : GitContentViewState
|
||||
data class Error(val message: String) : GitContentViewState
|
||||
data class Diff(val diff: GitDiff) : GitContentViewState
|
||||
data class File(val file: GitFile) : GitContentViewState
|
||||
}
|
||||
|
||||
/** A single in-flight or completed write mutation on the selected repo. */
|
||||
sealed interface GitMutationState {
|
||||
data object Idle : GitMutationState
|
||||
data class InProgress(val label: String) : GitMutationState
|
||||
data class Error(val label: String, val message: String) : GitMutationState
|
||||
data class Success(val label: String, val head: String) : GitMutationState
|
||||
}
|
||||
|
||||
/** A commit-message generation attempt (AI magic-wand). */
|
||||
sealed interface GitMessageGenerationState {
|
||||
data object Idle : GitMessageGenerationState
|
||||
data object Loading : GitMessageGenerationState
|
||||
data class Ready(val message: String, val notice: String) : GitMessageGenerationState
|
||||
}
|
||||
|
||||
/** Fixed per-use confirmation tokens matching the plugin's server constants. */
|
||||
object GitConfirmationStrings {
|
||||
const val DISCARD = "discard"
|
||||
const val PUSH = "push"
|
||||
const val DIRTY_CHECKOUT = "checkout-dirty"
|
||||
}
|
||||
|
||||
data class GitTarget(
|
||||
val scopeKey: String,
|
||||
val repoId: String,
|
||||
val generation: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* View model for the Git State Android surface (read + write).
|
||||
*
|
||||
* Loads the scanned repo list from the Hermes-Relay plugin and, on selection,
|
||||
* fetches working-tree status + branches. Mutations (stage/unstage/discard/
|
||||
* commit/fetch/pull/push/checkout) all require the ``plugin.api.write`` grant:
|
||||
* ``configure`` binds one connection/profile/Dashboard owner and every mutation
|
||||
* refuses (surfacing a readable message, never a POST) when that owner's grant
|
||||
* is absent. Destructive ops
|
||||
* (discard/push/dirty-checkout) additionally require a per-use confirmation
|
||||
* string the caller echoes from GitConfirmationStrings.
|
||||
*/
|
||||
class GitStateViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private val _repos = MutableStateFlow<GitStateUiState>(GitStateUiState.Loading)
|
||||
val repos: StateFlow<GitStateUiState> = _repos.asStateFlow()
|
||||
|
||||
private val _detail = MutableStateFlow<GitRepoDetailState>(GitRepoDetailState.Idle)
|
||||
val detail: StateFlow<GitRepoDetailState> = _detail.asStateFlow()
|
||||
|
||||
private val _content = MutableStateFlow<GitContentViewState>(GitContentViewState.Idle)
|
||||
val content: StateFlow<GitContentViewState> = _content.asStateFlow()
|
||||
|
||||
private val _mutation = MutableStateFlow<GitMutationState>(GitMutationState.Idle)
|
||||
val mutation: StateFlow<GitMutationState> = _mutation.asStateFlow()
|
||||
|
||||
private val _messageGeneration =
|
||||
MutableStateFlow<GitMessageGenerationState>(GitMessageGenerationState.Idle)
|
||||
val messageGeneration: StateFlow<GitMessageGenerationState> = _messageGeneration.asStateFlow()
|
||||
|
||||
private val _pushAfterCommit = MutableStateFlow(false)
|
||||
val pushAfterCommit: StateFlow<Boolean> = _pushAfterCommit.asStateFlow()
|
||||
|
||||
private val _stashNotice = MutableStateFlow<String?>(null)
|
||||
val stashNotice: StateFlow<String?> = _stashNotice.asStateFlow()
|
||||
|
||||
private val _writeGrant = MutableStateFlow(false)
|
||||
val writeGrant: StateFlow<Boolean> = _writeGrant.asStateFlow()
|
||||
|
||||
private val _selectedRepoId = MutableStateFlow<String?>(null)
|
||||
val selectedRepoId: StateFlow<String?> = _selectedRepoId.asStateFlow()
|
||||
|
||||
private var api: GitStateApiClient? = null
|
||||
private var reposJob: Job? = null
|
||||
private var detailJob: Job? = null
|
||||
private var contentJob: Job? = null
|
||||
private var mutationJob: Job? = null
|
||||
private var messageJob: Job? = null
|
||||
private var scopeKey: String? = null
|
||||
private var targetGeneration: Long = 0
|
||||
fun selectedRepoIdForDisplay(): String? = _selectedRepoId.value
|
||||
|
||||
fun currentTarget(): GitTarget? {
|
||||
val owner = scopeKey ?: return null
|
||||
val repo = _selectedRepoId.value ?: return null
|
||||
return GitTarget(owner, repo, targetGeneration)
|
||||
}
|
||||
|
||||
fun configure(dashboard: DashboardApiClient?, ownerKey: String?) {
|
||||
reposJob?.cancel()
|
||||
detailJob?.cancel()
|
||||
contentJob?.cancel()
|
||||
mutationJob?.cancel()
|
||||
messageJob?.cancel()
|
||||
targetGeneration += 1
|
||||
scopeKey = ownerKey
|
||||
_selectedRepoId.value = null
|
||||
_writeGrant.value = false
|
||||
_detail.value = GitRepoDetailState.Idle
|
||||
_content.value = GitContentViewState.Idle
|
||||
_mutation.value = GitMutationState.Idle
|
||||
_messageGeneration.value = GitMessageGenerationState.Idle
|
||||
_stashNotice.value = null
|
||||
api = dashboard?.let(::GitStateApiClient)
|
||||
loadRepos()
|
||||
}
|
||||
|
||||
/** Grants the plugin.api.write capability for this connection/profile. */
|
||||
fun setWriteGrant(ownerKey: String?, granted: Boolean) {
|
||||
if (ownerKey != scopeKey) return
|
||||
_writeGrant.value = granted
|
||||
}
|
||||
|
||||
fun hasWriteGrant(): Boolean = _writeGrant.value
|
||||
|
||||
fun loadRepos() {
|
||||
val client = api ?: run {
|
||||
_repos.value = GitStateUiState.Error("Dashboard connection unavailable")
|
||||
return
|
||||
}
|
||||
val expectedScope = scopeKey
|
||||
reposJob?.cancel()
|
||||
reposJob = viewModelScope.launch {
|
||||
_repos.value = GitStateUiState.Loading
|
||||
client.repos().fold(
|
||||
onSuccess = { list ->
|
||||
if (scopeKey == expectedScope) {
|
||||
_repos.value = GitStateUiState.Ready(list, null)
|
||||
}
|
||||
},
|
||||
onFailure = { error ->
|
||||
if (scopeKey == expectedScope) {
|
||||
val message = error.message.orEmpty()
|
||||
_repos.value = if (
|
||||
message.contains("HTTP 404", ignoreCase = true) ||
|
||||
message.contains("No such API endpoint", ignoreCase = true)
|
||||
) {
|
||||
GitStateUiState.Unavailable(
|
||||
"Git isn't available on this Hermes host yet.",
|
||||
)
|
||||
} else {
|
||||
GitStateUiState.Error(message.ifBlank { "Failed to load repositories" })
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun selectRepo(repoId: String) {
|
||||
val client = api ?: return
|
||||
targetGeneration += 1
|
||||
_selectedRepoId.value = repoId
|
||||
val target = currentTarget() ?: return
|
||||
_content.value = GitContentViewState.Idle
|
||||
_mutation.value = GitMutationState.Idle
|
||||
detailJob?.cancel()
|
||||
contentJob?.cancel()
|
||||
detailJob = viewModelScope.launch {
|
||||
_detail.value = GitRepoDetailState.Loading
|
||||
val statusResult = client.status(repoId)
|
||||
val branchesResult = client.branches(repoId)
|
||||
if (currentTarget() != target) return@launch
|
||||
if (statusResult.isFailure) {
|
||||
_detail.value = GitRepoDetailState.Error(
|
||||
statusResult.exceptionOrNull()?.message ?: "Failed to load status",
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
val status: GitStatus = statusResult.getOrThrow()
|
||||
val branches: List<GitBranch> = branchesResult.getOrDefault(emptyList())
|
||||
_detail.value = GitRepoDetailState.Ready(status, branches)
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs one owner/repository-bound mutation without cancelling another mutation. */
|
||||
private fun runMutation(
|
||||
label: String,
|
||||
expectedTarget: GitTarget? = null,
|
||||
onSuccess: (GitTarget) -> Unit = {},
|
||||
block: suspend (GitStateApiClient, String) -> Result<GitMutationState>,
|
||||
) {
|
||||
val client = api ?: run {
|
||||
_mutation.value = GitMutationState.Error(label, "Dashboard connection unavailable")
|
||||
return
|
||||
}
|
||||
val target = currentTarget() ?: run {
|
||||
_mutation.value = GitMutationState.Error(label, "No repository selected")
|
||||
return
|
||||
}
|
||||
if (expectedTarget != null && expectedTarget != target) {
|
||||
_mutation.value = GitMutationState.Error(label, "Repository context changed; review the action again.")
|
||||
return
|
||||
}
|
||||
if (!_writeGrant.value) {
|
||||
_mutation.value = GitMutationState.Error(
|
||||
label,
|
||||
"Allow plugin changes (plugin.api.write) before using this action.",
|
||||
)
|
||||
return
|
||||
}
|
||||
if (mutationJob?.isActive == true) {
|
||||
_mutation.value = GitMutationState.Error(label, "Another Git action is still in progress.")
|
||||
return
|
||||
}
|
||||
detailJob?.cancel()
|
||||
contentJob?.cancel()
|
||||
mutationJob = viewModelScope.launch {
|
||||
_mutation.value = GitMutationState.InProgress(label)
|
||||
block(client, target.repoId).fold(
|
||||
onSuccess = {
|
||||
if (currentTarget() != target) return@fold
|
||||
_mutation.value = it
|
||||
_content.value = GitContentViewState.Idle
|
||||
refreshDetail(client, target)
|
||||
onSuccess(target)
|
||||
},
|
||||
onFailure = { error ->
|
||||
if (currentTarget() == target) {
|
||||
_mutation.value = GitMutationState.Error(
|
||||
label,
|
||||
error.message ?: "Git action failed",
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun refreshDetail(client: GitStateApiClient, target: GitTarget) {
|
||||
val statusResult = client.status(target.repoId)
|
||||
val branchesResult = client.branches(target.repoId)
|
||||
if (currentTarget() == target && statusResult.isSuccess) {
|
||||
_detail.value = GitRepoDetailState.Ready(
|
||||
statusResult.getOrDefault(GitStatus()),
|
||||
branchesResult.getOrDefault(emptyList()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Read operations ────────────────────────────────────────────────────
|
||||
|
||||
fun loadDiff(path: String, kind: String) {
|
||||
val target = currentTarget() ?: return
|
||||
val client = api ?: return
|
||||
contentJob?.cancel()
|
||||
contentJob = viewModelScope.launch {
|
||||
_content.value = GitContentViewState.Loading
|
||||
client.diff(target.repoId, path, kind).fold(
|
||||
onSuccess = { diff ->
|
||||
if (currentTarget() == target) {
|
||||
_content.value = GitContentViewState.Diff(diff)
|
||||
}
|
||||
},
|
||||
onFailure = { error ->
|
||||
if (currentTarget() == target) {
|
||||
_content.value = GitContentViewState.Error(
|
||||
error.message ?: "Failed to load diff",
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun loadFile(path: String) {
|
||||
val target = currentTarget() ?: return
|
||||
val client = api ?: return
|
||||
contentJob?.cancel()
|
||||
contentJob = viewModelScope.launch {
|
||||
_content.value = GitContentViewState.Loading
|
||||
client.file(target.repoId, path).fold(
|
||||
onSuccess = { file ->
|
||||
if (currentTarget() == target) {
|
||||
_content.value = GitContentViewState.File(file)
|
||||
}
|
||||
},
|
||||
onFailure = { error ->
|
||||
if (currentTarget() == target) {
|
||||
_content.value = GitContentViewState.Error(
|
||||
error.message ?: "Failed to load file",
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Write operations ───────────────────────────────────────────────────
|
||||
|
||||
fun stage(paths: List<String>) = runMutation("Stage") { c, r ->
|
||||
c.stage(r, paths).map { GitMutationState.Success("stage", it.head) }
|
||||
}
|
||||
|
||||
fun unstage(paths: List<String>) = runMutation("Unstage") { c, r ->
|
||||
c.unstage(r, paths).map { GitMutationState.Success("unstage", it.head) }
|
||||
}
|
||||
|
||||
fun discard(
|
||||
paths: List<String>,
|
||||
confirmation: String,
|
||||
deleteUntracked: Boolean = false,
|
||||
expectedTarget: GitTarget? = null,
|
||||
) =
|
||||
runMutation("Discard", expectedTarget = expectedTarget) { c, r ->
|
||||
c.discard(r, paths, confirmation, deleteUntracked)
|
||||
.map { GitMutationState.Success("discard", it.head) }
|
||||
}
|
||||
|
||||
fun commit(message: String, onSuccess: (GitTarget) -> Unit = {}) =
|
||||
runMutation("Commit", onSuccess = onSuccess) { c, r ->
|
||||
c.commit(r, message).map {
|
||||
GitMutationState.Success("commit", it.head)
|
||||
}
|
||||
}
|
||||
|
||||
fun commitSelected(message: String, paths: List<String>) = runMutation("Commit") { c, r ->
|
||||
c.commitSelected(r, message, paths).map {
|
||||
GitMutationState.Success("commit", it.head)
|
||||
}
|
||||
}
|
||||
|
||||
fun fetch(remote: String = "origin") = runMutation("Fetch") { c, r ->
|
||||
c.fetch(r, remote).map { GitMutationState.Success("fetch", it.head) }
|
||||
}
|
||||
|
||||
fun pull(remote: String = "origin", branch: String = "") = runMutation("Pull") { c, r ->
|
||||
c.pull(r, remote, branch).map { GitMutationState.Success("pull", it.head) }
|
||||
}
|
||||
|
||||
fun push(
|
||||
confirmation: String,
|
||||
remote: String = "origin",
|
||||
branch: String = "",
|
||||
expectedTarget: GitTarget? = null,
|
||||
) =
|
||||
runMutation("Push", expectedTarget = expectedTarget) { c, r ->
|
||||
c.push(r, confirmation, remote, branch).map { GitMutationState.Success("push", it.head) }
|
||||
}
|
||||
|
||||
fun checkout(
|
||||
ref: String,
|
||||
confirmation: String? = null,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
expectedTarget: GitTarget? = null,
|
||||
) = runMutation("Checkout", expectedTarget = expectedTarget) { c, r ->
|
||||
c.checkout(r, ref, confirmation, newBranch, track)
|
||||
.map { GitMutationState.Success("checkout", it.head) }
|
||||
}
|
||||
|
||||
// ── Phase 3 extras ─────────────────────────────────────────────────────
|
||||
|
||||
/** Toggle the push-after-commit flow (default OFF; never bypasses confirm). */
|
||||
fun setPushAfterCommit(enabled: Boolean) {
|
||||
_pushAfterCommit.value = enabled
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a commit-message suggestion from the staged diff (AI magic-wand).
|
||||
* Empty staged diff / model-unavailable degrade to a notice, never an error.
|
||||
* Uses the shared write grant gate (a POST is never sent without the grant).
|
||||
*/
|
||||
fun generateCommitMessage(paths: List<String>? = null) {
|
||||
val client = api ?: run {
|
||||
_messageGeneration.value =
|
||||
GitMessageGenerationState.Ready("", "Dashboard connection unavailable")
|
||||
return
|
||||
}
|
||||
val target = currentTarget() ?: run {
|
||||
_messageGeneration.value = GitMessageGenerationState.Ready("", "No repository selected")
|
||||
return
|
||||
}
|
||||
if (!_writeGrant.value) {
|
||||
_messageGeneration.value = GitMessageGenerationState.Ready(
|
||||
"",
|
||||
"Allow plugin changes (plugin.api.write) before using this action.",
|
||||
)
|
||||
return
|
||||
}
|
||||
messageJob?.cancel()
|
||||
messageJob = viewModelScope.launch {
|
||||
_messageGeneration.value = GitMessageGenerationState.Loading
|
||||
val result = if (paths != null) {
|
||||
client.commitMessageSelected(target.repoId, paths)
|
||||
} else {
|
||||
client.commitMessage(target.repoId)
|
||||
}
|
||||
if (currentTarget() != target) return@launch
|
||||
result.fold(
|
||||
onSuccess = { msg ->
|
||||
_messageGeneration.value = GitMessageGenerationState.Ready(msg.message, msg.notice)
|
||||
},
|
||||
onFailure = { error ->
|
||||
_messageGeneration.value = GitMessageGenerationState.Ready(
|
||||
"",
|
||||
error.message ?: "Could not generate a commit message.",
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checkout that auto-stashes a dirty tree first. No confirmation is needed
|
||||
* because a stash is recoverable. Surfaces the stash message via [stashNotice].
|
||||
*/
|
||||
fun stashCheckout(ref: String, newBranch: String = "", track: Boolean = false) {
|
||||
val client = api ?: run {
|
||||
_mutation.value = GitMutationState.Error("Stash Checkout", "Dashboard connection unavailable")
|
||||
return
|
||||
}
|
||||
val target = currentTarget() ?: run {
|
||||
_mutation.value = GitMutationState.Error("Stash Checkout", "No repository selected")
|
||||
return
|
||||
}
|
||||
if (!_writeGrant.value) {
|
||||
_mutation.value = GitMutationState.Error(
|
||||
"Stash Checkout",
|
||||
"Allow plugin changes (plugin.api.write) before using this action.",
|
||||
)
|
||||
return
|
||||
}
|
||||
_stashNotice.value = null
|
||||
if (mutationJob?.isActive == true) {
|
||||
_mutation.value = GitMutationState.Error(
|
||||
"Stash Checkout",
|
||||
"Another Git action is still in progress.",
|
||||
)
|
||||
return
|
||||
}
|
||||
detailJob?.cancel()
|
||||
contentJob?.cancel()
|
||||
mutationJob = viewModelScope.launch {
|
||||
_mutation.value = GitMutationState.InProgress("Stash Checkout")
|
||||
client.stashCheckout(target.repoId, ref, newBranch, track).fold(
|
||||
onSuccess = { result ->
|
||||
if (currentTarget() != target) return@fold
|
||||
if (result.stashed) {
|
||||
_stashNotice.value =
|
||||
"Stashed changes on $ref as \"${result.stashMessage}\". Use \"git stash pop\" to restore them."
|
||||
}
|
||||
_mutation.value = GitMutationState.Success("stash-checkout", result.head)
|
||||
_content.value = GitContentViewState.Idle
|
||||
refreshDetail(client, target)
|
||||
},
|
||||
onFailure = { error ->
|
||||
if (currentTarget() == target) {
|
||||
_mutation.value = GitMutationState.Error(
|
||||
"Stash Checkout",
|
||||
error.message ?: "Git action failed",
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearStashNotice() {
|
||||
_stashNotice.value = null
|
||||
}
|
||||
|
||||
/** True when the push-after-commit toggle is currently enabled. */
|
||||
fun isPushAfterCommitEnabled(): Boolean = _pushAfterCommit.value
|
||||
|
||||
/** True when the named destructive op needs a confirmation echo. */
|
||||
fun requiresConfirmation(op: String): Boolean = op in setOf("discard", "push", "dirty-checkout")
|
||||
|
||||
/** Fixed confirmation token for a destructive op (matches the server). */
|
||||
fun confirmationFor(op: String): String? = when (op) {
|
||||
"discard" -> GitConfirmationStrings.DISCARD
|
||||
"push" -> GitConfirmationStrings.PUSH
|
||||
"dirty-checkout" -> GitConfirmationStrings.DIRTY_CHECKOUT
|
||||
else -> null
|
||||
}
|
||||
|
||||
fun clearMutationError() {
|
||||
if (_mutation.value is GitMutationState.Error) {
|
||||
_mutation.value = GitMutationState.Idle
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ sealed interface PluginsHubState {
|
||||
data object Disconnected : PluginsHubState
|
||||
data object Loading : PluginsHubState
|
||||
data class Ready(
|
||||
val ownerKey: String,
|
||||
val plugins: List<PluginHubItem>,
|
||||
val preview: PluginCatalogPreview,
|
||||
val refreshing: Boolean = false,
|
||||
@@ -220,6 +221,7 @@ class PluginsViewModel(application: Application) : AndroidViewModel(application)
|
||||
_hubState.value = result.fold(
|
||||
onSuccess = { items ->
|
||||
PluginsHubState.Ready(
|
||||
ownerKey = expectedKey,
|
||||
plugins = items,
|
||||
preview = catalogPreview(items),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
|
||||
/**
|
||||
* Fail-closed dispatch policy for Android Supervised Mode.
|
||||
*
|
||||
* This intentionally runs before demo handling, route selection, slash.exec,
|
||||
* command.dispatch, steering, and queueing. Kotlin's default trim recognizes
|
||||
* Unicode whitespace, preventing an indented slash command from bypassing the
|
||||
* client restriction.
|
||||
*/
|
||||
internal fun supervisedMessageBlockReason(
|
||||
policy: SupervisedModePolicy,
|
||||
text: String,
|
||||
): String? {
|
||||
if (!policy.enabled) return null
|
||||
if (!policy.isConfigured) {
|
||||
return "Supervised mode is unavailable until the parent selects a profile."
|
||||
}
|
||||
if (text.trimStart().startsWith('/')) {
|
||||
return "Slash commands are unavailable in supervised mode."
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -21,6 +21,8 @@ import com.hermesandroid.relay.data.DEFAULT_VOICE_STOP_PHRASES
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.RealtimeConversationContextMessage
|
||||
import com.hermesandroid.relay.data.SupervisedCapabilities
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.data.ToolCall
|
||||
import com.hermesandroid.relay.data.VoiceEngineMode
|
||||
import com.hermesandroid.relay.data.VoiceIntentTrace
|
||||
@@ -279,6 +281,23 @@ internal fun realtimeTranscriptState(micCaptureActive: Boolean): VoiceState =
|
||||
*/
|
||||
enum class InteractionMode { TapToTalk, HoldToTalk, Continuous }
|
||||
|
||||
internal fun isVoiceCommandAllowed(
|
||||
action: VoiceCommandAction,
|
||||
policy: SupervisedModePolicy,
|
||||
): Boolean {
|
||||
if (!policy.enabled) return true
|
||||
val capabilities: SupervisedCapabilities = policy.capabilities
|
||||
return when (action) {
|
||||
VoiceCommandAction.StartNewChat -> capabilities.newChat
|
||||
VoiceCommandAction.StopResponse,
|
||||
VoiceCommandAction.CancelBackgroundTask -> capabilities.cancelResponse
|
||||
VoiceCommandAction.EndVoiceChat,
|
||||
VoiceCommandAction.PauseContinuousListening,
|
||||
VoiceCommandAction.ResumeContinuousListening,
|
||||
VoiceCommandAction.RepeatBackgroundAnswer -> capabilities.voice
|
||||
}
|
||||
}
|
||||
|
||||
internal fun InteractionMode.storageValue(): String = when (this) {
|
||||
InteractionMode.TapToTalk -> "tap"
|
||||
InteractionMode.HoldToTalk -> "hold"
|
||||
@@ -723,6 +742,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private var voicePreferences: VoicePreferencesRepository? = null
|
||||
private var voicePreferencesJob: Job? = null
|
||||
private var voiceEngineMode: VoiceEngineMode = VoiceEngineMode.HermesVoiceOutput
|
||||
private var supervisedModePolicy: SupervisedModePolicy = SupervisedModePolicy()
|
||||
private var voiceStopPhrases: List<String> = DEFAULT_VOICE_STOP_PHRASES
|
||||
private var finalAnswerOnly: Boolean = false
|
||||
private var realtimeTraceDetails: Boolean = false
|
||||
@@ -1380,6 +1400,28 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply the active Android client policy at the voice coordinator boundary. */
|
||||
fun updateSupervisedModePolicy(policy: SupervisedModePolicy) {
|
||||
supervisedModePolicy = policy
|
||||
val supervised = policy.enabled
|
||||
voiceAudioClient?.setRouteOverride(if (supervised) VoiceAudioRoute.Standard else null)
|
||||
if (supervised) {
|
||||
if (voiceEngineMode == VoiceEngineMode.RealtimeAgent) closeRealtimeSession()
|
||||
voiceEngineMode = VoiceEngineMode.HermesVoiceOutput
|
||||
_voiceStats.update {
|
||||
it.copy(
|
||||
voiceEngineMode = VoiceEngineMode.HermesVoiceOutput.storageValue,
|
||||
)
|
||||
}
|
||||
if (!policy.capabilities.voice && _uiState.value.voiceMode) exitVoiceMode()
|
||||
} else {
|
||||
val prefs = voicePreferences ?: return
|
||||
viewModelScope.launch {
|
||||
prefs.settings.firstOrNull()?.let { applyVoiceSettingsSnapshot(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun persistInteractionMode(mode: InteractionMode) {
|
||||
val prefs = voicePreferences ?: return
|
||||
viewModelScope.launch {
|
||||
@@ -1485,7 +1527,11 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
) {
|
||||
closeRealtimeSession()
|
||||
}
|
||||
voiceEngineMode = nextEngineMode
|
||||
voiceEngineMode = if (supervisedModePolicy.enabled) {
|
||||
VoiceEngineMode.HermesVoiceOutput
|
||||
} else {
|
||||
nextEngineMode
|
||||
}
|
||||
voiceStopPhrases = settings.stopPhrases
|
||||
finalAnswerOnly = settings.finalAnswerOnly
|
||||
realtimeTraceDetails = settings.realtimeTraceDetails
|
||||
@@ -1506,7 +1552,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
it.copy(
|
||||
vadThresholdMs = settings.silenceThresholdMs,
|
||||
interactionMode = settings.interactionMode,
|
||||
voiceEngineMode = settings.engineMode,
|
||||
voiceEngineMode = voiceEngineMode.storageValue,
|
||||
realtimeModel = settings.realtimeModel,
|
||||
realtimeVoice = settings.realtimeVoice,
|
||||
)
|
||||
@@ -1540,6 +1586,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
activationId: String? = null,
|
||||
expectScreenContext: Boolean = false,
|
||||
) {
|
||||
if (supervisedModePolicy.enabled && !supervisedModePolicy.capabilities.voice) return
|
||||
val freshEntry = !_uiState.value.voiceMode
|
||||
val orphanedRun = _uiState.value
|
||||
.takeIf { freshEntry }
|
||||
@@ -2430,6 +2477,10 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
if (!canSpeakSettledResponse(state, providerRealtimeAgentTurnActive.get())) {
|
||||
return false
|
||||
}
|
||||
if (
|
||||
supervisedModePolicy.enabled &&
|
||||
voiceAudioClient?.effectiveRoute != VoiceAudioRoute.Standard
|
||||
) return false
|
||||
|
||||
val spoken = sanitizeForTts(text)
|
||||
if (spoken.isBlank()) return false
|
||||
@@ -3007,6 +3058,17 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!isVoiceCommandAllowed(action, supervisedModePolicy)) {
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
state = VoiceState.Idle,
|
||||
outputAudioActive = false,
|
||||
responseText = "That voice action is disabled by Parent controls.",
|
||||
)
|
||||
}
|
||||
return action
|
||||
}
|
||||
|
||||
Log.i(TAG, "Hands-free voice command action=$action source=${if (fromRealtime) "realtime" else "stt"}")
|
||||
DiagnosticsLog.record(
|
||||
category = DiagnosticCategory.Voice,
|
||||
@@ -3076,12 +3138,23 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
setError("Voice pipeline not initialized")
|
||||
return
|
||||
}
|
||||
if (
|
||||
supervisedModePolicy.enabled &&
|
||||
audioClient.effectiveRoute != VoiceAudioRoute.Standard
|
||||
) {
|
||||
setError("Supervised voice requires the Standard Hermes voice route")
|
||||
return
|
||||
}
|
||||
currentTurnPcm = inputPcm
|
||||
currentTurnPcmSampleRate = inputSampleRate
|
||||
resetBrokeredToolSpeechState()
|
||||
resetRealtimeSpeechCoalescer()
|
||||
resetTtsTurnStats()
|
||||
val engineModeForTurn = voiceEngineMode
|
||||
val engineModeForTurn = if (supervisedModePolicy.enabled) {
|
||||
VoiceEngineMode.HermesVoiceOutput
|
||||
} else {
|
||||
voiceEngineMode
|
||||
}
|
||||
Log.i(
|
||||
TAG,
|
||||
"Processing voice input engine=${engineModeForTurn.storageValue} " +
|
||||
@@ -3230,7 +3303,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
// ever mis-edited. If/when a `BuildFlavor.bridgeTier3` compile-
|
||||
// time constant exists we should still short-circuit here for
|
||||
// clarity, but today the factory already does the right thing.
|
||||
val bridgeHandler = voiceBridgeIntentHandler
|
||||
val bridgeHandler = voiceBridgeIntentHandler.takeUnless { supervisedModePolicy.enabled }
|
||||
|
||||
// === PHASE3-voice-cancel-midcountdown ===
|
||||
// Voice-in-voice cancel: if a destructive action is currently
|
||||
@@ -4906,7 +4979,8 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
private fun shouldPreferRealtimeVoice(): Boolean =
|
||||
voiceOutputAvailable != false &&
|
||||
!supervisedModePolicy.enabled &&
|
||||
voiceOutputAvailable != false &&
|
||||
realtimePcmPlayer != null &&
|
||||
voiceClient != null &&
|
||||
// Use the RESOLVED route: AutoVoiceAudioClient.effectiveRoute maps
|
||||
|
||||
@@ -657,6 +657,14 @@
|
||||
<string name="settings_analytics_desc">Estatísticas de uso, TTFT, tokens e integridade</string>
|
||||
<string name="settings_diagnostics">Diagnóstico</string>
|
||||
<string name="settings_diagnostics_desc">Verificações de status e atividade recente da API, do relay, da sessão e da voz</string>
|
||||
<string name="settings_advanced">Avançado</string>
|
||||
<string name="settings_advanced_desc">Modo supervisionado e outros recursos opcionais</string>
|
||||
<string name="settings_advanced_intro">Recursos opcionais e especializados ficam aqui para manter a tela principal de Configurações organizada.</string>
|
||||
<string name="settings_supervised_mode">Modo supervisionado</string>
|
||||
<string name="settings_supervised_desc">Escolha um perfil e os recursos de chat permitidos</string>
|
||||
<string name="settings_supervised_on">Ativado</string>
|
||||
<string name="settings_supervised_on_profile">Ativado · %1$s</string>
|
||||
<string name="settings_supervised_ready_profile">Pronto · %1$s</string>
|
||||
<string name="settings_developer_options">Opções do desenvolvedor</string>
|
||||
<string name="settings_developer_options_desc">Flags de recursos, gerenciamento de dados e opções experimentais</string>
|
||||
<string name="settings_whats_new">Novidades</string>
|
||||
@@ -3850,6 +3858,48 @@
|
||||
<string name="plugins_keep">Manter</string>
|
||||
<string name="plugins_remove">Remover</string>
|
||||
<string name="plugins_remove_confirm">Remover “%1$s”? Esta página do plugin não aparecerá mais nos dispositivos Android conectados.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_back">Voltar</string>
|
||||
<string name="git_state_staged">Preparados</string>
|
||||
<string name="git_state_modified">Modificados</string>
|
||||
<string name="git_state_untracked">Não rastreados</string>
|
||||
<string name="git_state_branches">Ramos</string>
|
||||
<string name="git_state_truncated">Resultados truncados — apenas as primeiras entradas são exibidas.</string>
|
||||
<string name="git_state_no_changes">(sem alterações)</string>
|
||||
|
||||
<string name="git_state_write_grant_required">Alterações de gravação exigem a permissão de alterações de plugin. Ative "Permitir alterações de plugins (plugin.api.write)" nas configurações de permissão de Plugins.</string>
|
||||
<string name="git_state_stage">Preparar</string>
|
||||
<string name="git_state_unstage">Despreparar</string>
|
||||
<string name="git_state_discard">Descartar</string>
|
||||
<string name="git_state_commit">Confirmar</string>
|
||||
<string name="git_state_commit_title">Confirmar alterações preparadas</string>
|
||||
<string name="git_state_commit_message_hint">Mensagem do commit</string>
|
||||
<string name="git_state_commit_confirm">Confirmar</string>
|
||||
<string name="git_state_cancel">Cancelar</string>
|
||||
<string name="git_state_fetch">Buscar</string>
|
||||
<string name="git_state_pull">Puxar</string>
|
||||
<string name="git_state_push">Enviar</string>
|
||||
<string name="git_state_new_branch_hint">Nome da nova ramificação</string>
|
||||
<string name="git_state_create_branch">Criar ramificação</string>
|
||||
<string name="git_state_track_remote">Rastrear ramificação remota</string>
|
||||
<string name="git_state_switch">Alternar</string>
|
||||
<string name="git_state_current">Atual</string>
|
||||
<string name="git_state_mutation_in_progress">%1$s em andamento…</string>
|
||||
<string name="git_state_mutation_success">%1$s concluído. HEAD %2$s</string>
|
||||
<string name="git_state_mutation_failed">%1$s falhou: %2$s</string>
|
||||
<string name="git_state_confirm_discard_title">Descartar alterações?</string>
|
||||
<string name="git_state_confirm_discard_text">As alterações locais dos arquivos selecionados serão descartadas e não poderão ser recuperadas.</string>
|
||||
<string name="git_state_confirm_discard_confirm">Descartar</string>
|
||||
<string name="git_state_confirm_push_title">Enviar alterações?</string>
|
||||
<string name="git_state_confirm_push_text">Envia a ramificação atual para o repositório remoto. Isso publica os commits locais no repositório remoto.</string>
|
||||
<string name="git_state_confirm_push_confirm">Enviar</string>
|
||||
<string name="git_state_confirm_checkout_dirty_title">Alternar ramificação com alterações locais?</string>
|
||||
<string name="git_state_confirm_checkout_dirty_text">A árvore de trabalho tem alterações não confirmadas. A alternância pode carregá-las para a ramificação de destino.</string>
|
||||
<string name="git_state_confirm_checkout_confirm">Alternar</string>
|
||||
<string name="git_state_generate_message">Gerar mensagem de commit</string>
|
||||
<string name="git_state_generating_message">Gerando mensagem de commit…</string>
|
||||
<string name="git_state_push_after_commit">Enviar após o commit</string>
|
||||
<string name="git_state_switch_stash">Alternar (guardar se houver alterações)</string>
|
||||
<string name="support_bundle_review">Revisar informações de suporte</string>
|
||||
<string name="support_bundle_title">Informações de suporte</string>
|
||||
<string name="support_bundle_privacy">Nada é enviado automaticamente. Revise a exportação local com até %1$d relatórios.</string>
|
||||
@@ -4215,4 +4265,13 @@
|
||||
<string name="custom_theme_saved_to">Alterações salvas em %1$s</string>
|
||||
<string name="custom_theme_modified">Alterações não salvas</string>
|
||||
<string name="custom_theme_saved_count">%1$d temas salvos</string>
|
||||
<string name="chat_settings_show_git_workspace">Mostrar o espaço de trabalho Git no chat</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Mostra a branch e as alterações acima do campo de mensagem</string>
|
||||
<string name="chat_git_open_workspace">Abrir o espaço de trabalho Git</string>
|
||||
<string name="chat_git_branch">Branch %1$s</string>
|
||||
<string name="chat_git_additions">%1$d adições</string>
|
||||
<string name="chat_git_deletions">%1$d exclusões</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d alteração</item><item quantity="other">%1$d alterações</item></plurals>
|
||||
<string name="settings_git_workspace">Espaço de trabalho Git</string>
|
||||
<string name="settings_git_workspace_desc">Revise alterações, branches, commits e remotos</string>
|
||||
</resources>
|
||||
|
||||
@@ -698,6 +698,14 @@
|
||||
<string name="settings_analytics_desc">使用统计、TTFT、token、健康状态</string>
|
||||
<string name="settings_diagnostics">诊断</string>
|
||||
<string name="settings_diagnostics_desc">状态检查,以及最近的 API、Relay、会话和语音活动</string>
|
||||
<string name="settings_advanced">高级</string>
|
||||
<string name="settings_advanced_desc">受监督模式和其他可选功能</string>
|
||||
<string name="settings_advanced_intro">可选和专用功能集中在此,以保持主设置界面简洁。</string>
|
||||
<string name="settings_supervised_mode">受监督模式</string>
|
||||
<string name="settings_supervised_desc">选择配置文件和允许的聊天功能</string>
|
||||
<string name="settings_supervised_on">已开启</string>
|
||||
<string name="settings_supervised_on_profile">已开启 · %1$s</string>
|
||||
<string name="settings_supervised_ready_profile">已就绪 · %1$s</string>
|
||||
<string name="settings_developer_options">开发者选项</string>
|
||||
<string name="settings_developer_options_desc">功能标志、数据管理、实验性</string>
|
||||
<string name="settings_whats_new">新功能</string>
|
||||
@@ -3938,6 +3946,48 @@
|
||||
<string name="plugins_keep">保留</string>
|
||||
<string name="plugins_remove">移除</string>
|
||||
<string name="plugins_remove_confirm">要移除“%1$s”吗?此插件页面将不再显示在已连接的 Android 设备上。</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_back">返回</string>
|
||||
<string name="git_state_staged">已暂存</string>
|
||||
<string name="git_state_modified">已修改</string>
|
||||
<string name="git_state_untracked">未跟踪</string>
|
||||
<string name="git_state_branches">分支</string>
|
||||
<string name="git_state_truncated">结果已截断 — 仅显示前几条。</string>
|
||||
<string name="git_state_no_changes">(无更改)</string>
|
||||
|
||||
<string name="git_state_write_grant_required">写入更改需要插件更改权限。请在“插件”的权限设置中启用“允许插件更改 (plugin.api.write)”。</string>
|
||||
<string name="git_state_stage">暂存</string>
|
||||
<string name="git_state_unstage">取消暂存</string>
|
||||
<string name="git_state_discard">丢弃</string>
|
||||
<string name="git_state_commit">提交</string>
|
||||
<string name="git_state_commit_title">提交已暂存的更改</string>
|
||||
<string name="git_state_commit_message_hint">提交消息</string>
|
||||
<string name="git_state_commit_confirm">提交</string>
|
||||
<string name="git_state_cancel">取消</string>
|
||||
<string name="git_state_fetch">获取</string>
|
||||
<string name="git_state_pull">拉取</string>
|
||||
<string name="git_state_push">推送</string>
|
||||
<string name="git_state_new_branch_hint">新分支名称</string>
|
||||
<string name="git_state_create_branch">创建分支</string>
|
||||
<string name="git_state_track_remote">跟踪远程分支</string>
|
||||
<string name="git_state_switch">切换</string>
|
||||
<string name="git_state_current">当前</string>
|
||||
<string name="git_state_mutation_in_progress">%1$s 正在进行…</string>
|
||||
<string name="git_state_mutation_success">%1$s 已完成。HEAD %2$s</string>
|
||||
<string name="git_state_mutation_failed">%1$s 失败:%2$s</string>
|
||||
<string name="git_state_confirm_discard_title">丢弃更改?</string>
|
||||
<string name="git_state_confirm_discard_text">所选文件的本地更改将被丢弃,且无法恢复。</string>
|
||||
<string name="git_state_confirm_discard_confirm">丢弃</string>
|
||||
<string name="git_state_confirm_push_title">推送更改?</string>
|
||||
<string name="git_state_confirm_push_text">将当前分支推送到其远程仓库。这会把本地提交发送到远程仓库。</string>
|
||||
<string name="git_state_confirm_push_confirm">推送</string>
|
||||
<string name="git_state_confirm_checkout_dirty_title">切换包含本地更改的分支?</string>
|
||||
<string name="git_state_confirm_checkout_dirty_text">工作区有未提交的更改。切换后,这些更改可能会被带到目标分支。</string>
|
||||
<string name="git_state_confirm_checkout_confirm">切换</string>
|
||||
<string name="git_state_generate_message">生成提交信息</string>
|
||||
<string name="git_state_generating_message">正在生成提交信息…</string>
|
||||
<string name="git_state_push_after_commit">提交后推送</string>
|
||||
<string name="git_state_switch_stash">切换(有更改时暂存)</string>
|
||||
<string name="support_bundle_review">查看支持信息</string>
|
||||
<string name="support_bundle_title">支持信息</string>
|
||||
<string name="support_bundle_privacy">不会自动上传任何内容。请查看最多包含 %1$d 个报告的本地导出。</string>
|
||||
@@ -4300,4 +4350,13 @@
|
||||
<string name="custom_theme_saved_to">更改已保存到 %1$s</string>
|
||||
<string name="custom_theme_modified">未保存的更改</string>
|
||||
<string name="custom_theme_saved_count">已保存 %1$d 个预设</string>
|
||||
<string name="chat_settings_show_git_workspace">在聊天中显示 Git 工作区</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">在输入框上方显示分支和更改</string>
|
||||
<string name="chat_git_open_workspace">打开 Git 工作区</string>
|
||||
<string name="chat_git_branch">分支 %1$s</string>
|
||||
<string name="chat_git_additions">新增 %1$d 行</string>
|
||||
<string name="chat_git_deletions">删除 %1$d 行</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="other">%1$d 个更改</item></plurals>
|
||||
<string name="settings_git_workspace">Git 工作区</string>
|
||||
<string name="settings_git_workspace_desc">查看更改、分支、提交和远程仓库</string>
|
||||
</resources>
|
||||
|
||||
@@ -698,6 +698,14 @@
|
||||
<string name="settings_analytics_desc">Nutzungsstatistiken, TTFT, Token, Status</string>
|
||||
<string name="settings_diagnostics">Diagnose</string>
|
||||
<string name="settings_diagnostics_desc">Statusprüfungen sowie letzte API-, Relay-, Sitzungs- und Sprachaktivitäten</string>
|
||||
<string name="settings_advanced">Erweitert</string>
|
||||
<string name="settings_advanced_desc">Beaufsichtigter Modus und weitere optionale Funktionen</string>
|
||||
<string name="settings_advanced_intro">Optionale und spezielle Funktionen befinden sich hier, damit die Haupteinstellungen übersichtlich bleiben.</string>
|
||||
<string name="settings_supervised_mode">Beaufsichtigter Modus</string>
|
||||
<string name="settings_supervised_desc">Profil und erlaubte Chatfunktionen auswählen</string>
|
||||
<string name="settings_supervised_on">Ein</string>
|
||||
<string name="settings_supervised_on_profile">Ein · %1$s</string>
|
||||
<string name="settings_supervised_ready_profile">Bereit · %1$s</string>
|
||||
<string name="settings_developer_options">Entwickleroptionen</string>
|
||||
<string name="settings_developer_options_desc">Funktionsschalter, Datenverwaltung, Experimente</string>
|
||||
<string name="settings_whats_new">Neuigkeiten</string>
|
||||
@@ -4010,6 +4018,48 @@
|
||||
<string name="plugins_keep">Behalten</string>
|
||||
<string name="plugins_remove">Entfernen</string>
|
||||
<string name="plugins_remove_confirm">„%1$s“ entfernen? Diese Plugin-Seite wird auf verbundenen Android-Geräten nicht mehr angezeigt.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_back">Zurück</string>
|
||||
<string name="git_state_staged">Gestaged</string>
|
||||
<string name="git_state_modified">Geändert</string>
|
||||
<string name="git_state_untracked">Unverfolgt</string>
|
||||
<string name="git_state_branches">Branches</string>
|
||||
<string name="git_state_truncated">Ergebnisse abgeschnitten – nur die ersten Einträge werden angezeigt.</string>
|
||||
<string name="git_state_no_changes">(keine Änderungen)</string>
|
||||
|
||||
<string name="git_state_write_grant_required">Für Schreibvorgänge ist die Plugin-Änderungsberechtigung erforderlich. Aktivieren Sie „Änderungen durch Plugins zulassen (plugin.api.write)“ in den Plugin-Berechtigungseinstellungen.</string>
|
||||
<string name="git_state_stage">Bereitstellen</string>
|
||||
<string name="git_state_unstage">Zurücksetzen</string>
|
||||
<string name="git_state_discard">Verwerfen</string>
|
||||
<string name="git_state_commit">Committen</string>
|
||||
<string name="git_state_commit_title">Bereitgestellte Änderungen committen</string>
|
||||
<string name="git_state_commit_message_hint">Commit-Nachricht</string>
|
||||
<string name="git_state_commit_confirm">Committen</string>
|
||||
<string name="git_state_cancel">Abbrechen</string>
|
||||
<string name="git_state_fetch">Abrufen</string>
|
||||
<string name="git_state_pull">Pullen</string>
|
||||
<string name="git_state_push">Pushen</string>
|
||||
<string name="git_state_new_branch_hint">Name des neuen Branches</string>
|
||||
<string name="git_state_create_branch">Branch erstellen</string>
|
||||
<string name="git_state_track_remote">Remote-Branch verfolgen</string>
|
||||
<string name="git_state_switch">Wechseln</string>
|
||||
<string name="git_state_current">Aktuell</string>
|
||||
<string name="git_state_mutation_in_progress">%1$s läuft…</string>
|
||||
<string name="git_state_mutation_success">%1$s abgeschlossen. HEAD %2$s</string>
|
||||
<string name="git_state_mutation_failed">%1$s fehlgeschlagen: %2$s</string>
|
||||
<string name="git_state_confirm_discard_title">Änderungen verwerfen?</string>
|
||||
<string name="git_state_confirm_discard_text">Lokale Änderungen an den ausgewählten Dateien werden verworfen und können nicht wiederhergestellt werden.</string>
|
||||
<string name="git_state_confirm_discard_confirm">Verwerfen</string>
|
||||
<string name="git_state_confirm_push_title">Änderungen pushen?</string>
|
||||
<string name="git_state_confirm_push_text">Pushen Sie den aktuellen Branch zu seinem Remote. Dabei werden lokale Commits an das Remote-Repository gesendet.</string>
|
||||
<string name="git_state_confirm_push_confirm">Pushen</string>
|
||||
<string name="git_state_confirm_checkout_dirty_title">Branch mit lokalen Änderungen wechseln?</string>
|
||||
<string name="git_state_confirm_checkout_dirty_text">Der Arbeitsbaum enthält nicht committete Änderungen. Beim Wechseln werden sie möglicherweise auf den Zielbranch übertragen.</string>
|
||||
<string name="git_state_confirm_checkout_confirm">Wechseln</string>
|
||||
<string name="git_state_generate_message">Commit-Nachricht generieren</string>
|
||||
<string name="git_state_generating_message">Commit-Nachricht wird generiert…</string>
|
||||
<string name="git_state_push_after_commit">Nach Commit pushen</string>
|
||||
<string name="git_state_switch_stash">Wechseln (bei Änderungen stashen)</string>
|
||||
<string name="support_bundle_review">Supportinformationen prüfen</string>
|
||||
<string name="support_bundle_title">Supportinformationen</string>
|
||||
<string name="support_bundle_privacy">Nichts wird automatisch hochgeladen. Prüfen Sie den lokalen Export mit bis zu %1$d Berichten.</string>
|
||||
@@ -4375,4 +4425,13 @@
|
||||
<string name="custom_theme_saved_to">Änderungen in %1$s gespeichert</string>
|
||||
<string name="custom_theme_modified">Nicht gespeicherte Änderungen</string>
|
||||
<string name="custom_theme_saved_count">%1$d gespeicherte Presets</string>
|
||||
<string name="chat_settings_show_git_workspace">Git-Arbeitsbereich im Chat anzeigen</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Zeigt Branch und Änderungen über dem Eingabefeld an</string>
|
||||
<string name="chat_git_open_workspace">Git-Arbeitsbereich öffnen</string>
|
||||
<string name="chat_git_branch">Branch %1$s</string>
|
||||
<string name="chat_git_additions">%1$d Hinzufügungen</string>
|
||||
<string name="chat_git_deletions">%1$d Löschungen</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d Änderung</item><item quantity="other">%1$d Änderungen</item></plurals>
|
||||
<string name="settings_git_workspace">Git-Arbeitsbereich</string>
|
||||
<string name="settings_git_workspace_desc">Änderungen, Branches, Commits und Remotes prüfen</string>
|
||||
</resources>
|
||||
|
||||
@@ -625,6 +625,14 @@
|
||||
<string name="settings_analytics_desc">Estadísticas de uso, TTFT, tokens, salud</string>
|
||||
<string name="settings_diagnostics">Diagnóstico</string>
|
||||
<string name="settings_diagnostics_desc">Verificaciones de estado, además de actividad reciente de API, relay, sesión y voz</string>
|
||||
<string name="settings_advanced">Avanzado</string>
|
||||
<string name="settings_advanced_desc">Modo supervisado y otras funciones opcionales</string>
|
||||
<string name="settings_advanced_intro">Las funciones opcionales y especializadas están aquí para mantener despejada la pantalla principal de Ajustes.</string>
|
||||
<string name="settings_supervised_mode">Modo supervisado</string>
|
||||
<string name="settings_supervised_desc">Elige un perfil y las funciones de chat permitidas</string>
|
||||
<string name="settings_supervised_on">Activado</string>
|
||||
<string name="settings_supervised_on_profile">Activado · %1$s</string>
|
||||
<string name="settings_supervised_ready_profile">Listo · %1$s</string>
|
||||
<string name="settings_developer_options">Opciones de desarrollador</string>
|
||||
<string name="settings_developer_options_desc">Indicadores de funciones, gestión de datos, experimental.</string>
|
||||
<string name="settings_whats_new">Novedades</string>
|
||||
@@ -3695,6 +3703,48 @@
|
||||
<string name="plugins_keep">Conservar</string>
|
||||
<string name="plugins_remove">Eliminar</string>
|
||||
<string name="plugins_remove_confirm">¿Eliminar «%1$s»? Esta página del plugin dejará de aparecer en los dispositivos Android conectados.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_back">Atrás</string>
|
||||
<string name="git_state_staged">Preparados</string>
|
||||
<string name="git_state_modified">Modificados</string>
|
||||
<string name="git_state_untracked">Sin seguimiento</string>
|
||||
<string name="git_state_branches">Ramas</string>
|
||||
<string name="git_state_truncated">Resultados truncados: solo se muestran las primeras entradas.</string>
|
||||
<string name="git_state_no_changes">(sin cambios)</string>
|
||||
|
||||
<string name="git_state_write_grant_required">Los cambios de escritura requieren el permiso de cambios de plugin. Activa «Permitir cambios de plugins (plugin.api.write)» en la configuración de permisos de Plugins.</string>
|
||||
<string name="git_state_stage">Preparar</string>
|
||||
<string name="git_state_unstage">Quitar de preparados</string>
|
||||
<string name="git_state_discard">Descartar</string>
|
||||
<string name="git_state_commit">Confirmar</string>
|
||||
<string name="git_state_commit_title">Confirmar cambios preparados</string>
|
||||
<string name="git_state_commit_message_hint">Mensaje de confirmación</string>
|
||||
<string name="git_state_commit_confirm">Confirmar</string>
|
||||
<string name="git_state_cancel">Cancelar</string>
|
||||
<string name="git_state_fetch">Obtener</string>
|
||||
<string name="git_state_pull">Traer</string>
|
||||
<string name="git_state_push">Enviar</string>
|
||||
<string name="git_state_new_branch_hint">Nombre de la nueva rama</string>
|
||||
<string name="git_state_create_branch">Crear rama</string>
|
||||
<string name="git_state_track_remote">Seguir rama remota</string>
|
||||
<string name="git_state_switch">Cambiar</string>
|
||||
<string name="git_state_current">Actual</string>
|
||||
<string name="git_state_mutation_in_progress">%1$s en curso…</string>
|
||||
<string name="git_state_mutation_success">%1$s completado. HEAD %2$s</string>
|
||||
<string name="git_state_mutation_failed">%1$s falló: %2$s</string>
|
||||
<string name="git_state_confirm_discard_title">¿Descartar cambios?</string>
|
||||
<string name="git_state_confirm_discard_text">Los cambios locales de los archivos seleccionados se descartarán y no podrán recuperarse.</string>
|
||||
<string name="git_state_confirm_discard_confirm">Descartar</string>
|
||||
<string name="git_state_confirm_push_title">¿Enviar cambios?</string>
|
||||
<string name="git_state_confirm_push_text">Envía la rama actual a su remoto. Esto sube los commits locales al repositorio remoto.</string>
|
||||
<string name="git_state_confirm_push_confirm">Enviar</string>
|
||||
<string name="git_state_confirm_checkout_dirty_title">¿Cambiar de rama con cambios locales?</string>
|
||||
<string name="git_state_confirm_checkout_dirty_text">El árbol de trabajo tiene cambios sin confirmar. Cambiar puede trasladarlos a la rama de destino.</string>
|
||||
<string name="git_state_confirm_checkout_confirm">Cambiar</string>
|
||||
<string name="git_state_generate_message">Generar mensaje de confirmación</string>
|
||||
<string name="git_state_generating_message">Generando mensaje de confirmación…</string>
|
||||
<string name="git_state_push_after_commit">Enviar después de confirmar</string>
|
||||
<string name="git_state_switch_stash">Cambiar (guardar en stash si hay cambios)</string>
|
||||
<string name="support_bundle_review">Revisar información de soporte</string>
|
||||
<string name="support_bundle_title">Información de soporte</string>
|
||||
<string name="support_bundle_privacy">Nada se sube automáticamente. Revisa la exportación local con hasta %1$d informes.</string>
|
||||
@@ -4060,4 +4110,13 @@
|
||||
<string name="custom_theme_saved_to">Cambios guardados en %1$s</string>
|
||||
<string name="custom_theme_modified">Cambios sin guardar</string>
|
||||
<string name="custom_theme_saved_count">%1$d preajustes guardados</string>
|
||||
<string name="chat_settings_show_git_workspace">Mostrar el espacio de Git en el chat</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Muestra la rama y los cambios encima del cuadro de texto</string>
|
||||
<string name="chat_git_open_workspace">Abrir el espacio de Git</string>
|
||||
<string name="chat_git_branch">Rama %1$s</string>
|
||||
<string name="chat_git_additions">%1$d adiciones</string>
|
||||
<string name="chat_git_deletions">%1$d eliminaciones</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d cambio</item><item quantity="other">%1$d cambios</item></plurals>
|
||||
<string name="settings_git_workspace">Espacio de Git</string>
|
||||
<string name="settings_git_workspace_desc">Revisa cambios, ramas, commits y remotos</string>
|
||||
</resources>
|
||||
|
||||
@@ -698,6 +698,14 @@
|
||||
<string name="settings_analytics_desc">使用状況統計、TTFT、トークン、ヘルス</string>
|
||||
<string name="settings_diagnostics">診断</string>
|
||||
<string name="settings_diagnostics_desc">ステータス チェック、および最近の API、Relay、セッション、および音声アクティビティ</string>
|
||||
<string name="settings_advanced">詳細設定</string>
|
||||
<string name="settings_advanced_desc">監督モードとその他のオプション機能</string>
|
||||
<string name="settings_advanced_intro">メインの設定画面をシンプルに保つため、オプション機能と専門機能はここにまとめられています。</string>
|
||||
<string name="settings_supervised_mode">監督モード</string>
|
||||
<string name="settings_supervised_desc">プロファイルと許可するチャット機能を選択</string>
|
||||
<string name="settings_supervised_on">オン</string>
|
||||
<string name="settings_supervised_on_profile">オン · %1$s</string>
|
||||
<string name="settings_supervised_ready_profile">準備完了 · %1$s</string>
|
||||
<string name="settings_developer_options">開発者向けオプション</string>
|
||||
<string name="settings_developer_options_desc">機能フラグ、データ管理、実験的</string>
|
||||
<string name="settings_whats_new">新着情報</string>
|
||||
@@ -4009,6 +4017,48 @@
|
||||
<string name="plugins_keep">保持</string>
|
||||
<string name="plugins_remove">削除</string>
|
||||
<string name="plugins_remove_confirm">「%1$s」を削除しますか?接続された Android 端末にこのプラグインページは表示されなくなります。</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_back">戻る</string>
|
||||
<string name="git_state_staged">ステージ済み</string>
|
||||
<string name="git_state_modified">変更</string>
|
||||
<string name="git_state_untracked">未追跡</string>
|
||||
<string name="git_state_branches">ブランチ</string>
|
||||
<string name="git_state_truncated">結果は切り詰められています。最初の項目のみ表示されます。</string>
|
||||
<string name="git_state_no_changes">(変更なし)</string>
|
||||
|
||||
<string name="git_state_write_grant_required">書き込み変更にはプラグイン変更権限が必要です。Plugins の権限設定で「プラグインの変更を許可する(plugin.api.write)」を有効にしてください。</string>
|
||||
<string name="git_state_stage">ステージ</string>
|
||||
<string name="git_state_unstage">ステージ解除</string>
|
||||
<string name="git_state_discard">破棄</string>
|
||||
<string name="git_state_commit">コミット</string>
|
||||
<string name="git_state_commit_title">ステージ済みの変更をコミット</string>
|
||||
<string name="git_state_commit_message_hint">コミットメッセージ</string>
|
||||
<string name="git_state_commit_confirm">コミット</string>
|
||||
<string name="git_state_cancel">キャンセル</string>
|
||||
<string name="git_state_fetch">フェッチ</string>
|
||||
<string name="git_state_pull">プル</string>
|
||||
<string name="git_state_push">プッシュ</string>
|
||||
<string name="git_state_new_branch_hint">新しいブランチ名</string>
|
||||
<string name="git_state_create_branch">ブランチを作成</string>
|
||||
<string name="git_state_track_remote">リモートブランチを追跡</string>
|
||||
<string name="git_state_switch">切り替え</string>
|
||||
<string name="git_state_current">現在</string>
|
||||
<string name="git_state_mutation_in_progress">%1$s を実行中…</string>
|
||||
<string name="git_state_mutation_success">%1$s が完了しました。HEAD %2$s</string>
|
||||
<string name="git_state_mutation_failed">%1$s に失敗しました: %2$s</string>
|
||||
<string name="git_state_confirm_discard_title">変更を破棄しますか?</string>
|
||||
<string name="git_state_confirm_discard_text">選択したファイルへのローカル変更は破棄され、元に戻せません。</string>
|
||||
<string name="git_state_confirm_discard_confirm">破棄</string>
|
||||
<string name="git_state_confirm_push_title">変更をプッシュしますか?</string>
|
||||
<string name="git_state_confirm_push_text">現在のブランチをリモートにプッシュします。ローカルのコミットがリモートリポジトリに送信されます。</string>
|
||||
<string name="git_state_confirm_push_confirm">プッシュ</string>
|
||||
<string name="git_state_confirm_checkout_dirty_title">ローカル変更のあるブランチに切り替えますか?</string>
|
||||
<string name="git_state_confirm_checkout_dirty_text">作業ツリーに未コミットの変更があります。切り替えると、それらが対象ブランチへ引き継がれる可能性があります。</string>
|
||||
<string name="git_state_confirm_checkout_confirm">切り替え</string>
|
||||
<string name="git_state_generate_message">コミットメッセージを生成</string>
|
||||
<string name="git_state_generating_message">コミットメッセージを生成中…</string>
|
||||
<string name="git_state_push_after_commit">コミット後にプッシュ</string>
|
||||
<string name="git_state_switch_stash">切り替え(変更があればスタッシュ)</string>
|
||||
<string name="support_bundle_review">サポート情報を確認</string>
|
||||
<string name="support_bundle_title">サポート情報</string>
|
||||
<string name="support_bundle_privacy">自動アップロードはありません。最大 %1$d 件のレポートを含む端末内エクスポートを確認してください。</string>
|
||||
@@ -4373,4 +4423,13 @@
|
||||
<string name="custom_theme_saved_to">変更を %1$s に保存しました</string>
|
||||
<string name="custom_theme_modified">未保存の変更</string>
|
||||
<string name="custom_theme_saved_count">保存済み %1$d 件</string>
|
||||
<string name="chat_settings_show_git_workspace">チャットに Git ワークスペースを表示</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">入力欄の上にブランチと変更内容を表示します</string>
|
||||
<string name="chat_git_open_workspace">Git ワークスペースを開く</string>
|
||||
<string name="chat_git_branch">ブランチ %1$s</string>
|
||||
<string name="chat_git_additions">%1$d 件の追加</string>
|
||||
<string name="chat_git_deletions">%1$d 件の削除</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="other">%1$d 件の変更</item></plurals>
|
||||
<string name="settings_git_workspace">Git ワークスペース</string>
|
||||
<string name="settings_git_workspace_desc">変更、ブランチ、コミット、リモートを確認</string>
|
||||
</resources>
|
||||
|
||||
@@ -668,6 +668,14 @@
|
||||
<string name="settings_analytics_desc">Статистика использования, TTFT, токены, состояние</string>
|
||||
<string name="settings_diagnostics">Диагностика</string>
|
||||
<string name="settings_diagnostics_desc">Проверка состояния, а также недавняя активность API, Relay, сессий и голосовых данных</string>
|
||||
<string name="settings_advanced">Дополнительно</string>
|
||||
<string name="settings_advanced_desc">Режим с контролем и другие дополнительные функции</string>
|
||||
<string name="settings_advanced_intro">Дополнительные и специальные функции собраны здесь, чтобы не перегружать главный экран настроек.</string>
|
||||
<string name="settings_supervised_mode">Режим с контролем</string>
|
||||
<string name="settings_supervised_desc">Выберите профиль и разрешённые функции чата</string>
|
||||
<string name="settings_supervised_on">Вкл.</string>
|
||||
<string name="settings_supervised_on_profile">Вкл. · %1$s</string>
|
||||
<string name="settings_supervised_ready_profile">Готово · %1$s</string>
|
||||
<string name="settings_developer_options">Настройки разработчика</string>
|
||||
<string name="settings_developer_options_desc">Флаги функций, управление данными, экспериментальные</string>
|
||||
<string name="settings_whats_new">Что нового</string>
|
||||
@@ -3731,6 +3739,48 @@
|
||||
<string name="plugins_keep">Оставить</string>
|
||||
<string name="plugins_remove">Удалить</string>
|
||||
<string name="plugins_remove_confirm">Удалить «%1$s»? Эта страница плагина больше не будет отображаться на подключённых устройствах Android.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_back">Назад</string>
|
||||
<string name="git_state_staged">В индексе</string>
|
||||
<string name="git_state_modified">Изменённые</string>
|
||||
<string name="git_state_untracked">Неотслеживаемые</string>
|
||||
<string name="git_state_branches">Ветки</string>
|
||||
<string name="git_state_truncated">Результаты усечены — показаны только первые записи.</string>
|
||||
<string name="git_state_no_changes">(без изменений)</string>
|
||||
|
||||
<string name="git_state_write_grant_required">Для записи изменений требуется разрешение на изменение плагина. Включите «Разрешить изменения плагинов (plugin.api.write)» в настройках разрешений Plugins.</string>
|
||||
<string name="git_state_stage">Добавить в индекс</string>
|
||||
<string name="git_state_unstage">Убрать из индекса</string>
|
||||
<string name="git_state_discard">Отменить</string>
|
||||
<string name="git_state_commit">Коммит</string>
|
||||
<string name="git_state_commit_title">Зафиксировать индексированные изменения</string>
|
||||
<string name="git_state_commit_message_hint">Сообщение коммита</string>
|
||||
<string name="git_state_commit_confirm">Коммит</string>
|
||||
<string name="git_state_cancel">Отмена</string>
|
||||
<string name="git_state_fetch">Обновить</string>
|
||||
<string name="git_state_pull">Вытянуть</string>
|
||||
<string name="git_state_push">Отправить</string>
|
||||
<string name="git_state_new_branch_hint">Имя новой ветки</string>
|
||||
<string name="git_state_create_branch">Создать ветку</string>
|
||||
<string name="git_state_track_remote">Отслеживать удалённую ветку</string>
|
||||
<string name="git_state_switch">Переключить</string>
|
||||
<string name="git_state_current">Текущая</string>
|
||||
<string name="git_state_mutation_in_progress">%1$s выполняется…</string>
|
||||
<string name="git_state_mutation_success">%1$s завершено. HEAD %2$s</string>
|
||||
<string name="git_state_mutation_failed">%1$s не удалось: %2$s</string>
|
||||
<string name="git_state_confirm_discard_title">Отменить изменения?</string>
|
||||
<string name="git_state_confirm_discard_text">Локальные изменения выбранных файлов будут отменены и их нельзя будет восстановить.</string>
|
||||
<string name="git_state_confirm_discard_confirm">Отменить</string>
|
||||
<string name="git_state_confirm_push_title">Отправить изменения?</string>
|
||||
<string name="git_state_confirm_push_text">Отправить текущую ветку в её удалённый репозиторий. Это передаст локальные коммиты в удалённый репозиторий.</string>
|
||||
<string name="git_state_confirm_push_confirm">Отправить</string>
|
||||
<string name="git_state_confirm_checkout_dirty_title">Переключить ветку с локальными изменениями?</string>
|
||||
<string name="git_state_confirm_checkout_dirty_text">В рабочем дереве есть незакоммиченные изменения. Переключение может перенести их в целевую ветку.</string>
|
||||
<string name="git_state_confirm_checkout_confirm">Переключить</string>
|
||||
<string name="git_state_generate_message">Создать сообщение коммита</string>
|
||||
<string name="git_state_generating_message">Создание сообщения коммита…</string>
|
||||
<string name="git_state_push_after_commit">Отправить после коммита</string>
|
||||
<string name="git_state_switch_stash">Переключить (сохранить изменения, если есть)</string>
|
||||
<string name="support_bundle_review">Проверить сведения для поддержки</string>
|
||||
<string name="support_bundle_title">Сведения для поддержки</string>
|
||||
<string name="support_bundle_privacy">Ничего не загружается автоматически. Проверьте локальный экспорт с не более чем %1$d отчётами.</string>
|
||||
@@ -4102,4 +4152,13 @@
|
||||
<string name="custom_theme_saved_to">Изменения сохранены в %1$s</string>
|
||||
<string name="custom_theme_modified">Несохраненные изменения</string>
|
||||
<string name="custom_theme_saved_count">Сохранено тем: %1$d</string>
|
||||
<string name="chat_settings_show_git_workspace">Показывать рабочую область Git в чате</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Показывает ветку и изменения над полем ввода</string>
|
||||
<string name="chat_git_open_workspace">Открыть рабочую область Git</string>
|
||||
<string name="chat_git_branch">Ветка %1$s</string>
|
||||
<string name="chat_git_additions">Добавлено строк: %1$d</string>
|
||||
<string name="chat_git_deletions">Удалено строк: %1$d</string>
|
||||
<plurals name="chat_git_change_count"><item quantity="one">%1$d изменение</item><item quantity="few">%1$d изменения</item><item quantity="many">%1$d изменений</item><item quantity="other">%1$d изменения</item></plurals>
|
||||
<string name="settings_git_workspace">Рабочая область Git</string>
|
||||
<string name="settings_git_workspace_desc">Изменения, ветки, коммиты и удалённые репозитории</string>
|
||||
</resources>
|
||||
|
||||
@@ -736,6 +736,14 @@
|
||||
<string name="settings_analytics_desc">Usage stats, TTFT, tokens, health</string>
|
||||
<string name="settings_diagnostics">Diagnostics</string>
|
||||
<string name="settings_diagnostics_desc">Status checks, plus recent API, relay, session, and voice activity</string>
|
||||
<string name="settings_advanced">Advanced</string>
|
||||
<string name="settings_advanced_desc">Supervised mode and other optional features</string>
|
||||
<string name="settings_advanced_intro">Optional and specialized features live here to keep the main Settings screen focused.</string>
|
||||
<string name="settings_supervised_mode">Supervised mode</string>
|
||||
<string name="settings_supervised_desc">Choose a profile and approved chat features</string>
|
||||
<string name="settings_supervised_on">On</string>
|
||||
<string name="settings_supervised_on_profile">On · %1$s</string>
|
||||
<string name="settings_supervised_ready_profile">Ready · %1$s</string>
|
||||
<string name="settings_developer_options">Developer options</string>
|
||||
<string name="settings_developer_options_desc">Feature flags, data management, experimental</string>
|
||||
<string name="settings_whats_new">What\'s New</string>
|
||||
@@ -783,6 +791,16 @@
|
||||
<string name="chat_settings_keep_keyboard_open_desc">Stay in the composer after sending. Turn off to dismiss the keyboard after each sent message.</string>
|
||||
<string name="chat_settings_large_pastes">Convert large pastes to attachments</string>
|
||||
<string name="chat_settings_large_pastes_desc">Turn pastes of 5,000 or more characters into reviewable text attachments. On by default.</string>
|
||||
<string name="chat_settings_show_git_workspace">Show Git workspace in Chat</string>
|
||||
<string name="chat_settings_show_git_workspace_desc">Show the Git status entry and changes rail in Chat. The full Git workspace remains available when this is off.</string>
|
||||
<string name="chat_git_open_workspace">Open Git workspace</string>
|
||||
<string name="chat_git_branch">Git branch %1$s</string>
|
||||
<string name="chat_git_additions">%1$d additions</string>
|
||||
<string name="chat_git_deletions">%1$d deletions</string>
|
||||
<plurals name="chat_git_change_count">
|
||||
<item quantity="one">%1$d change</item>
|
||||
<item quantity="other">%1$d changes</item>
|
||||
</plurals>
|
||||
<string name="chat_large_paste_attached">Large paste added as a text attachment</string>
|
||||
<string name="chat_large_paste_too_large">Pasted text exceeds the %1$d MB attachment limit</string>
|
||||
<string name="chat_settings_physical_keyboard_enter">Physical keyboard Enter key</string>
|
||||
@@ -4206,6 +4224,51 @@
|
||||
<string name="plugins_keep">Keep</string>
|
||||
<string name="plugins_remove">Remove</string>
|
||||
<string name="plugins_remove_confirm">Remove “%1$s”? This plugin page will no longer appear on connected Android devices.</string>
|
||||
<string name="git_state_title">Git</string>
|
||||
<string name="git_state_back">Back</string>
|
||||
<string name="git_state_staged">Staged</string>
|
||||
<string name="git_state_modified">Modified</string>
|
||||
<string name="git_state_untracked">Untracked</string>
|
||||
<string name="git_state_branches">Branches</string>
|
||||
<string name="git_state_truncated">Results truncated — showing the first entries only.</string>
|
||||
<string name="git_state_no_changes">(no changes)</string>
|
||||
|
||||
<!-- Git write surface (Phase 2). All mutations require the plugin.api.write grant. -->
|
||||
<string name="git_state_write_grant_required">Write changes require the plugin change permission. Enable “Allow plugin changes (plugin.api.write)” in the Plugins grant settings.</string>
|
||||
<string name="git_state_stage">Stage</string>
|
||||
<string name="git_state_unstage">Unstage</string>
|
||||
<string name="git_state_discard">Discard</string>
|
||||
<string name="git_state_commit">Commit</string>
|
||||
<string name="git_state_commit_title">Commit staged changes</string>
|
||||
<string name="git_state_commit_message_hint">Commit message</string>
|
||||
<string name="git_state_commit_confirm">Commit</string>
|
||||
<string name="git_state_cancel">Cancel</string>
|
||||
<string name="git_state_fetch">Fetch</string>
|
||||
<string name="git_state_pull">Pull</string>
|
||||
<string name="git_state_push">Push</string>
|
||||
<string name="git_state_new_branch_hint">New branch name</string>
|
||||
<string name="git_state_create_branch">Create branch</string>
|
||||
<string name="git_state_track_remote">Track remote branch</string>
|
||||
<string name="git_state_switch">Switch</string>
|
||||
<string name="git_state_current">Current</string>
|
||||
<string name="git_state_mutation_in_progress">%1$s in progress…</string>
|
||||
<string name="git_state_mutation_success">%1$s completed. HEAD %2$s</string>
|
||||
<string name="git_state_mutation_failed">%1$s failed: %2$s</string>
|
||||
<!-- Destructive-op confirmations (token is sent only on explicit user confirmation). -->
|
||||
<string name="git_state_confirm_discard_title">Discard changes?</string>
|
||||
<string name="git_state_confirm_discard_text">Local changes to the selected file(s) will be discarded and cannot be recovered.</string>
|
||||
<string name="git_state_confirm_discard_confirm">Discard</string>
|
||||
<string name="git_state_confirm_push_title">Push changes?</string>
|
||||
<string name="git_state_confirm_push_text">Push the current branch to its remote. This sends local commits to the remote repository.</string>
|
||||
<string name="git_state_confirm_push_confirm">Push</string>
|
||||
<string name="git_state_confirm_checkout_dirty_title">Switch branch with local changes?</string>
|
||||
<string name="git_state_confirm_checkout_dirty_text">The working tree has uncommitted changes. Switching may carry them onto the target branch.</string>
|
||||
<string name="git_state_confirm_checkout_confirm">Switch</string>
|
||||
<string name="git_state_generate_message">Generate commit message</string>
|
||||
<string name="git_state_generating_message">Generating commit message…</string>
|
||||
<string name="git_state_push_after_commit">Push after commit</string>
|
||||
<string name="git_state_switch_stash">Switch (stash if dirty)</string>
|
||||
|
||||
<string name="support_bundle_review">Review support information</string>
|
||||
<string name="support_bundle_title">Support information</string>
|
||||
<string name="support_bundle_privacy">Nothing is uploaded automatically. Review the exact local export below. It contains up to %1$d recent reports.</string>
|
||||
@@ -4382,4 +4445,6 @@
|
||||
<string name="provider_usage_capability_relay_body">Credential pools, structured Nous balances, and OpenCode Go are provided by the Relay plugin.</string>
|
||||
<string name="provider_usage_capability_basic_title">Basic usage from Hermes</string>
|
||||
<string name="provider_usage_capability_basic_body">Install or update the Relay plugin for credential pools, structured Nous balances, and OpenCode Go.</string>
|
||||
<string name="settings_git_workspace">Git workspace</string>
|
||||
<string name="settings_git_workspace_desc">Review changes, branches, commits, and remotes</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.hermesandroid.relay.auth
|
||||
|
||||
import com.hermesandroid.relay.data.SupervisedCapabilities
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import kotlinx.serialization.json.boolean
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedModeAuthPayloadTest {
|
||||
@Test fun `active policy reports only public capability ids`() {
|
||||
val payload = relaySupervisedModePayload(
|
||||
SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(attachments = true, voice = true),
|
||||
),
|
||||
)
|
||||
assertTrue(payload.getValue("active").jsonPrimitive.boolean)
|
||||
assertEquals("willow", payload.getValue("profile_label").jsonPrimitive.content)
|
||||
val capabilities = payload.getValue("capabilities").jsonArray.map { it.jsonPrimitive.content }
|
||||
assertTrue("text_chat" in capabilities)
|
||||
assertTrue("attachments" in capabilities)
|
||||
assertTrue("voice" in capabilities)
|
||||
assertFalse(capabilities.any { it.contains("model") || it.contains("tool") })
|
||||
}
|
||||
|
||||
@Test fun `inactive update explicitly clears Relay tag`() {
|
||||
val payload = relaySupervisedModePayload(SupervisedModePolicy())
|
||||
assertFalse(payload.getValue("active").jsonPrimitive.boolean)
|
||||
assertEquals(setOf("active"), payload.keys)
|
||||
}
|
||||
|
||||
@Test fun `live update uses typed correlated system envelope`() {
|
||||
val envelope = relaySupervisedModeUpdateEnvelope(
|
||||
SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(voice = true),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals("system", envelope.channel)
|
||||
assertEquals("supervised.update", envelope.type)
|
||||
assertTrue(envelope.id.isNotBlank())
|
||||
val mode = envelope.payload.getValue("supervised_mode")
|
||||
.jsonObject
|
||||
assertTrue(mode.getValue("active").jsonPrimitive.boolean)
|
||||
assertEquals("willow", mode.getValue("profile_label").jsonPrimitive.content)
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,25 @@ class ChatInputPreferencesTest {
|
||||
assertEquals(true, repository.convertLargePastesToAttachments.first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Git workspace in Chat defaults on and round trips without replacing other settings`() = runTest {
|
||||
val unrelatedKey = stringPreferencesKey("unrelated_git_chat_test")
|
||||
val store = InMemoryChatInputDataStore(
|
||||
mutablePreferencesOf(unrelatedKey to "keep-me"),
|
||||
)
|
||||
val repository = ChatInputPreferencesRepository(store)
|
||||
|
||||
assertEquals(true, repository.showGitWorkspaceInChat.first())
|
||||
|
||||
repository.setShowGitWorkspaceInChat(false)
|
||||
assertEquals(false, repository.showGitWorkspaceInChat.first())
|
||||
assertEquals("keep-me", store.data.first()[unrelatedKey])
|
||||
|
||||
repository.setShowGitWorkspaceInChat(true)
|
||||
assertEquals(true, repository.showGitWorkspaceInChat.first())
|
||||
assertEquals("keep-me", store.data.first()[unrelatedKey])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enter defaults to send and unknown values fall back safely`() = runTest {
|
||||
assertEquals(
|
||||
|
||||
@@ -10,17 +10,19 @@ class SessionActivityRegistryTest {
|
||||
private val scope = SessionActivityScope.of("connection-a", "default")
|
||||
|
||||
@Test
|
||||
fun `directory owner is checking until status is unavailable or confirms idle`() {
|
||||
fun `directory owner stays neutral until status confirms live activity`() {
|
||||
val checking = SessionActivityRegistry().reduce(
|
||||
SessionActivityUpdate.ObserveOwner(owner, generation = 1, observedAtMillis = 1),
|
||||
)
|
||||
assertEquals(SessionActivityPhase.Idle, checking.record(owner)?.phase())
|
||||
assertEquals(SessionActivityState.Checking, checking.record(owner)?.presentationState())
|
||||
assertEquals(SessionActivityFreshness.Revalidating, checking.record(owner)?.freshness)
|
||||
assertNull(checking.record(owner)?.presentationState())
|
||||
|
||||
val unavailable = checking.reduce(
|
||||
SessionActivityUpdate.StatusUnavailable(scope, generation = 1, observedAtMillis = 2),
|
||||
)
|
||||
assertEquals(SessionActivityState.Unavailable, unavailable.record(owner)?.presentationState())
|
||||
assertEquals(SessionActivityFreshness.Unavailable, unavailable.record(owner)?.freshness)
|
||||
assertNull(unavailable.record(owner)?.presentationState())
|
||||
|
||||
val confirmedIdle = checking.reduce(activeList(scope, generation = 1))
|
||||
assertEquals(SessionActivityPhase.Idle, confirmedIdle.record(owner)?.phase())
|
||||
@@ -28,6 +30,17 @@ class SessionActivityRegistryTest {
|
||||
assertNull(confirmedIdle.record(owner)?.presentationState())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `directory refresh cannot restore checking after active status is unavailable`() {
|
||||
val state = SessionActivityRegistry()
|
||||
.reduce(SessionActivityUpdate.ObserveOwner(owner, generation = 1, observedAtMillis = 1))
|
||||
.reduce(SessionActivityUpdate.StatusUnavailable(scope, generation = 1, observedAtMillis = 2))
|
||||
.reduce(SessionActivityUpdate.ObserveOwner(owner, generation = 1, observedAtMillis = 3))
|
||||
|
||||
assertEquals(SessionActivityFreshness.Unavailable, state.record(owner)?.freshness)
|
||||
assertNull(state.record(owner)?.presentationState())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `directory observation cannot downgrade confirmed live evidence`() {
|
||||
val state = SessionActivityRegistry()
|
||||
@@ -184,7 +197,7 @@ class SessionActivityRegistryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failed or unsupported status refresh is unavailable rather than idle`() {
|
||||
fun `failed or unsupported status refresh preserves evidence but presents a neutral row`() {
|
||||
val state = SessionActivityRegistry()
|
||||
.reduce(
|
||||
SessionActivityUpdate.LiveState(
|
||||
@@ -206,7 +219,7 @@ class SessionActivityRegistryTest {
|
||||
|
||||
assertEquals(SessionActivityPhase.Working, state.record(owner)?.phase())
|
||||
assertEquals(SessionActivityFreshness.Unavailable, state.record(owner)?.freshness)
|
||||
assertEquals(SessionActivityState.Unavailable, state.record(owner)?.presentationState())
|
||||
assertNull(state.record(owner)?.presentationState())
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -226,7 +239,7 @@ class SessionActivityRegistryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `presentation keeps starting background and revalidation distinct from working`() {
|
||||
fun `presentation keeps starting and background distinct while revalidation stays neutral`() {
|
||||
val starting = SessionActivityRegistry().reduce(
|
||||
SessionActivityUpdate.LocalSend(owner, generation = 1, observedAtMillis = 1),
|
||||
)
|
||||
@@ -240,7 +253,7 @@ class SessionActivityRegistryTest {
|
||||
val checking = starting.reduce(
|
||||
SessionActivityUpdate.BeginGeneration(scope, generation = 2, observedAtMillis = 2),
|
||||
)
|
||||
assertEquals(SessionActivityState.Checking, checking.record(owner)?.presentationState())
|
||||
assertNull(checking.record(owner)?.presentationState())
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -287,7 +300,7 @@ class SessionActivityRegistryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `restored needs-input checkpoint stays checking until live confirmation`() {
|
||||
fun `restored needs-input checkpoint stays neutral until live confirmation`() {
|
||||
val state = SessionActivityRegistry().reduce(
|
||||
SessionActivityUpdate.RestoreCheckpoint(
|
||||
owner = owner,
|
||||
@@ -298,7 +311,7 @@ class SessionActivityRegistryTest {
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(SessionActivityState.Checking, state.record(owner)?.presentationState())
|
||||
assertNull(state.record(owner)?.presentationState())
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -323,7 +336,7 @@ class SessionActivityRegistryTest {
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(SessionActivityState.Checking, state.record(owner)?.presentationState())
|
||||
assertNull(state.record(owner)?.presentationState())
|
||||
|
||||
state = state.reduce(
|
||||
SessionActivityUpdate.PendingInputOpened(
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import androidx.datastore.preferences.core.mutablePreferencesOf
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedModeStoreTest {
|
||||
|
||||
@Test
|
||||
fun freshConnectionUsesRestrictiveDefaults() = runTest {
|
||||
val store = SupervisedModeStore.forTesting(InMemorySupervisedPreferencesDataStore())
|
||||
|
||||
val policy = store.policyFlow("connection-a").first()
|
||||
|
||||
assertFalse(policy.enabled)
|
||||
assertFalse(policy.isConfigured)
|
||||
assertFalse(policy.isActive)
|
||||
assertFalse(policy.capabilities.attachments)
|
||||
assertFalse(policy.capabilities.voice)
|
||||
assertFalse(policy.visibility.resolved().showModelName)
|
||||
assertFalse(policy.visibility.resolved().showTechnicalRoute)
|
||||
assertTrue(policy.parentAccess.requireDeviceAuthentication)
|
||||
assertEquals(5, policy.parentAccess.timeoutMinutes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun policyRoundTripsWithCapabilitiesLimitsAndVisibility() = runTest {
|
||||
val dataStore = InMemorySupervisedPreferencesDataStore()
|
||||
val store = SupervisedModeStore.forTesting(dataStore)
|
||||
val saved = SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = " willow ",
|
||||
capabilities = SupervisedCapabilities(
|
||||
attachments = true,
|
||||
voice = true,
|
||||
attachmentMaxCount = 6,
|
||||
attachmentMaxFileMb = 20,
|
||||
attachmentCategories = setOf(
|
||||
SupervisedAttachmentCategory.Images,
|
||||
SupervisedAttachmentCategory.Documents,
|
||||
),
|
||||
sessionActions = SupervisedSessionActions(
|
||||
pin = true,
|
||||
rename = true,
|
||||
shareTranscript = true,
|
||||
),
|
||||
),
|
||||
appearance = SupervisedAppearance(
|
||||
appThemeId = "rose",
|
||||
themePreference = "dark",
|
||||
showPet = true,
|
||||
allowProfileIconChanges = true,
|
||||
allowBackgroundChanges = true,
|
||||
),
|
||||
visibility = SupervisedVisibility(
|
||||
preset = SupervisedVisibilityPreset.Custom,
|
||||
showAgentIdentity = true,
|
||||
showModelName = true,
|
||||
showToolNames = true,
|
||||
),
|
||||
)
|
||||
|
||||
store.setPolicy("connection-a", saved)
|
||||
val restored = SupervisedModeStore.forTesting(dataStore).policyFlow("connection-a").first()
|
||||
|
||||
assertTrue(restored.isActive)
|
||||
assertEquals("willow", restored.pinnedProfileName)
|
||||
assertEquals(6, restored.capabilities.attachmentMaxCount)
|
||||
assertEquals(20, restored.capabilities.attachmentMaxFileMb)
|
||||
assertEquals(saved.capabilities.attachmentCategories, restored.capabilities.attachmentCategories)
|
||||
assertEquals(saved.capabilities.sessionActions, restored.capabilities.sessionActions)
|
||||
assertEquals("rose", restored.appearance.appThemeId)
|
||||
assertEquals("dark", restored.appearance.themePreference)
|
||||
assertTrue(restored.appearance.showPet)
|
||||
assertTrue(restored.appearance.allowProfileIconChanges)
|
||||
assertTrue(restored.appearance.allowBackgroundChanges)
|
||||
assertEquals(SupervisedVisibilityPreset.Custom, restored.visibility.preset)
|
||||
assertTrue(restored.visibility.showModelName)
|
||||
assertTrue(restored.visibility.showToolNames)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun connectionsAreIsolatedAndClearRemovesOnlyTarget() = runTest {
|
||||
val store = SupervisedModeStore.forTesting(InMemorySupervisedPreferencesDataStore())
|
||||
store.setPolicy("connection-a", SupervisedModePolicy(true, "willow"))
|
||||
store.setPolicy("connection-b", SupervisedModePolicy(true, "juniper"))
|
||||
|
||||
store.clear("connection-a")
|
||||
|
||||
assertFalse(store.policyFlow("connection-a").first().enabled)
|
||||
assertEquals("juniper", store.policyFlow("connection-b").first().pinnedProfileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun updateAndSetEnabledPreserveOtherPolicyFields() = runTest {
|
||||
val store = SupervisedModeStore.forTesting(InMemorySupervisedPreferencesDataStore())
|
||||
store.setPolicy(
|
||||
"connection-a",
|
||||
SupervisedModePolicy(
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(voice = true),
|
||||
),
|
||||
)
|
||||
|
||||
store.setEnabled("connection-a", true)
|
||||
store.updatePolicy("connection-a") {
|
||||
it.copy(visibility = it.visibility.copy(preset = SupervisedVisibilityPreset.Transparent))
|
||||
}
|
||||
|
||||
val policy = store.policyFlow("connection-a").first()
|
||||
assertTrue(policy.isActive)
|
||||
assertTrue(policy.capabilities.voice)
|
||||
assertEquals(SupervisedVisibilityPreset.Transparent, policy.visibility.preset)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidLimitsAreNormalizedAndEmptyCategoriesFallBackToImages() = runTest {
|
||||
val store = SupervisedModeStore.forTesting(InMemorySupervisedPreferencesDataStore())
|
||||
store.setPolicy(
|
||||
"connection-a",
|
||||
SupervisedModePolicy(
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(
|
||||
attachmentMaxCount = Int.MAX_VALUE,
|
||||
attachmentMaxFileMb = -1,
|
||||
attachmentCategories = emptySet(),
|
||||
),
|
||||
parentAccess = SupervisedParentAccess(
|
||||
requireDeviceAuthentication = false,
|
||||
timeoutMinutes = 0,
|
||||
),
|
||||
appearance = SupervisedAppearance(
|
||||
appThemeId = "missing-theme",
|
||||
themePreference = "sepia",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val policy = store.policyFlow("connection-a").first()
|
||||
assertEquals(SupervisedCapabilities.MAX_ATTACHMENT_COUNT, policy.capabilities.attachmentMaxCount)
|
||||
assertEquals(1, policy.capabilities.attachmentMaxFileMb)
|
||||
assertEquals(setOf(SupervisedAttachmentCategory.Images), policy.capabilities.attachmentCategories)
|
||||
assertTrue(policy.parentAccess.requireDeviceAuthentication)
|
||||
assertEquals(SupervisedParentAccess.MIN_TIMEOUT_MINUTES, policy.parentAccess.timeoutMinutes)
|
||||
assertEquals("hermes-relay", policy.appearance.appThemeId)
|
||||
assertEquals("auto", policy.appearance.themePreference)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun simplePresetResolvesToSafeValuesEvenIfStoredFlagsDiffer() {
|
||||
val visibility = SupervisedVisibility(
|
||||
preset = SupervisedVisibilityPreset.Simple,
|
||||
showModelName = true,
|
||||
showTechnicalRoute = true,
|
||||
showReasoning = true,
|
||||
).resolved()
|
||||
|
||||
assertFalse(visibility.showModelName)
|
||||
assertFalse(visibility.showTechnicalRoute)
|
||||
assertFalse(visibility.showReasoning)
|
||||
assertTrue(visibility.showAgentIdentity)
|
||||
assertTrue(visibility.showConnectionStatus)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun malformedPersistedPolicyFailsClosed() = runTest {
|
||||
val policyKey = androidx.datastore.preferences.core.stringPreferencesKey(
|
||||
"supervised_mode_policies_v1",
|
||||
)
|
||||
val dataStore = InMemorySupervisedPreferencesDataStore(
|
||||
mutablePreferencesOf(policyKey to "{not-valid-json"),
|
||||
)
|
||||
|
||||
val policy = SupervisedModeStore.forTesting(dataStore)
|
||||
.policyFlow("connection-a")
|
||||
.first()
|
||||
|
||||
assertTrue(policy.enabled)
|
||||
assertFalse(policy.isConfigured)
|
||||
assertFalse(policy.isActive)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearAllDoesNotClearUnrelatedPreferences() = runTest {
|
||||
val unrelatedKey = androidx.datastore.preferences.core.stringPreferencesKey("unrelated")
|
||||
val dataStore = InMemorySupervisedPreferencesDataStore(
|
||||
mutablePreferencesOf(unrelatedKey to "kept"),
|
||||
)
|
||||
val store = SupervisedModeStore.forTesting(dataStore)
|
||||
store.setPolicy("connection-a", SupervisedModePolicy(true, "willow"))
|
||||
|
||||
store.clearAll()
|
||||
|
||||
assertFalse(store.policyFlow("connection-a").first().enabled)
|
||||
assertEquals("kept", dataStore.data.first()[unrelatedKey])
|
||||
}
|
||||
}
|
||||
|
||||
private class InMemorySupervisedPreferencesDataStore(
|
||||
initial: Preferences = emptyPreferences(),
|
||||
) : DataStore<Preferences> {
|
||||
private val state = MutableStateFlow(initial)
|
||||
override val data: Flow<Preferences> = state
|
||||
|
||||
override suspend fun updateData(
|
||||
transform: suspend (t: Preferences) -> Preferences,
|
||||
): Preferences {
|
||||
val updated = transform(state.value)
|
||||
state.value = updated
|
||||
return updated
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedSessionPolicyTest {
|
||||
@Test fun `session action summary derives none mixed and all`() {
|
||||
val none = SupervisedSessionActions()
|
||||
val mixed = none.copy(rename = true, delete = true)
|
||||
val all = none.withAll(true)
|
||||
|
||||
assertTrue(none.noneEnabled)
|
||||
assertEquals(2, mixed.enabledCount)
|
||||
assertFalse(mixed.noneEnabled)
|
||||
assertFalse(mixed.allEnabled)
|
||||
assertTrue(all.allEnabled)
|
||||
assertEquals(SupervisedSessionActions.TOTAL, all.enabledCount)
|
||||
}
|
||||
|
||||
@Test fun `supervised history and granular flag are both required`() {
|
||||
val base = SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(
|
||||
conversationHistory = true,
|
||||
sessionActions = SupervisedSessionActions(rename = true),
|
||||
),
|
||||
)
|
||||
|
||||
assertTrue(base.allowsSessionAction(SupervisedSessionAction.Rename))
|
||||
assertFalse(base.allowsSessionAction(SupervisedSessionAction.Delete))
|
||||
assertFalse(
|
||||
base.copy(
|
||||
capabilities = base.capabilities.copy(conversationHistory = false),
|
||||
).allowsSessionAction(SupervisedSessionAction.Rename),
|
||||
)
|
||||
assertTrue(SupervisedModePolicy().allowsSessionAction(SupervisedSessionAction.Delete))
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.hermesandroid.relay.network.relay
|
||||
|
||||
import com.hermesandroid.relay.network.relay.models.Envelope
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ChannelMultiplexerSupervisedUpdateTest {
|
||||
@Test fun `supervised update acknowledgement reaches system auth handler`() {
|
||||
val multiplexer = ChannelMultiplexer()
|
||||
val received = mutableListOf<Envelope>()
|
||||
multiplexer.registerHandler("system") { received += it }
|
||||
|
||||
val acknowledgement = Envelope(
|
||||
channel = "system",
|
||||
type = "supervised.updated",
|
||||
id = "update-1",
|
||||
)
|
||||
multiplexer.route(acknowledgement)
|
||||
|
||||
assertEquals(listOf(acknowledgement), received)
|
||||
}
|
||||
|
||||
@Test fun `correlated system error reaches system auth handler`() {
|
||||
val multiplexer = ChannelMultiplexer()
|
||||
val received = mutableListOf<Envelope>()
|
||||
multiplexer.registerHandler("system") { received += it }
|
||||
|
||||
val error = Envelope(channel = "system", type = "error", id = "update-2")
|
||||
multiplexer.route(error)
|
||||
|
||||
assertEquals(listOf(error), received)
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.hermesandroid.relay.network.shared
|
||||
|
||||
import com.hermesandroid.relay.data.VoiceAudioRoute
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class AutoVoiceAudioClientSupervisionTest {
|
||||
@Test
|
||||
fun `route override forces standard even when auto prefers ready relay`() = runTest {
|
||||
val standard = FakeVoiceClient(VoiceAudioRoute.Standard, "standard")
|
||||
val relay = FakeVoiceClient(VoiceAudioRoute.Relay, "relay")
|
||||
val router = AutoVoiceAudioClient(
|
||||
standardClient = standard,
|
||||
relayClient = relay,
|
||||
routeProvider = { VoiceAudioRoute.Auto },
|
||||
standardReadyProvider = { true },
|
||||
relayReadyProvider = { true },
|
||||
)
|
||||
|
||||
assertEquals("relay", router.transcribe(File("voice.wav")).getOrThrow())
|
||||
router.setRouteOverride(VoiceAudioRoute.Standard)
|
||||
assertEquals(VoiceAudioRoute.Standard, router.effectiveRoute)
|
||||
assertEquals("standard", router.transcribe(File("voice.wav")).getOrThrow())
|
||||
router.setRouteOverride(null)
|
||||
assertEquals("relay", router.transcribe(File("voice.wav")).getOrThrow())
|
||||
}
|
||||
|
||||
private class FakeVoiceClient(
|
||||
override val route: VoiceAudioRoute,
|
||||
private val transcript: String,
|
||||
) : VoiceAudioClient {
|
||||
override suspend fun transcribe(audioFile: File): Result<String> = Result.success(transcript)
|
||||
override suspend fun synthesize(text: String): Result<File> = Result.success(File("voice.mp3"))
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package com.hermesandroid.relay.screenshots
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.ui.components.ChatGitContextButton
|
||||
import com.hermesandroid.relay.ui.components.ChatGitWorkspaceRail
|
||||
import com.hermesandroid.relay.ui.components.ChatGitWorkspaceSummary
|
||||
import com.hermesandroid.relay.ui.screens.GitStateScreen
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.viewmodel.GitStateViewModel
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w400dp-h800dp-432dpi")
|
||||
class GitWorkspaceScreenshotTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
server.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun detailWorkspaceMatchesApprovedInformationHierarchy() {
|
||||
enqueue("""{"repos":[{"id":"hermes-relay","name":"hermes-relay","root":"/srv/projects/hermes-relay","current_branch":"main","dirty":true}]}""")
|
||||
enqueue(
|
||||
"""{"counts":{"staged":1,"modified":1,"untracked":1,"changes":3,"additions":24,"deletions":7},"staged":[{"path":"app/src/main/kotlin/RelayApp.kt","additions":12,"deletions":3}],"modified":[{"path":"plugin/git_state.py","additions":8,"deletions":4}],"untracked":[{"path":"docs/git-workspace.md","additions":null,"deletions":null}],"truncated":false}""",
|
||||
)
|
||||
enqueue("""{"branches":[{"name":"main","upstream":"origin/main","ahead":1,"behind":0,"is_current":true},{"name":"dev","upstream":"origin/dev","ahead":0,"behind":0,"is_current":false}]}""")
|
||||
enqueue(
|
||||
"""{"path":"plugin/git_state.py","kind":"unstaged","diff":"@@ repository containment @@\n+ def is_within_repo(path):\n- return false\n+ return path.startswith(repo_root)","truncated":false}""",
|
||||
)
|
||||
val app = ApplicationProvider.getApplicationContext<Application>()
|
||||
val viewModel = GitStateViewModel(app)
|
||||
val owner = "visual-owner"
|
||||
viewModel.configure(DashboardApiClient(server.url("/").toString()), owner)
|
||||
viewModel.setWriteGrant(owner, true)
|
||||
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
GitStateScreen(viewModel = viewModel, onBack = {})
|
||||
}
|
||||
}
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
runCatching { compose.onNodeWithText("3 changes").assertExists() }.isSuccess
|
||||
}
|
||||
compose.onNodeWithContentDescription("Select plugin/git_state.py").performClick()
|
||||
compose.onNodeWithText("git_state.py").performClick()
|
||||
compose.waitUntil(5_000) {
|
||||
runCatching { compose.onNodeWithText("@@ repository containment @@", substring = true).assertExists() }.isSuccess
|
||||
}
|
||||
compose.onRoot().captureRoboImage("build/store-shots/15_git_workspace.png")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun chatRailMatchesApprovedCompactTreatment() {
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(androidx.compose.material3.MaterialTheme.colorScheme.background),
|
||||
) {
|
||||
ChatGitContextButton(
|
||||
onClick = {},
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(16.dp),
|
||||
)
|
||||
Column(
|
||||
Modifier.fillMaxWidth().align(Alignment.BottomCenter).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(5.dp),
|
||||
) {
|
||||
ChatGitWorkspaceRail(
|
||||
summary = ChatGitWorkspaceSummary("main", 3, 24, 7),
|
||||
onClick = {},
|
||||
)
|
||||
Box(
|
||||
Modifier.fillMaxWidth().background(
|
||||
androidx.compose.material3.MaterialTheme.colorScheme.surfaceContainer,
|
||||
androidx.compose.foundation.shape.RoundedCornerShape(18.dp),
|
||||
).padding(vertical = 28.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.onRoot().captureRoboImage("build/ui-evidence/chat-git-workspace-rail.png")
|
||||
}
|
||||
|
||||
private fun enqueue(body: String) {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(body),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import com.hermesandroid.relay.data.GitBranch
|
||||
import com.hermesandroid.relay.data.GitRepo
|
||||
import com.hermesandroid.relay.data.GitStatus
|
||||
import com.hermesandroid.relay.data.GitStatusCounts
|
||||
import com.hermesandroid.relay.data.GitStatusEntry
|
||||
import com.hermesandroid.relay.viewmodel.GitRepoDetailState
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class GitWorkspaceProjectionTest {
|
||||
private val parent = GitRepo("parent", "projects", "/srv/projects")
|
||||
private val nested = GitRepo("nested", "relay", "/srv/projects/hermes-relay")
|
||||
|
||||
@Test
|
||||
fun exactSessionRootWinsAndCwdUsesLongestSegmentMatch() {
|
||||
assertEquals(
|
||||
nested,
|
||||
selectGitRepoForWorkspace(listOf(parent, nested), null, nested.root, null),
|
||||
)
|
||||
assertEquals(
|
||||
nested,
|
||||
selectGitRepoForWorkspace(
|
||||
listOf(parent, nested),
|
||||
null,
|
||||
null,
|
||||
"/srv/projects/hermes-relay/app/src",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ambiguousCatalogDoesNotInventASelection() {
|
||||
assertNull(selectGitRepoForWorkspace(listOf(parent, nested), null, null, null))
|
||||
assertNull(selectGitRepoForWorkspace(listOf(parent, nested), nested.id, null, null))
|
||||
assertEquals(parent, selectGitRepoForWorkspace(listOf(parent), null, null, null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun summaryCountsEachChangedPathOnce() {
|
||||
val summary = buildChatGitWorkspaceSummary(
|
||||
nested,
|
||||
GitRepoDetailState.Ready(
|
||||
status = GitStatus(
|
||||
counts = GitStatusCounts(additions = 24, deletions = 7),
|
||||
staged = listOf(GitStatusEntry("shared.kt")),
|
||||
modified = listOf(GitStatusEntry("shared.kt"), GitStatusEntry("other.kt")),
|
||||
untracked = listOf(GitStatusEntry("new.kt")),
|
||||
),
|
||||
branches = listOf(GitBranch("dev", isCurrent = true)),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals("dev", summary?.branch)
|
||||
assertEquals(3, summary?.changeCount)
|
||||
assertEquals(24, summary?.additions)
|
||||
assertEquals(7, summary?.deletions)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import com.hermesandroid.relay.data.SupervisedAppearance
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedAppearancePolicyTest {
|
||||
private val policy = SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
appearance = SupervisedAppearance(
|
||||
appThemeId = "rose",
|
||||
themePreference = "dark",
|
||||
showPet = false,
|
||||
),
|
||||
)
|
||||
|
||||
@Test fun `locked supervised root uses only its own theme`() {
|
||||
val resolved = resolveSupervisedTheme(policy, false, "midnight", "light")
|
||||
|
||||
assertEquals("rose", resolved.appThemeId)
|
||||
assertEquals("dark", resolved.themePreference)
|
||||
assertFalse(resolved.useGlobalCustomTheme)
|
||||
}
|
||||
|
||||
@Test fun `parent access restores ordinary app theme`() {
|
||||
val resolved = resolveSupervisedTheme(policy, true, "midnight", "light")
|
||||
|
||||
assertEquals("midnight", resolved.appThemeId)
|
||||
assertEquals("light", resolved.themePreference)
|
||||
assertTrue(resolved.useGlobalCustomTheme)
|
||||
}
|
||||
|
||||
@Test fun `pet visibility follows supervised policy only while locked`() {
|
||||
assertFalse(shouldShowPetInSupervisedMode(policy, false))
|
||||
assertTrue(shouldShowPetInSupervisedMode(policy, true))
|
||||
assertTrue(
|
||||
shouldShowPetInSupervisedMode(
|
||||
policy.copy(appearance = policy.appearance.copy(showPet = true)),
|
||||
false,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `enabled recovery policy stays on restricted appearance defaults`() {
|
||||
val recovery = SupervisedModePolicy(enabled = true)
|
||||
val resolved = resolveSupervisedTheme(recovery, false, "rose", "dark")
|
||||
|
||||
assertEquals("hermes-relay", resolved.appThemeId)
|
||||
assertEquals("auto", resolved.themePreference)
|
||||
assertFalse(resolved.useGlobalCustomTheme)
|
||||
assertFalse(shouldShowPetInSupervisedMode(recovery, false))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import com.hermesandroid.relay.data.SupervisedCapabilities
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedNavigationPolicyTest {
|
||||
@Test fun `locked surface permits only approved destinations`() {
|
||||
assertTrue(isSupervisedRouteAllowed("chat?sessionId=owned", false))
|
||||
assertTrue(isSupervisedRouteAllowed("settings", false))
|
||||
assertTrue(isSupervisedRouteAllowed(Screen.SupervisedAppearanceSettings.route, false))
|
||||
// The full Appearance destination includes profile/avatar/pet controls.
|
||||
// The supervised Settings root owns its own allowlisted theme controls.
|
||||
assertFalse(isSupervisedRouteAllowed("settings/appearance", false))
|
||||
assertFalse(isSupervisedRouteAllowed("settings/about", false))
|
||||
assertFalse(isSupervisedRouteAllowed(Screen.AdvancedSettings.route, false))
|
||||
assertFalse(isSupervisedRouteAllowed("manage", false))
|
||||
assertFalse(isSupervisedRouteAllowed("settings/developer", false))
|
||||
assertFalse(isSupervisedRouteAllowed("settings/supervised", false))
|
||||
assertFalse(isSupervisedRouteAllowed(null, false))
|
||||
}
|
||||
|
||||
@Test fun `parent unlock permits full navigation`() {
|
||||
assertTrue(isSupervisedRouteAllowed("manage", true))
|
||||
assertTrue(isSupervisedRouteAllowed(Screen.AdvancedSettings.route, true))
|
||||
}
|
||||
|
||||
@Test fun `supervised redirect waits until the navigation graph has a route`() {
|
||||
assertFalse(shouldRedirectSupervisedRoute(true, false, null))
|
||||
assertTrue(isSupervisedRouteContentAllowed(true, false, null))
|
||||
assertFalse(shouldRedirectSupervisedRoute(true, false, Screen.Chat.route))
|
||||
assertTrue(isSupervisedRouteContentAllowed(true, false, Screen.Chat.route))
|
||||
assertTrue(shouldRedirectSupervisedRoute(true, false, Screen.AdvancedSettings.route))
|
||||
assertFalse(isSupervisedRouteContentAllowed(true, false, Screen.AdvancedSettings.route))
|
||||
assertFalse(shouldRedirectSupervisedRoute(true, true, Screen.AdvancedSettings.route))
|
||||
assertTrue(isSupervisedRouteContentAllowed(true, true, Screen.AdvancedSettings.route))
|
||||
}
|
||||
|
||||
@Test fun `navigation waits for connection store before trusting null active id`() {
|
||||
assertFalse(isRelayNavigationHydrated(false, null, false))
|
||||
assertTrue(isRelayNavigationHydrated(true, null, false))
|
||||
assertFalse(isRelayNavigationHydrated(true, "home", false))
|
||||
assertTrue(isRelayNavigationHydrated(true, "home", true))
|
||||
}
|
||||
|
||||
@Test fun `parent access relocks as soon as chat becomes current`() {
|
||||
assertTrue(shouldRelockParentAccess(true, true, "chat?sessionId=ignored"))
|
||||
assertFalse(shouldRelockParentAccess(true, true, "settings/supervised"))
|
||||
assertFalse(shouldRelockParentAccess(false, true, "chat"))
|
||||
assertFalse(shouldRelockParentAccess(true, false, "chat"))
|
||||
}
|
||||
|
||||
@Test fun `supervised route session requires history pinned profile and trusted ownership proof`() {
|
||||
val policy = SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(conversationHistory = true),
|
||||
)
|
||||
|
||||
assertFalse(mayRestoreSupervisedSessionRoute(policy, "session-1", "willow", false))
|
||||
assertFalse(mayRestoreSupervisedSessionRoute(policy, "session-1", "parent", true))
|
||||
assertTrue(mayRestoreSupervisedSessionRoute(policy, "session-1", "WILLOW", true))
|
||||
assertFalse(
|
||||
mayRestoreSupervisedSessionRoute(
|
||||
policy.copy(capabilities = policy.capabilities.copy(conversationHistory = false)),
|
||||
"session-1",
|
||||
"willow",
|
||||
true,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `supervised external route discards session profile and proactive targets`() {
|
||||
val policy = SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(conversationHistory = true),
|
||||
)
|
||||
val external = SupervisedChatRouteArgs(
|
||||
sessionId = "parent-session",
|
||||
profile = "willow",
|
||||
proactiveChatId = "phone",
|
||||
)
|
||||
|
||||
assertTrue(
|
||||
sanitizeSupervisedChatRouteArgs(policy, external, false) ==
|
||||
SupervisedChatRouteArgs(),
|
||||
)
|
||||
assertTrue(
|
||||
sanitizeSupervisedChatRouteArgs(policy, external, true) ==
|
||||
external.copy(proactiveChatId = null),
|
||||
)
|
||||
assertTrue(
|
||||
sanitizeSupervisedChatRouteArgs(SupervisedModePolicy(), external, false) == external,
|
||||
)
|
||||
}
|
||||
|
||||
@Test fun `first enable requires configured policy secure screen and successful device credential`() {
|
||||
val configured = SupervisedModePolicy(pinnedProfileName = "willow")
|
||||
|
||||
assertFalse(
|
||||
mayEnableSupervisedMode(
|
||||
configured,
|
||||
deviceSecure = false,
|
||||
deviceCredentialConfirmed = true,
|
||||
),
|
||||
)
|
||||
assertFalse(
|
||||
mayEnableSupervisedMode(
|
||||
configured,
|
||||
deviceSecure = true,
|
||||
deviceCredentialConfirmed = false,
|
||||
),
|
||||
)
|
||||
assertFalse(mayEnableSupervisedMode(SupervisedModePolicy(), true, true))
|
||||
assertTrue(mayEnableSupervisedMode(configured, true, true))
|
||||
assertFalse(mayEnableSupervisedMode(configured.copy(enabled = true), true, true))
|
||||
}
|
||||
}
|
||||
+5
-19
@@ -5,12 +5,10 @@ import org.junit.Test
|
||||
|
||||
class MorphingSphereMotionPolicyTest {
|
||||
@Test
|
||||
fun `visible idle sphere uses lightweight ambient motion`() {
|
||||
fun `every visible sphere uses smooth procedural motion`() {
|
||||
assertEquals(
|
||||
SphereMotionMode.AmbientLayer,
|
||||
SphereMotionMode.Procedural,
|
||||
sphereMotionMode(
|
||||
state = SphereState.Idle,
|
||||
voiceMode = false,
|
||||
motionVisible = true,
|
||||
fixedTime = null,
|
||||
fixedColorPhase = null,
|
||||
@@ -19,26 +17,14 @@ class MorphingSphereMotionPolicyTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hidden or paused idle sphere is still`() {
|
||||
fun `hidden or paused sphere is still`() {
|
||||
assertEquals(
|
||||
SphereMotionMode.Still,
|
||||
sphereMotionMode(SphereState.Idle, false, false, null, null),
|
||||
sphereMotionMode(false, null, null),
|
||||
)
|
||||
assertEquals(
|
||||
SphereMotionMode.Still,
|
||||
sphereMotionMode(SphereState.Idle, false, true, 0f, 0f),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `visible active and voice states keep procedural motion`() {
|
||||
assertEquals(
|
||||
SphereMotionMode.Procedural,
|
||||
sphereMotionMode(SphereState.Thinking, false, true, null, null),
|
||||
)
|
||||
assertEquals(
|
||||
SphereMotionMode.Procedural,
|
||||
sphereMotionMode(SphereState.Idle, true, true, null, null),
|
||||
sphereMotionMode(true, 0f, 0f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.hermesandroid.relay.data.ChatSession
|
||||
import com.hermesandroid.relay.data.SessionActivityState
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SessionDrawerPolicyTest {
|
||||
@@ -144,6 +145,17 @@ class SessionDrawerPolicyTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `full row border is limited to foreground live work`() {
|
||||
assertTrue(sessionActivityShowsRowBorder(SessionActivityState.Starting))
|
||||
assertTrue(sessionActivityShowsRowBorder(SessionActivityState.Working))
|
||||
assertFalse(sessionActivityShowsRowBorder(SessionActivityState.NeedsInput))
|
||||
assertFalse(sessionActivityShowsRowBorder(SessionActivityState.BackgroundWork))
|
||||
assertFalse(sessionActivityShowsRowBorder(SessionActivityState.Checking))
|
||||
assertFalse(sessionActivityShowsRowBorder(SessionActivityState.Unavailable))
|
||||
assertFalse(sessionActivityShowsRowBorder(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `profile project status and pull request filters compose`() {
|
||||
val wanted = row(
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedImagePresentationTest {
|
||||
@Test
|
||||
fun `disabled assistant images strip markdown without exposing a fetchable source`() {
|
||||
val content = "Here it is  and "
|
||||
|
||||
val (body, images) = assistantImageContent(content, showImages = false)
|
||||
|
||||
assertEquals("Here it is and", body)
|
||||
assertTrue(images.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enabled assistant images preserve all supported sources`() {
|
||||
val content = " "
|
||||
|
||||
val (_, images) = assistantImageContent(content, showImages = true)
|
||||
|
||||
assertEquals(listOf("https://example.com/a.png", "/tmp/b.png"), images.map { it.src })
|
||||
}
|
||||
}
|
||||
+8
-3
@@ -333,7 +333,7 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unsupportedActiveListProjectsUnavailableInsteadOfRestWorking() {
|
||||
fun unsupportedActiveListLeavesRowsNeutralAcrossDirectoryRefresh() {
|
||||
bindActivityTestDirectory()
|
||||
handler.updateSessions(
|
||||
listOf(SessionItem(id = STORED_SESSION_ID, title = "Recent", isActive = true)),
|
||||
@@ -344,9 +344,14 @@ class ChatViewModelGatewayInboundTurnTest {
|
||||
gatewayHarness.awaitRpc("session.active_list")
|
||||
|
||||
awaitCondition {
|
||||
viewModel.backgroundSessionActivityStates.value["default:$STORED_SESSION_ID"] ==
|
||||
SessionActivityState.Unavailable
|
||||
"default:$STORED_SESSION_ID" !in viewModel.backgroundSessionActivityStates.value
|
||||
}
|
||||
|
||||
viewModel.updateSessionActivityDirectory(
|
||||
rows = listOf("default" to STORED_SESSION_ID),
|
||||
)
|
||||
|
||||
assertFalse("default:$STORED_SESSION_ID" in viewModel.backgroundSessionActivityStates.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.filterIsInstance
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [35])
|
||||
class GitStateExtrasViewModelTest {
|
||||
private val ownerKey = "connection-a\u0000default\u0000dashboard"
|
||||
private val mainDispatcher = UnconfinedTestDispatcher()
|
||||
private lateinit var application: Application
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
Dispatchers.setMain(mainDispatcher)
|
||||
application = ApplicationProvider.getApplicationContext()
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
server.shutdown()
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
private fun viewModel(grant: Boolean = true): GitStateViewModel {
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), ownerKey)
|
||||
vm.setWriteGrant(ownerKey, grant)
|
||||
return vm
|
||||
}
|
||||
|
||||
private fun enqueueJson(body: String) {
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(body),
|
||||
)
|
||||
}
|
||||
|
||||
private fun selectAlpha(vm: GitStateViewModel) {
|
||||
enqueueJson("""{"repos":[{"id":"alpha","name":"alpha","root":"/p/alpha","current_branch":"main","dirty":true}]}""")
|
||||
enqueueJson("""{"counts":{"staged":1,"modified":0,"untracked":0},"staged":[{"path":"a.txt"}],"modified":[],"untracked":[],"truncated":false}""")
|
||||
enqueueJson("""{"branches":[{"name":"main","upstream":"origin/main","ahead":0,"behind":0,"is_current":true}]}""")
|
||||
runBlocking { withTimeout(5_000) { vm.repos.filterIsInstance<GitStateUiState.Ready>().first() } }
|
||||
vm.selectRepo("alpha")
|
||||
runBlocking { withTimeout(5_000) { vm.detail.filterIsInstance<GitRepoDetailState.Ready>().first() } }
|
||||
repeat(3) { server.takeRequest() }
|
||||
}
|
||||
|
||||
// ── AI commit message (magic-wand) ─────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun `generate commit message pre-fills the suggestion via selected paths`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueueJson("""{"message":"feat: add feature","notice":""}""")
|
||||
vm.generateCommitMessage(listOf("a.txt"))
|
||||
val state = withTimeout(5_000) {
|
||||
vm.messageGeneration.filterIsInstance<GitMessageGenerationState.Ready>().first()
|
||||
}
|
||||
assertEquals("feat: add feature", state.message)
|
||||
assertEquals("", state.notice)
|
||||
val req = server.takeRequest()
|
||||
assertTrue(req.path!!.contains("/git/commit_message_selected"))
|
||||
assertTrue(req.body.readUtf8().contains("a.txt"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `generate message without grant is refused before any POST`() = runBlocking {
|
||||
val vm = viewModel(grant = false)
|
||||
selectAlpha(vm)
|
||||
vm.generateCommitMessage(null)
|
||||
val state = withTimeout(5_000) {
|
||||
vm.messageGeneration.filterIsInstance<GitMessageGenerationState.Ready>().first()
|
||||
}
|
||||
assertTrue(state.notice.contains("plugin.api.write"))
|
||||
assertEquals(3, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty staged diff surfaces notice without error`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueueJson("""{"message":"","notice":"nothing staged"}""")
|
||||
vm.generateCommitMessage(listOf("a.txt"))
|
||||
val state = withTimeout(5_000) {
|
||||
vm.messageGeneration.filterIsInstance<GitMessageGenerationState.Ready>().first()
|
||||
}
|
||||
assertEquals("", state.message)
|
||||
assertEquals("nothing staged", state.notice)
|
||||
}
|
||||
|
||||
// ── Push-after-commit toggle ───────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun `push after commit defaults off and toggles`() {
|
||||
val vm = viewModel()
|
||||
assertTrue(!vm.isPushAfterCommitEnabled())
|
||||
vm.setPushAfterCommit(true)
|
||||
assertTrue(vm.isPushAfterCommitEnabled())
|
||||
vm.setPushAfterCommit(false)
|
||||
assertTrue(!vm.isPushAfterCommitEnabled())
|
||||
}
|
||||
|
||||
// ── Stash-checkout ─────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun `stash checkout surfaces the stash notice on success`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueueJson(
|
||||
"""{"head":"abc","stashed":true,"stash_message":"git-state: feature","status":{"counts":{"staged":0,"modified":0,"untracked":0},"staged":[],"modified":[],"untracked":[],"truncated":false},"branches":[]}""",
|
||||
)
|
||||
// refreshDetail fires two reads (status + branches).
|
||||
enqueueJson("""{"counts":{"staged":0,"modified":0,"untracked":0},"staged":[],"modified":[],"untracked":[],"truncated":false}""")
|
||||
enqueueJson("""{"branches":[]}""")
|
||||
vm.stashCheckout("feature")
|
||||
withTimeout(5_000) { vm.mutation.filterIsInstance<GitMutationState.Success>().first() }
|
||||
val notice = withTimeout(5_000) { vm.stashNotice.first { it != null } }!!
|
||||
assertTrue(notice.contains("git-state: feature"))
|
||||
assertTrue(notice.contains("git stash pop"))
|
||||
val req = server.takeRequest()
|
||||
assertTrue(req.path!!.contains("/git/stash_checkout"))
|
||||
assertTrue(req.body.readUtf8().contains("feature"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stash checkout without grant is refused before any POST`() = runBlocking {
|
||||
val vm = viewModel(grant = false)
|
||||
selectAlpha(vm)
|
||||
vm.stashCheckout("feature")
|
||||
val state = withTimeout(5_000) {
|
||||
vm.mutation.filterIsInstance<GitMutationState.Error>().first()
|
||||
}
|
||||
assertTrue(state.message.contains("plugin.api.write"))
|
||||
assertEquals(3, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `clean stash checkout yields no stash notice`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueueJson(
|
||||
"""{"head":"abc","stashed":false,"stash_message":"","status":{"counts":{"staged":0,"modified":0,"untracked":0},"staged":[],"modified":[],"untracked":[],"truncated":false},"branches":[]}""",
|
||||
)
|
||||
enqueueJson("""{"counts":{"staged":0,"modified":0,"untracked":0},"staged":[],"modified":[],"untracked":[],"truncated":false}""")
|
||||
enqueueJson("""{"branches":[]}""")
|
||||
vm.stashCheckout("feature")
|
||||
withTimeout(5_000) { vm.mutation.filterIsInstance<GitMutationState.Success>().first() }
|
||||
// No stash notice for a clean checkout.
|
||||
assertEquals(null, vm.stashNotice.value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.filterIsInstance
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [35])
|
||||
class GitStateViewModelTest {
|
||||
private val ownerKey = "connection-a\u0000default\u0000dashboard"
|
||||
private val mainDispatcher = UnconfinedTestDispatcher()
|
||||
private lateinit var application: Application
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
Dispatchers.setMain(mainDispatcher)
|
||||
application = ApplicationProvider.getApplicationContext()
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
server.shutdown()
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
private fun viewModel(): GitStateViewModel {
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), ownerKey)
|
||||
return vm
|
||||
}
|
||||
|
||||
private fun enqueueJson(body: String) {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(body),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `loadRepos maps repo list and notice`() = runBlocking {
|
||||
enqueueJson(
|
||||
"""{"repos":[{"id":"alpha","name":"alpha","root":"/p/alpha","current_branch":"main","dirty":false}],"notice":null}""",
|
||||
)
|
||||
val vm = viewModel()
|
||||
val state = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Ready>().first()
|
||||
}
|
||||
assertEquals(1, state.repos.size)
|
||||
assertEquals("alpha", state.repos.single().name)
|
||||
assertNotNull(vm.repos.value)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `loadRepos surfaces server error`() = runBlocking {
|
||||
server.enqueue(MockResponse().setResponseCode(400).setBody("""{"detail":"unknown repository"}"""))
|
||||
val vm = viewModel()
|
||||
val state = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Error>().first()
|
||||
}
|
||||
assertTrue(state.message.isNotBlank())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `loadRepos maps missing plugin route to friendly unavailable state`() = runBlocking {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setResponseCode(404)
|
||||
.setBody("""{"detail":"No such API endpoint"}"""),
|
||||
)
|
||||
val vm = viewModel()
|
||||
val state = withTimeout(5_000) {
|
||||
vm.repos.filterIsInstance<GitStateUiState.Unavailable>().first()
|
||||
}
|
||||
assertEquals("Git isn't available on this Hermes host yet.", state.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `selectRepo loads status and branches and preserves truncation flag`() = runBlocking {
|
||||
enqueueJson(
|
||||
"""{"repos":[{"id":"alpha","name":"alpha","root":"/p/alpha","current_branch":"main","dirty":true}]}""",
|
||||
)
|
||||
// status
|
||||
enqueueJson(
|
||||
"""{"counts":{"staged":1,"modified":2,"untracked":3},"staged":[{"path":"a.txt"}],"modified":[],"untracked":[],"truncated":true}""",
|
||||
)
|
||||
// branches
|
||||
enqueueJson(
|
||||
"""{"branches":[{"name":"main","upstream":"origin/main","ahead":1,"behind":0,"is_current":true}]}""",
|
||||
)
|
||||
val vm = viewModel()
|
||||
withTimeout(5_000) { vm.repos.filterIsInstance<GitStateUiState.Ready>().first() }
|
||||
vm.selectRepo("alpha")
|
||||
val ready = withTimeout(5_000) {
|
||||
vm.detail.filterIsInstance<GitRepoDetailState.Ready>().first()
|
||||
}
|
||||
assertEquals(1, ready.status.counts.staged)
|
||||
assertEquals(2, ready.status.counts.modified)
|
||||
assertEquals(3, ready.status.counts.untracked)
|
||||
assertEquals(-1, ready.status.counts.changes)
|
||||
assertEquals(0, ready.status.counts.additions)
|
||||
assertEquals(0, ready.status.counts.deletions)
|
||||
assertNull(ready.status.staged.single().additions)
|
||||
assertTrue(ready.status.truncated)
|
||||
assertEquals("main", ready.branches.single().name)
|
||||
assertTrue(ready.branches.single().isCurrent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `loadDiff surfaces truncated diff`() = runBlocking {
|
||||
enqueueJson("""{"repos":[{"id":"alpha","name":"alpha","root":"/p/alpha"}]}""")
|
||||
enqueueJson("""{"counts":{"staged":0,"modified":1,"untracked":0},"staged":[],"modified":[{"path":"a.txt"}],"untracked":[],"truncated":false}""")
|
||||
enqueueJson("""{"branches":[]}""")
|
||||
enqueueJson("""{"path":"a.txt","kind":"unstaged","diff":"+change","truncated":true}""")
|
||||
|
||||
val vm = viewModel()
|
||||
withTimeout(5_000) { vm.repos.filterIsInstance<GitStateUiState.Ready>().first() }
|
||||
vm.selectRepo("alpha")
|
||||
withTimeout(5_000) { vm.detail.filterIsInstance<GitRepoDetailState.Ready>().first() }
|
||||
vm.loadDiff("a.txt", "unstaged")
|
||||
val content = withTimeout(5_000) {
|
||||
vm.content.filterIsInstance<GitContentViewState.Diff>().first()
|
||||
}
|
||||
assertEquals("a.txt", content.diff.path)
|
||||
assertTrue(content.diff.truncated)
|
||||
assertTrue(content.diff.diff.contains("change"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `loadFile surfaces content and truncation`() = runBlocking {
|
||||
enqueueJson("""{"repos":[{"id":"alpha","name":"alpha","root":"/p/alpha"}]}""")
|
||||
enqueueJson("""{"counts":{"staged":0,"modified":0,"untracked":1},"staged":[],"modified":[],"untracked":[{"path":"new.txt"}],"truncated":false}""")
|
||||
enqueueJson("""{"branches":[]}""")
|
||||
enqueueJson("""{"path":"new.txt","content":"hello world","truncated":false}""")
|
||||
|
||||
val vm = viewModel()
|
||||
withTimeout(5_000) { vm.repos.filterIsInstance<GitStateUiState.Ready>().first() }
|
||||
vm.selectRepo("alpha")
|
||||
withTimeout(5_000) { vm.detail.filterIsInstance<GitRepoDetailState.Ready>().first() }
|
||||
vm.loadFile("new.txt")
|
||||
val content = withTimeout(5_000) {
|
||||
vm.content.filterIsInstance<GitContentViewState.File>().first()
|
||||
}
|
||||
assertEquals("hello world", content.file.content)
|
||||
assertFalse(content.file.truncated)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `selectRepo surfaces status error for unknown repo`() = runBlocking {
|
||||
enqueueJson("""{"repos":[{"id":"alpha","name":"alpha","root":"/p/alpha"}]}""")
|
||||
server.enqueue(MockResponse().setResponseCode(400).setBody("""{"detail":"unknown repository: bogus"}"""))
|
||||
enqueueJson("""{"branches":[]}""")
|
||||
val vm = viewModel()
|
||||
withTimeout(5_000) { vm.repos.filterIsInstance<GitStateUiState.Ready>().first() }
|
||||
vm.selectRepo("bogus")
|
||||
val error = withTimeout(5_000) {
|
||||
vm.detail.filterIsInstance<GitRepoDetailState.Error>().first()
|
||||
}
|
||||
assertTrue(error.message.contains("unknown repository"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.filterIsInstance
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.test.UnconfinedTestDispatcher
|
||||
import kotlinx.coroutines.test.resetMain
|
||||
import kotlinx.coroutines.test.setMain
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [35])
|
||||
class GitStateWriteViewModelTest {
|
||||
private val ownerKey = "connection-a\u0000default\u0000dashboard"
|
||||
private val mainDispatcher = UnconfinedTestDispatcher()
|
||||
private lateinit var application: Application
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
Dispatchers.setMain(mainDispatcher)
|
||||
application = ApplicationProvider.getApplicationContext()
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
server.shutdown()
|
||||
Dispatchers.resetMain()
|
||||
}
|
||||
|
||||
private fun viewModel(grant: Boolean = true): GitStateViewModel {
|
||||
val vm = GitStateViewModel(application)
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), ownerKey)
|
||||
vm.setWriteGrant(ownerKey, grant)
|
||||
return vm
|
||||
}
|
||||
|
||||
private fun enqueueJson(body: String) {
|
||||
server.enqueue(
|
||||
MockResponse()
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(body),
|
||||
)
|
||||
}
|
||||
|
||||
/** Loads the repo list + selects ``alpha`` so a mutation has a target. */
|
||||
private fun selectAlpha(vm: GitStateViewModel) {
|
||||
enqueueJson("""{"repos":[{"id":"alpha","name":"alpha","root":"/p/alpha","current_branch":"main","dirty":true}]}""")
|
||||
enqueueJson("""{"counts":{"staged":1,"modified":0,"untracked":0},"staged":[{"path":"a.txt"}],"modified":[],"untracked":[],"truncated":false}""")
|
||||
enqueueJson("""{"branches":[{"name":"main","upstream":"origin/main","ahead":0,"behind":0,"is_current":true}]}""")
|
||||
runBlocking { withTimeout(5_000) { vm.repos.filterIsInstance<GitStateUiState.Ready>().first() } }
|
||||
vm.selectRepo("alpha")
|
||||
runBlocking { withTimeout(5_000) { vm.detail.filterIsInstance<GitRepoDetailState.Ready>().first() } }
|
||||
// Drain the three read requests (repos/status/branches) so the next
|
||||
// takeRequest() returns the mutation POST we actually assert on.
|
||||
repeat(3) { server.takeRequest() }
|
||||
}
|
||||
|
||||
private fun enqueuePostSuccess(head: String) {
|
||||
enqueueJson("""{"head":"$head","status":{"counts":{"staged":0,"modified":0,"untracked":0},"staged":[],"modified":[],"untracked":[],"truncated":false}}""")
|
||||
// refreshDetail fires two more requests (status + branches).
|
||||
enqueueJson("""{"counts":{"staged":0,"modified":0,"untracked":0},"staged":[],"modified":[],"untracked":[],"truncated":false}""")
|
||||
enqueueJson("""{"branches":[]}""")
|
||||
}
|
||||
|
||||
// ── Grant gating (security first) ──────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun `stage without write grant is refused before any POST`() = runBlocking {
|
||||
val vm = viewModel(grant = false)
|
||||
selectAlpha(vm)
|
||||
vm.stage(listOf("a.txt"))
|
||||
val state = withTimeout(5_000) {
|
||||
vm.mutation.filterIsInstance<GitMutationState.Error>().first()
|
||||
}
|
||||
assertTrue(state.message.contains("plugin.api.write"))
|
||||
// No write POST was sent (only the 3 read requests for load/select).
|
||||
assertEquals(3, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `discard without write grant is refused`() = runBlocking {
|
||||
val vm = viewModel(grant = false)
|
||||
selectAlpha(vm)
|
||||
vm.discard(listOf("a.txt"), GitConfirmationStrings.DISCARD)
|
||||
val state = withTimeout(5_000) {
|
||||
vm.mutation.filterIsInstance<GitMutationState.Error>().first()
|
||||
}
|
||||
assertTrue(state.message.contains("plugin.api.write"))
|
||||
assertEquals(3, server.requestCount)
|
||||
}
|
||||
|
||||
// ── Happy paths ────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun `stage sends POST and surfaces success + fresh status`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueuePostSuccess("abc123")
|
||||
vm.stage(listOf("a.txt"))
|
||||
val state = withTimeout(5_000) {
|
||||
vm.mutation.filterIsInstance<GitMutationState.Success>().first()
|
||||
}
|
||||
assertEquals("stage", state.label)
|
||||
assertEquals("abc123", state.head)
|
||||
val req = server.takeRequest()
|
||||
assertTrue(req.path!!.contains("/git/stage"))
|
||||
assertTrue(req.body.readUtf8().contains("a.txt"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `commit sends message and returns head`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueuePostSuccess("deadbeef")
|
||||
vm.commit("add feature")
|
||||
val state = withTimeout(5_000) {
|
||||
vm.mutation.filterIsInstance<GitMutationState.Success>().first()
|
||||
}
|
||||
assertEquals("commit", state.label)
|
||||
val req = server.takeRequest()
|
||||
assertTrue(req.path!!.contains("/git/commit"))
|
||||
assertTrue(req.body.readUtf8().contains("add feature"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `commit success callback fires only after successful response`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueuePostSuccess("abc")
|
||||
var committedTarget: GitTarget? = null
|
||||
|
||||
vm.commit("add feature") { committedTarget = it }
|
||||
withTimeout(5_000) { vm.mutation.filterIsInstance<GitMutationState.Success>().first() }
|
||||
|
||||
assertEquals("alpha", committedTarget?.repoId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `commit failure never invokes success callback`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
server.enqueue(MockResponse().setResponseCode(400).setBody("""{"detail":"failed"}"""))
|
||||
var callbackCalled = false
|
||||
|
||||
vm.commit("add feature") { callbackCalled = true }
|
||||
withTimeout(5_000) { vm.mutation.filterIsInstance<GitMutationState.Error>().first() }
|
||||
|
||||
assertFalse(callbackCalled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `connection change revokes grant and rejects prior target`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
val priorTarget = vm.currentTarget()!!
|
||||
enqueueJson("""{"repos":[]}""")
|
||||
|
||||
vm.configure(DashboardApiClient(server.url("/").toString()), "connection-b")
|
||||
vm.setWriteGrant(ownerKey, true)
|
||||
withTimeout(5_000) { vm.repos.filterIsInstance<GitStateUiState.Ready>().first() }
|
||||
vm.push(GitConfirmationStrings.PUSH, expectedTarget = priorTarget)
|
||||
|
||||
assertFalse(vm.hasWriteGrant())
|
||||
assertEquals(null, vm.currentTarget())
|
||||
assertTrue(vm.mutation.value is GitMutationState.Error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `discard echoes the fixed confirmation token`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueuePostSuccess("abc")
|
||||
vm.discard(listOf("a.txt"), GitConfirmationStrings.DISCARD)
|
||||
withTimeout(5_000) { vm.mutation.filterIsInstance<GitMutationState.Success>().first() }
|
||||
val req = server.takeRequest()
|
||||
assertTrue(req.path!!.contains("/git/discard"))
|
||||
assertTrue(req.body.readUtf8().contains(GitConfirmationStrings.DISCARD))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `push echoes the confirmation token`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueuePostSuccess("abc")
|
||||
vm.push(GitConfirmationStrings.PUSH)
|
||||
withTimeout(5_000) { vm.mutation.filterIsInstance<GitMutationState.Success>().first() }
|
||||
val req = server.takeRequest()
|
||||
assertTrue(req.path!!.contains("/git/push"))
|
||||
assertTrue(req.body.readUtf8().contains(GitConfirmationStrings.PUSH))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fetch and pull send their endpoints`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
enqueuePostSuccess("abc")
|
||||
vm.fetch()
|
||||
withTimeout(5_000) { vm.mutation.filterIsInstance<GitMutationState.Success>().first() }
|
||||
assertTrue(server.takeRequest().path!!.contains("/git/fetch"))
|
||||
// Drain the two refreshDetail reads (status + branches) so the next
|
||||
// takeRequest() sees only the pull POST.
|
||||
repeat(2) { server.takeRequest() }
|
||||
|
||||
enqueuePostSuccess("xyz")
|
||||
vm.pull("origin", "main")
|
||||
withTimeout(5_000) { vm.mutation.filterIsInstance<GitMutationState.Success>().first() }
|
||||
assertTrue(server.takeRequest().path!!.contains("/git/pull"))
|
||||
}
|
||||
|
||||
// ── Error branches ─────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun `commit surfaces server error as readable message`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
server.enqueue(
|
||||
MockResponse().setResponseCode(400).setBody("""{"detail":"commit message must not be empty"}"""),
|
||||
)
|
||||
vm.commit(" ")
|
||||
val state = withTimeout(5_000) {
|
||||
vm.mutation.filterIsInstance<GitMutationState.Error>().first()
|
||||
}
|
||||
assertTrue(state.message.contains("must not be empty"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `discard wrong confirmation surfaces server 403`() = runBlocking {
|
||||
val vm = viewModel()
|
||||
selectAlpha(vm)
|
||||
server.enqueue(
|
||||
MockResponse().setResponseCode(403).setBody("""{"detail":"confirmation did not match"}"""),
|
||||
)
|
||||
vm.discard(listOf("a.txt"), "wrong")
|
||||
val state = withTimeout(5_000) {
|
||||
vm.mutation.filterIsInstance<GitMutationState.Error>().first()
|
||||
}
|
||||
assertTrue(state.message.contains("confirmation") || state.message.contains("403"))
|
||||
}
|
||||
|
||||
// ── Confirmation gating helpers ────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
fun `requiresConfirmation and confirmationFor match destructive ops`() {
|
||||
val vm = viewModel()
|
||||
assertTrue(vm.requiresConfirmation("discard"))
|
||||
assertTrue(vm.requiresConfirmation("push"))
|
||||
assertTrue(vm.requiresConfirmation("dirty-checkout"))
|
||||
assertEquals(GitConfirmationStrings.DISCARD, vm.confirmationFor("discard"))
|
||||
assertEquals(GitConfirmationStrings.PUSH, vm.confirmationFor("push"))
|
||||
assertEquals(GitConfirmationStrings.DIRTY_CHECKOUT, vm.confirmationFor("dirty-checkout"))
|
||||
assertEquals(null, vm.confirmationFor("commit"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedChatPolicyTest {
|
||||
@Test
|
||||
fun `normal mode preserves slash commands`() {
|
||||
assertNull(supervisedMessageBlockReason(SupervisedModePolicy(), " /model"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enabled policy fails closed without pinned profile`() {
|
||||
assertEquals(
|
||||
"Supervised mode is unavailable until the parent selects a profile.",
|
||||
supervisedMessageBlockReason(SupervisedModePolicy(enabled = true), "hello"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active policy blocks slash commands after unicode whitespace`() {
|
||||
val policy = SupervisedModePolicy(enabled = true, pinnedProfileName = "willow")
|
||||
assertEquals(
|
||||
"Slash commands are unavailable in supervised mode.",
|
||||
supervisedMessageBlockReason(policy, "\u2003\t /model hidden"),
|
||||
)
|
||||
assertNull(supervisedMessageBlockReason(policy, "please explain /model"))
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.SupervisedCapabilities
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
import com.hermesandroid.relay.voice.VoiceCommandAction
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class SupervisedVoiceCommandPolicyTest {
|
||||
@Test
|
||||
fun `normal mode preserves every voice command`() {
|
||||
VoiceCommandAction.entries.forEach { action ->
|
||||
assertTrue(isVoiceCommandAllowed(action, SupervisedModePolicy()))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `supervised mode gates new chat and cancellation independently`() {
|
||||
val policy = SupervisedModePolicy(
|
||||
enabled = true,
|
||||
pinnedProfileName = "willow",
|
||||
capabilities = SupervisedCapabilities(
|
||||
voice = true,
|
||||
newChat = false,
|
||||
cancelResponse = false,
|
||||
),
|
||||
)
|
||||
|
||||
assertFalse(isVoiceCommandAllowed(VoiceCommandAction.StartNewChat, policy))
|
||||
assertFalse(isVoiceCommandAllowed(VoiceCommandAction.StopResponse, policy))
|
||||
assertFalse(isVoiceCommandAllowed(VoiceCommandAction.CancelBackgroundTask, policy))
|
||||
assertTrue(isVoiceCommandAllowed(VoiceCommandAction.EndVoiceChat, policy))
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 127 KiB |
@@ -91,6 +91,19 @@ the `relay_plugin_draft` tool to create or replace a generated declarative page.
|
||||
tool accepts the same bounded schema as Android, stores JSON atomically below
|
||||
`HERMES_HOME/mobile-plugins`, and rejects every `action.request`. Generated previews
|
||||
therefore cannot reach Relay management APIs or acquire executable backend behavior.
|
||||
The contribution ID `git` is reserved for the Relay plugin's native Git workspace;
|
||||
generated drafts cannot shadow or duplicate that route.
|
||||
|
||||
Android presents that reserved contribution as a first-class native surface rather
|
||||
than a generic declarative page. When the live plugin API confirms Git is available,
|
||||
Chat can show a compact branch/change rail and a dot-only context action; **Chat →
|
||||
Show Git workspace in Chat** hides those two Chat affordances without disabling the
|
||||
workspace. The full native workspace remains reachable from Settings and Plugins and
|
||||
owns repository/branch selection, diffs, staging, confirmed destructive actions,
|
||||
commits, and remotes. Session `git_repo_root`/`cwd` metadata selects an exact matching
|
||||
repository when possible; ambiguous catalogs require an explicit user choice. Mobile
|
||||
discovery alone is not treated as runtime readiness: a missing Git API route renders a
|
||||
retryable unavailable state instead of exposing the raw Dashboard error.
|
||||
|
||||
The Relay mobile manifest exposes drafts as preview pages under the authenticated
|
||||
`hermes-relay` plugin namespace. Android polls the catalog every five seconds while
|
||||
|
||||
+119
-2
@@ -1,6 +1,6 @@
|
||||
# Hermes-Relay — Decisions & Implementation Guide
|
||||
|
||||
> Updated: 2026-04-06
|
||||
> Updated: 2026-08-24
|
||||
>
|
||||
> Read this before SPEC.md — it tells you what to build, what was deferred, and why.
|
||||
|
||||
@@ -3692,7 +3692,124 @@ be considered later without being silently introduced now.
|
||||
|
||||
---
|
||||
|
||||
## ADR 66 — Android Bot Mode is a separate upstream-owned messaging workspace
|
||||
## ADR 66 — Android Supervised Mode is a parent-controlled client policy
|
||||
|
||||
**Status:** Implemented in code; physical managed-device certification pending (2026-08-24).
|
||||
|
||||
**Context.** Some operators prepare a deliberately restricted Hermes profile
|
||||
for use through a parent-supervised Android client. The profile remains the
|
||||
authority for its model, prompt, tools, provider credentials, content behavior,
|
||||
and server-side data. Hermes-Relay should help a parent present a smaller,
|
||||
proctored phone interface without representing that interface as end-to-end
|
||||
child security or as a server-enforced account type.
|
||||
|
||||
**Decision.** Android will treat Supervised Mode as an opt-in, locally enforced
|
||||
policy pinned to one existing Connection and one existing Hermes profile. The
|
||||
parent is responsible for preparing and reviewing that profile before enabling
|
||||
the mode. Entering, changing, or leaving the parent policy requires Android
|
||||
device authentication. That prompt authenticates an enrolled device user, not
|
||||
a distinct server-side parent identity. While the policy is active, the app restores directly
|
||||
into a restricted root and never renders the ordinary app behind an
|
||||
authentication prompt. A missing Connection, missing profile, malformed policy,
|
||||
failed authentication, process restart, or restored route that cannot prove its
|
||||
owner fails closed to the restricted surface.
|
||||
|
||||
The ordinary Chat screen stays visually quiet. It does not carry a persistent
|
||||
"supervised" banner. Its existing Settings action opens only approved
|
||||
preferences; a separate **Parent access** row authenticates before showing the
|
||||
policy editor or full application settings. Backgrounding, inactivity, process
|
||||
recreation, and leaving parent settings relock parent access according to the
|
||||
policy. Deep links, notification actions, restored navigation, shortcuts, and
|
||||
programmatic routes pass the same gate.
|
||||
|
||||
The parent policy controls capabilities rather than imposing a special
|
||||
attachment count. Initial capabilities are text chat, new chat, cancel, steer,
|
||||
attachments, standard voice, generated-media viewing, save/share media, copy,
|
||||
retry, quote/reply, and edit/resend. Attachments and voice are independently
|
||||
enabled. When attachments are enabled, Android retains the normal supported
|
||||
attachment flow and its existing size/type limits unless the parent selects a
|
||||
stricter limit; disabling attachments removes every picker, paste-to-file,
|
||||
camera/share-to-chat, and restored-draft entry point. Disabling voice removes
|
||||
capture, voice intents, and voice settings from the restricted surface. Provider
|
||||
credentials remain on the configured Hermes host under the existing standard
|
||||
voice contract.
|
||||
|
||||
The restricted composer does not expose the command palette, slash
|
||||
autocomplete, server command catalog, or command-generated action cards. A
|
||||
leading slash is rejected locally rather than dispatched; approved outcomes
|
||||
such as New chat and Cancel remain explicit typed UI actions. Approval,
|
||||
clarification, secret, and elevated-access requests are denied or skipped
|
||||
immediately with a bounded notice. The supervised user cannot authorize them;
|
||||
a parent may retry from the authenticated full client.
|
||||
|
||||
Restricted Settings contains only parent-approved, non-authoritative choices,
|
||||
such as a supervised-only theme, text size, language, haptics, accessibility,
|
||||
message presentation, sensitive-media blur, and permitted voice playback
|
||||
preferences. Connections, Manage, profiles, models, personalities, reasoning,
|
||||
approvals, tools, plugins, Terminal, TUI, Bridge, Device Control, notification
|
||||
companion, diagnostics, logs, files, credentials, developer controls, Relay
|
||||
management, and other sessions are absent rather than shown disabled.
|
||||
|
||||
The parent may allow the configured floating pet and may independently let the
|
||||
supervised user change the phone-local profile icon or an already-installed chat
|
||||
background. The parent retains those appearance controls when supervised-user
|
||||
changes are disabled. Conversation history and its mutations are separate
|
||||
permissions: pin, rename, archive/restore, transcript sharing, and delete are
|
||||
individually allowlisted, while technical session identifiers and cross-profile
|
||||
administration remain hidden. Delete retains its confirmation step.
|
||||
|
||||
The parent also chooses what Chat discloses. **Simple** is the default: agent
|
||||
name/avatar plus generic Connected, Working, and Reconnecting states; it hides
|
||||
model, profile, provider/route, context, token/usage, reasoning, and tool detail.
|
||||
**Transparent** may add timestamps, bounded usage/context information, and
|
||||
approved activity labels without exposing arguments, results, paths, or
|
||||
credentials. **Custom** exposes the individual visibility switches. Model name
|
||||
and profile name default off in every new policy. Required errors, safety
|
||||
notices, parent-action states, and connection failures cannot be hidden by a
|
||||
cosmetic visibility choice.
|
||||
|
||||
Session selection is limited to the pinned profile. New chat creates a new
|
||||
conversation for that profile; history visibility, transcript retention, and
|
||||
conversation actions follow the parent policy. Ending Supervised Mode may clear
|
||||
local drafts, pending media, and restricted caches, but does not imply deletion
|
||||
of server-owned session history. Server history remains available through the
|
||||
parent's ordinary authenticated Hermes surfaces.
|
||||
|
||||
When the optional Relay plugin is paired, Android reports a bounded
|
||||
client-declared `supervised` tag and a non-sensitive policy summary with its
|
||||
ordinary device identity. Relay and its UI may display that tag and allow the
|
||||
operator to revoke the paired Relay session through the existing revocation
|
||||
model. The tag is informational: Relay does not interpret or enforce the Android
|
||||
policy, pin a profile, filter Gateway traffic, or certify the client. Revoking
|
||||
the Relay session removes Relay-backed capabilities but cannot revoke a direct
|
||||
Dashboard/Gateway session or remotely disable an Android-only policy. Without
|
||||
Relay pairing, Supervised Mode remains usable and locally enforced.
|
||||
|
||||
**Security and product boundary.** This mode restricts the official Android UI,
|
||||
not the Hermes agent or server. It cannot secure another client, a modified APK,
|
||||
direct server access, server-side tools, provider output, or a parent account
|
||||
whose credentials are available elsewhere. It is not a substitute for profile
|
||||
hardening, provider safety controls, parental review, operating-system controls,
|
||||
or applicable legal obligations. Public language uses **Supervised Mode** or
|
||||
**parent-controlled client**, not "child account," "safe for children," or
|
||||
"server enforced."
|
||||
|
||||
**Verification gate.** Implementation requires policy, authentication,
|
||||
navigation, process-death, deep-link, notification, capability, attachment,
|
||||
voice, session-ownership, Relay-tag, and revocation tests. Physical testing must
|
||||
cover the exact Android build on a managed/restricted device, including relock,
|
||||
restart, offline recovery, and attempts to escape the restricted root. Until
|
||||
that evidence exists, documentation and release notes must call the feature
|
||||
planned or experimental and must not call it child-ready.
|
||||
|
||||
**Consequences.** The project gains a generalized, low-noise supervised client
|
||||
without creating a new Hermes account type or making Relay a chat authorization
|
||||
proxy. Parents receive clear local controls and optional paired-device
|
||||
visibility, while server ownership and the limits of client-side enforcement
|
||||
remain explicit.
|
||||
---
|
||||
|
||||
## ADR 67 — Android Bot Mode is a separate upstream-owned messaging workspace
|
||||
|
||||
**Status:** Accepted (2026-08-24).
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "15a2c5ffe5bed203117291fcff6a2f0d39f2181bd0b7f709746e5a659f48e7fd",
|
||||
"main": "098132a6a5c94d038fd44f4768e7f9287561f5970b420c034d1c05c6232ac4ab",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -30,7 +30,7 @@
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "43677454b94dd7810adc9b685266598353b851b549b151de31cfa053cf74f6c1"
|
||||
},
|
||||
"website_source_sha256": "2de54aed7fd3c4e02ecbf57a4e9069ce64a3fd8d2874dc41b63732924fb354e1"
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
"en": {
|
||||
"native_name": "English",
|
||||
@@ -44,11 +44,11 @@
|
||||
}
|
||||
},
|
||||
"es": {
|
||||
"native_name": "Español",
|
||||
"native_name": "Espa\u00f1ol",
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "15a2c5ffe5bed203117291fcff6a2f0d39f2181bd0b7f709746e5a659f48e7fd",
|
||||
"main": "098132a6a5c94d038fd44f4768e7f9287561f5970b420c034d1c05c6232ac4ab",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -65,14 +65,14 @@
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "43677454b94dd7810adc9b685266598353b851b549b151de31cfa053cf74f6c1"
|
||||
},
|
||||
"website_source_sha256": "2de54aed7fd3c4e02ecbf57a4e9069ce64a3fd8d2874dc41b63732924fb354e1"
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
"ja": {
|
||||
"native_name": "日本語",
|
||||
"native_name": "\u65e5\u672c\u8a9e",
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "15a2c5ffe5bed203117291fcff6a2f0d39f2181bd0b7f709746e5a659f48e7fd",
|
||||
"main": "098132a6a5c94d038fd44f4768e7f9287561f5970b420c034d1c05c6232ac4ab",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -89,14 +89,14 @@
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "43677454b94dd7810adc9b685266598353b851b549b151de31cfa053cf74f6c1"
|
||||
},
|
||||
"website_source_sha256": "2de54aed7fd3c4e02ecbf57a4e9069ce64a3fd8d2874dc41b63732924fb354e1"
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
"pt-BR": {
|
||||
"native_name": "Português (Brasil)",
|
||||
"native_name": "Portugu\u00eas (Brasil)",
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "15a2c5ffe5bed203117291fcff6a2f0d39f2181bd0b7f709746e5a659f48e7fd",
|
||||
"main": "098132a6a5c94d038fd44f4768e7f9287561f5970b420c034d1c05c6232ac4ab",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -113,14 +113,14 @@
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "43677454b94dd7810adc9b685266598353b851b549b151de31cfa053cf74f6c1"
|
||||
},
|
||||
"website_source_sha256": "2de54aed7fd3c4e02ecbf57a4e9069ce64a3fd8d2874dc41b63732924fb354e1"
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
},
|
||||
"ru": {
|
||||
"native_name": "Русский",
|
||||
"native_name": "\u0420\u0443\u0441\u0441\u043a\u0438\u0439",
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "15a2c5ffe5bed203117291fcff6a2f0d39f2181bd0b7f709746e5a659f48e7fd",
|
||||
"main": "098132a6a5c94d038fd44f4768e7f9287561f5970b420c034d1c05c6232ac4ab",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -131,11 +131,11 @@
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"native_name": "简体中文",
|
||||
"native_name": "\u7b80\u4f53\u4e2d\u6587",
|
||||
"verification": "ai-translated",
|
||||
"review_refs": [],
|
||||
"source_sha256": {
|
||||
"main": "15a2c5ffe5bed203117291fcff6a2f0d39f2181bd0b7f709746e5a659f48e7fd",
|
||||
"main": "098132a6a5c94d038fd44f4768e7f9287561f5970b420c034d1c05c6232ac4ab",
|
||||
"sideload": "4abff4f1069091ec2de735c3037a7ec7d77699cb4321e8511a622437bceaf7c2"
|
||||
},
|
||||
"surfaces": {
|
||||
@@ -152,7 +152,7 @@
|
||||
"guide/release-tracks.md": "1e793410f433b12f503ac1649afec8820a712aff74b38202693aa9a0d6ad0a26",
|
||||
"guide/troubleshooting.md": "43677454b94dd7810adc9b685266598353b851b549b151de31cfa053cf74f6c1"
|
||||
},
|
||||
"website_source_sha256": "2de54aed7fd3c4e02ecbf57a4e9069ce64a3fd8d2874dc41b63732924fb354e1"
|
||||
"website_source_sha256": "d2d244b8b4f51dbec1503e134acdbc5252574b38511fe1fcda1b7b0a63e5f9a3"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +108,12 @@
|
||||
"title": "Start a conversation",
|
||||
"source": "assets/screenshots/supplemental/14_startup.png",
|
||||
"captureNote": "Current empty-chat chrome, idle visualization, model and effort controls, and public-safe suggestions."
|
||||
},
|
||||
{
|
||||
"id": "15_git_workspace",
|
||||
"title": "Native Git workspace",
|
||||
"source": "assets/screenshots/supplemental/15_git_workspace.png",
|
||||
"captureNote": "Real native Git workspace with public-safe repository status, line totals, filters, selection, inline diff, branch controls, commit action, and no live host data."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -91,9 +91,9 @@ This app is a community project and is not affiliated with or endorsed by NousRe
|
||||
Paste into Play Console → **What's new** (≤500 characters):
|
||||
|
||||
```
|
||||
v1.13.1 - Accurate session activity
|
||||
v1.13.2 - Supervised Mode and clearer activity
|
||||
|
||||
Session activity now follows live Hermes runtime state instead of a recent-activity estimate. Working, Starting, Needs input, Idle, Checking, Unavailable, and Background work stay accurate, and stale state clears only after a complete, unambiguous update.
|
||||
Supervised Mode adds a parent-configured, profile-pinned chat view with device-authenticated settings. Parents can limit attachments, Standard voice, generated media, history, actions, and technical details. Session rows stay neutral while live activity is unavailable, and returning from parent settings no longer blanks Supervised Chat.
|
||||
```
|
||||
## Category
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ Play 2:1 clipping), and only mock public-safe data.
|
||||
### Run
|
||||
|
||||
```bash
|
||||
./gradlew :app:testGooglePlayDebugUnitTest --tests "*StoreScreenshotTest*"
|
||||
./gradlew :app:testGooglePlayDebugUnitTest --tests "*StoreScreenshotTest*" --tests "*GitWorkspaceScreenshotTest*"
|
||||
# Output: app/build/store-shots/<scene>.png (1080x2160, exactly 2:1)
|
||||
```
|
||||
|
||||
@@ -149,6 +149,9 @@ The canonical marketing lineup intentionally exercises current product seams:
|
||||
coverage beyond the two Play-listing frames.
|
||||
- Supplemental `14_startup` preserves the lower-information empty-chat frame
|
||||
outside the eight-slot Play lineup.
|
||||
- Supplemental `15_git_workspace` renders the real native Git screen from a
|
||||
deterministic plugin API fixture. It is used by README, user docs, and the
|
||||
website but intentionally remains outside the eight-slot Play lineup.
|
||||
|
||||
### Render any view going forward
|
||||
|
||||
|
||||
+5
-1
@@ -7,7 +7,7 @@ Android's declarative plugin surface is specified in
|
||||
|
||||
**Status:** v1.0.0 stable. The default path supports chat, Manage, and voice on vanilla upstream Hermes without installing the Relay plugin. Relay is additive: terminal, bridge/device control, notification companion, remote access, extra/provider-native voice, desktop tooling, and dashboard Relay management. Historical phase notes remain in this file for context; the current route ownership source of truth is [`docs/upstream-surface-matrix.md`](upstream-surface-matrix.md).
|
||||
**Repo:** [Codename-11/hermes-relay](https://github.com/Codename-11/hermes-relay)
|
||||
**Updated:** 2026-08-22
|
||||
**Updated:** 2026-08-24
|
||||
|
||||
---
|
||||
|
||||
@@ -46,6 +46,10 @@ token, terminal/bridge grants, and optional network candidates.
|
||||
4. **Clean UX** — Material 3, minimal setup, and clear route identity for Vanilla Hermes vs Relay.
|
||||
5. **Offline-aware** — graceful degradation when connection drops. Auto-reconnect with exponential backoff.
|
||||
6. **Server-side state** — the app is a thin client. Sessions, history, memory, profiles, and dashboard state live on the Hermes server.
|
||||
7. **Supervision is a client policy** — Android may offer a parent-controlled,
|
||||
profile-pinned restricted interface, but it does not claim to make the
|
||||
selected Hermes profile, server, or agent child-safe. See ADR 66 and the
|
||||
[Supervised Mode guide](../user-docs/guide/supervised-mode.md).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[versions]
|
||||
appVersionName = "1.13.1"
|
||||
appVersionCode = "50"
|
||||
appVersionName = "1.13.2"
|
||||
appVersionCode = "51"
|
||||
agp = "9.3.2"
|
||||
kotlin = "2.4.10"
|
||||
compose-bom = "2026.08.00"
|
||||
|
||||
Vendored
+8
-8
File diff suppressed because one or more lines are too long
@@ -0,0 +1,337 @@
|
||||
"""Read and write Git state endpoints for the Hermes-Relay dashboard plugin.
|
||||
|
||||
Mounted by hermes-agent at ``/api/plugins/hermes-relay/git/*``. These routes
|
||||
power both the dashboard tab and the Android mobile page.
|
||||
|
||||
Route map
|
||||
---------
|
||||
Read (GET, no grant):
|
||||
- ``GET /git/repos`` → scanned repo list under the configured base path
|
||||
- ``GET /git/status`` → grouped working-tree status for one repo
|
||||
- ``GET /git/branches`` → branch list (name, upstream, ahead/behind, current)
|
||||
- ``GET /git/diff`` → per-file diff (kind=staged|unstaged)
|
||||
- ``GET /git/file`` → read a tracked file
|
||||
|
||||
Write (POST, require the plugin's ``plugin.api.write`` grant, which the app
|
||||
enforces client-side before ever sending the request — the same gate used for
|
||||
every mutating plugin action in PluginsViewModel.invokeAction):
|
||||
- ``POST /git/stage`` — stage path list → fresh status
|
||||
- ``POST /git/unstage`` — unstage path list → fresh status
|
||||
- ``POST /git/discard`` — discard paths (confirmation) → fresh status
|
||||
- ``POST /git/commit`` — commit staged index (message) → {head,status}
|
||||
- ``POST /git/commit_selected``— commit selected paths (message+paths)
|
||||
- ``POST /git/fetch`` — fetch a remote → {branches,status}
|
||||
- ``POST /git/pull`` — pull remote/branch → fresh status
|
||||
- ``POST /git/push`` — push (confirmation) → {branches,status}
|
||||
- ``POST /git/checkout`` — switch branch (new_branch/track; dirty→confirmation)
|
||||
|
||||
Destructive writes (discard, push, dirty checkout) enforce a per-use
|
||||
confirmation string server-side: missing/wrong → 403. Dirty/conflict trees →
|
||||
409. The HTTP mapping keeps raw stack traces and JSON dumps out of the UI.
|
||||
|
||||
Security
|
||||
--------
|
||||
- ``repo`` is an opaque id validated against the scanned allowlist; unknown
|
||||
ids → 400.
|
||||
- File paths are validated to reject traversal and absolute escapes.
|
||||
- Remote URLs are scrubbed of embedded userinfo.
|
||||
- No ``shell=True`` anywhere: every git invocation uses argument lists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Body, HTTPException, Query
|
||||
|
||||
from .. import git_state
|
||||
|
||||
router = APIRouter(prefix="/git")
|
||||
|
||||
|
||||
def _bad_request(exc: Exception) -> HTTPException:
|
||||
return HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
# Structured error taxonomy → HTTP status. The UI renders ``detail`` (a
|
||||
# human-readable message) plus ``code`` for styling; no raw traces/JSON dumps.
|
||||
_GIT_ERROR_STATUS = {
|
||||
"non-repo": 400,
|
||||
"dirty": 409,
|
||||
"conflict": 409,
|
||||
"auth": 502,
|
||||
"network": 502,
|
||||
"invalid-input": 400,
|
||||
"missing-confirmation": 403,
|
||||
"wrong-confirmation": 403,
|
||||
}
|
||||
|
||||
|
||||
def _write_error(exc: git_state.GitError) -> HTTPException:
|
||||
status = _GIT_ERROR_STATUS.get(exc.code, 400)
|
||||
return HTTPException(status_code=status, detail=str(exc))
|
||||
|
||||
|
||||
def _resolve(repo: str) -> Any:
|
||||
return git_state.resolve_repo(git_state.base_path(), repo)
|
||||
|
||||
|
||||
@router.get("/repos")
|
||||
async def get_repos() -> dict[str, Any]:
|
||||
"""Return the scanned repo list plus a notice when the base path is missing."""
|
||||
base = git_state.base_path()
|
||||
repos = git_state.scan_repos(base)
|
||||
notice = None
|
||||
if not base.is_dir():
|
||||
notice = f"Git base path not found: {base}"
|
||||
return {"repos": repos, "base_path": str(base), "notice": notice}
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def get_status(repo: str = Query(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.repo_status(_resolve(repo))
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.get("/branches")
|
||||
async def get_branches(repo: str = Query(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return {"branches": git_state.repo_branches(_resolve(repo))}
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.get("/diff")
|
||||
async def get_diff(
|
||||
repo: str = Query(...),
|
||||
path: str = Query(...),
|
||||
kind: str = Query("unstaged"),
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.repo_diff(_resolve(repo), path, kind)
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.get("/file")
|
||||
async def get_file(repo: str = Query(...), path: str = Query(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.read_file(_resolve(repo), path)
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
# ── Write endpoints ────────────────────────────────────────────────────────
|
||||
# Every write requires the plugin.api.write grant (enforced client-side). The
|
||||
# router re-validates repo + paths against the allowlist/traversal rules and
|
||||
# classifies git failures into a structured error the UI can render.
|
||||
|
||||
def _require_repo(body: dict[str, Any]) -> Any:
|
||||
repo = body.get("repo")
|
||||
if not isinstance(repo, str) or not repo:
|
||||
raise git_state.GitStateError("repo is required")
|
||||
return git_state.resolve_repo(git_state.base_path(), repo)
|
||||
|
||||
|
||||
@router.post("/stage")
|
||||
async def post_stage(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.stage(_require_repo(body), _paths(body))
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/unstage")
|
||||
async def post_unstage(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.unstage(_require_repo(body), _paths(body))
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/discard")
|
||||
async def post_discard(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.discard(
|
||||
_require_repo(body),
|
||||
_paths(body),
|
||||
confirmation=body.get("confirmation"),
|
||||
delete_untracked=bool(body.get("delete_untracked", False)),
|
||||
)
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/commit")
|
||||
async def post_commit(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.commit(_require_repo(body), _message(body))
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/commit_selected")
|
||||
async def post_commit_selected(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.commit_selected(_require_repo(body), _message(body), _paths(body))
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/fetch")
|
||||
async def post_fetch(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.fetch(_require_repo(body), _remote(body))
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/pull")
|
||||
async def post_pull(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.pull(_require_repo(body), _remote(body), _branch(body))
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/push")
|
||||
async def post_push(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
return git_state.push(
|
||||
_require_repo(body),
|
||||
_remote(body),
|
||||
_branch(body),
|
||||
confirmation=body.get("confirmation"),
|
||||
)
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/checkout")
|
||||
async def post_checkout(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
try:
|
||||
new_branch = _str_opt(body, "new_branch")
|
||||
return git_state.checkout(
|
||||
_require_repo(body),
|
||||
_ref(body, allow_empty=bool(new_branch)),
|
||||
confirmation=body.get("confirmation"),
|
||||
new_branch=new_branch,
|
||||
track=bool(body.get("track", False)),
|
||||
)
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/stash_checkout")
|
||||
async def post_stash_checkout(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
"""Checkout that auto-stashes a dirty tree first.
|
||||
|
||||
Unlike a plain dirty checkout, no confirmation is required: a stash is
|
||||
recoverable (``git stash pop``), so this is not a data-loss path. The
|
||||
response carries ``stashed`` + ``stash_message`` so the UI can surface the
|
||||
stash after a successful switch.
|
||||
"""
|
||||
try:
|
||||
new_branch = _str_opt(body, "new_branch")
|
||||
return git_state.stash_checkout(
|
||||
_require_repo(body),
|
||||
_ref(body, allow_empty=bool(new_branch)),
|
||||
new_branch=new_branch,
|
||||
track=bool(body.get("track", False)),
|
||||
)
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/commit_message")
|
||||
async def post_commit_message(body: dict[str, Any] = Body(...)) -> dict[str, Any]:
|
||||
"""Generate a conventional-style commit message from the staged diff.
|
||||
|
||||
Empty staged diff → ``{message:"", notice:"nothing staged"}`` without calling
|
||||
the model. A missing/failed model degrades to an empty message + a
|
||||
``model unavailable`` notice — never a 500. Only staged content is sent.
|
||||
"""
|
||||
try:
|
||||
return await git_state.commit_message(_require_repo(body))
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
@router.post("/commit_message_selected")
|
||||
async def post_commit_message_selected(
|
||||
body: dict[str, Any] = Body(...),
|
||||
) -> dict[str, Any]:
|
||||
"""Generate a message from the staged diff of the given ``paths`` only."""
|
||||
try:
|
||||
return await git_state.commit_message_selected(
|
||||
_require_repo(body), _paths(body)
|
||||
)
|
||||
except git_state.GitError as exc:
|
||||
raise _write_error(exc) from exc
|
||||
except git_state.GitStateError as exc:
|
||||
raise _bad_request(exc) from exc
|
||||
|
||||
|
||||
def _paths(body: dict[str, Any]) -> list[str]:
|
||||
paths = body.get("paths")
|
||||
if not isinstance(paths, list) or not paths or not all(isinstance(p, str) for p in paths):
|
||||
raise git_state.GitStateError("paths must be a non-empty list of strings")
|
||||
return paths
|
||||
|
||||
|
||||
def _message(body: dict[str, Any]) -> str:
|
||||
message = body.get("message")
|
||||
if not isinstance(message, str):
|
||||
raise git_state.GitStateError("message is required")
|
||||
return message
|
||||
|
||||
|
||||
def _remote(body: dict[str, Any]) -> str:
|
||||
remote = body.get("remote", "origin")
|
||||
if not isinstance(remote, str):
|
||||
raise git_state.GitStateError("remote must be a string")
|
||||
return remote or "origin"
|
||||
|
||||
|
||||
def _branch(body: dict[str, Any]) -> str:
|
||||
branch = body.get("branch", "")
|
||||
if not isinstance(branch, str):
|
||||
raise git_state.GitStateError("branch must be a string")
|
||||
return branch
|
||||
|
||||
|
||||
def _ref(body: dict[str, Any], *, allow_empty: bool = False) -> str:
|
||||
ref = body.get("ref", "" if allow_empty else None)
|
||||
if not isinstance(ref, str) or (not ref and not allow_empty):
|
||||
raise git_state.GitStateError("ref is required")
|
||||
return ref
|
||||
|
||||
|
||||
def _str_opt(body: dict[str, Any], key: str) -> str:
|
||||
value = body.get(key)
|
||||
return value if isinstance(value, str) else ""
|
||||
|
||||
|
||||
__all__ = ["router"]
|
||||
@@ -32,6 +32,15 @@ async def get_mobile_manifest() -> dict[str, Any]:
|
||||
|
||||
@router.get("/pages/{plugin_id}")
|
||||
async def get_mobile_page(plugin_id: str = Path(...)) -> dict[str, Any]:
|
||||
# The static read-only Git page is served directly from the git_state
|
||||
# module (not the generated-page store). It carries no filesystem paths
|
||||
# per the android-plugins.md document contract.
|
||||
if plugin_id == "git":
|
||||
from .. import git_state
|
||||
|
||||
document = git_state.build_git_document(git_state.base_path())
|
||||
document["host_revision"] = 1
|
||||
return document
|
||||
try:
|
||||
entry = _store().get(plugin_id)
|
||||
document = dict(entry["document"])
|
||||
|
||||
@@ -142,6 +142,7 @@ def _validate_public_url(url: str) -> str:
|
||||
|
||||
router = APIRouter()
|
||||
router.include_router(_plugin_module("dashboard.mobile_plugin_api").router)
|
||||
router.include_router(_plugin_module("dashboard.git_api").router)
|
||||
|
||||
|
||||
def _relay_unreachable(err: Exception) -> HTTPException:
|
||||
|
||||
@@ -6,6 +6,7 @@ import RelayManagement from "./tabs/RelayManagement.jsx";
|
||||
import BridgeActivity from "./tabs/BridgeActivity.jsx";
|
||||
import MediaInspector from "./tabs/MediaInspector.jsx";
|
||||
import RemoteAccess from "./tabs/RemoteAccess.jsx";
|
||||
import GitState from "./tabs/GitState.jsx";
|
||||
import RelayStatusSlot from "./components/RelayStatusSlot.jsx";
|
||||
import MobileConnectDialog from "./components/MobileConnectDialog.jsx";
|
||||
import { Button, Switch } from "./lib/ui-shims.jsx";
|
||||
@@ -19,6 +20,7 @@ const TABS = [
|
||||
{ key: "activity", label: "Activity" },
|
||||
{ key: "media", label: "Media" },
|
||||
{ key: "remote", label: "Remote Access" },
|
||||
{ key: "git", label: "Git" },
|
||||
];
|
||||
|
||||
function readAutoRefresh() {
|
||||
@@ -113,6 +115,7 @@ function RelayPluginRoot() {
|
||||
{tab === "activity" && <BridgeActivity autoRefresh={autoRefresh} />}
|
||||
{tab === "media" && <MediaInspector autoRefresh={autoRefresh} />}
|
||||
{tab === "remote" && <RemoteAccess autoRefresh={autoRefresh} />}
|
||||
{tab === "git" && <GitState autoRefresh={autoRefresh} />}
|
||||
</div>
|
||||
<MobileConnectDialog
|
||||
open={mobileConnectOpen}
|
||||
|
||||
@@ -139,3 +139,107 @@ export function mintPairingWithMode({ mode, publicUrl, prefer, ...rest } = {}) {
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
// ── Git State tab ───────────────────────────────────────────────────────────
|
||||
|
||||
export function getGitRepos() {
|
||||
return fetchJSON("/git/repos");
|
||||
}
|
||||
|
||||
export function getGitStatus(repo) {
|
||||
return fetchJSON(`/git/status?repo=${encodeURIComponent(repo)}`);
|
||||
}
|
||||
|
||||
export function getGitBranches(repo) {
|
||||
return fetchJSON(`/git/branches?repo=${encodeURIComponent(repo)}`);
|
||||
}
|
||||
|
||||
export function getGitDiff(repo, path, kind = "unstaged") {
|
||||
return fetchJSON(
|
||||
`/git/diff?repo=${encodeURIComponent(repo)}&path=${encodeURIComponent(path)}&kind=${encodeURIComponent(kind)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function getGitFile(repo, path) {
|
||||
return fetchJSON(
|
||||
`/git/file?repo=${encodeURIComponent(repo)}&path=${encodeURIComponent(path)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// ── Git State write operations ────────────────────────────────────────────
|
||||
// Every write POST goes through the authenticated Dashboard plugin namespace.
|
||||
// Android separately enforces its local plugin.api.write preference before it
|
||||
// calls this namespace. Destructive ops pass a per-use confirmation token.
|
||||
|
||||
function postGit(path, body) {
|
||||
return fetchJSON(path, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
}
|
||||
|
||||
export function gitStage(repo, paths) {
|
||||
return postGit("/git/stage", { repo, paths });
|
||||
}
|
||||
|
||||
export function gitUnstage(repo, paths) {
|
||||
return postGit("/git/unstage", { repo, paths });
|
||||
}
|
||||
|
||||
export function gitDiscard(repo, paths, confirmation, deleteUntracked = false) {
|
||||
return postGit("/git/discard", {
|
||||
repo,
|
||||
paths,
|
||||
confirmation,
|
||||
delete_untracked: deleteUntracked,
|
||||
});
|
||||
}
|
||||
|
||||
export function gitCommit(repo, message) {
|
||||
return postGit("/git/commit", { repo, message });
|
||||
}
|
||||
|
||||
export function gitFetch(repo, remote = "origin") {
|
||||
return postGit("/git/fetch", { repo, remote });
|
||||
}
|
||||
|
||||
export function gitPull(repo, remote = "origin", branch = "") {
|
||||
return postGit("/git/pull", { repo, remote, branch });
|
||||
}
|
||||
|
||||
export function gitPush(repo, confirmation, remote = "origin", branch = "") {
|
||||
return postGit("/git/push", { repo, remote, branch, confirmation });
|
||||
}
|
||||
|
||||
export function gitCheckout(repo, ref, opts = {}) {
|
||||
const body = {
|
||||
repo,
|
||||
ref,
|
||||
confirmation: opts.confirmation,
|
||||
new_branch: opts.newBranch || "",
|
||||
track: !!opts.track,
|
||||
};
|
||||
return postGit("/git/checkout", body);
|
||||
}
|
||||
|
||||
// ── Git State Phase 3 extras ───────────────────────────────────────────────
|
||||
// AI commit-message suggestions + auto-stashing checkout.
|
||||
|
||||
export function gitCommitMessage(repo) {
|
||||
return postGit("/git/commit_message", { repo });
|
||||
}
|
||||
|
||||
export function gitCommitMessageSelected(repo, paths) {
|
||||
return postGit("/git/commit_message_selected", { repo, paths });
|
||||
}
|
||||
|
||||
export function gitStashCheckout(repo, ref, opts = {}) {
|
||||
const body = {
|
||||
repo,
|
||||
ref,
|
||||
new_branch: opts.newBranch || "",
|
||||
track: !!opts.track,
|
||||
};
|
||||
return postGit("/git/stash_checkout", body);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user