Compare commits
103
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
75feb55adf | ||
|
|
e20540d16f | ||
|
|
c932adbc7b | ||
|
|
23cec497ce | ||
|
|
1739dc36a2 | ||
|
|
c917a94fcb | ||
|
|
e1a72ee8af | ||
|
|
94f9ba4305 | ||
|
|
3186afdde8 | ||
|
|
0261a342cf | ||
|
|
f4c212f800 | ||
|
|
3bb294c6c3 | ||
|
|
dc73cc74b1 | ||
|
|
607bc95b73 | ||
|
|
3b4da0305e | ||
|
|
3af0092b8f | ||
|
|
9cfa4c8b8c | ||
|
|
a7c860a2e3 | ||
|
|
ed71b02b01 | ||
|
|
a90dc85466 | ||
|
|
67a60143cb | ||
|
|
c3276fa7e5 | ||
|
|
99ac20de35 | ||
|
|
0650102230 | ||
|
|
8d4f324717 | ||
|
|
c9ee5348bf | ||
|
|
ee2a7840a2 | ||
|
|
52dd399565 | ||
|
|
86a0421163 | ||
|
|
0e191f946d | ||
|
|
065912f2bf | ||
|
|
075138433e | ||
|
|
92e65bbfc2 | ||
|
|
7ccd4ac4c9 | ||
|
|
5739e17750 | ||
|
|
037f4e91c8 | ||
|
|
685c3c5a24 | ||
|
|
6dc18abc4d | ||
|
|
ee43a87cec | ||
|
|
ce961b81d9 | ||
|
|
c7b392b26f | ||
|
|
0a04efbbcf | ||
|
|
11977dad56 | ||
|
|
c8fea9c061 | ||
|
|
b0a8909dc7 | ||
|
|
57c236e7da | ||
|
|
8156a821eb | ||
|
|
b015acb063 | ||
|
|
f4b366389b | ||
|
|
e6368dada8 | ||
|
|
e55662e0e1 | ||
|
|
051844bc14 | ||
|
|
1e5ce986be | ||
|
|
06b24631e3 | ||
|
|
2d2e54ba79 | ||
|
|
ee59149b41 | ||
|
|
23a6231b20 | ||
|
|
a4fac4550a | ||
|
|
88ab48cfc0 | ||
|
|
7c03f8554f | ||
|
|
367e5d271c | ||
|
|
47a395ab76 | ||
|
|
e7cbed3c8f | ||
|
|
2f7bd843bc | ||
|
|
d1527d47e4 | ||
|
|
bc0853360a | ||
|
|
b72ab5aef2 | ||
|
|
40fcb80a7d | ||
|
|
ff64548085 | ||
|
|
35362b8895 | ||
|
|
ff7ca89b90 | ||
|
|
042f02b852 | ||
|
|
5fc85c1699 | ||
|
|
c01c6cf457 | ||
|
|
22780881e1 | ||
|
|
201e204290 | ||
|
|
eb8434e508 | ||
|
|
597b13e2db | ||
|
|
946b333109 | ||
|
|
8b3731b22f | ||
|
|
b76ba7a314 | ||
|
|
2c15bd4207 | ||
|
|
949add15b1 | ||
|
|
6a93d13ecb | ||
|
|
cbc02bb407 | ||
|
|
525f6b5fc0 | ||
|
|
58e8b1edb6 | ||
|
|
d42fa91698 | ||
|
|
a2be512c45 | ||
|
|
6a66710763 | ||
|
|
9690071e7d | ||
|
|
698b45cbb3 | ||
|
|
afa875d89f | ||
|
|
aff758fb99 | ||
|
|
8625963846 | ||
|
|
e0b726de85 | ||
|
|
dbf71a87f4 | ||
|
|
95ed8e6edb | ||
|
|
d26bf6c25b | ||
|
|
181e10f2ad | ||
|
|
857a1551f3 | ||
|
|
00052d20d9 | ||
|
|
2ec7b7aac9 |
@@ -4,6 +4,7 @@ function classifyCiPaths(paths) {
|
||||
const forceAll = paths.some((path) => [
|
||||
'.github/workflows/ci-required.yml',
|
||||
'.github/workflows/release-backmerge.yml',
|
||||
'.github/workflows/approve-release-train.yml',
|
||||
'.github/scripts/classify-ci-paths.cjs',
|
||||
'.github/scripts/classify-ci-paths.test.cjs',
|
||||
'scripts/plan_release_backmerge.py',
|
||||
@@ -13,15 +14,17 @@ function classifyCiPaths(paths) {
|
||||
const under = (prefixes) => paths.some((path) => prefixes.some((prefix) => path.startsWith(prefix)));
|
||||
|
||||
return {
|
||||
android: forceAll || under(['app/', 'relay-core/', 'relay-ui/', 'ui-preview/', 'quest/', 'gradle/']) || exact([
|
||||
android: forceAll || under(['app/', 'gradle/']) || exact([
|
||||
'build.gradle.kts', 'settings.gradle.kts', 'gradle.properties', 'gradlew', 'gradlew.bat',
|
||||
'scripts/check-android-locales.py', 'scripts/android-locale-harness.py',
|
||||
'scripts/check-android-collection-apis.py', 'scripts/check-android-native-compat.py',
|
||||
'scripts/check-android-release-notes.py',
|
||||
'scripts/android_release_artifacts.py',
|
||||
'scripts/android-lane.ps1', 'scripts/android-prepush.py', 'scripts/dev.bat', 'scripts/dev.sh',
|
||||
'scripts/tests/android_prepush_test.py',
|
||||
'scripts/tests/check_android_native_compat_test.py',
|
||||
'scripts/tests/check_android_release_notes_test.py',
|
||||
'scripts/tests/android_release_artifacts_test.py',
|
||||
'.github/workflows/android-on-demand.yml', '.github/workflows/ci-android.yml',
|
||||
'.github/workflows/play-preflight-android.yml',
|
||||
'.github/workflows/approve-release-android.yml',
|
||||
@@ -29,12 +32,16 @@ function classifyCiPaths(paths) {
|
||||
]),
|
||||
desktop: forceAll || under(['desktop/']) || exact([
|
||||
'.github/workflows/ci-desktop.yml',
|
||||
'.github/workflows/approve-release-extensions.yml',
|
||||
'.github/workflows/release-cli.yml',
|
||||
]),
|
||||
plugin: forceAll || paths.some((path) => /^plugin\/[^/]+\.py$/.test(path)) ||
|
||||
under(['plugin/relay/', 'plugin/tools/', 'plugin/tests/', 'relay_server/', 'hermes_relay_bootstrap/']) || exact([
|
||||
'plugin/plugin.yaml', 'pyproject.toml', 'scripts/check-plugin-version-sync.py',
|
||||
'scripts/check-server-version-sync.py', 'scripts/bump-plugin-version.sh',
|
||||
'scripts/bump-server-version.sh', '.github/workflows/ci-plugin.yml',
|
||||
'.github/workflows/approve-release-extensions.yml',
|
||||
'.github/workflows/release-plugin.yml',
|
||||
]),
|
||||
dashboard: forceAll || under(['plugin/dashboard/']) || exact([
|
||||
'.github/workflows/ci-dashboard.yml',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { readFileSync } = require('node:fs');
|
||||
const { join } = require('node:path');
|
||||
const { classifyCiPaths } = require('./classify-ci-paths.cjs');
|
||||
|
||||
const none = {
|
||||
@@ -14,9 +16,11 @@ const none = {
|
||||
|
||||
assert.deepEqual(classifyCiPaths(['README.md']), none);
|
||||
assert.deepEqual(classifyCiPaths(['desktop/src/cli.ts']), { ...none, desktop: true });
|
||||
assert.deepEqual(classifyCiPaths(['relay-core/src/main/kotlin/Wire.kt']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['experiments/quest/src/main/kotlin/Quest.kt']), none);
|
||||
assert.deepEqual(classifyCiPaths(['scripts/check-android-release-notes.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/check-android-native-compat.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/android_release_artifacts.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/tests/android_release_artifacts_test.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/tests/check_android_native_compat_test.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/android-lane.ps1']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/android-prepush.py']), { ...none, android: true });
|
||||
@@ -24,6 +28,13 @@ assert.deepEqual(classifyCiPaths(['scripts/dev.bat']), { ...none, android: true
|
||||
assert.deepEqual(classifyCiPaths(['scripts/dev.sh']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['scripts/tests/android_prepush_test.py']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/android-on-demand.yml']), { ...none, android: true });
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/approve-release-extensions.yml']), {
|
||||
...none,
|
||||
desktop: true,
|
||||
plugin: true,
|
||||
});
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/release-cli.yml']), { ...none, desktop: true });
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/release-plugin.yml']), { ...none, plugin: true });
|
||||
assert.deepEqual(classifyCiPaths(['plugin/relay/server.py']), { ...none, plugin: true });
|
||||
assert.deepEqual(classifyCiPaths(['plugin/dashboard/src/App.tsx']), { ...none, dashboard: true });
|
||||
assert.deepEqual(classifyCiPaths(['user-docs/index.md']), { ...none, docs: true });
|
||||
@@ -47,5 +58,73 @@ assert.deepEqual(classifyCiPaths(['.github/workflows/release-backmerge.yml']), {
|
||||
contract: true,
|
||||
docs: true,
|
||||
});
|
||||
assert.deepEqual(classifyCiPaths(['.github/workflows/approve-release-train.yml']), {
|
||||
android: true,
|
||||
desktop: true,
|
||||
plugin: true,
|
||||
dashboard: true,
|
||||
contract: true,
|
||||
docs: true,
|
||||
});
|
||||
|
||||
const repoRoot = join(__dirname, '..', '..');
|
||||
const approvalWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'approve-release-extensions.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const cliReleaseWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'release-cli.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const pluginReleaseWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'release-plugin.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const desktopCiWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'ci-desktop.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const androidPreflightWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'play-preflight-android.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const androidApprovalWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'approve-release-android.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const androidReleaseWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'release-android.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const requiredChecksWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'ci-required.yml'),
|
||||
'utf8',
|
||||
);
|
||||
const releaseTrainWorkflow = readFileSync(
|
||||
join(repoRoot, '.github', 'workflows', 'approve-release-train.yml'),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
assert.match(approvalWorkflow, /permissions:\r?\n contents: read/);
|
||||
assert.match(
|
||||
approvalWorkflow,
|
||||
/approve:[\s\S]*?permissions:\r?\n actions: write\r?\n contents: write/,
|
||||
);
|
||||
assert.match(
|
||||
approvalWorkflow,
|
||||
/ref: \$\{\{ contains\(inputs\.version, '-'\) && 'dev' \|\| 'main' \}\}/,
|
||||
);
|
||||
assert.match(cliReleaseWorkflow, /workflow_dispatch:[\s\S]*?Approved CLI\+UI version/);
|
||||
assert.match(cliReleaseWorkflow, /name: Restore exact-source tray build cache[\s\S]*?actions\/cache@v5/);
|
||||
assert.match(desktopCiWorkflow, /name: Restore exact-source tray build cache[\s\S]*?actions\/cache@v5/);
|
||||
assert.match(pluginReleaseWorkflow, /workflow_dispatch:[\s\S]*?Approved Plugin version/);
|
||||
assert.match(androidPreflightWorkflow, /Package immutable preflight artifacts/);
|
||||
assert.match(androidApprovalWorkflow, /Android public approval accepts stable SemVer only/);
|
||||
assert.match(androidReleaseWorkflow, /Download exact stable preflight artifacts/);
|
||||
assert.match(androidReleaseWorkflow, /artifact-ids: \$\{\{ needs\.validate\.outputs\.preflight_artifact_id \}\}/);
|
||||
assert.match(requiredChecksWorkflow, /name: Reuse exact-tree required checks/);
|
||||
assert.match(requiredChecksWorkflow, /name: required-checks-\$\{\{ needs\.changes\.outputs\.tree \}\}/);
|
||||
assert.match(releaseTrainWorkflow, /name: Hermes-Relay Coordinated Release Approval/);
|
||||
assert.match(releaseTrainWorkflow, /Coordinated Android approval is stable-only/);
|
||||
|
||||
console.log('CI path classification tests passed.');
|
||||
|
||||
@@ -40,6 +40,10 @@ jobs:
|
||||
echo "::error::Hermes-Relay Android Release Approval must run from main, not $GITHUB_REF"
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! "$REQUESTED_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::error::Android public approval accepts stable SemVer only: $REQUESTED_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
TOML_VERSION=$(grep -oP 'appVersionName\s*=\s*"\K[^"]+' gradle/libs.versions.toml)
|
||||
if [ "$REQUESTED_VERSION" != "$TOML_VERSION" ]; then
|
||||
echo "::error::Requested version $REQUESTED_VERSION does not match appVersionName $TOML_VERSION"
|
||||
@@ -56,13 +60,21 @@ jobs:
|
||||
RELEASE_TREE: ${{ steps.metadata.outputs.tree }}
|
||||
run: |
|
||||
ARTIFACT_NAME="play-preflight-${VERSION}-${RELEASE_TREE}"
|
||||
COUNT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | length')
|
||||
if [ "$COUNT" -lt 1 ]; then
|
||||
ARTIFACT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | sort_by(.created_at) | last')
|
||||
RUN_ID=$(jq -r '.workflow_run.id // empty' <<<"$ARTIFACT")
|
||||
if [ -z "$RUN_ID" ]; then
|
||||
echo "::error::No successful Play preflight found for version $VERSION with tree $RELEASE_TREE"
|
||||
exit 1
|
||||
fi
|
||||
echo "Verified Play preflight proof: $ARTIFACT_NAME"
|
||||
RUN=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}")
|
||||
CONCLUSION=$(jq -r '.conclusion' <<<"$RUN")
|
||||
WORKFLOW_PATH=$(jq -r '.path' <<<"$RUN")
|
||||
if [ "$WORKFLOW_PATH" != ".github/workflows/play-preflight-android.yml" ] || [ "$CONCLUSION" != "success" ]; then
|
||||
echo "::error::Preflight artifact came from ${WORKFLOW_PATH} with conclusion ${CONCLUSION}"
|
||||
exit 1
|
||||
fi
|
||||
echo "Verified immutable Play preflight artifacts: $ARTIFACT_NAME (run $RUN_ID)"
|
||||
|
||||
- name: Ensure release tag does not already exist
|
||||
env:
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
name: Hermes-Relay Plugin and CLI+UI Release Approval
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
surface:
|
||||
description: "Release surface"
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- plugin
|
||||
- desktop
|
||||
version:
|
||||
description: "Approved version (for example 1.11.2 or 0.4.0-beta.7)"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: approve-${{ inputs.surface }}-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate release source and metadata
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
source_branch: ${{ steps.metadata.outputs.source_branch }}
|
||||
source_sha: ${{ steps.metadata.outputs.source_sha }}
|
||||
tag: ${{ steps.metadata.outputs.tag }}
|
||||
workflow: ${{ steps.metadata.outputs.workflow }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ contains(inputs.version, '-') && 'dev' || 'main' }}
|
||||
|
||||
- name: Validate approval request
|
||||
id: metadata
|
||||
env:
|
||||
REQUESTED_SURFACE: ${{ inputs.surface }}
|
||||
REQUESTED_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$REQUESTED_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "::error::Version must be SemVer with an optional prerelease suffix: $REQUESTED_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$REQUESTED_VERSION" == *-* ]]; then
|
||||
source_branch="dev"
|
||||
else
|
||||
source_branch="main"
|
||||
fi
|
||||
if [ "$GITHUB_REF" != "refs/heads/main" ]; then
|
||||
echo "::error::Release approval must run from the trusted main workflow definition, not $GITHUB_REF"
|
||||
exit 1
|
||||
fi
|
||||
git fetch origin "$source_branch" --no-tags
|
||||
source_sha="$(git rev-parse HEAD)"
|
||||
expected_sha="$(git rev-parse FETCH_HEAD)"
|
||||
if [ "$source_sha" != "$expected_sha" ]; then
|
||||
echo "::error::Checked out $source_sha, but origin/$source_branch is $expected_sha"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$REQUESTED_SURFACE" in
|
||||
plugin)
|
||||
tag="server-v${REQUESTED_VERSION}"
|
||||
workflow="release-plugin.yml"
|
||||
python3 scripts/check-plugin-version-sync.py --expect "$REQUESTED_VERSION"
|
||||
if ! grep -Eq "^## \[Plugin ${REQUESTED_VERSION}\]" CHANGELOG.md; then
|
||||
echo "::error::CHANGELOG.md has no Plugin release heading for $REQUESTED_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
desktop)
|
||||
tag="desktop-v${REQUESTED_VERSION}"
|
||||
workflow="release-cli.yml"
|
||||
node desktop/scripts/cli-version-sync.mjs --expect "$REQUESTED_VERSION"
|
||||
if ! grep -Fq "## [$REQUESTED_VERSION]" CHANGELOG.md; then
|
||||
echo "::error::CHANGELOG.md has no CLI+UI release heading for $REQUESTED_VERSION"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
echo "::error::Unsupported release surface: $REQUESTED_SURFACE"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
echo "workflow=$workflow" >> "$GITHUB_OUTPUT"
|
||||
echo "source_branch=$source_branch" >> "$GITHUB_OUTPUT"
|
||||
echo "source_sha=$source_sha" >> "$GITHUB_OUTPUT"
|
||||
|
||||
approve:
|
||||
name: Create release tag and start publication
|
||||
needs: validate
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Verify release source has not moved
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
SOURCE_BRANCH: ${{ needs.validate.outputs.source_branch }}
|
||||
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
|
||||
run: |
|
||||
current_sha=$(gh api "/repos/${GITHUB_REPOSITORY}/git/ref/heads/${SOURCE_BRANCH}" --jq .object.sha)
|
||||
if [ "$current_sha" != "$SOURCE_SHA" ]; then
|
||||
echo "::error::$SOURCE_BRANCH moved from $SOURCE_SHA to $current_sha; run approval again"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Ensure release tag does not already exist
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ needs.validate.outputs.tag }}
|
||||
run: |
|
||||
if gh api "/repos/${GITHUB_REPOSITORY}/git/ref/tags/${RELEASE_TAG}" >/dev/null 2>&1; then
|
||||
echo "::error::Tag $RELEASE_TAG already exists"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Create approved release tag
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ needs.validate.outputs.tag }}
|
||||
RELEASE_SHA: ${{ needs.validate.outputs.source_sha }}
|
||||
run: |
|
||||
gh api --method POST "/repos/${GITHUB_REPOSITORY}/git/refs" \
|
||||
-f ref="refs/tags/${RELEASE_TAG}" \
|
||||
-f sha="$RELEASE_SHA"
|
||||
|
||||
- name: Start the immutable tag release workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_WORKFLOW: ${{ needs.validate.outputs.workflow }}
|
||||
RELEASE_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
# A tag created by GITHUB_TOKEN does not recursively start workflows.
|
||||
# Dispatch the trusted definition from main; release jobs check out
|
||||
# and validate the immutable tag created above.
|
||||
gh workflow run "$RELEASE_WORKFLOW" \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f version="$RELEASE_VERSION"
|
||||
|
||||
- name: Approval summary
|
||||
run: |
|
||||
echo "## Release approved" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "Created \`${{ needs.validate.outputs.tag }}\` from \`${{ needs.validate.outputs.source_branch }}\` at \`${{ needs.validate.outputs.source_sha }}\`." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "Dispatched \`${{ needs.validate.outputs.workflow }}\` to validate and publish that immutable tag." >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -0,0 +1,120 @@
|
||||
name: Hermes-Relay Coordinated Release Approval
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
android:
|
||||
description: "Approve Hermes-Relay Android"
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
android_version:
|
||||
description: "Android version when selected"
|
||||
required: false
|
||||
type: string
|
||||
plugin:
|
||||
description: "Approve Hermes-Relay Plugin"
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
plugin_version:
|
||||
description: "Plugin version when selected"
|
||||
required: false
|
||||
type: string
|
||||
desktop:
|
||||
description: "Approve Hermes-Relay CLI+UI"
|
||||
required: true
|
||||
default: false
|
||||
type: boolean
|
||||
desktop_version:
|
||||
description: "CLI+UI version when selected"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: approve-coordinated-release
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate selected release surfaces
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Require versions for every selected surface
|
||||
env:
|
||||
ANDROID: ${{ inputs.android }}
|
||||
ANDROID_VERSION: ${{ inputs.android_version }}
|
||||
PLUGIN: ${{ inputs.plugin }}
|
||||
PLUGIN_VERSION: ${{ inputs.plugin_version }}
|
||||
DESKTOP: ${{ inputs.desktop }}
|
||||
DESKTOP_VERSION: ${{ inputs.desktop_version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ "$ANDROID" != "true" ] && [ "$PLUGIN" != "true" ] && [ "$DESKTOP" != "true" ]; then
|
||||
echo "::error::Select at least one release surface"
|
||||
exit 1
|
||||
fi
|
||||
for pair in \
|
||||
"$ANDROID:$ANDROID_VERSION:Android" \
|
||||
"$PLUGIN:$PLUGIN_VERSION:Plugin" \
|
||||
"$DESKTOP:$DESKTOP_VERSION:CLI+UI"; do
|
||||
IFS=: read -r selected version label <<<"$pair"
|
||||
if [ "$selected" = "true" ] && [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "::error::$label requires a valid SemVer version"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [ "$ANDROID" = "true" ] && [[ "$ANDROID_VERSION" == *-* ]]; then
|
||||
echo "::error::Coordinated Android approval is stable-only; use a dev candidate tag for prereleases"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
android:
|
||||
name: Approve Hermes-Relay Android
|
||||
needs: validate
|
||||
if: inputs.android
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch Android approval
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ inputs.android_version }}
|
||||
run: gh workflow run approve-release-android.yml --repo "$GITHUB_REPOSITORY" --ref main -f version="$VERSION"
|
||||
|
||||
plugin:
|
||||
name: Approve Hermes-Relay Plugin
|
||||
needs: validate
|
||||
if: inputs.plugin
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch Plugin approval
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ inputs.plugin_version }}
|
||||
run: |
|
||||
gh workflow run approve-release-extensions.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f surface=plugin \
|
||||
-f version="$VERSION"
|
||||
|
||||
desktop:
|
||||
name: Approve Hermes-Relay CLI+UI
|
||||
needs: validate
|
||||
if: inputs.desktop
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dispatch CLI+UI approval
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ inputs.desktop_version }}
|
||||
run: |
|
||||
gh workflow run approve-release-extensions.yml \
|
||||
--repo "$GITHUB_REPOSITORY" \
|
||||
--ref main \
|
||||
-f surface=desktop \
|
||||
-f version="$VERSION"
|
||||
@@ -20,10 +20,6 @@ on:
|
||||
branches: [main, dev]
|
||||
paths:
|
||||
- "app/**"
|
||||
- "relay-core/**"
|
||||
- "relay-ui/**"
|
||||
- "ui-preview/**"
|
||||
- "quest/**"
|
||||
- "gradle/**"
|
||||
- "build.gradle.kts"
|
||||
- "settings.gradle.kts"
|
||||
|
||||
@@ -107,6 +107,18 @@ jobs:
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Restore exact-source tray build cache
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
desktop/tray/target
|
||||
key: ${{ runner.os }}-tray-rust-${{ hashFiles('desktop/tray/Cargo.lock') }}-${{ hashFiles('desktop/tray/Cargo.toml', 'desktop/tray/build.rs', 'desktop/tray/src/**/*.rs') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-tray-rust-${{ hashFiles('desktop/tray/Cargo.lock') }}-
|
||||
|
||||
- name: Install deps
|
||||
run: npm ci && npm --prefix tray ci
|
||||
|
||||
|
||||
@@ -101,6 +101,7 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
|
||||
@@ -34,6 +34,7 @@ on:
|
||||
- all-final
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
@@ -52,6 +53,8 @@ jobs:
|
||||
dashboard: ${{ steps.filter.outputs.dashboard }}
|
||||
contract: ${{ steps.filter.outputs.contract }}
|
||||
docs: ${{ steps.filter.outputs.docs }}
|
||||
release_pr: ${{ steps.release.outputs.release_pr }}
|
||||
tree: ${{ steps.tree.outputs.tree }}
|
||||
steps:
|
||||
- name: Checkout pull request merge
|
||||
if: github.event_name == 'pull_request'
|
||||
@@ -69,6 +72,26 @@ jobs:
|
||||
- name: Test path classifier
|
||||
run: node .github/scripts/classify-ci-paths.test.cjs
|
||||
|
||||
- name: Record checked tree
|
||||
id: tree
|
||||
run: echo "tree=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Detect canonical release promotion
|
||||
id: release
|
||||
env:
|
||||
BASE_REF: ${{ github.base_ref }}
|
||||
HEAD_REF: ${{ github.head_ref }}
|
||||
HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}
|
||||
run: |
|
||||
if [ "$GITHUB_EVENT_NAME" = "pull_request" ] && \
|
||||
[ "$BASE_REF" = "main" ] && \
|
||||
[ "$HEAD_REF" = "dev" ] && \
|
||||
[ "$HEAD_REPOSITORY" = "$GITHUB_REPOSITORY" ]; then
|
||||
echo "release_pr=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "release_pr=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Classify changed files
|
||||
id: filter
|
||||
uses: actions/github-script@v8
|
||||
@@ -123,43 +146,117 @@ jobs:
|
||||
core.notice(`Changed paths: ${paths.join(', ')}`);
|
||||
core.notice(`Selected checks: ${Object.entries(outputs).filter(([, value]) => value).map(([key]) => key).join(', ') || 'none'}`);
|
||||
|
||||
android:
|
||||
release-proof:
|
||||
name: Reuse exact-tree required checks
|
||||
needs: changes
|
||||
if: needs.changes.outputs.android == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
if: needs.changes.outputs.release_pr == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
reuse: ${{ steps.proof.outputs.reuse }}
|
||||
artifact_id: ${{ steps.proof.outputs.artifact_id }}
|
||||
run_id: ${{ steps.proof.outputs.run_id }}
|
||||
tree: ${{ steps.proof.outputs.tree }}
|
||||
steps:
|
||||
- name: Checkout simulated release merge
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Locate exact-tree proof
|
||||
id: proof
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
DEV_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
merge_tree=$(git rev-parse 'HEAD^{tree}')
|
||||
dev_tree=$(git rev-parse "${DEV_SHA}^{tree}")
|
||||
echo "reuse=false" >> "$GITHUB_OUTPUT"
|
||||
echo "tree=$dev_tree" >> "$GITHUB_OUTPUT"
|
||||
if [ "$merge_tree" != "$dev_tree" ]; then
|
||||
echo "Release merge changes the dev tree ($dev_tree -> $merge_tree); running full CI."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
artifact_name="required-checks-${dev_tree}"
|
||||
artifact=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${artifact_name}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | sort_by(.created_at) | last')
|
||||
artifact_id=$(jq -r '.id // empty' <<<"$artifact")
|
||||
run_id=$(jq -r '.workflow_run.id // empty' <<<"$artifact")
|
||||
if [ -z "$artifact_id" ] || [ -z "$run_id" ]; then
|
||||
echo "No reusable proof exists for tree $dev_tree; running full CI."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
run=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}")
|
||||
conclusion=$(jq -r '.conclusion' <<<"$run")
|
||||
workflow_path=$(jq -r '.path' <<<"$run")
|
||||
if [ "$workflow_path" != ".github/workflows/ci-required.yml" ] || [ "$conclusion" != "success" ]; then
|
||||
echo "::error::Required-check proof came from ${workflow_path} with conclusion ${conclusion}"
|
||||
exit 1
|
||||
fi
|
||||
echo "artifact_id=$artifact_id" >> "$GITHUB_OUTPUT"
|
||||
echo "run_id=$run_id" >> "$GITHUB_OUTPUT"
|
||||
echo "reuse=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Download exact-tree proof
|
||||
if: steps.proof.outputs.reuse == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
artifact-ids: ${{ steps.proof.outputs.artifact_id }}
|
||||
github-token: ${{ github.token }}
|
||||
repository: ${{ github.repository }}
|
||||
run-id: ${{ steps.proof.outputs.run_id }}
|
||||
path: required-check-proof
|
||||
|
||||
- name: Verify exact-tree proof
|
||||
if: steps.proof.outputs.reuse == 'true'
|
||||
env:
|
||||
EXPECTED_TREE: ${{ steps.proof.outputs.tree }}
|
||||
run: |
|
||||
jq -e \
|
||||
--arg repository "$GITHUB_REPOSITORY" \
|
||||
--arg tree "$EXPECTED_TREE" \
|
||||
'.schemaVersion == 1 and .repository == $repository and .tree == $tree' \
|
||||
required-check-proof/required-checks.json
|
||||
|
||||
android:
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.android == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-android.yml
|
||||
|
||||
android_on_demand:
|
||||
needs: changes
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.android_preset != 'auto'
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.release-proof.outputs.reuse != 'true' && github.event_name == 'workflow_dispatch' && inputs.android_preset != 'auto' }}
|
||||
uses: ./.github/workflows/android-on-demand.yml
|
||||
with:
|
||||
head_sha: ${{ inputs.head_sha }}
|
||||
preset: ${{ inputs.android_preset }}
|
||||
|
||||
desktop:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.desktop == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.desktop == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-desktop.yml
|
||||
|
||||
plugin:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.plugin == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.plugin == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-plugin.yml
|
||||
|
||||
dashboard:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.dashboard == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.dashboard == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-dashboard.yml
|
||||
|
||||
contract:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.contract == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.contract == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
uses: ./.github/workflows/ci-contract.yml
|
||||
|
||||
docs:
|
||||
name: Build public docs
|
||||
needs: changes
|
||||
if: needs.changes.outputs.docs == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
||||
needs: [changes, release-proof]
|
||||
if: ${{ always() && needs.changes.result == 'success' && needs.changes.outputs.docs == 'true' && needs.release-proof.outputs.reuse != 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto') }}
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
@@ -181,10 +278,12 @@ jobs:
|
||||
guard:
|
||||
name: Required checks
|
||||
if: always()
|
||||
needs: [changes, android, android_on_demand, desktop, plugin, dashboard, contract, docs]
|
||||
needs: [changes, release-proof, android, android_on_demand, desktop, plugin, dashboard, contract, docs]
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CHANGES_RESULT: ${{ needs.changes.result }}
|
||||
RELEASE_PROOF_RESULT: ${{ needs.release-proof.result }}
|
||||
REUSED_REQUIRED_CHECKS: ${{ needs.release-proof.outputs.reuse }}
|
||||
ANDROID_RESULT: ${{ needs.android.result }}
|
||||
ANDROID_ON_DEMAND_RESULT: ${{ needs.android_on_demand.result }}
|
||||
DESKTOP_RESULT: ${{ needs.desktop.result }}
|
||||
@@ -197,7 +296,7 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
failed=0
|
||||
for check in CHANGES ANDROID ANDROID_ON_DEMAND DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
|
||||
for check in CHANGES RELEASE_PROOF ANDROID ANDROID_ON_DEMAND DESKTOP PLUGIN DASHBOARD CONTRACT DOCS; do
|
||||
result_var="${check}_RESULT"
|
||||
result="${!result_var}"
|
||||
echo "$check: $result"
|
||||
@@ -207,3 +306,26 @@ jobs:
|
||||
esac
|
||||
done
|
||||
exit "$failed"
|
||||
|
||||
- name: Write exact-tree proof
|
||||
if: ${{ needs.release-proof.outputs.reuse != 'true' }}
|
||||
env:
|
||||
CHECKED_TREE: ${{ needs.changes.outputs.tree }}
|
||||
run: |
|
||||
mkdir -p required-check-proof
|
||||
jq -n \
|
||||
--arg repository "$GITHUB_REPOSITORY" \
|
||||
--arg tree "$CHECKED_TREE" \
|
||||
--arg commit "$GITHUB_SHA" \
|
||||
--arg run_id "$GITHUB_RUN_ID" \
|
||||
'{schemaVersion: 1, repository: $repository, tree: $tree, commit: $commit, runId: $run_id}' \
|
||||
> required-check-proof/required-checks.json
|
||||
|
||||
- name: Upload exact-tree proof
|
||||
if: ${{ needs.release-proof.outputs.reuse != 'true' }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: required-checks-${{ needs.changes.outputs.tree }}
|
||||
path: required-check-proof/required-checks.json
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
#
|
||||
# Run manually from the final dev or untagged main tree before creating
|
||||
# android-v*. The job
|
||||
# builds the same signed release artifacts, scans final DEX, and uploads the
|
||||
# Google Play bundle as a production DRAFT. A successful upload is the automated
|
||||
# Play gate while no public GitHub Release or sideload APK exists. Console-only
|
||||
# pre-review and pre-launch reports are informational and do not block release.
|
||||
# builds the signed release artifacts once, scans the final packages, and uploads
|
||||
# the Google Play bundle as a production DRAFT. The exact signed APK/AAB,
|
||||
# mappings, manifest, and checksums remain private Actions artifacts until
|
||||
# approval publishes those same bytes. Console-only pre-review and pre-launch
|
||||
# reports are informational and do not block release.
|
||||
|
||||
name: Hermes-Relay Android Play Preflight
|
||||
|
||||
@@ -98,7 +99,12 @@ jobs:
|
||||
HERMES_KEYSTORE_PASSWORD: ${{ secrets.HERMES_KEYSTORE_PASSWORD }}
|
||||
HERMES_KEY_ALIAS: ${{ secrets.HERMES_KEY_ALIAS }}
|
||||
HERMES_KEY_PASSWORD: ${{ secrets.HERMES_KEY_PASSWORD }}
|
||||
run: ./gradlew bundleRelease assembleRelease --console=plain
|
||||
run: |
|
||||
./gradlew \
|
||||
:app:bundleGooglePlayRelease \
|
||||
:app:assembleGooglePlayRelease \
|
||||
:app:assembleSideloadRelease \
|
||||
--console=plain
|
||||
|
||||
- name: Scan final release DEX
|
||||
run: |
|
||||
@@ -106,6 +112,12 @@ jobs:
|
||||
--apk app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
--apk app/build/outputs/apk/sideload/release/*.apk
|
||||
|
||||
- name: Verify packaged native compatibility
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
app/build/outputs/apk/sideload/release/*.apk
|
||||
|
||||
- name: Upload private production draft to Play
|
||||
env:
|
||||
PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
|
||||
@@ -121,27 +133,27 @@ jobs:
|
||||
--resolution-strategy=ignore \
|
||||
--release-name="Hermes-Relay Android v${{ steps.metadata.outputs.version }}"
|
||||
|
||||
- name: Record successful preflight for the exact commit
|
||||
- name: Package immutable preflight artifacts
|
||||
run: |
|
||||
mkdir -p app/build/reports
|
||||
cat > app/build/reports/play-preflight.json <<EOF
|
||||
{
|
||||
"version": "${{ steps.metadata.outputs.version }}",
|
||||
"versionCode": "${{ steps.metadata.outputs.version_code }}",
|
||||
"commit": "$GITHUB_SHA",
|
||||
"tree": "${{ steps.metadata.outputs.tree }}",
|
||||
"track": "production",
|
||||
"status": "draft"
|
||||
}
|
||||
EOF
|
||||
python3 scripts/android_release_artifacts.py package \
|
||||
--version "${{ steps.metadata.outputs.version }}" \
|
||||
--version-code "${{ steps.metadata.outputs.version_code }}" \
|
||||
--commit "$GITHUB_SHA" \
|
||||
--tree "${{ steps.metadata.outputs.tree }}" \
|
||||
--sideload-apk app/build/outputs/apk/sideload/release/*.apk \
|
||||
--google-play-aab app/build/outputs/bundle/googlePlayRelease/*.aab \
|
||||
--sideload-mapping app/build/outputs/mapping/sideloadRelease/mapping.txt \
|
||||
--google-play-mapping app/build/outputs/mapping/googlePlayRelease/mapping.txt \
|
||||
--output app/build/preflight-artifacts
|
||||
|
||||
- name: Upload preflight proof
|
||||
- name: Upload immutable preflight artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: play-preflight-${{ steps.metadata.outputs.version }}-${{ steps.metadata.outputs.tree }}
|
||||
path: app/build/reports/play-preflight.json
|
||||
path: app/build/preflight-artifacts/*
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
compression-level: 0
|
||||
|
||||
- name: Preflight summary
|
||||
run: |
|
||||
@@ -152,4 +164,4 @@ jobs:
|
||||
echo "- Release tree: \`${{ steps.metadata.outputs.tree }}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "- Play track/status: **Production draft**" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "The signed build, DEX scan, and Play draft upload passed. Ensure this exact release tree is on main, then run **Hermes-Relay Android Release Approval** from main. Console-only reports are informational and non-blocking." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "The signed build, package scans, and Play draft upload passed. Approval will publish these exact private artifacts if the unchanged tree reaches main. Console-only reports are informational and non-blocking." >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
@@ -36,6 +36,9 @@ jobs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
version_code: ${{ steps.version.outputs.version_code }}
|
||||
prerelease: ${{ steps.version.outputs.prerelease }}
|
||||
release_tree: ${{ steps.version.outputs.release_tree }}
|
||||
preflight_artifact_id: ${{ steps.preflight.outputs.artifact_id }}
|
||||
preflight_run_id: ${{ steps.preflight.outputs.run_id }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
@@ -66,6 +69,7 @@ jobs:
|
||||
echo "version=$REF_VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"
|
||||
echo "release_tree=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify version sync
|
||||
run: |
|
||||
@@ -110,25 +114,38 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Require successful Play preflight for this exact release tree
|
||||
id: preflight
|
||||
if: ${{ !contains(steps.version.outputs.version, '-') }}
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
RELEASE_TREE=$(git rev-parse 'HEAD^{tree}')
|
||||
RELEASE_TREE="${{ steps.version.outputs.release_tree }}"
|
||||
ARTIFACT_NAME="play-preflight-${VERSION}-${RELEASE_TREE}"
|
||||
COUNT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | length')
|
||||
if [ "$COUNT" -lt 1 ]; then
|
||||
ARTIFACT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||
--jq '[.artifacts[] | select(.expired == false)] | sort_by(.created_at) | last')
|
||||
ARTIFACT_ID=$(jq -r '.id // empty' <<<"$ARTIFACT")
|
||||
RUN_ID=$(jq -r '.workflow_run.id // empty' <<<"$ARTIFACT")
|
||||
if [ -z "$ARTIFACT_ID" ] || [ -z "$RUN_ID" ]; then
|
||||
echo "::error::No successful Play preflight found for version $VERSION with tree $RELEASE_TREE"
|
||||
echo "Run Hermes-Relay Android Play Preflight from the final dev tree, merge that unchanged tree to main, then approve the release."
|
||||
exit 1
|
||||
fi
|
||||
echo "Play preflight proof found: $ARTIFACT_NAME"
|
||||
RUN=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/runs/${RUN_ID}")
|
||||
CONCLUSION=$(jq -r '.conclusion' <<<"$RUN")
|
||||
WORKFLOW_PATH=$(jq -r '.path' <<<"$RUN")
|
||||
if [ "$WORKFLOW_PATH" != ".github/workflows/play-preflight-android.yml" ] || [ "$CONCLUSION" != "success" ]; then
|
||||
echo "::error::Preflight artifact came from ${WORKFLOW_PATH} with conclusion ${CONCLUSION}"
|
||||
exit 1
|
||||
fi
|
||||
echo "artifact_id=$ARTIFACT_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "run_id=$RUN_ID" >> "$GITHUB_OUTPUT"
|
||||
echo "Play preflight artifacts verified: $ARTIFACT_NAME (run $RUN_ID, artifact $ARTIFACT_ID)"
|
||||
|
||||
ci:
|
||||
name: CI Checks
|
||||
name: CI Checks (prerelease only)
|
||||
needs: validate
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
@@ -168,6 +185,7 @@ jobs:
|
||||
release:
|
||||
name: Build & Publish Release
|
||||
needs: [validate, ci]
|
||||
if: ${{ always() && needs.validate.result == 'success' && (needs.ci.result == 'success' || needs.ci.result == 'skipped') }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
@@ -186,31 +204,33 @@ jobs:
|
||||
with:
|
||||
cache-read-only: false
|
||||
|
||||
- name: Decode release keystore
|
||||
- name: Download exact stable preflight artifacts
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
artifact-ids: ${{ needs.validate.outputs.preflight_artifact_id }}
|
||||
github-token: ${{ github.token }}
|
||||
repository: ${{ github.repository }}
|
||||
run-id: ${{ needs.validate.outputs.preflight_run_id }}
|
||||
path: app/build/preflight-artifacts
|
||||
|
||||
- name: Verify exact stable preflight artifacts
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
run: |
|
||||
python3 scripts/android_release_artifacts.py verify \
|
||||
--version "${{ needs.validate.outputs.version }}" \
|
||||
--version-code "${{ needs.validate.outputs.version_code }}" \
|
||||
--tree "${{ needs.validate.outputs.release_tree }}" \
|
||||
--directory app/build/preflight-artifacts
|
||||
|
||||
- name: Decode release keystore for candidate build
|
||||
env:
|
||||
HERMES_KEYSTORE_BASE64: ${{ secrets.HERMES_KEYSTORE_BASE64 }}
|
||||
if: env.HERMES_KEYSTORE_BASE64 != ''
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' && env.HERMES_KEYSTORE_BASE64 != '' }}
|
||||
run: |
|
||||
echo "$HERMES_KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.keystore"
|
||||
echo "HERMES_KEYSTORE_PATH=$RUNNER_TEMP/release.keystore" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build stable release artifacts (APK + AAB)
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
env:
|
||||
HERMES_KEYSTORE_PASSWORD: ${{ secrets.HERMES_KEYSTORE_PASSWORD }}
|
||||
HERMES_KEY_ALIAS: ${{ secrets.HERMES_KEY_ALIAS }}
|
||||
HERMES_KEY_PASSWORD: ${{ secrets.HERMES_KEY_PASSWORD }}
|
||||
# `assembleRelease` and `bundleRelease` are flavor-wide task aliases
|
||||
# (added by `flavorDimensions += "track"` in app/build.gradle.kts), so
|
||||
# this one line builds ALL four artifacts at once. Filenames come from
|
||||
# `archivesName` (set in app/build.gradle.kts) which injects the app
|
||||
# version, so `<version>` below is `libs.versions.appVersionName`:
|
||||
# app/build/outputs/apk/googlePlay/release/hermes-relay-<version>-googlePlay-release.apk
|
||||
# app/build/outputs/apk/sideload/release/hermes-relay-<version>-sideload-release.apk
|
||||
# app/build/outputs/bundle/googlePlayRelease/hermes-relay-<version>-googlePlay-release.aab
|
||||
# app/build/outputs/bundle/sideloadRelease/hermes-relay-<version>-sideload-release.aab
|
||||
run: ./gradlew bundleRelease assembleRelease
|
||||
|
||||
- name: Build side-by-side release candidate APK
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
env:
|
||||
@@ -234,10 +254,10 @@ jobs:
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: android-r8-mappings-${{ needs.validate.outputs.version }}-${{ github.sha }}
|
||||
name: android-r8-mappings-${{ needs.validate.outputs.version }}-${{ needs.validate.outputs.release_tree }}
|
||||
path: |
|
||||
app/build/outputs/mapping/googlePlayRelease/mapping.txt
|
||||
app/build/outputs/mapping/sideloadRelease/mapping.txt
|
||||
app/build/preflight-artifacts/mapping-googlePlayRelease.txt
|
||||
app/build/preflight-artifacts/mapping-sideloadRelease.txt
|
||||
if-no-files-found: error
|
||||
retention-days: 90
|
||||
|
||||
@@ -254,8 +274,7 @@ jobs:
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
run: |
|
||||
python3 scripts/check-android-collection-apis.py \
|
||||
--apk app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
--apk app/build/outputs/apk/sideload/release/*.apk
|
||||
--apk app/build/preflight-artifacts/*-sideload-release.apk
|
||||
|
||||
- name: Scan candidate DEX for unsupported collection APIs
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
@@ -267,8 +286,7 @@ jobs:
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
run: |
|
||||
python3 scripts/check-android-native-compat.py \
|
||||
app/build/outputs/apk/googlePlay/release/*.apk \
|
||||
app/build/outputs/apk/sideload/release/*.apk
|
||||
app/build/preflight-artifacts/*-sideload-release.apk
|
||||
|
||||
- name: Verify candidate packaged ONNX Runtime compatibility
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
@@ -278,23 +296,10 @@ jobs:
|
||||
|
||||
- name: List produced artifacts (debug aid)
|
||||
run: |
|
||||
echo "=== APK outputs ==="
|
||||
echo "=== Reused stable artifacts ==="
|
||||
find app/build/preflight-artifacts -maxdepth 1 -type f -print 2>/dev/null || true
|
||||
echo "=== Candidate APK outputs ==="
|
||||
find app/build/outputs/apk -name '*.apk' -print 2>/dev/null || true
|
||||
echo "=== AAB outputs ==="
|
||||
find app/build/outputs/bundle -name '*.aab' -print 2>/dev/null || true
|
||||
|
||||
- name: Generate stable checksums
|
||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||
# Flavor dimension adds an extra path segment to the AGP output layout.
|
||||
# APKs live under `apk/<flavor>/release/`, AABs under `bundle/<flavor>Release/`
|
||||
# (note the concatenated camelCase — AGP path quirk, documented but
|
||||
# different between APK and AAB). Checksums cover EXACTLY the files
|
||||
# attached to the GitHub Release (see the 2-asset policy on the
|
||||
# release step below) so SHA256SUMS.txt matches the assets 1:1.
|
||||
run: |
|
||||
cd app/build/outputs
|
||||
sha256sum apk/sideload/release/*.apk bundle/googlePlayRelease/*.aab > SHA256SUMS.txt
|
||||
cat SHA256SUMS.txt
|
||||
|
||||
- name: Generate candidate checksums
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
@@ -340,9 +345,9 @@ jobs:
|
||||
# Deliberate 2-asset policy (#144): attach ONLY the installable
|
||||
# sideload APK and Play AAB, plus checksums covering those files.
|
||||
files: |
|
||||
app/build/outputs/apk/sideload/release/*.apk
|
||||
app/build/outputs/bundle/googlePlayRelease/*.aab
|
||||
app/build/outputs/SHA256SUMS.txt
|
||||
app/build/preflight-artifacts/*-sideload-release.apk
|
||||
app/build/preflight-artifacts/*-googlePlay-release.aab
|
||||
app/build/preflight-artifacts/SHA256SUMS.txt
|
||||
|
||||
- name: Create candidate GitHub prerelease
|
||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||
@@ -364,18 +369,17 @@ jobs:
|
||||
run: |
|
||||
echo "## Hermes-Relay Android v${{ needs.validate.outputs.version }}" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$PRERELEASE" = "true" ] && [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
||||
echo "✅ **Release-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
elif [ "$PRERELEASE" = "true" ]; then
|
||||
echo "⚠️ **Debug-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
if [ "$PRERELEASE" != "true" ]; then
|
||||
echo "✅ **Published the exact signed Play-preflight artifacts**" >> "$GITHUB_STEP_SUMMARY"
|
||||
elif [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
||||
echo "✅ **Signed with release keystore** — suitable for Play Store upload" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "✅ **Release-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo "⚠️ **Debug-signed** (no \`HERMES_KEYSTORE_BASE64\` secret) — NOT suitable for Play Store. Add the secret in repo settings to enable release signing." >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "⚠️ **Debug-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo "### Artifacts" >> "$GITHUB_STEP_SUMMARY"
|
||||
echo '```' >> "$GITHUB_STEP_SUMMARY"
|
||||
find app/build/preflight-artifacts -maxdepth 1 -type f -exec ls -la {} + >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
|
||||
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"
|
||||
|
||||
@@ -3,6 +3,12 @@ name: Hermes-Relay CLI+UI Release
|
||||
on:
|
||||
push:
|
||||
tags: ['desktop-v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Approved CLI+UI version"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -20,6 +26,7 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v7
|
||||
@@ -34,10 +41,16 @@ jobs:
|
||||
- name: Extract and validate tag version
|
||||
id: version
|
||||
shell: bash
|
||||
env:
|
||||
DISPATCHED_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#desktop-v}"
|
||||
if [[ -z "$version" || "$version" == "$GITHUB_REF_NAME" ]]; then
|
||||
if [ -n "$DISPATCHED_VERSION" ]; then
|
||||
version="$DISPATCHED_VERSION"
|
||||
else
|
||||
version="${GITHUB_REF_NAME#desktop-v}"
|
||||
fi
|
||||
if [ -z "$version" ] || { [ -z "$DISPATCHED_VERSION" ] && [ "$version" = "$GITHUB_REF_NAME" ]; }; then
|
||||
echo "Expected a desktop-v* tag, got $GITHUB_REF_NAME" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -51,11 +64,12 @@ jobs:
|
||||
- name: Verify tag belongs to the correct integration branch
|
||||
shell: bash
|
||||
working-directory: .
|
||||
env:
|
||||
TAG_VERSION: ${{ steps.version.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="${GITHUB_REF_NAME#desktop-v}"
|
||||
tag_commit="$(git rev-parse "${GITHUB_REF_NAME}^{commit}")"
|
||||
if [[ "$version" == *-* ]]; then
|
||||
tag_commit="$(git rev-parse HEAD)"
|
||||
if [[ "$TAG_VERSION" == *-* ]]; then
|
||||
git fetch origin dev --no-tags
|
||||
if ! git merge-base --is-ancestor "$tag_commit" origin/dev; then
|
||||
echo "CLI+UI prereleases must be tagged from dev; $tag_commit is not in origin/dev" >&2
|
||||
@@ -78,6 +92,8 @@ jobs:
|
||||
working-directory: desktop
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Setup Node.js (for npm ci + tsc)
|
||||
uses: actions/setup-node@v7
|
||||
@@ -271,6 +287,8 @@ jobs:
|
||||
working-directory: desktop
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v7
|
||||
@@ -289,6 +307,18 @@ jobs:
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Restore exact-source tray build cache
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
desktop/tray/target
|
||||
key: ${{ runner.os }}-tray-rust-${{ hashFiles('desktop/tray/Cargo.lock') }}-${{ hashFiles('desktop/tray/Cargo.toml', 'desktop/tray/build.rs', 'desktop/tray/src/**/*.rs') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-tray-rust-${{ hashFiles('desktop/tray/Cargo.lock') }}-
|
||||
|
||||
- name: Install deps
|
||||
run: npm ci && npm --prefix tray ci
|
||||
|
||||
@@ -411,6 +441,11 @@ jobs:
|
||||
if ($versionOutput -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
|
||||
throw "installed CLI version mismatch: expected $env:EXPECTED_DESKTOP_VERSION, got '$versionOutput'"
|
||||
}
|
||||
$tray = Join-Path $installDir 'hermes-relay-tray.exe'
|
||||
$trayVersion = (Get-Item -LiteralPath $tray).VersionInfo.ProductVersion
|
||||
if ($trayVersion -ne $env:EXPECTED_DESKTOP_VERSION) {
|
||||
throw "installed UI version mismatch: expected $env:EXPECTED_DESKTOP_VERSION, got '$trayVersion'"
|
||||
}
|
||||
$helpOutput = (& $cli --help | Out-String)
|
||||
if ($LASTEXITCODE -ne 0 -or $helpOutput -notmatch 'Usage:') {
|
||||
throw 'installed CLI --help smoke failed'
|
||||
@@ -451,7 +486,7 @@ jobs:
|
||||
throw "installer lifecycle changed the pre-existing tray startup preference"
|
||||
}
|
||||
|
||||
Write-Host "packaged installer lifecycle smoke OK version=$versionOutput install=$installDir"
|
||||
Write-Host "packaged installer lifecycle smoke OK cli=$versionOutput ui=$trayVersion install=$installDir"
|
||||
} finally {
|
||||
Get-Process -Name 'hermes-relay-tray' -ErrorAction SilentlyContinue |
|
||||
Stop-Process -Force -ErrorAction SilentlyContinue
|
||||
@@ -483,6 +518,7 @@ jobs:
|
||||
name: Publish GitHub Release
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- validate-release
|
||||
- build-cli-binaries
|
||||
- smoke-windows-cli-release-asset
|
||||
- smoke-macos-cli-release-asset
|
||||
@@ -492,10 +528,8 @@ jobs:
|
||||
# Needed so CLI_RELEASE_NOTES.md is available to render into the release body
|
||||
# (the other publish-release steps only consume downloaded build artifacts).
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Extract CLI+UI version
|
||||
id: version
|
||||
run: echo "version=${GITHUB_REF_NAME#desktop-v}" >> "$GITHUB_OUTPUT"
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -515,8 +549,8 @@ jobs:
|
||||
# (desktop-v0.3.0) so install/pin commands stay accurate without manual edits.
|
||||
- name: Render release notes
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
TAG: ${{ github.ref_name }}
|
||||
VERSION: ${{ needs.validate-release.outputs.version }}
|
||||
TAG: desktop-v${{ needs.validate-release.outputs.version }}
|
||||
run: |
|
||||
sed -e "s/__VERSION__/${VERSION}/g" -e "s/__TAG__/${TAG}/g" \
|
||||
CLI_RELEASE_NOTES.md > cli_release_notes_rendered.md
|
||||
@@ -525,10 +559,10 @@ jobs:
|
||||
- name: Publish GitHub Release
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
name: Hermes-Relay CLI+UI v${{ steps.version.outputs.version }}
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: Hermes-Relay CLI+UI v${{ needs.validate-release.outputs.version }}
|
||||
tag_name: desktop-v${{ needs.validate-release.outputs.version }}
|
||||
draft: false
|
||||
prerelease: ${{ contains(steps.version.outputs.version, 'alpha') || contains(steps.version.outputs.version, 'beta') || contains(steps.version.outputs.version, 'rc') }}
|
||||
prerelease: ${{ contains(needs.validate-release.outputs.version, '-') }}
|
||||
fail_on_unmatched_files: true
|
||||
body_path: cli_release_notes_rendered.md
|
||||
files: |
|
||||
|
||||
@@ -4,6 +4,12 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "server-v*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: "Approved Plugin version"
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -19,10 +25,19 @@ jobs:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('server-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Extract version from tag
|
||||
id: version
|
||||
run: echo "version=${GITHUB_REF#refs/tags/server-v}" >> "$GITHUB_OUTPUT"
|
||||
env:
|
||||
DISPATCHED_VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
if [ -n "$DISPATCHED_VERSION" ]; then
|
||||
version="$DISPATCHED_VERSION"
|
||||
else
|
||||
version="${GITHUB_REF#refs/tags/server-v}"
|
||||
fi
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify Plugin version sync and changelog
|
||||
run: |
|
||||
@@ -61,6 +76,8 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('server-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v7
|
||||
@@ -85,6 +102,7 @@ jobs:
|
||||
- name: Run focused Plugin tests
|
||||
run: |
|
||||
python -m pytest \
|
||||
plugin/tests/test_manifest_compatibility.py \
|
||||
plugin/tests/test_relay_security.py \
|
||||
plugin/tests/test_voice_routes.py \
|
||||
plugin/tests/test_session_grants.py \
|
||||
@@ -98,6 +116,8 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && format('server-v{0}', inputs.version) || github.ref }}
|
||||
|
||||
- name: Set up Python 3.11
|
||||
uses: actions/setup-python@v7
|
||||
|
||||
+1
-4
@@ -24,10 +24,7 @@ Thumbs.db
|
||||
local.properties
|
||||
/build/
|
||||
/app/build/
|
||||
/relay-core/build/
|
||||
/relay-ui/build/
|
||||
/ui-preview/build/
|
||||
/quest/build/
|
||||
/experiments/quest/**/build/
|
||||
/app/release/
|
||||
*.apk
|
||||
*.aab
|
||||
|
||||
@@ -17,7 +17,7 @@ contract here and in `RELEASE.md`.
|
||||
- Android local/cloud verification → **[docs/android-build-lane.md](docs/android-build-lane.md)**
|
||||
- Android emulator lanes → **[docs/android-emulator-testing.md](docs/android-emulator-testing.md)** — suggest the smallest relevant API 36 lanes; never run the full matrix automatically
|
||||
- `android_*` toolset + MCP → **[docs/mcp-tooling.md](docs/mcp-tooling.md)**
|
||||
- Follow-ups / deferred work / known gaps → **[TODO.md](TODO.md)** (the single home for "what's next" — never DEVLOG, never scattered code comments)
|
||||
- Follow-ups / deferred work / known gaps → **[docs/project/TODO.md](docs/project/TODO.md)** (the single home for "what's next" — never DEVLOG, never scattered code comments)
|
||||
|
||||
## Branch contract
|
||||
|
||||
@@ -65,8 +65,10 @@ PR; never resolve those cases by choosing a side automatically.
|
||||
|
||||
- **Vanilla Hermes path = upstream-only.** The standard (no-plugin) connection
|
||||
uses the upstream Dashboard/Gateway for chat, authentication, Manage, sessions,
|
||||
and Vanilla Hermes voice. The API server is an optional automatic fallback and
|
||||
advanced headless-compatibility surface; Relay adds optional extensions. This
|
||||
and Vanilla Hermes voice. The API server is an explicit API-only/headless
|
||||
compatibility surface; Relay adds optional extensions. A Gateway-owned
|
||||
conversation never changes transport because Gateway auth or reachability
|
||||
changes. This
|
||||
path must work against unmodified upstream hermes-agent. Server-side needs go
|
||||
through upstream PRs or the optional relay plugin, never fork patches.
|
||||
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
|
||||
|
||||
+44
-3
@@ -6,18 +6,59 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [Android 1.15.1] - 2026-09-02
|
||||
|
||||
### Changed
|
||||
|
||||
- Chat and Bot Chat offer a compact Correct now / Queue next tray behind the composer. Chat settings sets the default; each message can override it. Stop pauses pending work until Resume, and editing or removing queued messages preserves the remaining order.
|
||||
- Wider Chat and Voice layouts keep text and controls centered and readable, including landscape Voice Focus.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Delivery and correction labels remain readable inside user-message bubbles.
|
||||
- Voice errors use a scrollable dialog with separate Retry and Dismiss actions.
|
||||
- Attachment previews stay open through rotation, and videos retain their original proportions. (#483)
|
||||
- Release builds preserve the native configuration names required for wake-word startup. (#444)
|
||||
- Standard Hermes attachments stream to disk while enforcing download size limits. (#531)
|
||||
- Session refresh no longer sustains a request loop. History loads, chat rendering, image previews, and media exports keep memory use bounded.
|
||||
- Image-generation progress remains visible between interim replies and media delivery.
|
||||
- New Gateway chats wait for session readiness before the first prompt; ownership refusals preserve the retryable prompt and server error.
|
||||
|
||||
## [0.4.0-beta.7] - 2026-09-02
|
||||
|
||||
### Fixed
|
||||
|
||||
- Windows updates detect a colocated management UI, report both installed versions, and update the CLI and UI together through the verified bundle installer. CLI-only installations keep their standalone updater.
|
||||
|
||||
## [Android 1.15.0] - 2026-08-31
|
||||
|
||||
### Changed
|
||||
|
||||
- **Android prefers current upstream Hermes for standard media, Git, usage, and notices.** Authenticated Dashboard file delivery, current-session `/api/git/*`, Gateway `usage.bars`, and keyed agent notices work without the optional Hermes-Relay Plugin; Relay remains additive for older-host media compatibility, sensitivity metadata, repository discovery and guarded mutations, multi-provider usage, and true Relay tools.
|
||||
- **Android Settings separates standard Hermes from Relay tools.** Media now sits with Chat and Voice under Hermes, while proactive Threads, Terminal, Notification Companion, Relay sessions, and Device Control remain clearly grouped behind the optional plugin.
|
||||
- **Android Supervised Mode uses app-specific parent access.** Parents choose a six-digit PIN or password, receive a shareable six-word recovery phrase, and can remove the credential without losing their supervised profile, capability, appearance, visibility, session, or relock settings. Android device credentials and biometrics no longer grant parent access.
|
||||
- **Android What's New now provides a readable, complete release record.** One overall title and summary lead into selected highlights, every remaining user-visible addition, improvement, and fix, and relevant compatibility boundaries. Toast counts and previews are derived from that same inventory, so View all no longer promises details the expanded dialog and history cannot show.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Standard Hermes attachments no longer demand Relay pairing.** Host-local images, audio, video, and files download through the authenticated Dashboard, stay loaded across history reconciliation, and fall back to one neutral compatibility card on older hosts instead of flashing `Relay URL not configured` or retrying indefinitely.
|
||||
- **Removing optional Relay does not strand Standard voice or leak preferences across connections.** Runtime fallback keeps Dashboard voice usable, preserves configured choices through temporary outages, and normalizes only connection-scoped named-profile settings after explicit Relay removal.
|
||||
- **Passively observed Desktop/TUI turns now show live activity in the Android session drawer.** A uniquely matched selected session projects Working or Waiting without Android resuming, activating, or interrupting the external runtime; ambiguous cross-profile matches remain neutral. (Related: #365)
|
||||
- **Android Chat keeps one transport owner through sign-out and outages.** Dashboard/Gateway conversations now preserve their transcript, draft, profile, and session for sign-in or retry instead of silently sending the next turn to a reachable Direct API database. Legacy API-only connections and explicitly selected Direct API chats remain supported.
|
||||
- **Android keeps completed chat text visible when Dashboard sign-in expires.** Generic and reason-coded history `401` responses settle the local turn, preserve its transcript, and surface the existing sign-in recovery without reading another profile's API history.
|
||||
- **Android keeps long-running context compaction alive.** A client-visible compaction status extends and refreshes the Gateway turn watchdog instead of interrupting healthy compression after the ordinary idle window. (Supersedes #484.)
|
||||
- **Android Bot Chats render loaded history immediately.** Route-owned chat screens observe their own handler state from first composition, including fast history loads that settle before another frame. (Supersedes #453.)
|
||||
- **Android Chat settles an owned Gateway turn when its terminal frame is lost.** An exact idle `session.active_list` snapshot now completes the matching local stream, reconciles durable history, and drains its queued follow-up without interrupting or claiming Desktop/TUI work.
|
||||
- **Supervised Gateway setup stays parent-owned.** Add Gateway is single-flight and checks live parent authority before allocating a draft, relock/back cancels the exact pending setup, and the locked Chat footer no longer attempts protected navigation.
|
||||
- **Generated images stay visible and use their intended Chat animation.** Completed image media survives a marker-lagging history refresh, and both the built-in `image_generate` tool and profile tools ending in `_create_image` use the image-generation presentation.
|
||||
|
||||
## [Plugin 1.11.1] - 2026-08-31
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Hermes-Relay Plugin installs through the native Hermes command again.** The manifest remains fully described for current hosts while avoiding the installer/runtime schema mismatch in affected Hermes releases.
|
||||
- **Relay prompt context advertises only real callable phone tools.** Phone-control and cross-platform delivery guidance now follows the exact selected session/profile tool catalog instead of implying unavailable `android_*` or `send_message` capabilities.
|
||||
|
||||
## [Android 1.14.0] - 2026-08-30
|
||||
|
||||
### Added
|
||||
@@ -66,7 +107,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
- **Dense pairing QRs scan reliably.** Dashboard, CLI, and TUI render integer-sized modules with a full quiet zone.
|
||||
- **Remote-access migration keeps existing listeners safe.** Recommended setup avoids taking over `:443`, explicit legacy cleanup remains available, and default disable actions remove only the listeners they own.
|
||||
|
||||
## [0.4.0-beta.6] - 2026-08-30
|
||||
## [0.4.0-beta.6] - 2026-08-31
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -1254,7 +1295,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
|
||||
- **Voice-exit chime firing on every Add-connection tap.** `ConnectionSwitchCoordinator.switchConnection` fires the `voiceStopCallback` unconditionally at step 3 (correct for connection-to-connection switches while voice is active), but `beginAddConnection` also routes through `switchConnection` to bind the placeholder Connection's auth store before the pair wizard runs — and `VoiceViewModel.exitVoiceMode()` was playing `sfxPlayer.playExit()` regardless of whether voice mode was actually on. Logcat confirmed the chime on every Add-connection FAB tap. Fix adds an idempotence guard at the top of `exitVoiceMode()`: early-return when `_uiState.value.voiceMode` is already false. Teardown is still safe to skip because every inner statement is null-guarded + try/catch-wrapped and would be a no-op on an already-stopped voice session; the only meaningful line is the `playExit()` SFX, which is what we're silencing.
|
||||
- **500 ms freeze on every Add-connection tap.** `ConnectionSwitchCoordinator.switchConnection` runs a `withTimeoutOrNull(AUTH_HYDRATE_TIMEOUT_MS = 500L)` block at step 10 to wait for the freshly-bound `AuthManager` to flip `AuthState` from `Loading` to `Paired`. The comment acknowledged Add-connection is the common path and the 500 ms was meant to be "imperceptible," but on-device it wasn't — the user perceived the delay (and the voice chime masking it) on every tap. The placeholder Connection created by `beginAddConnection` has `pairedAt == null` and an empty EncryptedSharedPreferences store, so `AuthState` will NEVER reach `Paired` — the 500 ms is pure stall. Fix short-circuits the hydrate wait when `target.pairedAt == null`: skip `withTimeoutOrNull` entirely for placeholders and log at DEBUG instead of the misleading "auth hydrate timeout" INFO. Real paired-to-paired switches still run the full hydrate wait because both sides have `pairedAt != null`.
|
||||
- **KDoc nested-comment trap in `ConnectionViewModel.relayReady` doc block.** A literal `/voice/*` path pattern inside the `relayReady` KDoc opened a nested block comment (Kotlin supports nested `/* */`, Java does not) whose `*/` then closed only the nested level — leaving the outer `/**` open for the remaining ~2200 lines of the file. Symptom: `MainActivity.kt:67` "Unresolved reference 'isReady'" plus ~50 cascading "Cannot infer type" errors across `PairedDevicesScreen`, `SettingsScreen`, `TerminalScreen`. Real errors (`Missing '}`, `Unclosed comment`) were the last two lines of `./gradlew compileGooglePlayDebugKotlin` output, easy to miss. Fix was a two-character rewrite: path patterns now wrapped in backticks AND `/*` → `/...` so the glob-looking character isn't in a block-comment position. Lesson logged in `DEVLOG.md` 2026-04-21; worth a sweep of other KDoc blocks for shell/regex-looking patterns before the next large diff.
|
||||
- **KDoc nested-comment trap in `ConnectionViewModel.relayReady` doc block.** A literal `/voice/*` path pattern inside the `relayReady` KDoc opened a nested block comment (Kotlin supports nested `/* */`, Java does not) whose `*/` then closed only the nested level — leaving the outer `/**` open for the remaining ~2200 lines of the file. Symptom: `MainActivity.kt:67` "Unresolved reference 'isReady'" plus ~50 cascading "Cannot infer type" errors across `PairedDevicesScreen`, `SettingsScreen`, `TerminalScreen`. Real errors (`Missing '}`, `Unclosed comment`) were the last two lines of `./gradlew compileGooglePlayDebugKotlin` output, easy to miss. Fix was a two-character rewrite: path patterns now wrapped in backticks AND `/*` → `/...` so the glob-looking character isn't in a block-comment position. Lesson logged in `docs/project/DEVLOG.md` 2026-04-21; worth a sweep of other KDoc blocks for shell/regex-looking patterns before the next large diff.
|
||||
|
||||
- **Orphan placeholder connections from abandoned Add-connection flows.** The `beginAddConnection` path pre-creates a placeholder Connection and switches to it before the pair wizard runs — so `applyPairingPayload` lands the token in the right auth store. Previously, cleanup of the placeholder was wired only to the explicit Cancel button and TopAppBar back arrow. System back (gesture back / predictive back) bypassed that branch, leaving the placeholder in the connection list forever. Two-part fix: (a) `PairScreen` now installs a `BackHandler` that routes system back through the same `onCancel` → `discardPlaceholderConnection` branch the explicit back arrow uses; (b) `ConnectionViewModel.init` sweeps for any existing orphans (tuple: `pairedAt == null && apiServerUrl.isBlank() && label == PLACEHOLDER_LABEL`) on cold start and removes them — the tuple cannot be produced by any real pairing, so the sweep is safe without a dry-run. If the active connection at startup points at an orphan, the sweep switches to the first surviving real connection before deleting. Fixes the "why does my chip say 'New connection…'" symptom on devices that were affected pre-fix.
|
||||
- **Pair flow now auto-starts the camera on Add connection.** `ConnectionWizard` gains an `autoStart: String?` param (currently only `"scan"` is honored). The Add-connection FAB on `ConnectionsSettingsScreen` passes it so the wizard fires the camera permission launcher on first composition instead of forcing users through the Method chooser — one obvious next step, one-tap flow. Re-pair surfaces intentionally leave `autoStart` null so the full Scan / Enter code / Show code chooser stays available there. The deep-link arg is plumbed through `Screen.Pair`'s route (`pair?connectionId=...&autoStart=...`) and `PairScreen`'s new `autoStart` param; unrecognized values fall through to the default Method step so future builds can add more targets without breaking old ones.
|
||||
@@ -2071,7 +2112,7 @@ picker.
|
||||
- **`CLAUDE.md`** — updated Git section with the new branching policy,
|
||||
added file-table entries for `hermes-relay-update`,
|
||||
`register_code_command`, and the expanded `install.sh`
|
||||
- **`TODO.md`** — captures open research questions around proper
|
||||
- **`docs/project/TODO.md`** — captures open research questions around proper
|
||||
Hermes plugin/skill/tool distribution
|
||||
- **`user-docs` vitepress site** — new "For AI Agents" copy-paste
|
||||
block on the home view, Feature Matrix component, two-track explainer,
|
||||
|
||||
@@ -1,22 +1,18 @@
|
||||
# Hermes-Relay CLI+UI v__VERSION__
|
||||
|
||||
**Release Date:** 2026-08-30
|
||||
**Release Date:** 2026-09-02
|
||||
|
||||
This beta preserves complete multi-route pairing while preventing Desktop from dialing Dashboard-ingress Relay routes before Dashboard WebSocket ticket support is available. (Related: #399)
|
||||
This beta fixes Windows updates so the installed CLI and management UI advance together. Explicit CLI-only installations keep their standalone update path.
|
||||
|
||||
**Beta phase.** Assets remain unsigned, so Windows SmartScreen and macOS Gatekeeper may warn on first launch. Standalone CLI binaries ship for Windows x64, Linux x64/arm64, and macOS x64/arm64; the management UI is Windows-only.
|
||||
|
||||
## What's changed
|
||||
|
||||
### Changed
|
||||
|
||||
- **Saved hosts retain the full route topology.** Dashboard, Relay, optional API, route priority, transport protection, certificate pins, and the selected host survive LAN, Tailscale, and public-route changes without creating duplicate hosts.
|
||||
- **API-less pairing is first-class.** Dashboard plus direct Relay can pair without inventing an optional API server, while secure-first ranking retains plain LAN as the final fallback.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Dashboard-ingress Relay routes fail closed on Desktop.** The daemon, host selector, and Relay transport reject ingress that requires a Dashboard WebSocket ticket and choose a compatible direct Relay fallback instead of attempting an unauthenticated dial.
|
||||
- **Pairing accepts the current v3 candidate shape.** Optional API records, same-origin Dashboard/Relay routes, and legacy top-level payloads remain compatible without collapsing route ownership.
|
||||
- `hermes-relay update` detects an installed management UI beside the CLI and reports both installed versions.
|
||||
- Bundle installations use the checksum-verified Windows installer to update and restart the affected CLI and UI together.
|
||||
- Explicit CLI-only installations continue to use the standalone binary updater.
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
+15
-6
@@ -82,6 +82,11 @@ Use the narrowest command that proves the change:
|
||||
5. `scripts/dev.bat prepush` only when full local verification is explicitly
|
||||
wanted or cloud execution is unavailable.
|
||||
|
||||
Android release preparation uses `python scripts/android-prepush.py
|
||||
--release-prep` while version notes are changing. It keeps local feedback to
|
||||
metadata and release-presentation tests; the exact pushed commit still goes
|
||||
through required CI and Play preflight before publication.
|
||||
|
||||
`install-fast` is intentionally phone-specific. Use `install` for a universal
|
||||
sideload debug APK or when the target ABI is not arm64. Release builds remain
|
||||
universal and are unaffected unless `-Phermes.devAbi` is explicitly supplied.
|
||||
@@ -254,16 +259,20 @@ translations may ship as `ai-translated`; do not claim fluent review unless a
|
||||
review reference is recorded. Focused correction PRs from fluent contributors
|
||||
are the canonical way to improve wording and can advance a locale to
|
||||
`community-reviewed` or `verified` under `docs/translation-playbook.md`.
|
||||
Translated READMEs use separate `README.<locale>.md` files; `README.md` remains
|
||||
the canonical project description. User docs may be added incrementally under
|
||||
`user-docs/<locale>/`, with links back to canonical English reference material.
|
||||
Translated README entrypoints live under `docs/readme/` as
|
||||
`README.<locale>.md`; root `README.md` remains the canonical project
|
||||
description. Keep translated entrypoints concise: summarize onboarding and
|
||||
core capabilities, link to localized user docs where available, and link back
|
||||
to English for fast-moving architecture, security, and operator detail. User
|
||||
docs may be added incrementally under `user-docs/<locale>/`, with links back to
|
||||
canonical English reference material.
|
||||
|
||||
## Changelog & writing conventions
|
||||
|
||||
This is a **public repo** — `CHANGELOG.md`, `DEVLOG.md`, the README, and everything under `docs/` ship publicly. Keep them clean:
|
||||
This is a **public repo** — `CHANGELOG.md`, `docs/project/DEVLOG.md`, the README, and everything under `docs/` ship publicly. Keep them clean:
|
||||
|
||||
- **`CHANGELOG.md`** follows [Keep a Changelog](https://keepachangelog.com/) (Added / Changed / Fixed). Append your change to the `## [Unreleased]` block in the PR. Entries can carry detail while they accumulate, but at release-prep the version block is **condensed to crisp public bullets** (1–2 lines each) — the deep "how we debugged it" narrative belongs in commit messages and `DEVLOG.md`, not the public changelog.
|
||||
- **`DEVLOG.md`** is a factual engineering log — what changed, why, and how it was verified. Keep it depersonalized and third-person; it's a record, not a diary.
|
||||
- **`CHANGELOG.md`** follows [Keep a Changelog](https://keepachangelog.com/) (Added / Changed / Fixed). Append your change to the `## [Unreleased]` block in the PR. Entries can carry detail while they accumulate, but at release-prep the version block is **condensed to crisp public bullets** (1–2 lines each) — the deep "how we debugged it" narrative belongs in commit messages and `docs/project/DEVLOG.md`, not the public changelog.
|
||||
- **`docs/project/DEVLOG.md`** is a factual engineering log — what changed, why, and how it was verified. Keep it depersonalized and third-person; it's a record, not a diary.
|
||||
- **No non-public wording anywhere committed:** no personal names (attribute impersonally — identity lives in git history), no real server hostnames/IPs or internal deployment names, no AI/assistant process self-narration, no fork/branch plumbing in user-facing notes. Generic example IPs in setup docs are fine.
|
||||
|
||||
Release notes (`RELEASE_NOTES.md`, `app/src/main/assets/whats_new.txt`, `docs/play-store-listing.md`) are theme-framed and user-facing; see [RELEASE.md](RELEASE.md) §2 "Scrub for public distribution" for the full checklist.
|
||||
|
||||
+5
-19
@@ -1,29 +1,15 @@
|
||||
# Hermes-Relay Plugin v__VERSION__
|
||||
|
||||
**Release Date:** August 30, 2026
|
||||
**Release Date:** August 31, 2026
|
||||
|
||||
## Summary
|
||||
|
||||
This release lets one authenticated Hermes Dashboard origin carry Gateway plus optional Relay extensions, adds a bounded Git workspace, and reorganizes the Dashboard plugin around operator tasks. Standard chat, session history, profiles, Manage, and standard voice remain upstream-owned and do not require this plugin.
|
||||
|
||||
## Added
|
||||
|
||||
- **Dashboard same-origin Relay ingress.** Fixed allowlisted HTTP and WebSocket routes proxy to the local Relay while Dashboard admission and Relay session authentication remain independent. (Related: #399)
|
||||
- **Bounded Git workspace.** Configured roots, path containment, line totals, diffs, branches, staging, commits, remotes, grants, and explicit confirmations protect repository operations.
|
||||
|
||||
## Changed
|
||||
|
||||
- **Task-oriented Dashboard UI.** Overview, Devices, Activity, Remote Access, Git, and Settings now have dedicated surfaces with QR-first pairing, responsive device cards, and honest media diagnostics. (#486)
|
||||
- **One explicit route topology.** Dashboard, CLI, and TUI pairing advertise Dashboard, Relay, and optional API surfaces with stable priorities across Tailscale, public HTTPS, and LAN.
|
||||
- **Dedicated Tailscale listener.** Recommended setup uses tailnet HTTPS `:10443` to local Dashboard `:9119`, avoiding ownership of a reverse proxy's `:443`. Existing `:443`, `:9119`, and direct `:8767` routes remain migration compatibility.
|
||||
This patch restores native installation compatibility on affected Hermes versions and makes Relay prompt context advertise only capabilities the selected session can actually call. Standard Chat, Manage, standard voice, and ordinary inbound files remain upstream-owned.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Public and roaming invites no longer synthesize closed direct Relay `:8767` or wrong Dashboard `:9119` routes.
|
||||
- Ambiguous, credential-bearing, or plaintext public candidates fail closed before an invite is exposed.
|
||||
- Dense pairing QRs use integer-sized modules and a full quiet zone.
|
||||
- Inactive optional API routes are omitted; protected Dashboard-ingress `401/403` responses display as authentication-required while direct Relay and API failures remain failures.
|
||||
- Default Tailscale disable actions remove only owned listeners, and explicit migration cleanup accepts only the bounded supported ports.
|
||||
- **Native installer compatibility.** The plugin keeps its complete current manifest while avoiding the installer/runtime schema mismatch that caused `manifest_version 2` installs to fail after an apparent Hermes update.
|
||||
- **Capability-gated phone context.** Phone-control and cross-platform delivery guidance now follows the selected session/profile tool catalog instead of implying unavailable `android_*` or `send_message` callables.
|
||||
|
||||
## Install / update
|
||||
|
||||
@@ -35,7 +21,7 @@ This release lets one authenticated Hermes Dashboard origin carry Gateway plus o
|
||||
# or, if already installed:
|
||||
hermes-relay-update
|
||||
|
||||
Restart or reload the Hermes Dashboard and Relay after updating so the new manifest, routes, and committed Dashboard bundle are active.
|
||||
Restart or reload the Hermes Dashboard and Relay after updating so the new manifest and prompt context are active.
|
||||
|
||||
## Verify
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<p align="center">
|
||||
<img src="assets/play-store-feature-1024x500.png" alt="Hermes-Relay — your Hermes agent, in your pocket" width="800">
|
||||
<img src="assets/readme-hero-v2.jpg" alt="Hermes-Relay — Your Hermes agent. Wherever you are. Android, Voice, Desktop." width="1000">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -21,7 +21,13 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>English</strong> · <a href="README.zh-CN.md">简体中文</a><br>
|
||||
<strong>English</strong> ·
|
||||
<a href="docs/readme/README.de.md">Deutsch</a> ·
|
||||
<a href="docs/readme/README.es.md">Español</a> ·
|
||||
<a href="docs/readme/README.ja.md">日本語</a> ·
|
||||
<a href="docs/readme/README.pt-BR.md">Português (Brasil)</a> ·
|
||||
<a href="docs/readme/README.ru.md">Русский</a> ·
|
||||
<a href="docs/readme/README.zh-CN.md">简体中文</a><br>
|
||||
<a href="https://hermes-relay.dev/docs/">Documentation</a> ·
|
||||
<a href="https://github.com/Codename-11/hermes-relay/releases">Releases</a> ·
|
||||
<a href="https://github.com/Codename-11/hermes-relay/discussions">Discussions</a> ·
|
||||
@@ -38,10 +44,10 @@ Hermes-Relay puts your [Hermes agent](https://github.com/NousResearch/hermes-age
|
||||
- **📱 Android app** — streaming chat, hands-free voice, native plugin pages, and the full Hermes dashboard (models, keys, skills, profiles), rebuilt native. Add a floating Petdex companion or optionally make Hermes your Android assistant; sideload builds can also let the agent read and act on your screen.
|
||||
- **⌨️ Hermes-Relay CLI** *(beta)* — a single binary that gives the agent **hands on any machine you pair**: files, terminal, search, screenshots — consent-gated.
|
||||
|
||||
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough for the upstream standard path: chat, management, voice, Petdex, and ordinary installed-plugin pages. The Hermes-Relay plugin is optional for that base but encouraged for the complete current experience: Terminal/TUI, notifications, media, desktop tools, enhanced voice, Relay sessions, page drafts, and optional Device Control. Hermes-Relay prefers compatible upstream surfaces as they become available instead of keeping duplicate extension paths. **Connect Hermes first, then grant Hermes-Relay separately; the same one-time invite contract pairs Android or the Desktop CLI.**
|
||||
A vanilla [hermes-agent](https://github.com/NousResearch/hermes-agent) install is enough for the upstream standard path: chat, management, voice, inbound files, Petdex, and ordinary installed-plugin pages. The Hermes-Relay plugin is optional for that base but encouraged for the complete current experience: Terminal/TUI, notifications, desktop tools, enhanced voice, Relay sessions, page drafts, optional Device Control, and media compatibility or metadata. Hermes-Relay prefers compatible upstream surfaces as they become available instead of keeping duplicate extension paths. **Connect Hermes first, then grant Hermes-Relay separately; the same one-time invite contract pairs Android or the Desktop CLI.**
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/diagrams/architecture-homepage.png" alt="How Hermes-Relay connects — upstream Hermes owns Chat, Manage, and standard Voice; the encouraged Relay extension fills current gaps for Terminal, notifications, media, enhanced voice, sessions, desktop tools, and optional Device Control." width="900">
|
||||
<img src="assets/readme-connection-map-v2.png" alt="How Hermes-Relay connects — Dashboard and Gateway own the standard Android path for Chat, Manage, Voice, and inbound files; the optional Relay plugin separately adds Android enhancements plus CLI and UI tools; sideload adds Device Control." width="1000">
|
||||
</p>
|
||||
|
||||
## Quick Start (Android)
|
||||
@@ -50,7 +56,7 @@ Install → connect → talk, in about two minutes.
|
||||
|
||||
### 1 · Install the app
|
||||
|
||||
- **Google Play** *(easiest — auto-updates)* — [**install from Google Play**](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay). Chat, voice, sessions, and Manage work with standard Hermes; pairing the Hermes-Relay plugin adds Terminal/TUI, media, notifications, and Relay sessions.
|
||||
- **Google Play** *(easiest — auto-updates)* — [**install from Google Play**](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay). Chat, voice, sessions, Manage, and inbound files work with standard Hermes; pairing the Hermes-Relay plugin adds Terminal/TUI, notifications, Relay sessions, and media enhancements.
|
||||
- **APK** *(full phone-control feature set)* — download the file ending in **`-sideload-release.apk`** from the newest `android-v*` release on [GitHub Releases](https://github.com/Codename-11/hermes-relay/releases) and open it (allow your browser to install unknown apps the first time). Integrity verification, signing fingerprint, and per-build details are in the [Sideload guide](https://hermes-relay.dev/docs/guide/getting-started.html#sideload-apk).
|
||||
|
||||
Sideload builds check GitHub for updates and show a one-tap banner when you're behind; Play builds update through the Store. See [Release tracks](https://hermes-relay.dev/docs/guide/release-tracks) for the capability matrix.
|
||||
@@ -58,7 +64,7 @@ Sideload builds check GitHub for updates and show a one-tap banner when you're b
|
||||
### 2 · Have the Hermes Dashboard running
|
||||
|
||||
The normal Android connection uses the upstream Hermes Dashboard/Gateway for
|
||||
chat, sign-in, sessions, Manage, and voice. Installing Hermes and choosing a
|
||||
chat, sign-in, sessions, Manage, voice, and inbound files. Installing Hermes and choosing a
|
||||
provider is vanilla Hermes setup:
|
||||
|
||||
```bash
|
||||
@@ -77,16 +83,15 @@ the [remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
|
||||
|
||||
### 3 · Connect and talk
|
||||
|
||||
For a plugin-enabled host, open the Web Dashboard's **Relay** page, click
|
||||
**Connect mobile app**, and scan that tokenless QR from Android **Connect → Scan
|
||||
Hermes setup QR**. It contains only the Dashboard address and configures the
|
||||
upstream Chat, sessions, Manage, sign-in, and standard voice connection.
|
||||
|
||||
Without the Dashboard plugin, use **Find Hermes on LAN** or enter the Dashboard
|
||||
address manually (conventionally `http://<host>:9119`). Sign in through the
|
||||
Use **Find Hermes on LAN** or enter the Dashboard address manually
|
||||
(conventionally `http://<host>:9119`). Sign in through the
|
||||
Dashboard's configured provider when prompted. The app probes the available
|
||||
upstream capabilities and finishes with a connection summary.
|
||||
|
||||
If the Relay Dashboard page is already installed, **Connect mobile app** offers
|
||||
the same standard connection as a tokenless QR. It contains only the Dashboard
|
||||
address and does not install, enable, or pair Relay.
|
||||
|
||||
The separate API server can be discovered automatically or added later under
|
||||
**Advanced** as a chat fallback or for a headless compatibility setup. Its API
|
||||
key is requested only when that optional endpoint is configured. Existing
|
||||
@@ -99,7 +104,7 @@ The wizard probes everything and finishes with a capability card:
|
||||
| **Chat** | Dashboard/Gateway ready — you can talk |
|
||||
| **Manage** | Models, keys, skills, and profiles are available from the phone |
|
||||
| **Voice** | Speech ready via your server (or one Manage sign-in away) |
|
||||
| **API fallback** | Optional API route available/unavailable |
|
||||
| **Direct API** | Optional API-only compatibility route available/unavailable |
|
||||
| **Relay** | Recommended extensions paired/unpaired; never blocks the upstream path |
|
||||
|
||||
One dashboard sign-in unlocks Chat, Manage, sessions, and standard voice. That's
|
||||
@@ -109,9 +114,9 @@ the whole Vanilla Hermes setup.
|
||||
|
||||
### 4 · Recommended: pair Relay for the complete experience
|
||||
|
||||
Install Relay for Terminal/TUI, notifications, media handoff, desktop tools,
|
||||
enhanced voice, Relay sessions, approval-gated page drafts, and optional Device
|
||||
Control:
|
||||
Install Relay for Terminal/TUI, notifications, desktop tools, enhanced voice,
|
||||
Relay sessions, approval-gated page drafts, optional Device Control, and media
|
||||
compatibility or sensitivity metadata:
|
||||
|
||||
```bash
|
||||
hermes plugins install Codename-11/hermes-relay/plugin --enable
|
||||
@@ -140,7 +145,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
[Desktop CLI pairing](https://hermes-relay.dev/docs/desktop/pairing) ·
|
||||
[server, TLS, legacy install, and uninstall reference](https://hermes-relay.dev/docs/reference/relay-server)
|
||||
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. The API fallback is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
**Requirements:** Android 8.0+ (SDK 26) · current upstream [hermes-agent](https://github.com/NousResearch/hermes-agent) with the Dashboard/Gateway enabled · Python 3.11+ when installing the Hermes-Relay plugin. Direct API is optional; the Hermes-Relay plugin is encouraged for the complete experience.
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -161,7 +166,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
||||
|
||||
<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>
|
||||
<sub><b>Native Git workspace</b> — upstream session context with optional Relay discovery and operations</sub>
|
||||
</p>
|
||||
|
||||
### Simplified Chinese
|
||||
@@ -215,7 +220,7 @@ hermes-relay update # self-update via GitHub Releases
|
||||
|
||||
It pairs against the **same relay and credential store** as the Android app — pair once from either, both work. Tagged on the `desktop-v*` [release track](https://github.com/Codename-11/hermes-relay/releases?q=desktop), with historical releases still visible under `cli-v*`.
|
||||
|
||||
On Windows, the default installer adds the optional compact **Hermes-Relay CLI UI** tray popup for host selection and pairing, connection and daemon state, per-host Ask/Trusted/Full Access, local grant dialogs, authorized-client revocation, activity, settings, and emergency stop. It is a management surface only—chat, TUI, plugins, voice, and agent sessions remain CLI/upstream concerns.
|
||||
On Windows, the default installer adds the optional compact **Hermes-Relay CLI UI** tray popup for host selection and pairing, connection and daemon state, per-host Ask/Trusted/Full Access, local grant dialogs, authorized-client revocation, activity, settings, and emergency stop. `hermes-relay update` detects this bundle and updates the CLI and UI together; explicit CLI-only installations stay headless and continue using the standalone binary updater. The UI is a management surface only—chat, TUI, plugins, voice, and agent sessions remain CLI/upstream concerns.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
@@ -239,17 +244,17 @@ remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs
|
||||
## How It Works
|
||||
|
||||
```
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [chat fallback, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media, relay voice, sessions]
|
||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice, inbound files]
|
||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [Direct API chat, sessions, runs]
|
||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media enhancements, relay voice, sessions]
|
||||
CLI (WSS) --> Relay (:8767) [machine tools, tui, terminal]
|
||||
```
|
||||
|
||||
Chat prefers the Hermes dashboard gateway when Manage auth is ready, then falls
|
||||
back to the upstream API server SSE path with the API key. Manage and Vanilla Hermes
|
||||
Standard connections keep Chat on the Hermes Dashboard/Gateway. Explicit API-only
|
||||
connections use the upstream Direct API SSE path with an API key. Manage and Vanilla Hermes
|
||||
voice ride the Hermes dashboard with its own one-time sign-in, so a vanilla
|
||||
install needs no plugin for either. The optional relay on `:8767` adds the power
|
||||
surfaces: terminal, bridge phone control, media handoff, machine tools, and
|
||||
install needs no plugin for those surfaces or ordinary inbound files. The optional relay on `:8767` adds
|
||||
terminal, bridge phone control, media compatibility/metadata, machine tools, and
|
||||
relay-side voice, which is preferred automatically when paired. One QR can
|
||||
configure API, dashboard, and relay routes without merging their auth models.
|
||||
|
||||
|
||||
-109
@@ -1,109 +0,0 @@
|
||||
<p align="center">
|
||||
<img src="assets/play-store-feature-1024x500.png" alt="Hermes-Relay — 随身携带您的 Hermes 代理" width="800">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>运行在您的电脑上,连接到您的设备。</strong><br>
|
||||
Hermes-Relay 是 <a href="https://github.com/NousResearch/hermes-agent">Hermes Agent</a> 的原生 Android 客户端,提供流式聊天、免手动语音和代理管理;另有单文件 CLI,让代理在已配对的电脑上安全使用终端、文件和截图工具。
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>简体中文</strong> · <a href="README.md">English</a><br>
|
||||
<a href="https://hermes-relay.dev/docs/zh-CN/">中文文档</a> ·
|
||||
<a href="https://github.com/Codename-11/hermes-relay/releases">版本下载</a> ·
|
||||
<a href="https://github.com/Codename-11/hermes-relay/discussions">社区讨论</a> ·
|
||||
<a href="CHANGELOG.md">更新日志</a>
|
||||
</p>
|
||||
|
||||
> 英文 [README.md](README.md) 是最新、完整的项目说明。本页维护中文安装入口和核心功能摘要;协议、架构和维护者文档以英文版本为准。
|
||||
|
||||
## 功能简介
|
||||
|
||||
- **Android 应用**:流式聊天、会话历史、文件附件、Hermes 管理、语音模式、原生插件页面、Petdex 悬浮宠物、多连接和配置文件;也可将 Hermes 设为 Android 助手。
|
||||
- **无需插件的标准路径**:聊天、管理和标准语音可直接连接未修改的上游 Hermes Agent。
|
||||
- **可选 Relay 插件**:增加终端、手机控制、媒体传输、通知助手、Relay 语音、电脑工具,以及需确认的代理创建插件页面草稿。
|
||||
- **安全连接**:二维码配对、Android Keystore、证书固定、按通道授权和可配置会话有效期。
|
||||
- **远程使用**:可配置 Tailscale 或 HTTPS 地址,在家庭局域网和远程路由之间自动切换。
|
||||
- **两种 Android 发行渠道**:Google Play 版本适合日常使用;sideload 版本包含完整手机控制能力。
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. 安装 Android 应用
|
||||
|
||||
- [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay):自动更新,包含聊天、语音、管理、终端、媒体和通知功能。
|
||||
- [GitHub Releases](https://github.com/Codename-11/hermes-relay/releases):下载最新 `android-v*` 版本中以 `-sideload-release.apk` 结尾的文件,获得完整手机控制功能。
|
||||
|
||||
### 2. 启动 Hermes API 服务
|
||||
|
||||
手机需要能够访问 Hermes API 服务,并使用 API 密钥进行身份验证:
|
||||
|
||||
```bash
|
||||
hermes setup --portal
|
||||
|
||||
mkdir -p ~/.hermes
|
||||
API_SERVER_KEY="$(openssl rand -hex 32)"
|
||||
cat >> ~/.hermes/.env <<EOF
|
||||
API_SERVER_ENABLED=true
|
||||
API_SERVER_HOST=0.0.0.0
|
||||
API_SERVER_PORT=8642
|
||||
API_SERVER_KEY=$API_SERVER_KEY
|
||||
EOF
|
||||
chmod 600 ~/.hermes/.env
|
||||
|
||||
echo "Android API URL: http://<电脑IP>:8642 key: $API_SERVER_KEY"
|
||||
hermes gateway
|
||||
```
|
||||
|
||||
`0.0.0.0` 会让同一网络中的设备访问 API。请保留强密钥;离开可信局域网时,应使用 Tailscale 或 HTTPS 反向代理,不要直接把端口暴露到互联网。
|
||||
|
||||
### 3. 在手机上连接
|
||||
|
||||
打开应用后,可以:
|
||||
|
||||
- 扫描局域网中的 Hermes;
|
||||
- 手动输入 `http://<主机>:8642` 和 API 密钥;
|
||||
- 扫描包含 API、Dashboard 和可选 Relay 地址的设置二维码。
|
||||
|
||||
如需在手机上管理模型、密钥、技能和配置文件,请运行 Hermes Dashboard,并在应用的 **管理** 页面登录一次。同一登录会话也会启用标准语音。
|
||||
|
||||
### 4. 可选:安装 Relay
|
||||
|
||||
仅在需要终端、手机控制、媒体路由、Relay 会话、实时语音、电脑工具或代理创建插件页面草稿时安装:
|
||||
|
||||
```bash
|
||||
hermes plugins install Codename-11/hermes-relay/plugin --enable
|
||||
hermes relay doctor
|
||||
hermes relay start --no-ssl
|
||||
hermes pair
|
||||
```
|
||||
|
||||
已安装的 Hermes 插件可通过已认证的 Dashboard 向 Android 提供由应用安全渲染的原生页面,无需在手机上运行插件代码。Relay 1.5.0 另支持需用户确认的代理创建页面草稿。
|
||||
|
||||
完整说明请阅读[中文快速开始](https://hermes-relay.dev/docs/zh-CN/guide/quick-start);远程访问、协议和高级配置暂时链接到英文参考文档。
|
||||
|
||||
安装问题、早期想法、一般交流和作品分享请使用 [GitHub Discussions](https://github.com/Codename-11/hermes-relay/discussions)。可复现的错误和明确、可执行的功能请求请提交到 [Issues](https://github.com/Codename-11/hermes-relay/issues/new)。
|
||||
|
||||
## 中文界面
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/Zh01.jpg" alt="中文设置界面" width="100%"><br><sub><b>设置</b></sub></td>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/Zh02.jpg" alt="中文管理界面" width="100%"><br><sub><b>管理</b></sub></td>
|
||||
<td align="center" width="33%"><img src="assets/screenshots/Zh03.jpg" alt="中文导航界面" width="100%"><br><sub><b>导航</b></sub></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 参与翻译
|
||||
|
||||
Android 英文资源是规范来源。新增语言必须保持资源名称、类型和格式参数一致,并通过:
|
||||
|
||||
```bash
|
||||
python scripts/check-android-locales.py
|
||||
./gradlew lint
|
||||
```
|
||||
|
||||
翻译规范、目录命名、复数和占位符规则见 [docs/localization.md](docs/localization.md)。
|
||||
|
||||
## 许可证
|
||||
|
||||
[MIT](LICENSE) — Copyright (c) 2026 [Axiom-Labs](https://codename-11.dev)
|
||||
+87
-45
@@ -628,6 +628,21 @@ and the release notes and learn only what the software does.
|
||||
|
||||
### 3. Build and verify locally
|
||||
|
||||
During release-note/version iteration, use the narrow release-prep lane:
|
||||
|
||||
```powershell
|
||||
python scripts/android-prepush.py --release-prep
|
||||
```
|
||||
|
||||
It runs release metadata checks plus the rendered Changelog/What's New tests in
|
||||
the serialized Android lane. Once the exact commit is pushed, current-head CI
|
||||
and Play preflight own lint, focused shards, both-flavor assemblies, signing,
|
||||
and final package scans. Do not repeat the complete local release build unless
|
||||
cloud execution is unavailable or explicit local artifact/device proof is
|
||||
needed.
|
||||
|
||||
For that explicit full local proof:
|
||||
|
||||
```bat
|
||||
scripts\dev.bat bundle
|
||||
keytool -printcert -jarfile app\build\outputs\bundle\googlePlayRelease\hermes-relay-*-googlePlay-release.aab
|
||||
@@ -661,14 +676,17 @@ The preflight workflow:
|
||||
3. builds and release-signs the same APK/AAB variants used by the public release;
|
||||
4. scans the final minified APK DEX for unsupported collection calls;
|
||||
5. uploads the Google Play AAB as a private **Production draft**; and
|
||||
6. records a 30-day preflight proof keyed to the version and Git tree hash.
|
||||
6. retains the exact signed sideload APK, Play AAB, R8 mappings, manifest, and
|
||||
checksums as one immutable 30-day artifact keyed to version and Git tree.
|
||||
|
||||
No sideload APK or GitHub Release is published by preflight. A successful signed
|
||||
build, final DEX scan, and Production-draft upload is the automated Play release
|
||||
gate. Play Console pre-review and pre-launch reports are informational and
|
||||
non-blocking because their detailed results are not exposed through the release
|
||||
automation API. If the release source changes after preflight, rerun it—the
|
||||
approval workflow matches the complete Git tree, not just the version number.
|
||||
build, final package scans, and Production-draft upload is the automated Play
|
||||
release gate. The private artifact is immutable and hash-verified again before
|
||||
publication; the stable release workflow does not rebuild those bytes. Play
|
||||
Console pre-review and pre-launch reports are informational and non-blocking
|
||||
because their detailed results are not exposed through the release automation
|
||||
API. If the release source changes after preflight, rerun it—the approval
|
||||
workflow matches the complete Git tree, not just the version number.
|
||||
|
||||
GitHub exposes manual workflows only after their workflow file exists on the
|
||||
default branch. For the first release that introduces this process, merge the
|
||||
@@ -709,12 +727,13 @@ from `main`; every release job explicitly checks out and verifies the immutable
|
||||
an existing tag or changing its artifact tree. Manual stable tags are still
|
||||
guarded by the same preflight proof in the tag workflow.
|
||||
|
||||
The tag-triggered `.github/workflows/release-android.yml` rebuilds and scans the
|
||||
artifacts, changes the existing Play Production draft to `completed` (submitting
|
||||
it for review), and only after Play accepts that operation creates the public
|
||||
GitHub Release with the sideload APK. A missing preflight, changed release tree,
|
||||
missing Play credential, or Play submission failure prevents public GitHub
|
||||
publication.
|
||||
The tag-triggered `.github/workflows/release-android.yml` downloads the exact
|
||||
private preflight artifact by ID, verifies its source workflow, manifest, tree,
|
||||
version, sizes, and hashes, reruns the package scanners, then changes the
|
||||
existing Play Production draft to `completed` (submitting it for review). Only
|
||||
after Play accepts that operation does it publish those same APK/AAB bytes on
|
||||
GitHub. A missing preflight, changed release tree, artifact mismatch, missing
|
||||
Play credential, or Play submission failure prevents public publication.
|
||||
|
||||
Plugin/Python version files are intentionally not part of an Android app
|
||||
release unless the plugin package itself is also being released.
|
||||
@@ -743,14 +762,19 @@ git commit -m "release(server): server-v0.6.2"
|
||||
git push origin dev
|
||||
|
||||
# Open the release PR (dev -> main) and merge with --no-ff.
|
||||
# After merge, tag from the new main tip:
|
||||
git checkout main
|
||||
git pull --ff-only origin main
|
||||
git tag server-v0.6.2
|
||||
git push origin server-v0.6.2
|
||||
# Then run "Hermes-Relay Plugin and CLI+UI Release Approval" from main,
|
||||
# select plugin, and enter 0.6.2. The workflow selects and validates main
|
||||
# before it creates server-v0.6.2 and starts the immutable-tag release workflow.
|
||||
```
|
||||
|
||||
Pushing `server-v*` triggers `.github/workflows/release-plugin.yml`, which
|
||||
For a Plugin prerelease, keep the release-prepared commit on `dev` and run the
|
||||
same trusted approval workflow from `main`; the version suffix makes it select
|
||||
and validate the exact `origin/dev` tip before creating the tag. Stable versions
|
||||
select `origin/main` instead.
|
||||
Direct `server-v*` tag pushes remain a recovery path and are guarded by the same
|
||||
branch-containment and metadata checks.
|
||||
|
||||
The approval workflow dispatches `.github/workflows/release-plugin.yml`, which
|
||||
validates all plugin-owned version metadata with
|
||||
`scripts/check-plugin-version-sync.py`. Run
|
||||
`python scripts/check-version-tracks.py` locally before tagging when a change
|
||||
@@ -781,20 +805,25 @@ git add desktop/package.json desktop/package-lock.json desktop/src/version.ts `
|
||||
git commit -m "release(desktop): desktop-v0.4.0-alpha.2"
|
||||
git push origin dev
|
||||
|
||||
# Open the release PR (dev -> main) and merge with --no-ff.
|
||||
# After merge, tag from main:
|
||||
git switch main
|
||||
git pull --ff-only origin main
|
||||
cd desktop
|
||||
npm run check:version-sync -- --expect 0.4.0-alpha.2
|
||||
cd ..
|
||||
git tag desktop-v0.4.0-alpha.2
|
||||
git push origin desktop-v0.4.0-alpha.2
|
||||
# This is a prerelease: run "Hermes-Relay Plugin and CLI+UI Release Approval"
|
||||
# from main, select desktop, and enter 0.4.0-alpha.2. The workflow validates dev
|
||||
# before it creates the tag and starts the immutable-tag release workflow.
|
||||
```
|
||||
|
||||
The tag workflow rejects version drift and tags whose commit is not in
|
||||
`origin/main`, reruns CLI tests, builds all four standalone binaries, tests and
|
||||
packages the Windows tray, generates checksums, and publishes the GitHub Release.
|
||||
For a stable CLI+UI version, first merge the release PR from `dev` to `main`,
|
||||
then run the approval workflow from `main`. The version determines the source:
|
||||
prereleases select the exact `origin/dev` tip and stable releases select the
|
||||
exact `origin/main` tip before creating any tag. Direct `desktop-v*` tag pushes
|
||||
remain a recovery path.
|
||||
|
||||
The release workflow rejects version drift and requires prerelease tags to be
|
||||
contained in `origin/dev` and stable tags to be contained in `origin/main`. It
|
||||
reruns CLI tests, builds all four standalone binaries, tests and packages the
|
||||
Windows tray, generates checksums, and publishes the GitHub Release.
|
||||
Trusted desktop CI and the release installer job share a Cargo/target cache
|
||||
keyed by the lockfile and exact tray sources. A `main` push for the release tree
|
||||
warms the exact cache before the immutable tag build; a miss safely performs the
|
||||
ordinary Rust/Tauri build.
|
||||
|
||||
### 6. Play review and publishing behavior
|
||||
|
||||
@@ -895,7 +924,7 @@ gradlew promoteReleaseArtifact --from-track=internal --promote-track=production
|
||||
(This step was only needed as a retrofit for v0.1.0 — v0.1.1+ inherit
|
||||
the Download section automatically from `RELEASE_NOTES.md`.)
|
||||
- Confirm Play Console shows the new versionCode on the target track.
|
||||
- Update `DEVLOG.md` with a short entry for the release.
|
||||
- Update `docs/project/DEVLOG.md` with a short entry for the release.
|
||||
|
||||
## CI Behavior
|
||||
|
||||
@@ -903,28 +932,40 @@ Android, Plugin, dashboard, and desktop now have separate CI/release lanes.
|
||||
This keeps a dashboard CSS fix from running the full server suite, and keeps
|
||||
plugin changes from forcing an Android app `versionCode` bump.
|
||||
|
||||
Every successful `Required checks` run records a short-lived proof keyed to the
|
||||
checked Git tree. For the canonical `dev` → `main` release PR, CI first proves
|
||||
the simulated merge tree is identical to the `dev` tree. If an unexpired proof
|
||||
from a successful Required-checks run exists, the PR verifies and reuses it;
|
||||
otherwise it automatically falls back to the normal path-aware matrix. Content
|
||||
changes can never reuse an older proof because they change the tree hash.
|
||||
|
||||
On every push of a tag matching `android-v*`, `.github/workflows/release-android.yml`:
|
||||
|
||||
1. Verifies a stable tag resolves to a commit contained in `main`, or a
|
||||
prerelease tag resolves to a commit contained in `dev`, and that the tag matches `appVersionName` in
|
||||
`gradle/libs.versions.toml` (mismatches fail the workflow).
|
||||
2. Runs the Android debug build and the stable sideload pairing/connection
|
||||
regression slice with explicit timeouts.
|
||||
3. Decodes `HERMES_KEYSTORE_BASE64` into `$RUNNER_TEMP/release.keystore`
|
||||
and exports `HERMES_KEYSTORE_PATH` (skipped if the secret is unset).
|
||||
4. For stable releases, builds all four flavored release artifacts
|
||||
(`./gradlew bundleRelease assembleRelease`); only the sideload APK and
|
||||
googlePlay AAB are attached. For prereleases, builds only the side-by-side
|
||||
`sideloadCandidate` APK.
|
||||
5. Generates `SHA256SUMS.txt` covering the two attached files.
|
||||
6. For stable releases only, promotes the exact preflighted Production draft to
|
||||
2. For stable releases, verifies and downloads the exact immutable Play
|
||||
preflight artifact; prereleases run the focused CI slice and build the
|
||||
side-by-side `sideloadCandidate` APK.
|
||||
3. Revalidates stable artifact hashes, DEX collection compatibility, packaged
|
||||
native compatibility, and retained R8 mappings without recompiling.
|
||||
4. Generates candidate checksums when applicable; stable checksums come from
|
||||
the verified preflight artifact and cover the two public files.
|
||||
5. For stable releases only, promotes the exact preflighted Production draft to
|
||||
`completed`; prereleases never upload to Play.
|
||||
7. Creates a GitHub Release named `Hermes-Relay Android v<version>` with `RELEASE_NOTES.md` as
|
||||
6. Creates a GitHub Release named `Hermes-Relay Android v<version>` with `RELEASE_NOTES.md` as
|
||||
the body. Attaches the APK, AAB, and `SHA256SUMS.txt`. Tags any version
|
||||
containing a dash (e.g. `android-v0.2.0-beta.1`) as a prerelease automatically.
|
||||
8. Prints a `$GITHUB_STEP_SUMMARY` with the release and Play result.
|
||||
7. Prints a `$GITHUB_STEP_SUMMARY` with the release and Play result.
|
||||
|
||||
On every push of a tag matching `server-v*`,
|
||||
For an approved multi-surface train, run **Hermes-Relay Coordinated Release
|
||||
Approval** from `main`, select the affected surfaces, and enter their prepared
|
||||
versions. It dispatches Android, Plugin, and CLI+UI approval jobs concurrently;
|
||||
each surface keeps its independent source, validation, tag, artifact, and
|
||||
publication workflow.
|
||||
|
||||
On every direct push of a tag matching `server-v*`, or after an approved
|
||||
dispatch from `.github/workflows/approve-release-extensions.yml`,
|
||||
`.github/workflows/release-plugin.yml`:
|
||||
|
||||
1. Verifies a stable tag commit is contained in `main`, or a prerelease tag is
|
||||
@@ -937,7 +978,8 @@ On every push of a tag matching `server-v*`,
|
||||
5. Creates a GitHub Release named `Hermes-Relay Plugin v<version>` with the wheel,
|
||||
sdist, and checksum file attached.
|
||||
|
||||
On every push of a tag matching `desktop-v*`,
|
||||
On every direct push of a tag matching `desktop-v*`, or after an approved
|
||||
dispatch from `.github/workflows/approve-release-extensions.yml`,
|
||||
`.github/workflows/release-cli.yml` builds and publishes the CLI binaries and
|
||||
Windows tray installer. Its GitHub Release body comes from `CLI_RELEASE_NOTES.md`
|
||||
(rewritten per release — the CLI counterpart of `RELEASE_NOTES.md`); the workflow
|
||||
|
||||
+20
-24
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay Android v1.14.0
|
||||
# Hermes-Relay Android v1.15.1
|
||||
|
||||
**Release Date:** August 30, 2026
|
||||
**Release Date:** September 2, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.14.0-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.15.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).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,33 +12,29 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This release makes saved Hermes connections reliable across LAN, Tailscale, and public HTTPS while keeping Dashboard authentication bound to its exact trusted origin. It also adds delegated-agent previews and an optional native Git workspace, and improves Voice, Assistant, Threads, profile drafts, and Clarify interactions.
|
||||
|
||||
## Added
|
||||
|
||||
- **Delegated-agent previews.** Follow bounded lifecycle, progress, tool previews, and available read-only child history without leaving the parent chat. Partial history and reconnect gaps remain explicit. (#447)
|
||||
- **Native Git workspace.** Review repository state, diffs, branches, staging, commits, and remotes from Chat or Settings. Git operations require Hermes-Relay Plugin v1.11.0 and retain confirmation and grant boundaries.
|
||||
This patch improves chat, media, and voice reliability. It reduces memory-heavy work, keeps attachment previews stable through rotation, and makes follow-up message behavior and voice errors easier to understand.
|
||||
|
||||
## Changed
|
||||
|
||||
- **Route-aware connections.** Dashboard, Relay, and optional API health are evaluated independently across LAN, Tailscale, and public HTTPS. Same-origin Relay ingress stays on the Dashboard origin that owns authentication, while direct compatibility routes keep separate credentials. (Related: #399)
|
||||
- **Voice Focus controls.** Stop and immediate spoken steering remain accessible while Hermes is Thinking, Transcribing, or Speaking, including TalkBack, Switch Access, keyboard, and sideload overlay surfaces.
|
||||
- Choose Correct now or Queue next from a slim tray behind the composer. Chat settings sets the default; the tray overrides one message. Stop pauses the queue, Resume continues it, and editing or removing an item preserves its successors.
|
||||
- Chat and Voice use readable centered layouts on wider screens, including landscape Voice Focus.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Wake-word detection packages one compatible ONNX Runtime for sherpa and Java JNI on every supported ABI. (#444)
|
||||
- Continuous voice waits for barge-in microphone teardown before listening again. (#464)
|
||||
- Fresh chats retain their selected profile without reopening a previous session or carrying a proactive Thread route across profiles. (#436)
|
||||
- Provisional Threads can be removed locally and reconcile with promoted sessions without deleting server history. (#461)
|
||||
- Clarify cards expose a reachable Other answer, keyboard Send, and authoritative expiry behavior. (#446)
|
||||
- Passive Android browsing no longer claims or interrupts a turn owned by another client. (Related: #365)
|
||||
- Assistant sessions show retryable no-speech feedback, recover their active state after recreation, and redact conversation details behind the keyguard. (Related: #424)
|
||||
- Protected Relay ingress `401/403` responses are recognized as authentication boundaries rather than outages; malformed, different-origin, and direct unauthorized routes still fail closed.
|
||||
- Correction and delivery labels remain visible inside user-message bubbles.
|
||||
- Voice errors open in a scrollable dialog with separate Retry and Dismiss actions.
|
||||
- Attachment previews remain open through rotation, and video previews preserve their proportions.
|
||||
- Release optimization preserves the native speech configuration required for wake-word startup.
|
||||
- Standard Hermes attachments download directly to disk with bounded size checks.
|
||||
- Session refresh avoids repeated request loops; history loads, Markdown, image previews, and media exports keep memory use bounded.
|
||||
- Image-generation progress stays visible through gaps between interim replies and returned media.
|
||||
- The first prompt waits for Gateway session readiness. Ownership refusals retain the prompt for retry and show the original server error.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.14.0** (versionCode **52**).
|
||||
- Standard Chat, sessions, profiles, Manage, and standard voice continue to work against unmodified upstream Hermes without the optional Relay plugin.
|
||||
- Install Hermes-Relay Plugin v1.11.0 for same-origin Relay extensions, Git workspace actions, Bridge, media, proactive features, and enhanced voice.
|
||||
- Granular Device Control and the system Voice Focus overlay remain sideload-only; the Google Play build does not declare their restricted permissions.
|
||||
- Existing connections, drafts, sessions, profile ownership, and legacy direct Relay routes remain data-preserving compatibility paths.
|
||||
- App version: **1.15.1** (versionCode **54**).
|
||||
- Standard Chat, sessions, profiles, Manage, voice, and ordinary media use current upstream Hermes. Speech-to-text still requires a configured provider on the host.
|
||||
- Hermes-Relay Plugin **1.11.1** remains the current optional plugin release; this Android patch does not require a new plugin version.
|
||||
- Paused text queues can be restored. Attachment bytes are not persisted in preferences; unrestorable attachment queues must be reviewed and sent again.
|
||||
- Explicit Direct API/API-only connections remain supported and are not used as silent failover for Dashboard-owned chats.
|
||||
- Granular Device Control and the system Voice Focus overlay remain sideload-only.
|
||||
|
||||
@@ -367,8 +367,9 @@ dependencies {
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.okhttp.sse)
|
||||
|
||||
// Media3 ExoPlayer — gapless TTS queue playback (replaces MediaPlayer in VoicePlayer)
|
||||
// Media3 ExoPlayer + lifecycle-aware Compose video surface.
|
||||
implementation(libs.media3.exoplayer)
|
||||
implementation(libs.media3.ui.compose)
|
||||
|
||||
// android-vad Silero — on-device VAD for barge-in (B2)
|
||||
// Bundled ONNX Silero model (~2.2 MB); pulled from JitPack.
|
||||
|
||||
Vendored
+3
@@ -55,6 +55,9 @@
|
||||
-keep class androidx.camera.** { *; }
|
||||
-dontwarn androidx.camera.**
|
||||
|
||||
# sherpa-onnx JNI resolves Kotlin configuration classes and fields by name.
|
||||
-keep class com.k2fsa.sherpa.onnx.** { *; }
|
||||
|
||||
# ── General ──────────────────────────────────────────────────────────
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
-renamesourcefileattribute SourceFile
|
||||
|
||||
+79
@@ -15,6 +15,10 @@ import androidx.compose.ui.test.assertTextEquals
|
||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onAllNodesWithText
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onAllNodesWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
@@ -171,6 +175,81 @@ class GatewayExternalFixtureInstrumentedTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun queuedStopResume_preservesWorkAcrossLifecycleAndUsesExplicitResume() {
|
||||
val base = InstrumentationRegistry.getArguments().getString(ARG_FIXTURE_BASE_URL)?.trimEnd('/')
|
||||
assumeTrue("Pass a queued_stop_resume fixture URL", !base.isNullOrBlank())
|
||||
requireNotNull(base)
|
||||
val http = OkHttpClient.Builder().callTimeout(10, TimeUnit.SECONDS).build()
|
||||
assertEquals("queued_stop_resume", readFixtureJson(http, "$base/__fixture__/state")["scenario"]?.jsonString())
|
||||
val dashboard = DashboardApiClient(base, http)
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO).also { gatewayScope = it }
|
||||
val gateway = GatewayChatClient(
|
||||
initialDashboardClient = dashboard, okHttpClient = http, scope = scope,
|
||||
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||
reconnectJitterUnit = { 0.0 },
|
||||
).also { gatewayClient = it }
|
||||
val handler = ChatHandler().also { it.setSessionId(STORED_SESSION_ID) }
|
||||
val vm = ChatViewModel().also {
|
||||
it.initialize(null, handler)
|
||||
it.streamingEndpoint = "gateway"
|
||||
it.setProfileMessageLoaderWithMode { profile, session, mode -> dashboard.getSessionMessages(session, profile, mode) }
|
||||
it.updateGatewayClient(gateway)
|
||||
it.switchProfileContext(com.hermesandroid.relay.data.AgentDisplay.profileContextKey("fixture-queue", null), STORED_SESSION_ID)
|
||||
}.also { viewModel = it }
|
||||
compose.setContent {
|
||||
val queue by vm.queuedMessages.collectAsStateWithLifecycle()
|
||||
val paused by vm.queuePaused.collectAsStateWithLifecycle()
|
||||
com.hermesandroid.relay.ui.theme.HermesRelayTheme(themePreference = "dark") {
|
||||
androidx.compose.material3.Surface {
|
||||
Column {
|
||||
com.hermesandroid.relay.ui.components.ChatBusyActionSelector(
|
||||
com.hermesandroid.relay.data.BusyMessageAction.QueueNext, {}, onStop = vm::cancelStream,
|
||||
)
|
||||
com.hermesandroid.relay.ui.components.ChatMessageQueue(
|
||||
queue, paused, vm::resumeQueue, vm::clearQueue, {}, vm::removeQueuedAt, canEdit = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(runBlocking { gateway.prewarmAwait(STORED_SESSION_ID) })
|
||||
compose.runOnIdle { vm.sendMessage("Original work") }
|
||||
compose.waitUntil(10_000) { handler.isStreaming.value && vm.steerableTurn.value }
|
||||
compose.runOnIdle {
|
||||
vm.sendMessage("Remove this follow-up", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
vm.sendMessage("Keep this follow-up", com.hermesandroid.relay.data.BusyMessageAction.QueueNext)
|
||||
}
|
||||
compose.onAllNodesWithContentDescription("Remove queued message")[0].performClick()
|
||||
compose.onNodeWithContentDescription("Stop streaming").performClick()
|
||||
compose.onNodeWithText("Queue paused").assertIsDisplayed()
|
||||
assertEquals(listOf("Keep this follow-up"), vm.queuedMessages.value)
|
||||
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.CREATED)
|
||||
compose.activityRule.scenario.moveToState(androidx.lifecycle.Lifecycle.State.RESUMED)
|
||||
compose.onNodeWithText("Keep this follow-up").assertIsDisplayed()
|
||||
compose.onNodeWithText("Resume").performClick()
|
||||
try {
|
||||
compose.waitUntil(15_000) {
|
||||
vm.queuedMessages.value.isEmpty() && !handler.isStreaming.value &&
|
||||
handler.messages.value.any { it.content == "Resumed follow-up." }
|
||||
}
|
||||
} catch (error: androidx.compose.ui.test.ComposeTimeoutException) {
|
||||
throw AssertionError(
|
||||
"Synthetic queue fixture did not settle: queued=${vm.queuedMessages.value.size}, " +
|
||||
"paused=${vm.queuePaused.value}, streaming=${handler.isStreaming.value}, " +
|
||||
"messages=${handler.messages.value.map { it.role to it.content }}, " +
|
||||
"error=${handler.error.value}",
|
||||
error,
|
||||
)
|
||||
}
|
||||
val evidence = readFixtureJson(http, "$base/__fixture__/evidence")["entries"] as JsonArray
|
||||
assertEquals(2, evidence.rpcCount("prompt.submit"))
|
||||
assertEquals(1, evidence.rpcCount("session.interrupt"))
|
||||
assertEquals(0, evidence.rpcCount("session.redirect"))
|
||||
assertEquals("gateway", vm.streamingEndpoint)
|
||||
}
|
||||
|
||||
private fun JsonArray.rpcCount(method: String): Int = count { element ->
|
||||
val entry = element as? JsonObject ?: return@count false
|
||||
entry["kind"]?.jsonString() == "rpc" && entry["method"]?.jsonString() == method
|
||||
|
||||
+40
@@ -258,6 +258,46 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun terminalGapActiveList_settlesExactOwnedTurnAndRendersAuthoritativeHistory() {
|
||||
viewModel.sendMessage("Run an Android-owned task")
|
||||
fixture.awaitRpc("prompt.submit")
|
||||
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||
serverSocket.send(
|
||||
fixture.event(
|
||||
"message.delta",
|
||||
buildJsonObject { put("text", PARTIAL_ANSWER) },
|
||||
LIVE_SESSION_ID,
|
||||
),
|
||||
)
|
||||
compose.waitUntil(5_000) { handler.isStreaming.value }
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("STREAMING")
|
||||
|
||||
persistedHistory = listOf(
|
||||
MessageItem(
|
||||
id = PERSISTED_ANSWER_ID,
|
||||
sessionId = STORED_SESSION_ID,
|
||||
role = "assistant",
|
||||
content = JsonPrimitive(AUTHORITATIVE_ANSWER),
|
||||
),
|
||||
)
|
||||
fixture.activeSessionStatus = "idle"
|
||||
runBlocking { gatewayClient.listActiveSessions() }
|
||||
|
||||
compose.waitUntil(5_000) {
|
||||
!handler.isStreaming.value &&
|
||||
!gatewayClient.hasActiveTurn() &&
|
||||
handler.messages.value.singleOrNull()?.id == PERSISTED_ANSWER_ID
|
||||
}
|
||||
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||
compose.onNodeWithTag("message-$PERSISTED_ANSWER_ID")
|
||||
.assertTextEquals("${MessageRole.ASSISTANT.name}:$AUTHORITATIVE_ANSWER")
|
||||
assertEquals(1, fixture.rpcCount("prompt.submit"))
|
||||
assertEquals(0, fixture.rpcCount("session.interrupt"))
|
||||
assertEquals(0, fixture.rpcCount("session.activate"))
|
||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
||||
viewModel.setChatVisible(false)
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 509 KiB |
@@ -1,3 +1,3 @@
|
||||
v1.14.0 - Connections, delegated work, Git, and voice
|
||||
v1.15.1 - Steadier chat, media, and voice
|
||||
|
||||
Connections now recover independently across LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication. Preview delegated agents, use the optional native Git workspace, and get safer Continuous voice, Voice Focus, Assistant, Threads, profile drafts, and Clarify controls. Wake-word detection also packages a compatible native runtime.
|
||||
More reliable chats and media: fewer memory-heavy refreshes, smoother large histories, and attachment previews that survive rotation. Choose whether follow-ups correct the current response or wait in a queue. Voice errors are easier to read, image-generation progress stays visible, and wake-word startup and first-message readiness are fixed.
|
||||
|
||||
@@ -1,6 +1,185 @@
|
||||
{
|
||||
"schema": 3,
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.15.1",
|
||||
"title": "Steadier chat, media, and voice",
|
||||
"date": "2026-09-02",
|
||||
"summary": "Chats use less memory, attachment previews stay in place, and voice failures are easier to recover from. Follow-up controls make it clear whether a message changes the current response or waits for the next turn.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "follow-up-controls",
|
||||
"kind": "improved",
|
||||
"title": "Choose when follow-up messages are sent",
|
||||
"summary": "A slim tray behind the composer offers Correct now or Queue next. Chat settings sets the default, and a composer choice applies to one message. Stop pauses pending work until Resume; editing or removing an item keeps the remaining queue usable.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "tablet-layouts",
|
||||
"kind": "improved",
|
||||
"title": "Make better use of wider screens",
|
||||
"summary": "Chat and Voice keep text and controls on readable centered layouts. Landscape Voice Focus separates identity controls from conversation activity."
|
||||
},
|
||||
{
|
||||
"id": "delivery-labels",
|
||||
"kind": "fixed",
|
||||
"title": "Read message delivery status clearly",
|
||||
"summary": "Correction and delivery labels use contrasting text instead of disappearing into the message bubble."
|
||||
},
|
||||
{
|
||||
"id": "voice-error-dialog",
|
||||
"kind": "fixed",
|
||||
"title": "Read and dismiss voice errors",
|
||||
"summary": "Voice errors open in a contained dialog with scrollable details and separate Retry and Dismiss actions, without overlapping chat controls."
|
||||
},
|
||||
{
|
||||
"id": "attachment-previews",
|
||||
"kind": "fixed",
|
||||
"title": "Keep attachment previews open through rotation",
|
||||
"summary": "Image, video, audio, PDF, text, and file previews stay open as the screen rotates. Videos retain their original proportions.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "wake-word-startup",
|
||||
"kind": "fixed",
|
||||
"title": "Fix wake-word startup in release builds",
|
||||
"summary": "Release optimization now preserves the native speech configuration names needed to initialize wake-word detection."
|
||||
},
|
||||
{
|
||||
"id": "attachment-downloads",
|
||||
"kind": "fixed",
|
||||
"title": "Download attachments with less memory",
|
||||
"summary": "Standard Hermes attachments stream into the on-disk cache while download size limits remain enforced."
|
||||
},
|
||||
{
|
||||
"id": "chat-memory-safety",
|
||||
"kind": "fixed",
|
||||
"title": "Keep large chats and media manageable",
|
||||
"summary": "Automatic session refresh no longer loops. Routine history loads, chat rendering, image previews, and media exports use bounded memory instead of allocating entire large responses.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "image-progress",
|
||||
"kind": "fixed",
|
||||
"title": "Keep image-generation progress visible",
|
||||
"summary": "The working indicator stays visible between interim replies and the generated image, including gateways that omit tool activity events."
|
||||
},
|
||||
{
|
||||
"id": "first-message-readiness",
|
||||
"kind": "fixed",
|
||||
"title": "Wait for new chats to be ready",
|
||||
"summary": "The first message waits for the Gateway session to initialize. Ownership refusals keep the prompt retryable and show the server's error."
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Standard Chat, sessions, media, and voice continue to use upstream Hermes. Voice transcription still requires a configured speech-to-text provider on the Hermes host.",
|
||||
"Paused text queues can be restored. Attachment bytes are not stored in preferences; an attachment queue that cannot be restored must be reviewed and sent again."
|
||||
],
|
||||
"playNotes": "More reliable chats and media: fewer memory-heavy refreshes, smoother large histories, and attachment previews that survive rotation. Choose whether follow-ups correct the current response or wait in a queue. Voice errors are easier to read, image-generation progress stays visible, and wake-word startup and first-message readiness are fixed.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.15.0",
|
||||
"title": "Standard Hermes first, with clearer Relay boundaries",
|
||||
"date": "2026-08-31",
|
||||
"summary": "Chat, voice, attachments, inbound files, current-session Git, usage, and Hermes notices now prefer current upstream Dashboard and Gateway support. Relay stays optional for compatibility and the tools it uniquely provides.",
|
||||
"changes": [
|
||||
{
|
||||
"id": "upstream-standard-surfaces",
|
||||
"kind": "improved",
|
||||
"title": "Use standard Hermes without Relay prompts",
|
||||
"summary": "Chat attachments, inbound files, current-session Git, Nous usage, and Hermes notices use upstream routes first.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "stable-inbound-media",
|
||||
"kind": "fixed",
|
||||
"title": "Keep returned files loaded",
|
||||
"summary": "Images, audio, video, and documents download through the Dashboard and no longer flash Relay errors or return to Loading.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "supervised-parent-access",
|
||||
"kind": "improved",
|
||||
"title": "Use app-specific parent access",
|
||||
"summary": "A parent PIN or password plus recovery phrase protects Supervised Mode without trusting the phone unlock credential.",
|
||||
"highlight": true
|
||||
},
|
||||
{
|
||||
"id": "settings-relay-boundaries",
|
||||
"kind": "improved",
|
||||
"title": "See which features need Relay",
|
||||
"summary": "Media sits with standard Hermes settings while Threads, Terminal, notifications, enhanced voice, and device tools stay under Relay tools."
|
||||
},
|
||||
{
|
||||
"id": "complete-release-history",
|
||||
"kind": "improved",
|
||||
"title": "Read the complete release record",
|
||||
"summary": "What's New shows one release summary, selected highlights, every remaining change, and relevant compatibility notes."
|
||||
},
|
||||
{
|
||||
"id": "relay-removal-voice",
|
||||
"kind": "fixed",
|
||||
"title": "Keep Standard voice after removing Relay",
|
||||
"summary": "Dashboard voice remains ready, temporary outages preserve choices, and shared default-profile settings stay isolated."
|
||||
},
|
||||
{
|
||||
"id": "passive-external-activity",
|
||||
"kind": "fixed",
|
||||
"title": "Observe another client's activity safely",
|
||||
"summary": "A uniquely matched Desktop or TUI turn can show Working or Waiting without Android taking control."
|
||||
},
|
||||
{
|
||||
"id": "chat-transport-ownership",
|
||||
"kind": "fixed",
|
||||
"title": "Keep each chat on its chosen transport",
|
||||
"summary": "Dashboard chats preserve their transcript, draft, profile, and session through sign-out or outages instead of silently changing databases."
|
||||
},
|
||||
{
|
||||
"id": "history-auth-recovery",
|
||||
"kind": "fixed",
|
||||
"title": "Preserve completed replies at sign-in expiry",
|
||||
"summary": "A Dashboard history authentication failure keeps completed text visible and opens the existing sign-in recovery path."
|
||||
},
|
||||
{
|
||||
"id": "compaction-watchdog",
|
||||
"kind": "fixed",
|
||||
"title": "Let long context compaction finish",
|
||||
"summary": "Visible compaction activity refreshes the turn watchdog instead of being interrupted as idle."
|
||||
},
|
||||
{
|
||||
"id": "bot-chat-binding",
|
||||
"kind": "fixed",
|
||||
"title": "Render Bot Chat history immediately",
|
||||
"summary": "Route-owned Bot Chats observe their bound history from first composition."
|
||||
},
|
||||
{
|
||||
"id": "missing-terminal-recovery",
|
||||
"kind": "fixed",
|
||||
"title": "Settle turns after a lost terminal frame",
|
||||
"summary": "An exact idle live-session snapshot reconciles the Android-owned turn and drains its queued follow-up."
|
||||
},
|
||||
{
|
||||
"id": "supervised-gateway-setup",
|
||||
"kind": "fixed",
|
||||
"title": "Keep Gateway setup parent-owned",
|
||||
"summary": "Relock and back navigation cancel the exact pending setup without bypassing parent authority."
|
||||
},
|
||||
{
|
||||
"id": "generated-image-retention",
|
||||
"kind": "fixed",
|
||||
"title": "Keep completed generated images visible",
|
||||
"summary": "Generated media survives marker persistence lag and retains its intended Chat animation."
|
||||
}
|
||||
],
|
||||
"compatibility": [
|
||||
"Current upstream Hermes provides standard Chat, sessions, Manage, voice, attachments, inbound files, current-session Git reads, usage, and notices without the optional Hermes-Relay Plugin.",
|
||||
"Hermes-Relay Plugin 1.11.1 remains required for Terminal, proactive Threads and offline delivery, Notification Companion, Relay sessions, enhanced voice, Secure Link, and phone or device control.",
|
||||
"Granular Device Control and the system Voice Focus overlay remain sideload-only."
|
||||
],
|
||||
"playNotes": "Standard Chat, Voice, attachments, returned files, current-session Git, usage, and Hermes notices now prefer upstream Dashboard and Gateway support without requiring Relay. Returned media stays loaded, voice survives Relay removal, and Settings clearly separates standard Hermes from Relay tools. Supervised Mode also gains app-specific parent access and recovery.",
|
||||
"sections": []
|
||||
},
|
||||
{
|
||||
"version": "1.14.0",
|
||||
"title": "Connections, delegated work, Git, and voice",
|
||||
|
||||
@@ -1,31 +1,24 @@
|
||||
v1.14.0 - Connections, delegated work, Git, and voice
|
||||
v1.15.1 - Steadier chat, media, and voice
|
||||
|
||||
Summary
|
||||
* Connections now recover cleanly across networks. You can also follow delegated agents, work with Git repositories, and rely on steadier voice, sessions, Threads, profiles, Assistant, and Clarify controls.
|
||||
* Chats use less memory, attachment previews stay in place, and voice failures are easier to recover from. Follow-up controls make it clear whether a message changes the current response or waits for the next turn.
|
||||
|
||||
Highlights
|
||||
* Connections recover independently — Move between LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication.
|
||||
* Follow delegated-agent activity — See lifecycle, progress, tool previews, and available read-only child history from the parent chat.
|
||||
* Work with repositories from Android — Review status, diffs, branches, staging, commits, and remotes from Chat or Settings.
|
||||
* Steer voice at any time — Stop or redirect Hermes while it is Thinking, Transcribing, or Speaking, including with accessibility controls.
|
||||
* Choose when follow-up messages are sent — A slim tray behind the composer offers Correct now or Queue next. Chat settings sets the default, and a composer choice applies to one message. Stop pauses pending work until Resume; editing or removing an item keeps the remaining queue usable.
|
||||
* Keep attachment previews open through rotation — Image, video, audio, PDF, text, and file previews stay open as the screen rotates. Videos retain their original proportions.
|
||||
* Keep large chats and media manageable — Automatic session refresh no longer loops. Routine history loads, chat rendering, image previews, and media exports use bounded memory instead of allocating entire large responses.
|
||||
|
||||
Improved
|
||||
* Release notes stay out of your way — A dismissible post-update notice keeps startup usable and leaves the complete history available from Settings.
|
||||
* Chat uses one consistent presentation — The overlapping clean-focus mode was removed while the separate Voice Focus experience remains available.
|
||||
* Make better use of wider screens — Chat and Voice keep text and controls on readable centered layouts. Landscape Voice Focus separates identity controls from conversation activity.
|
||||
|
||||
Fixed
|
||||
* Wake-word detection starts reliably — Compatible native voice components are now packaged for every supported phone architecture.
|
||||
* The visible Sphere keeps moving smoothly — Foreground animation no longer falls back to a stepped ambient pulse.
|
||||
* Continuous voice keeps the microphone — The next listening turn waits for barge-in recording to release cleanly.
|
||||
* New chats keep the selected profile — Fresh drafts no longer reopen an older session or carry a Thread route into another profile.
|
||||
* Provisional Threads can be removed safely — Local removal and later session promotion no longer risk duplicate rows or server history.
|
||||
* Clarify keeps custom answers reachable — Other answers, keyboard Send, and expired prompts now behave consistently.
|
||||
* Browsing no longer interrupts another client — Passive Android observation does not claim a turn owned by Desktop, TUI, or another client.
|
||||
* Assistant sessions recover more clearly — No-speech feedback, recreated session state, and keyguard privacy now remain intact.
|
||||
* Protected Relay routes report the right problem — Authentication challenges are no longer presented as outages, while unsafe routes still fail closed.
|
||||
* Connections and sessions become ready sooner — Unavailable optional API and Relay routes no longer delay a healthy Dashboard or authenticated session history.
|
||||
* Read message delivery status clearly — Correction and delivery labels use contrasting text instead of disappearing into the message bubble.
|
||||
* Read and dismiss voice errors — Voice errors open in a contained dialog with scrollable details and separate Retry and Dismiss actions, without overlapping chat controls.
|
||||
* Fix wake-word startup in release builds — Release optimization now preserves the native speech configuration names needed to initialize wake-word detection.
|
||||
* Download attachments with less memory — Standard Hermes attachments stream into the on-disk cache while download size limits remain enforced.
|
||||
* Keep image-generation progress visible — The working indicator stays visible between interim replies and the generated image, including gateways that omit tool activity events.
|
||||
* Wait for new chats to be ready — The first message waits for the Gateway session to initialize. Ownership refusals keep the prompt retryable and show the server's error.
|
||||
|
||||
Compatibility
|
||||
* Standard Chat, sessions, profiles, Manage, and standard voice continue to work without the optional Hermes-Relay Plugin.
|
||||
* The Git workspace and same-origin Relay extensions require Hermes-Relay Plugin 1.11.0.
|
||||
* Granular Device Control and the system Voice Focus overlay remain available only in the sideload build.
|
||||
* Standard Chat, sessions, media, and voice continue to use upstream Hermes. Voice transcription still requires a configured speech-to-text provider on the Hermes host.
|
||||
* Paused text queues can be restored. Attachment bytes are not stored in preferences; an attachment queue that cannot be restored must be reviewed and sent again.
|
||||
|
||||
@@ -22,6 +22,26 @@ enum class PhysicalKeyboardEnterBehavior(val storedValue: String) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Default intent for a message submitted while an agent is responding. */
|
||||
enum class BusyMessageAction(val storedValue: String) {
|
||||
CorrectNow("correct_now"),
|
||||
QueueNext("queue_next");
|
||||
|
||||
companion object {
|
||||
fun fromStoredValue(value: String?): BusyMessageAction =
|
||||
entries.firstOrNull { it.storedValue == value } ?: CorrectNow
|
||||
}
|
||||
}
|
||||
|
||||
fun canCorrectBusyMessage(
|
||||
steerable: Boolean,
|
||||
hasAttachments: Boolean,
|
||||
hasPendingInput: Boolean,
|
||||
status: String?,
|
||||
text: String,
|
||||
): Boolean = steerable && !hasAttachments && !hasPendingInput &&
|
||||
status?.contains("compact", ignoreCase = true) != true && !text.trimStart().startsWith("/")
|
||||
|
||||
/** Device-level chat input preferences shared by every Hermes profile. */
|
||||
class ChatInputPreferencesRepository(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
@@ -29,6 +49,7 @@ class ChatInputPreferencesRepository(
|
||||
constructor(context: Context) : this(context.relayDataStore)
|
||||
|
||||
companion object {
|
||||
internal val KEY_BUSY_MESSAGE_ACTION = stringPreferencesKey("busy_message_action")
|
||||
internal val KEY_PHYSICAL_KEYBOARD_ENTER =
|
||||
stringPreferencesKey("physical_keyboard_enter_behavior")
|
||||
internal val KEY_CONVERT_LARGE_PASTES =
|
||||
@@ -45,6 +66,14 @@ class ChatInputPreferencesRepository(
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
|
||||
val busyMessageAction: Flow<BusyMessageAction> = dataStore.data
|
||||
.map { BusyMessageAction.fromStoredValue(it[KEY_BUSY_MESSAGE_ACTION]) }
|
||||
.distinctUntilChanged()
|
||||
|
||||
suspend fun setBusyMessageAction(action: BusyMessageAction) {
|
||||
dataStore.edit { it[KEY_BUSY_MESSAGE_ACTION] = action.storedValue }
|
||||
}
|
||||
|
||||
val convertLargePastesToAttachments: Flow<Boolean> = dataStore.data
|
||||
.map { preferences -> preferences[KEY_CONVERT_LARGE_PASTES] ?: true }
|
||||
.distinctUntilChanged()
|
||||
|
||||
@@ -35,6 +35,9 @@ data class ChatTurnCheckpoint(
|
||||
val baselineAssistantCount: Int,
|
||||
val pendingAsk: ChatTurnAskCheckpoint? = null,
|
||||
val queuedMessages: List<ChatQueuedMessageCheckpoint> = emptyList(),
|
||||
val queuePaused: Boolean = false,
|
||||
/** Only pending local work remains; never reattach the completed/stopped turn. */
|
||||
val queueOnly: Boolean = false,
|
||||
val startedAt: Long,
|
||||
val updatedAt: Long,
|
||||
) {
|
||||
|
||||
@@ -29,3 +29,24 @@ val Connection.capabilities: ConnectionCapabilities
|
||||
apiServerConfigured = apiServerUrl.isNotBlank(),
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Stable owner for an Auto chat before a conversation is opened.
|
||||
*
|
||||
* A legacy API-only record has no persisted Dashboard route; the conventional
|
||||
* same-host `:9119` derivation remains useful for an explicit upgrade, but it
|
||||
* must not silently turn that compatibility record into a Gateway-owned chat.
|
||||
* Once a Dashboard route (or authenticated Dashboard origin) is persisted,
|
||||
* standard Chat belongs to Gateway even while that route is signed out or
|
||||
* temporarily unreachable.
|
||||
*/
|
||||
val Connection.automaticChatTransport: SessionTransport
|
||||
get() {
|
||||
val dashboardPersisted = !dashboardUrl.isNullOrBlank() ||
|
||||
!authenticatedDashboardOrigin.isNullOrBlank()
|
||||
return if (dashboardPersisted) SessionTransport.GATEWAY else SessionTransport.SSE
|
||||
}
|
||||
|
||||
fun Connection.chatTransportForPreference(preference: String): SessionTransport =
|
||||
if (preference == "auto") automaticChatTransport
|
||||
else SessionTransport.forEndpoint(preference)
|
||||
|
||||
@@ -124,7 +124,7 @@ private fun EndpointCandidate?.secureLinkProtects(label: String, url: String): B
|
||||
val normalized = url.trim().trimEnd('/')
|
||||
val service = when (label) {
|
||||
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
|
||||
"API / sessions", "API fallback" -> "api"
|
||||
"API / sessions", "API fallback", "Direct API" -> "api"
|
||||
"Relay tools" -> "relay"
|
||||
else -> return false
|
||||
}
|
||||
@@ -170,7 +170,7 @@ fun computeConnectionSecurity(
|
||||
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||
add(
|
||||
classifySurfaceSecurity(
|
||||
label = "API fallback",
|
||||
label = "Direct API",
|
||||
url = it,
|
||||
activeEndpoint = apiEndpoint,
|
||||
isTailscaleDetected = isTailscaleDetected,
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardHttpException
|
||||
import com.hermesandroid.relay.plugins.runtime.ScopedPluginApiClient
|
||||
import java.io.IOException
|
||||
import java.net.URLEncoder
|
||||
import java.util.Locale
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonArray
|
||||
@@ -9,113 +15,178 @@ 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)) } }
|
||||
|
||||
/**
|
||||
* Uses official Dashboard `/api/git/…` reads for the active session repository.
|
||||
* Relay remains the discovery source and owns stronger write/preview extensions.
|
||||
* Operational upstream failures are never hidden by a Relay retry; only a 404
|
||||
* can fall back to a matching Relay-discovered repository.
|
||||
*/
|
||||
class GitStateApiClient(
|
||||
dashboard: DashboardApiClient,
|
||||
private val dashboard: DashboardApiClient,
|
||||
) {
|
||||
private val scoped = ScopedPluginApiClient("hermes-relay", dashboard)
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val reposById = linkedMapOf<String, GitRepo>()
|
||||
private val relayRepoIdsByRoot = linkedMapOf<String, String>()
|
||||
|
||||
suspend fun repos(): Result<List<GitRepo>> = scoped
|
||||
.get("git/repos")
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<ReposResponse>(element).repos
|
||||
suspend fun repos(
|
||||
sessionRepoPath: String? = null,
|
||||
includeRelayDiscovery: Boolean = true,
|
||||
): Result<List<GitRepo>> {
|
||||
reposById.clear()
|
||||
relayRepoIdsByRoot.clear()
|
||||
val path = sessionRepoPath?.trim().orEmpty()
|
||||
if (path.isBlank()) {
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.success(emptyList())
|
||||
}
|
||||
|
||||
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
|
||||
val upstream = upstreamStatus(path)
|
||||
if (upstream.isFailure) {
|
||||
val error = upstream.exceptionOrNull()!!
|
||||
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.failure(error)
|
||||
}
|
||||
val status = upstream.getOrNull()
|
||||
if (status == null) {
|
||||
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||
else Result.success(emptyList())
|
||||
}
|
||||
|
||||
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) }
|
||||
val standardRepo = GitRepo(
|
||||
id = UPSTREAM_SESSION_REPO_ID,
|
||||
name = path.replace('\\', '/').trimEnd('/').substringAfterLast('/').ifBlank { path },
|
||||
root = path,
|
||||
currentBranch = status.branch,
|
||||
dirty = status.changed > 0,
|
||||
route = GitRepositoryRoute.UPSTREAM,
|
||||
)
|
||||
|
||||
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) }
|
||||
// Plugin discovery is an enhancement. Once upstream answered, plugin
|
||||
// absence or breakage cannot take the standard session repository down.
|
||||
val relay = if (includeRelayDiscovery) relayRepos().getOrDefault(emptyList()) else emptyList()
|
||||
val merged = buildList {
|
||||
add(standardRepo)
|
||||
addAll(relay.filterNot { sameRoot(it.root, standardRepo.root) })
|
||||
}
|
||||
rememberRepos(merged)
|
||||
rememberRelayRepos(relay)
|
||||
return Result.success(merged)
|
||||
}
|
||||
|
||||
// ── 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 status(repo: String): Result<GitStatus> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayStatus(repo)
|
||||
return fallbackOnUnsupported(target, upstreamStatusWithFiles(target.root), ::relayStatus)
|
||||
}
|
||||
|
||||
suspend fun branches(repo: String): Result<List<GitBranch>> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayBranches(repo)
|
||||
return fallbackOnUnsupported(target, upstreamBranches(target.root), ::relayBranches)
|
||||
}
|
||||
|
||||
suspend fun diff(repo: String, path: String, kind: String): Result<GitDiff> {
|
||||
val target = reposById[repo]
|
||||
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayDiff(repo, path, kind)
|
||||
val upstream = dashboard.getJsonElement(
|
||||
upstreamPath(
|
||||
"/api/git/review/diff",
|
||||
mapOf(
|
||||
"path" to target.root,
|
||||
"file" to path,
|
||||
"scope" to "uncommitted",
|
||||
"staged" to (kind == "staged").toString(),
|
||||
),
|
||||
),
|
||||
).mapCatching { element ->
|
||||
GitDiff(
|
||||
path = path,
|
||||
kind = kind,
|
||||
diff = json.decodeFromJsonElement<UpstreamDiffResponse>(element).diff,
|
||||
)
|
||||
}
|
||||
return fallbackOnUnsupported(target, upstream) { relay -> relayDiff(relay, path, kind) }
|
||||
}
|
||||
|
||||
/** Clean tracked-file preview is a Relay enhancement; file-diff is not equivalent. */
|
||||
suspend fun file(repo: String, path: String): Result<GitFile> {
|
||||
val relay = relayRepoId(repo)
|
||||
?: return Result.failure(IOException("Tracked-file preview requires the Relay plugin"))
|
||||
return relayFile(relay, path)
|
||||
}
|
||||
|
||||
// Writes intentionally stay on Relay. The upstream Desktop mutation shape
|
||||
// does not carry plugin.api.write or the server-enforced confirmation echoes
|
||||
// used by this mobile surface, so it is not an equivalent safety contract.
|
||||
|
||||
suspend fun stage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
scoped.post("git/stage", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/stage", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun unstage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||
scoped.post("git/unstage", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/unstage", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun discard(
|
||||
repo: String,
|
||||
paths: List<String>,
|
||||
confirmation: String,
|
||||
deleteUntracked: Boolean = false,
|
||||
): Result<GitMutationResult> = scoped.post("git/discard", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/discard", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
put("confirmation", confirmation)
|
||||
put("delete_untracked", deleteUntracked)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commit(repo: String, message: String): Result<GitMutationResult> =
|
||||
scoped.post("git/commit", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/commit", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("message", message)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun commitSelected(
|
||||
repo: String,
|
||||
message: String,
|
||||
paths: List<String>,
|
||||
): Result<GitMutationResult> = scoped.post("git/commit_selected", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/commit_selected", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("message", message)
|
||||
put("paths", pathsArray(paths))
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun fetch(repo: String, remote: String = "origin"): Result<GitMutationResult> =
|
||||
scoped.post("git/fetch", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/fetch", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun pull(repo: String, remote: String = "origin", branch: String = ""): Result<GitMutationResult> =
|
||||
scoped.post("git/pull", buildJsonObject {
|
||||
put("repo", repo)
|
||||
relayWrite(repo) { relay -> scoped.post("git/pull", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun push(
|
||||
repo: String,
|
||||
confirmation: String,
|
||||
remote: String = "origin",
|
||||
branch: String = "",
|
||||
): Result<GitMutationResult> = scoped.post("git/push", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/push", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("remote", remote)
|
||||
put("branch", branch)
|
||||
put("confirmation", confirmation)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
suspend fun checkout(
|
||||
repo: String,
|
||||
@@ -123,41 +194,217 @@ class GitStateApiClient(
|
||||
confirmation: String? = null,
|
||||
newBranch: String = "",
|
||||
track: Boolean = false,
|
||||
): Result<GitMutationResult> = scoped.post("git/checkout", buildJsonObject {
|
||||
put("repo", repo)
|
||||
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/checkout", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("ref", ref)
|
||||
if (confirmation != null) put("confirmation", confirmation)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
}).decodeMutation() }
|
||||
|
||||
// ── Phase 3 extras ─────────────────────────────────────────────────────
|
||||
suspend fun commitMessage(repo: String): Result<GitCommitMessage> = relayWrite(repo) { relay ->
|
||||
scoped.post("git/commit_message", buildJsonObject { put("repo", relay) })
|
||||
.mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
||||
}
|
||||
|
||||
/** 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) }
|
||||
suspend fun commitMessageSelected(repo: String, paths: List<String>): Result<GitCommitMessage> =
|
||||
relayWrite(repo) { relay -> scoped.post("git/commit_message_selected", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("paths", pathsArray(paths))
|
||||
}).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)
|
||||
): Result<GitStashCheckoutResult> = relayWrite(repo) { relay -> scoped.post("git/stash_checkout", buildJsonObject {
|
||||
put("repo", relay)
|
||||
put("ref", ref)
|
||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||
put("track", track)
|
||||
}).mapCatching { json.decodeFromJsonElement<GitStashCheckoutResult>(it) }
|
||||
}).mapCatching { json.decodeFromJsonElement<GitStashCheckoutResult>(it) } }
|
||||
|
||||
private suspend fun relayRepos(): Result<List<GitRepo>> = scoped.get("git/repos").mapCatching {
|
||||
json.decodeFromJsonElement<ReposResponse>(it).repos
|
||||
}
|
||||
|
||||
private suspend fun relayStatus(repo: String): Result<GitStatus> = scoped
|
||||
.get("git/status", mapOf("repo" to repo))
|
||||
.mapCatching { json.decodeFromJsonElement<GitStatus>(it) }
|
||||
|
||||
private suspend fun relayBranches(repo: String): Result<List<GitBranch>> = scoped
|
||||
.get("git/branches", mapOf("repo" to repo))
|
||||
.mapCatching { json.decodeFromJsonElement<BranchesResponse>(it).branches }
|
||||
|
||||
private suspend fun relayDiff(repo: String, path: String, kind: String): Result<GitDiff> = scoped
|
||||
.get("git/diff", mapOf("repo" to repo, "path" to path, "kind" to kind))
|
||||
.mapCatching { json.decodeFromJsonElement<GitDiff>(it) }
|
||||
|
||||
private suspend fun relayFile(repo: String, path: String): Result<GitFile> = scoped
|
||||
.get("git/file", mapOf("repo" to repo, "path" to path))
|
||||
.mapCatching { json.decodeFromJsonElement<GitFile>(it) }
|
||||
|
||||
private suspend fun upstreamStatus(path: String): Result<UpstreamStatus?> = dashboard
|
||||
.getJsonElement(upstreamPath("/api/git/status", mapOf("path" to path)))
|
||||
.mapCatching { json.decodeFromJsonElement<UpstreamStatus?>(it) }
|
||||
|
||||
private suspend fun upstreamStatusWithFiles(path: String): Result<GitStatus> {
|
||||
val status = upstreamStatus(path).mapCatching {
|
||||
it ?: throw IOException("The active session path is not a Git repository")
|
||||
}.getOrElse { return Result.failure(it) }
|
||||
val review = dashboard.getJsonElement(
|
||||
upstreamPath("/api/git/review/list", mapOf("path" to path, "scope" to "uncommitted")),
|
||||
).mapCatching { json.decodeFromJsonElement<UpstreamReviewList>(it) }
|
||||
.getOrElse { return Result.failure(it) }
|
||||
val statusByPath = status.files.associateBy { it.path }
|
||||
val staged = mutableListOf<GitStatusEntry>()
|
||||
val modified = mutableListOf<GitStatusEntry>()
|
||||
val untracked = mutableListOf<GitStatusEntry>()
|
||||
review.files.forEach { file ->
|
||||
val entry = GitStatusEntry(file.path, file.added, file.removed)
|
||||
val fileStatus = statusByPath[file.path]
|
||||
if (fileStatus?.untracked == true) {
|
||||
untracked += entry
|
||||
} else {
|
||||
if (file.staged || fileStatus?.staged == true) staged += entry
|
||||
if (fileStatus?.unstaged == true || (!file.staged && fileStatus == null)) {
|
||||
modified += entry
|
||||
}
|
||||
}
|
||||
}
|
||||
return Result.success(
|
||||
GitStatus(
|
||||
counts = GitStatusCounts(
|
||||
staged = status.staged,
|
||||
modified = status.unstaged,
|
||||
untracked = status.untracked,
|
||||
changes = status.changed,
|
||||
additions = status.added,
|
||||
deletions = status.removed,
|
||||
),
|
||||
staged = staged,
|
||||
modified = modified,
|
||||
untracked = untracked,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun upstreamBranches(path: String): Result<List<GitBranch>> = dashboard
|
||||
.getJsonElement(upstreamPath("/api/git/branches", mapOf("path" to path)))
|
||||
.mapCatching { element ->
|
||||
json.decodeFromJsonElement<UpstreamBranches>(element).branches.map {
|
||||
GitBranch(name = it.name, isCurrent = it.checkedOut)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> fallbackOnUnsupported(
|
||||
target: GitRepo,
|
||||
upstream: Result<T>,
|
||||
relayCall: suspend (String) -> Result<T>,
|
||||
): Result<T> {
|
||||
if (upstream.isSuccess) return upstream
|
||||
val error = upstream.exceptionOrNull()!!
|
||||
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||
val relay = relayRepoIdsByRoot[normalizedRoot(target.root)] ?: return Result.failure(error)
|
||||
return relayCall(relay)
|
||||
}
|
||||
|
||||
private suspend fun <T> relayWrite(repo: String, block: suspend (String) -> Result<T>): Result<T> {
|
||||
val relay = relayRepoId(repo)
|
||||
?: return Result.failure(IOException("This Git action requires the Relay plugin enhancement"))
|
||||
return block(relay)
|
||||
}
|
||||
|
||||
private fun relayRepoId(repo: String): String? {
|
||||
val target = reposById[repo] ?: return repo.takeUnless { it == UPSTREAM_SESSION_REPO_ID }
|
||||
return if (target.route == GitRepositoryRoute.RELAY) target.id
|
||||
else relayRepoIdsByRoot[normalizedRoot(target.root)]
|
||||
}
|
||||
|
||||
private fun rememberRepos(repos: List<GitRepo>) {
|
||||
repos.forEach { reposById[it.id] = it }
|
||||
rememberRelayRepos(repos.filter { it.route == GitRepositoryRoute.RELAY })
|
||||
}
|
||||
|
||||
private fun rememberRelayRepos(repos: List<GitRepo>) {
|
||||
repos.forEach { relayRepoIdsByRoot[normalizedRoot(it.root)] = it.id }
|
||||
}
|
||||
|
||||
private fun upstreamPath(path: String, query: Map<String, String>): String = buildString {
|
||||
append(path)
|
||||
if (query.isNotEmpty()) {
|
||||
append('?')
|
||||
append(query.entries.joinToString("&") { (key, value) -> "${encode(key)}=${encode(value)}" })
|
||||
}
|
||||
}
|
||||
|
||||
private fun encode(value: String): String =
|
||||
URLEncoder.encode(value, Charsets.UTF_8.name()).replace("+", "%20")
|
||||
|
||||
private fun normalizedRoot(path: String): String {
|
||||
val normalized = path.trim().replace('\\', '/').trimEnd('/')
|
||||
return if (WINDOWS_ROOT.containsMatchIn(normalized) || normalized.startsWith("//")) {
|
||||
normalized.lowercase(Locale.ROOT)
|
||||
} else {
|
||||
normalized
|
||||
}
|
||||
}
|
||||
|
||||
private fun sameRoot(first: String, second: String): Boolean =
|
||||
normalizedRoot(first) == normalizedRoot(second)
|
||||
|
||||
private fun Result<kotlinx.serialization.json.JsonObject>.decodeMutation(): Result<GitMutationResult> =
|
||||
mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
||||
|
||||
private fun Throwable.isUnsupportedGitRoute(): Boolean =
|
||||
this is DashboardHttpException && statusCode == 404
|
||||
|
||||
private companion object {
|
||||
const val UPSTREAM_SESSION_REPO_ID = "__upstream_session__"
|
||||
val WINDOWS_ROOT = Regex("^[A-Za-z]:/")
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamStatus(
|
||||
val branch: String? = null,
|
||||
val staged: Int = 0,
|
||||
val unstaged: Int = 0,
|
||||
val untracked: Int = 0,
|
||||
val changed: Int = 0,
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val files: List<UpstreamStatusFile> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamStatusFile(
|
||||
val path: String,
|
||||
val staged: Boolean = false,
|
||||
val unstaged: Boolean = false,
|
||||
val untracked: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamReviewList(val files: List<UpstreamReviewFile> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamReviewFile(
|
||||
val path: String,
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val staged: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamBranches(val branches: List<UpstreamBranch> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamBranch(
|
||||
val name: String,
|
||||
@SerialName("checkedOut") val checkedOut: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class UpstreamDiffResponse(val diff: String = "")
|
||||
|
||||
@@ -3,7 +3,7 @@ package com.hermesandroid.relay.data
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/** A repository discovered by the plugin's /git/repos endpoint. */
|
||||
/** A current-session upstream repository or a Relay-discovered repository. */
|
||||
@Serializable
|
||||
data class GitRepo(
|
||||
val id: String,
|
||||
@@ -11,9 +11,19 @@ data class GitRepo(
|
||||
val root: String,
|
||||
@SerialName("current_branch") val currentBranch: String? = null,
|
||||
val dirty: Boolean = false,
|
||||
val route: GitRepositoryRoute = GitRepositoryRoute.RELAY,
|
||||
)
|
||||
|
||||
/** Working-tree status from /git/status. */
|
||||
@Serializable
|
||||
enum class GitRepositoryRoute {
|
||||
@SerialName("relay")
|
||||
RELAY,
|
||||
|
||||
@SerialName("upstream")
|
||||
UPSTREAM,
|
||||
}
|
||||
|
||||
/** Normalized working-tree status from upstream or Relay Git routes. */
|
||||
@Serializable
|
||||
data class GitStatus(
|
||||
val counts: GitStatusCounts = GitStatusCounts(),
|
||||
|
||||
@@ -344,6 +344,46 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
|
||||
dataStore.edit { it[key] = route.storageValue }
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear Relay-only selections after Relay has been explicitly removed from
|
||||
* the active connection. A temporarily unreachable configured Relay must
|
||||
* not call this: preserving the selection lets the richer route resume
|
||||
* when connectivity returns.
|
||||
*
|
||||
* [expectedScope] fences profile/connection changes that can race the
|
||||
* DataStore edit. Values are re-read inside the transaction instead of
|
||||
* trusting an earlier settings snapshot, so a newer user choice wins.
|
||||
* The legacy default-profile keys are global (their storage names predate
|
||||
* connection scoping), so they are never rewritten here: runtime fallback
|
||||
* handles an unpaired default profile without changing another
|
||||
* connection's selection.
|
||||
*/
|
||||
suspend fun reconcileRelayRemoval(expectedScope: VoiceProfileScope): Boolean {
|
||||
if (_scope.value != expectedScope || expectedScope.profileName == null) return false
|
||||
var changed = false
|
||||
dataStore.edit { prefs ->
|
||||
if (_scope.value != expectedScope) return@edit
|
||||
|
||||
val engine = VoiceEngineMode.fromStorage(
|
||||
resolveString(prefs, KEY_ENGINE_MODE, expectedScope, DEFAULT_ENGINE_MODE),
|
||||
)
|
||||
val route = VoiceAudioRoute.fromStorage(
|
||||
resolveString(prefs, KEY_AUDIO_ROUTE, expectedScope, DEFAULT_AUDIO_ROUTE),
|
||||
)
|
||||
if (engine == VoiceEngineMode.RealtimeAgent) {
|
||||
prefs[stringPreferencesKey(scopedName(KEY_ENGINE_MODE, expectedScope))] =
|
||||
VoiceEngineMode.HermesVoiceOutput.storageValue
|
||||
changed = true
|
||||
}
|
||||
if (route == VoiceAudioRoute.Relay) {
|
||||
prefs[stringPreferencesKey(scopedName(KEY_AUDIO_ROUTE, expectedScope))] =
|
||||
VoiceAudioRoute.Auto.storageValue
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
/** "" clears the override (relay falls back to the server's saved voice). */
|
||||
suspend fun setEnhancedVoice(voice: String) {
|
||||
val key = stringPreferencesKey(scopedName(KEY_ENH_VOICE, _scope.value))
|
||||
|
||||
@@ -348,7 +348,7 @@ class BridgeCommandHandler(
|
||||
* the multiplexer. The two paths are fully independent.
|
||||
*
|
||||
* Caught by Bailey's on-device test 2026-04-14 — see the v0.4.1
|
||||
* "voice intent local dispatch loop" entry in ROADMAP.md.
|
||||
* "voice intent local dispatch loop" entry in docs/project/ROADMAP.md.
|
||||
*/
|
||||
suspend fun handleLocalCommand(envelope: Envelope): LocalDispatchResult {
|
||||
if (envelope.type != "bridge.command") {
|
||||
|
||||
@@ -28,6 +28,7 @@ import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.io.IOException
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
internal const val RELAY_SESSION_HEADER: String = "X-Hermes-Relay-Session"
|
||||
|
||||
@@ -88,6 +89,7 @@ class RelayHttpClient(
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RelayHttpClient"
|
||||
private const val DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES = 100L * 1024L * 1024L
|
||||
const val MAX_MODEL_CAPABILITY_ROWS = 64
|
||||
private const val MAX_MODEL_CAPABILITY_PROVIDER_CHARS = 128
|
||||
private const val MAX_MODEL_CAPABILITY_MODEL_CHARS = 512
|
||||
@@ -257,7 +259,10 @@ class RelayHttpClient(
|
||||
* underlying exception with a human-readable message suitable for
|
||||
* surfacing in the attachment's `errorMessage` field.
|
||||
*/
|
||||
suspend fun fetchMedia(token: String): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
suspend fun fetchMedia(
|
||||
token: String,
|
||||
maxBytes: Long = DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES,
|
||||
): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) {
|
||||
return@withContext Result.failure(
|
||||
@@ -318,7 +323,7 @@ class RelayHttpClient(
|
||||
if (body == null) {
|
||||
return@withContext Result.failure(IOException("Empty response body"))
|
||||
}
|
||||
val bytes = body.bytes()
|
||||
val bytes = body.readBytesBounded(maxBytes)
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
@@ -352,6 +357,7 @@ class RelayHttpClient(
|
||||
suspend fun fetchMediaByPath(
|
||||
path: String,
|
||||
contentTypeHint: String? = null,
|
||||
maxBytes: Long = DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES,
|
||||
): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||
if (relayUrl.isEmpty()) {
|
||||
@@ -427,12 +433,16 @@ class RelayHttpClient(
|
||||
if (body == null) {
|
||||
return@withContext Result.failure(IOException("Empty response body"))
|
||||
}
|
||||
val bytes = body.bytes()
|
||||
val bytes = body.readBytesBounded(maxBytes)
|
||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.w(TAG, "fetchMediaByPath failed for $path: ${e.message}")
|
||||
Result.failure(IOException("Relay unreachable: ${e.message ?: "IO error"}"))
|
||||
if (e is RelayMediaLimitException) {
|
||||
Result.failure(e)
|
||||
} else {
|
||||
Result.failure(IOException("Relay unreachable: ${e.message ?: "IO error"}"))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "fetchMediaByPath unexpected error for $path: ${e.message}")
|
||||
Result.failure(e)
|
||||
@@ -1456,6 +1466,33 @@ class RelayHttpClient(
|
||||
return match?.groupValues?.get(1)?.trim()?.ifBlank { null }
|
||||
}
|
||||
|
||||
private fun okhttp3.ResponseBody.readBytesBounded(maxBytes: Long): ByteArray {
|
||||
if (maxBytes <= 0L) throw RelayMediaLimitException()
|
||||
val declared = contentLength().takeIf { it >= 0L }
|
||||
if (declared != null && declared > maxBytes) throw RelayMediaLimitException()
|
||||
val output = ByteArrayOutputStream(
|
||||
declared?.coerceAtMost(Int.MAX_VALUE.toLong())?.toInt() ?: DEFAULT_BUFFER_SIZE,
|
||||
)
|
||||
byteStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
total += count
|
||||
if (total > maxBytes) throw RelayMediaLimitException()
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
if (declared != null && total != declared) {
|
||||
throw IOException("Media file changed while it was being downloaded")
|
||||
}
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
private class RelayMediaLimitException :
|
||||
IOException("File exceeds the configured download limit")
|
||||
|
||||
/**
|
||||
* Parse the relay's `X-Media-Sensitive` response header into a bool.
|
||||
*
|
||||
@@ -1468,7 +1505,7 @@ class RelayHttpClient(
|
||||
return value == "1" || value == "true"
|
||||
}
|
||||
|
||||
/** Provider-neutral compatibility fetch for gateways without `account.usage`. */
|
||||
/** Provider-neutral enhancement for pools and providers upstream does not expose. */
|
||||
suspend fun fetchProviderUsage(
|
||||
profile: String? = null,
|
||||
sessionId: String? = null,
|
||||
|
||||
@@ -1540,19 +1540,28 @@ class ChatHandler {
|
||||
val prior = priorById[messageId]
|
||||
// Outbound attachments: prefer an id-match (covers any future
|
||||
// user-message id reconciliation), else fall back to the
|
||||
// content-keyed queue. Inbound attachments normally come back via
|
||||
// marker re-dispatch. One narrow exception retains a completed
|
||||
// image_generate result when the immediate post-turn history read
|
||||
// still lacks its MEDIA marker; otherwise the rendered image
|
||||
// disappears during the persistence-lag window.
|
||||
// content-keyed queue. Exact inbound marker attachments are also
|
||||
// carried by id: a history refresh must not replace a successfully
|
||||
// loaded image/file with a fresh LOADING placeholder. A process
|
||||
// restart has no prior attachment, so the marker still dispatches
|
||||
// normally and rehydrates it. One additional narrow exception
|
||||
// retains a completed image_generate result when the immediate
|
||||
// post-turn history read still lacks its MEDIA marker.
|
||||
val carriedAttachments = run {
|
||||
val persistedImagePaths = persistedImages.paths.toHashSet()
|
||||
val persistedMediaKeys = messageMediaHits.mapTo(HashSet()) { (_, hit) ->
|
||||
when (hit) {
|
||||
is MediaMarkerHit.RelayToken -> hit.token
|
||||
is MediaMarkerHit.BarePath -> hit.path
|
||||
}
|
||||
}
|
||||
val priorGeneratedImage = prior?.toolCalls.orEmpty().any { tool ->
|
||||
isImageGenerationToolName(tool.name) &&
|
||||
tool.isComplete && tool.success != false
|
||||
}
|
||||
val byId = prior?.attachments.orEmpty().filter { attachment ->
|
||||
attachment.relayToken == null ||
|
||||
attachment.relayToken in persistedMediaKeys ||
|
||||
(role == MessageRole.USER && attachment.relayToken in persistedImagePaths) ||
|
||||
(
|
||||
role == MessageRole.ASSISTANT &&
|
||||
@@ -1708,15 +1717,27 @@ class ChatHandler {
|
||||
is MediaMarkerHit.RelayToken -> {
|
||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == hit.token } == true
|
||||
if (!alreadyHydrated) {
|
||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
||||
onMediaAttachmentRequested(messageId, hit.token)
|
||||
}
|
||||
}
|
||||
}
|
||||
is MediaMarkerHit.BarePath -> {
|
||||
val dedupeKey = "$messageId:bare:${hit.path}"
|
||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||
Log.d(TAG, "Media marker (bare-path, reload): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
val alreadyHydrated = _messages.value
|
||||
.firstOrNull { it.matchesIdentity(messageId) }
|
||||
?.attachments
|
||||
?.any { it.relayToken == hit.path } == true
|
||||
if (!alreadyHydrated) {
|
||||
Log.d(TAG, "Media marker (bare-path, reload): ${hit.path}")
|
||||
onMediaBarePathRequested(messageId, hit.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+174
-4
@@ -49,6 +49,7 @@ import okhttp3.Request
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
@@ -293,6 +294,34 @@ internal fun copyBounded(
|
||||
return written
|
||||
}
|
||||
|
||||
internal fun copyMediaBounded(
|
||||
input: InputStream,
|
||||
output: OutputStream,
|
||||
declaredLength: Long?,
|
||||
limitBytes: Long,
|
||||
): Long {
|
||||
require(limitBytes > 0)
|
||||
require(declaredLength == null || declaredLength >= 0)
|
||||
if (declaredLength != null && declaredLength > limitBytes) {
|
||||
throw IOException("File exceeds the configured download limit")
|
||||
}
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var written = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > limitBytes) {
|
||||
throw IOException("File exceeds the configured download limit")
|
||||
}
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
if (declaredLength != null && written != declaredLength) {
|
||||
throw IOException("Media file changed while it was being downloaded")
|
||||
}
|
||||
return written
|
||||
}
|
||||
|
||||
/** One entry from `GET /api/audio/elevenlabs/voices` — non-secret voice metadata. */
|
||||
data class ElevenLabsVoice(
|
||||
val voiceId: String,
|
||||
@@ -310,6 +339,19 @@ data class ElevenLabsVoices(
|
||||
val voices: List<ElevenLabsVoice>,
|
||||
)
|
||||
|
||||
/**
|
||||
* Metadata for a file streamed from upstream's authenticated managed-files surface.
|
||||
*
|
||||
* The Dashboard applies its own managed-root, sensitive-file, and maximum-size
|
||||
* policy before the file leaves the Hermes host. Android applies the user's
|
||||
* stricter inbound-media cap while reading the response as a second boundary.
|
||||
*/
|
||||
data class DashboardFetchedFile(
|
||||
val sizeBytes: Long,
|
||||
val contentType: String,
|
||||
val fileName: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Native client for the Hermes dashboard/admin server (:9119).
|
||||
*
|
||||
@@ -381,6 +423,58 @@ class DashboardApiClient(
|
||||
executeJsonElement(request, normalized)
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a server-local artifact through current upstream Hermes.
|
||||
*
|
||||
* This is the same authenticated `/api/files/download` route official
|
||||
* Desktop uses for remote gateway files. The caller supplies its display
|
||||
* cap so a malicious or stale Content-Length cannot cause an unbounded
|
||||
* allocation. The supplied output is normally Android's on-disk media cache;
|
||||
* local playback supplies seeking, so `/api/files/stream` is unnecessary
|
||||
* on this path.
|
||||
*/
|
||||
suspend fun downloadManagedFile(
|
||||
serverPath: String,
|
||||
maxBytes: Long,
|
||||
output: OutputStream,
|
||||
): Result<DashboardFetchedFile> = withContext(Dispatchers.IO) {
|
||||
if (serverPath.isBlank()) {
|
||||
return@withContext Result.failure(IOException("Media path is empty"))
|
||||
}
|
||||
if (maxBytes <= 0L) {
|
||||
return@withContext Result.failure(IOException("Media download limit is invalid"))
|
||||
}
|
||||
val httpUrl = resolveUrl("/api/files/download")
|
||||
?.newBuilder()
|
||||
?.addQueryParameter("path", serverPath)
|
||||
?.build()
|
||||
?: return@withContext Result.failure(invalidUrlException())
|
||||
val request = Request.Builder().url(httpUrl).get().build()
|
||||
|
||||
executeCancellable(request, "Dashboard media download") { response ->
|
||||
val body = response.body
|
||||
val declaredLength = body.contentLength().takeIf { it >= 0L }
|
||||
if (declaredLength != null && declaredLength > maxBytes) {
|
||||
throw IOException("File exceeds the configured download limit")
|
||||
}
|
||||
val readTotal = body.byteStream().use { input ->
|
||||
copyMediaBounded(input, output, declaredLength, maxBytes)
|
||||
}
|
||||
DashboardFetchedFile(
|
||||
sizeBytes = readTotal,
|
||||
contentType = response.header("Content-Type")
|
||||
?.substringBefore(';')
|
||||
?.trim()
|
||||
?.takeIf(String::isNotEmpty)
|
||||
?: "application/octet-stream",
|
||||
fileName = response.header("Content-Disposition")
|
||||
?.let(::contentDispositionFileName)
|
||||
?: serverPath.substringAfterLast('/').substringAfterLast('\\')
|
||||
.takeIf(String::isNotBlank),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun postJsonObject(
|
||||
path: String,
|
||||
payload: JsonObject = JsonObject(emptyMap()),
|
||||
@@ -1262,7 +1356,7 @@ class DashboardApiClient(
|
||||
suspend fun getSessionMessages(
|
||||
sessionId: String,
|
||||
profile: String? = null,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>> = withContext(Dispatchers.IO) {
|
||||
val name = profile?.trim().orEmpty()
|
||||
loadSessionMessages(mode) { page ->
|
||||
@@ -1666,6 +1760,7 @@ class DashboardApiClient(
|
||||
// Mirrors current upstream `_MANAGED_FILE_MAX_BYTES`; enforcing it
|
||||
// client-side avoids uploading a body the Dashboard will reject.
|
||||
internal const val MAX_BACKUP_TRANSFER_BYTES = 100L * 1024L * 1024L
|
||||
internal const val MAX_JSON_RESPONSE_BYTES = 8L * 1024L * 1024L
|
||||
|
||||
fun pathSegment(value: String): String =
|
||||
URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
||||
@@ -2394,17 +2489,61 @@ data class StoredDashboardCookie(
|
||||
}
|
||||
|
||||
private fun Response.readJsonObject(json: Json): JsonObject {
|
||||
val raw = body.string()
|
||||
val raw = body.readUtf8Bounded(DashboardApiClient.MAX_JSON_RESPONSE_BYTES)
|
||||
if (raw.isBlank()) return JsonObject(emptyMap())
|
||||
return json.parseToJsonElement(raw).jsonObject
|
||||
}
|
||||
|
||||
private fun Response.readJsonElement(json: Json): JsonElement {
|
||||
val raw = body.string()
|
||||
val raw = body.readUtf8Bounded(DashboardApiClient.MAX_JSON_RESPONSE_BYTES)
|
||||
if (raw.isBlank()) return JsonObject(emptyMap())
|
||||
return json.parseToJsonElement(raw)
|
||||
}
|
||||
|
||||
internal fun okhttp3.ResponseBody.readUtf8Bounded(maxBytes: Long): String {
|
||||
require(maxBytes in 1..Int.MAX_VALUE.toLong()) { "Invalid response byte limit" }
|
||||
val declaredLength = contentLength()
|
||||
if (declaredLength > maxBytes) {
|
||||
throw IOException("Dashboard response exceeds Android's bounded JSON limit")
|
||||
}
|
||||
val initialSize = when {
|
||||
declaredLength in 1..maxBytes -> declaredLength.toInt()
|
||||
else -> minOf(maxBytes, DEFAULT_BUFFER_SIZE.toLong()).toInt()
|
||||
}
|
||||
val output = ByteArrayOutputStream(initialSize)
|
||||
byteStream().use { input ->
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
total += read
|
||||
if (total > maxBytes) {
|
||||
throw IOException("Dashboard response exceeds Android's bounded JSON limit")
|
||||
}
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
return output.toString(Charsets.UTF_8.name())
|
||||
}
|
||||
|
||||
private fun contentDispositionFileName(header: String): String? {
|
||||
val encoded = Regex("""filename\*=UTF-8''([^;]+)""", RegexOption.IGNORE_CASE)
|
||||
.find(header)
|
||||
?.groupValues
|
||||
?.getOrNull(1)
|
||||
?.let { runCatching { java.net.URLDecoder.decode(it, "UTF-8") }.getOrNull() }
|
||||
val plain = Regex("""filename=\"([^\"]+)\"|filename=([^;]+)""", RegexOption.IGNORE_CASE)
|
||||
.find(header)
|
||||
?.let { it.groupValues[1].ifBlank { it.groupValues[2] } }
|
||||
?.trim()
|
||||
?.trim('"')
|
||||
return (encoded ?: plain)
|
||||
?.substringAfterLast('/')
|
||||
?.substringAfterLast('\\')
|
||||
?.takeIf(String::isNotBlank)
|
||||
}
|
||||
|
||||
internal class DashboardHttpException(
|
||||
val statusCode: Int,
|
||||
message: String,
|
||||
@@ -2448,8 +2587,39 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
/** True only when the managed-file route itself is absent on this Hermes build. */
|
||||
internal fun Throwable.isDashboardManagedFilesUnsupported(): Boolean {
|
||||
var current: Throwable? = this
|
||||
val seen = java.util.Collections.newSetFromMap(
|
||||
java.util.IdentityHashMap<Throwable, Boolean>(),
|
||||
)
|
||||
while (current != null && seen.add(current)) {
|
||||
if (current is DashboardHttpException) {
|
||||
if (current.statusCode in setOf(405, 501)) return true
|
||||
if (current.statusCode == 404) {
|
||||
val detail = current.message.orEmpty()
|
||||
// FastAPI's missing-route response is the generic "Not Found".
|
||||
// A real managed-file miss says "File not found" and must not
|
||||
// silently escape to Relay's broader path policy.
|
||||
val isManagedFileMiss = detail.contains("File not found", ignoreCase = true) ||
|
||||
detail.contains("Path not found", ignoreCase = true)
|
||||
val isGenericRouteMiss = detail.trim().endsWith(": not found", ignoreCase = true) ||
|
||||
detail.contains("\"detail\":\"Not Found\"", ignoreCase = true) ||
|
||||
detail.contains("\"detail\": \"Not Found\"", ignoreCase = true)
|
||||
if (!isManagedFileMiss && isGenericRouteMiss) return true
|
||||
}
|
||||
}
|
||||
current = current.cause
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun apiFailure(response: Response, operation: String): IOException {
|
||||
val bodyDetail = runCatching { response.body.string() }.getOrDefault("")
|
||||
val bodyDetail = try {
|
||||
response.body.readUtf8Bounded(4L * 1024L)
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
val detail = bodyDetail.take(240).ifBlank { response.message }
|
||||
return DashboardHttpException(
|
||||
statusCode = response.code,
|
||||
|
||||
+272
-20
@@ -119,6 +119,10 @@ class GatewayChatClient(
|
||||
private val promptSubmitTimeoutMs: Long = PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,
|
||||
/** Test seam — idle-progress watchdog base. Production keeps [TURN_TIMEOUT_MS]. */
|
||||
private val turnIdleTimeoutMs: Long = TURN_TIMEOUT_MS,
|
||||
/** Test seam — lazy session.create/resume readiness barrier. */
|
||||
private val sessionReadyTimeoutMs: Long = SESSION_READY_TIMEOUT_MS,
|
||||
/** Test seam — compaction idle lease. Production keeps [COMPACTING_TIMEOUT_MS]. */
|
||||
private val compactingTimeoutMs: Long = COMPACTING_TIMEOUT_MS,
|
||||
/** Random source for ordinary reconnect full-jitter. */
|
||||
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
|
||||
) : GatewayProfileEditorClient {
|
||||
@@ -159,6 +163,19 @@ class GatewayChatClient(
|
||||
private const val ASK_SUDO_TIMEOUT_MS = 150_000L
|
||||
private const val ASK_UNBOUNDED_TIMEOUT_MS = 600_000L
|
||||
|
||||
/**
|
||||
* Server-side context compaction summarizes the transcript through a
|
||||
* (possibly slow) model with NO deltas or tool events flowing until it
|
||||
* finishes — near the context ceiling that silence routinely exceeds
|
||||
* [TURN_TIMEOUT_MS], so the idle watchdog would `session.interrupt` a
|
||||
* healthy compression, roll back its work, and retrigger on the next
|
||||
* prompt forever. A `status.update` event with kind `compacting`
|
||||
* (emitted at compaction start, and periodically by newer gateways)
|
||||
* arms this longer leash instead; any regular event rearms
|
||||
* [TURN_TIMEOUT_MS].
|
||||
*/
|
||||
private const val COMPACTING_TIMEOUT_MS = 600_000L
|
||||
|
||||
private const val RPC_TIMEOUT_MS = 15_000L
|
||||
const val PROFILE_AVATAR_MAX_BYTES = 2_000_000
|
||||
|
||||
@@ -176,6 +193,7 @@ class GatewayChatClient(
|
||||
* would have been abandoned server-side anyway.
|
||||
*/
|
||||
private const val PROMPT_SUBMIT_REQUEST_TIMEOUT_MS = 1_800_000L
|
||||
private const val SESSION_READY_TIMEOUT_MS = 300_000L
|
||||
private const val CONNECT_TIMEOUT_MS = 20_000L
|
||||
|
||||
/**
|
||||
@@ -263,7 +281,7 @@ class GatewayChatClient(
|
||||
.newBuilder()
|
||||
// The 10s default connectTimeout is LAN-tuned; a remote dashboard
|
||||
// reached over Tailscale (DERP cold start) can take longer to complete
|
||||
// the WS upgrade. A failed connect drops chat to the SSE fallback and a
|
||||
// the WS upgrade. A failed connect leaves Android on its Gateway owner and a
|
||||
// 5s cooldown, so give the first remote handshake room.
|
||||
.connectTimeout(20, TimeUnit.SECONDS)
|
||||
.pingInterval(30, TimeUnit.SECONDS)
|
||||
@@ -384,12 +402,24 @@ class GatewayChatClient(
|
||||
private val _serverProject = MutableStateFlow<GatewaySessionProject?>(null)
|
||||
val serverProject: StateFlow<GatewaySessionProject?> = _serverProject.asStateFlow()
|
||||
|
||||
/**
|
||||
* Exact model-callable tool names from upstream `session.info.tools` for
|
||||
* the selected live session/profile. Null means the gateway has not
|
||||
* supplied a catalog; an empty set means it authoritatively supplied none.
|
||||
*/
|
||||
private val _serverTools = MutableStateFlow<Set<String>?>(null)
|
||||
val serverTools: StateFlow<Set<String>?> = _serverTools.asStateFlow()
|
||||
|
||||
/** Serializes connect / session-establish so concurrent sends share one socket. */
|
||||
private val connectMutex = Mutex()
|
||||
|
||||
@Volatile
|
||||
private var webSocket: WebSocket? = null
|
||||
|
||||
/** Profile explicitly routed by the Dashboard `/api/ws?profile=` handshake. */
|
||||
@Volatile
|
||||
private var connectedSocketProfile: String? = null
|
||||
|
||||
/** Completed when the server's `gateway.ready` event arrives for the current socket. */
|
||||
@Volatile
|
||||
private var readySignal: CompletableDeferred<Unit>? = null
|
||||
@@ -398,6 +428,9 @@ class GatewayChatClient(
|
||||
/** Invalidates an older async prewarm when a newer session selection wins. */
|
||||
private val prewarmRequestGeneration = AtomicLong(0)
|
||||
private val pendingRpcs = ConcurrentHashMap<Long, CompletableDeferred<JsonObject>>()
|
||||
private val lazyLiveSessions = ConcurrentHashMap.newKeySet<String>()
|
||||
private val readyLiveSessions = ConcurrentHashMap.newKeySet<String>()
|
||||
private val sessionReadyWaiters = ConcurrentHashMap<String, CompletableDeferred<Unit>>()
|
||||
|
||||
/** Monotonic client-local fence for lazy child watch open/close races. */
|
||||
private val childWatchGeneration = AtomicLong(0)
|
||||
@@ -548,6 +581,28 @@ class GatewayChatClient(
|
||||
val terminalRequired: Boolean,
|
||||
)
|
||||
|
||||
/**
|
||||
* One exact turn settled from authoritative session state may still receive
|
||||
* the terminal frame that was already in flight. Consume only that terminal
|
||||
* so it cannot be reported as a second unmatched completion. A subsequent
|
||||
* message.start clears the drain because it establishes the next turn on
|
||||
* the same live runtime.
|
||||
*/
|
||||
@Volatile
|
||||
private var settledTurnDrain: SettledTurnDrain? = null
|
||||
|
||||
private data class SettledTurnDrain(
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
)
|
||||
|
||||
private data class ActiveTurnLivenessProbe(
|
||||
val turn: GatewayTurn,
|
||||
val storedSessionId: String,
|
||||
val liveSessionId: String,
|
||||
val progressGeneration: Long,
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates UI callbacks when the server starts a turn that has no matching
|
||||
* [sendTurn] call (for example a background-process completion). The
|
||||
@@ -677,6 +732,7 @@ class GatewayChatClient(
|
||||
): ActiveTurnHandle {
|
||||
val turn = GatewayTurn(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
androidOwned = true,
|
||||
onTransportAccepted = onTransportAccepted,
|
||||
)
|
||||
// Warm = the connection-establish phases are skipped this turn (socket
|
||||
@@ -724,6 +780,10 @@ class GatewayChatClient(
|
||||
cleanupStagedAttachments(stagedImagePaths)
|
||||
return@launch
|
||||
}
|
||||
// A newly accepted Android send is a distinct generation on
|
||||
// this runtime. Its terminal must never be consumed by the
|
||||
// prior turn's optional late-terminal drain.
|
||||
settledTurnDrain = null
|
||||
activeTurn = turn
|
||||
turn.armWatchdog()
|
||||
// Generic `file.attach` uploads are staged artifacts, not
|
||||
@@ -758,7 +818,7 @@ class GatewayChatClient(
|
||||
// Once this turn's own events are flowing (or it already
|
||||
// finished), the prompt provably reached the server — a
|
||||
// slow, lost, or socket-severed ack must NOT preflight-fail
|
||||
// into the SSE fallback, which would resubmit the same
|
||||
// into a second transport, which would resubmit the same
|
||||
// prompt as a duplicate turn. Recovery belongs to the
|
||||
// stream: the watchdog and mid-turn rejoin own it.
|
||||
if (turn.started || turn.ended || turn.transportRecoveryStarted) {
|
||||
@@ -782,7 +842,7 @@ class GatewayChatClient(
|
||||
// through the normal failed-turn callback instead.
|
||||
cleanupStagedAttachments(stagedImagePaths)
|
||||
turn.tracer.done("submit-rejected")
|
||||
turn.callbacks.onError(
|
||||
turn.callbacks.onSubmitRejected(
|
||||
submitError?.message ?: "Hermes rejected the new session",
|
||||
)
|
||||
return@launch
|
||||
@@ -849,7 +909,11 @@ class GatewayChatClient(
|
||||
liveSessionId = null
|
||||
storedSessionId = null
|
||||
liveSessionProfile = null
|
||||
failSessionReadyWaiters("gateway session cleared")
|
||||
lazyLiveSessions.clear()
|
||||
readyLiveSessions.clear()
|
||||
cancelledTurnDrain = null
|
||||
_serverTools.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1363,6 +1427,7 @@ class GatewayChatClient(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
deferEvents = true,
|
||||
androidOwned = true,
|
||||
).also { turn ->
|
||||
turn.markRecoveredStarted()
|
||||
activeTurn = turn
|
||||
@@ -1486,6 +1551,7 @@ class GatewayChatClient(
|
||||
boundTurn = GatewayTurn(
|
||||
callbacks = dispatchOn(callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
androidOwned = true,
|
||||
).also { turn ->
|
||||
turn.markRecoveredStarted()
|
||||
activeTurn = turn
|
||||
@@ -1519,6 +1585,7 @@ class GatewayChatClient(
|
||||
val queuedTurn = GatewayTurn(
|
||||
callbacks = dispatchOn(registration.callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
androidOwned = true,
|
||||
)
|
||||
// recoverTurn is resumed on its caller's coroutine context;
|
||||
// ChatViewModel calls it from Main, so this admission runs
|
||||
@@ -1765,18 +1832,17 @@ class GatewayChatClient(
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider-neutral account limits owned by upstream Hermes. Current hosts
|
||||
* may not expose this additive method yet; callers should treat JSON-RPC
|
||||
* method-not-found as capability absence and use the optional Relay
|
||||
* compatibility surface when paired.
|
||||
* Official upstream Nous usage bars. Current hosts may not expose this
|
||||
* additive method yet; callers should treat JSON-RPC method-not-found as
|
||||
* capability absence and use the optional Relay enhancement when paired.
|
||||
*/
|
||||
suspend fun providerUsage(): Result<JsonObject> {
|
||||
suspend fun usageBars(): Result<JsonObject> {
|
||||
try {
|
||||
connectMutex.withLock { ensureConnected() }
|
||||
} catch (e: Exception) {
|
||||
return Result.failure(e)
|
||||
}
|
||||
return rpc("account.usage", JsonObject(emptyMap()))
|
||||
return rpc("usage.bars", JsonObject(emptyMap()))
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2414,6 +2480,7 @@ class GatewayChatClient(
|
||||
} catch (error: Exception) {
|
||||
return GatewayActiveSessionsResult.TransientFailure(error)
|
||||
}
|
||||
val livenessProbe = captureActiveTurnLivenessProbe()
|
||||
val result = rpc(
|
||||
"session.active_list",
|
||||
buildJsonObject {
|
||||
@@ -2433,12 +2500,58 @@ class GatewayChatClient(
|
||||
val payload = result.getOrThrow()
|
||||
val rows = payload["sessions"] as? JsonArray
|
||||
?: throw GatewayRpcException("session.active_list returned no sessions array")
|
||||
GatewayActiveSessionsResult.Success(rows.map(::parseGatewayActiveSession))
|
||||
val sessions = rows.map(::parseGatewayActiveSession)
|
||||
reconcileActiveTurnFromSnapshot(livenessProbe, sessions)
|
||||
GatewayActiveSessionsResult.Success(sessions)
|
||||
} catch (parseError: Exception) {
|
||||
GatewayActiveSessionsResult.TransientFailure(parseError)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture only a locally submitted/recovered turn. Merely observing an
|
||||
* exact session through the shared Gateway socket never grants Android
|
||||
* authority to settle Desktop/TUI work.
|
||||
*/
|
||||
private fun captureActiveTurnLivenessProbe(): ActiveTurnLivenessProbe? {
|
||||
val turn = activeTurn ?: return null
|
||||
val generation = turn.captureLivenessGeneration() ?: return null
|
||||
val storedId = storedSessionId ?: return null
|
||||
val liveId = liveSessionId ?: return null
|
||||
return ActiveTurnLivenessProbe(turn, storedId, liveId, generation)
|
||||
}
|
||||
|
||||
/**
|
||||
* `session.active_list` is process-wide, but a row naming both identifiers
|
||||
* already owned by this client is authoritative for that exact runtime.
|
||||
* Fence the delayed snapshot by turn identity and progress generation so an
|
||||
* old idle result cannot settle a newer turn or race newer live events.
|
||||
*/
|
||||
private fun reconcileActiveTurnFromSnapshot(
|
||||
probe: ActiveTurnLivenessProbe?,
|
||||
sessions: List<GatewayActiveSession>,
|
||||
) {
|
||||
probe ?: return
|
||||
if (activeTurn !== probe.turn ||
|
||||
storedSessionId != probe.storedSessionId ||
|
||||
liveSessionId != probe.liveSessionId
|
||||
) return
|
||||
val exact = sessions.singleOrNull { row ->
|
||||
row.runtimeSessionId == probe.liveSessionId &&
|
||||
row.storedSessionId == probe.storedSessionId
|
||||
} ?: return
|
||||
if (exact.status != GatewayActiveSessionStatus.Idle) return
|
||||
if (probe.turn.settleFromAuthoritativeSessionState(
|
||||
running = false,
|
||||
source = "session.active_list",
|
||||
expectedProgressGeneration = probe.progressGeneration,
|
||||
)
|
||||
) {
|
||||
if (activeTurn === probe.turn) activeTurn = null
|
||||
if (!AppForegroundTracker.isForeground.value) scheduleBackgroundClose()
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop one process owned by the current live gateway session. */
|
||||
suspend fun killProcess(processId: String): Result<Unit> {
|
||||
if (processId.isBlank()) {
|
||||
@@ -2831,6 +2944,7 @@ class GatewayChatClient(
|
||||
activeTurn = null
|
||||
backgroundTurns.clear()
|
||||
cancelledTurnDrain = null
|
||||
settledTurnDrain = null
|
||||
unsolicitedTurnProvider = null
|
||||
coldPrewarmSessionReadyListener = null
|
||||
unmatchedTurnCompleteListener = null
|
||||
@@ -2956,9 +3070,10 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
val ticketMs = (System.nanoTime() - connectStart) / 1_000_000
|
||||
val socketProfile = currentSessionProfile()
|
||||
val url = dashboardClient.gatewayWebSocketUrl(
|
||||
ticket = ticket.ticket,
|
||||
profile = currentSessionProfile(),
|
||||
profile = socketProfile,
|
||||
)
|
||||
?: throw GatewayConnectAttemptException(
|
||||
"could not build /api/ws URL",
|
||||
@@ -2992,6 +3107,7 @@ class GatewayChatClient(
|
||||
if (readyFailure != null) {
|
||||
socket.cancel()
|
||||
webSocket = null
|
||||
connectedSocketProfile = null
|
||||
throw (readyFailure as? GatewayConnectAttemptException
|
||||
?: GatewayConnectAttemptException(
|
||||
"gateway connection failed: ${readyFailure.message}",
|
||||
@@ -3004,6 +3120,7 @@ class GatewayChatClient(
|
||||
val wsMs = (System.nanoTime() - connectStart) / 1_000_000 - ticketMs
|
||||
Log.i(TAG, "Gateway connected (/api/ws ready) — ticket=${ticketMs}ms ws=${wsMs}ms")
|
||||
hasEverReachedReady = true
|
||||
connectedSocketProfile = socketProfile
|
||||
coldStartFailureEpisodes = 0
|
||||
_reconnectDisposition.value = GatewayReconnectDisposition.None
|
||||
_connectionState.value = GatewayConnectionState.Ready
|
||||
@@ -3134,6 +3251,18 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
}
|
||||
if (info.containsKey("tools")) {
|
||||
val groups = info["tools"] as? JsonObject
|
||||
_serverTools.value = groups
|
||||
?.values
|
||||
?.asSequence()
|
||||
?.mapNotNull { it as? JsonArray }
|
||||
?.flatMap { it.asSequence() }
|
||||
?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
|
||||
?.filter { it.isNotBlank() }
|
||||
?.toSet()
|
||||
?: emptySet()
|
||||
}
|
||||
// Context usage: require used > 0 — a COLD resume resets counters and
|
||||
// reports 0 until the first turn rebuilds the prompt; painting 0 would
|
||||
// mislead on a session that actually has history.
|
||||
@@ -3149,6 +3278,7 @@ class GatewayChatClient(
|
||||
/** Apply a session create/resume result without leaking metadata from the prior session. */
|
||||
private fun applySessionResultInfo(result: JsonObject) {
|
||||
_serverProject.value = null
|
||||
_serverTools.value = null
|
||||
(result["info"] as? JsonObject)?.let { applySessionInfo(it) }
|
||||
}
|
||||
|
||||
@@ -3165,7 +3295,8 @@ class GatewayChatClient(
|
||||
?.stringField("profile_name")
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
if (actual != expected) {
|
||||
val socketConfirmed = actual == null && connectedSocketProfile == expected
|
||||
if (actual != expected && !socketConfirmed) {
|
||||
val detail = actual?.let { "Hermes returned profile '$it'" }
|
||||
?: "Hermes did not confirm profile ownership"
|
||||
throw GatewayPreflightException(
|
||||
@@ -3267,6 +3398,7 @@ class GatewayChatClient(
|
||||
val requestedProfile = currentSessionProfile()
|
||||
if (requestedStoredId != null && requestedStoredId != storedSessionId) {
|
||||
cancelledTurnDrain = null
|
||||
settledTurnDrain = null
|
||||
}
|
||||
if (
|
||||
liveSessionId != null &&
|
||||
@@ -3274,6 +3406,7 @@ class GatewayChatClient(
|
||||
requestedStoredId != null &&
|
||||
liveSessionProfile == requestedProfile
|
||||
) {
|
||||
awaitSessionReadyIfRequired(liveSessionId!!)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -3303,6 +3436,7 @@ class GatewayChatClient(
|
||||
liveSessionProfile = requestedProfile
|
||||
updateCancelledDrainLiveSession(requestedStoredId, live)
|
||||
applySessionResultInfo(result)
|
||||
awaitSessionReadyIfRequired(live, result)
|
||||
return
|
||||
}
|
||||
throw GatewayAuthoritativeResumeException(
|
||||
@@ -3336,7 +3470,47 @@ class GatewayChatClient(
|
||||
storedSessionId = stored
|
||||
liveSessionProfile = requestedProfile
|
||||
if (cancelledTurnDrain?.storedSessionId != stored) cancelledTurnDrain = null
|
||||
if (settledTurnDrain?.storedSessionId != stored) settledTurnDrain = null
|
||||
turn.callbacks.onSessionId(stored)
|
||||
awaitSessionReadyIfRequired(live, created)
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for current upstream's authoritative deferred-build edge instead of
|
||||
* racing a lazy session into compute-host turn isolation. Without this
|
||||
* barrier, the parent runtime can claim the durable lease before the child
|
||||
* rechecks it, causing the child to reject itself as a second live owner.
|
||||
*/
|
||||
private suspend fun awaitSessionReadyIfRequired(
|
||||
liveId: String,
|
||||
sessionResult: JsonObject? = null,
|
||||
) {
|
||||
val lazy = (sessionResult?.get("info") as? JsonObject)?.booleanField("lazy") == true
|
||||
if (lazy) lazyLiveSessions += liveId
|
||||
if (liveId !in lazyLiveSessions) return
|
||||
if (readyLiveSessions.remove(liveId)) {
|
||||
lazyLiveSessions.remove(liveId)
|
||||
return
|
||||
}
|
||||
val waiter = sessionReadyWaiters.computeIfAbsent(liveId) { CompletableDeferred() }
|
||||
if (readyLiveSessions.remove(liveId)) waiter.complete(Unit)
|
||||
try {
|
||||
withTimeout(sessionReadyTimeoutMs) { waiter.await() }
|
||||
lazyLiveSessions.remove(liveId)
|
||||
} catch (error: Exception) {
|
||||
throw GatewayPreflightException(
|
||||
error.message ?: "Hermes session initialization timed out",
|
||||
)
|
||||
} finally {
|
||||
sessionReadyWaiters.remove(liveId, waiter)
|
||||
}
|
||||
}
|
||||
|
||||
private fun failSessionReadyWaiters(message: String) {
|
||||
sessionReadyWaiters.values.forEach {
|
||||
it.completeExceptionally(GatewayRpcException(message))
|
||||
}
|
||||
sessionReadyWaiters.clear()
|
||||
}
|
||||
|
||||
private fun createListener(ready: CompletableDeferred<Unit>) = object : WebSocketListener() {
|
||||
@@ -3515,6 +3689,33 @@ class GatewayChatClient(
|
||||
return
|
||||
}
|
||||
|
||||
// Lazy create/resume returns before its AIAgent exists. The deferred
|
||||
// build publishes exact-session session.info when it is ready. Record
|
||||
// that edge before live-session routing so a fast build cannot race
|
||||
// the RPC response and strand the first submit.
|
||||
if (type == "session.info" && !eventSessionId.isNullOrBlank() &&
|
||||
payload?.booleanField("lazy") != true
|
||||
) {
|
||||
readyLiveSessions += eventSessionId
|
||||
sessionReadyWaiters.remove(eventSessionId)?.complete(Unit)
|
||||
}
|
||||
|
||||
// Deferred agent construction can fail after lazy session.create/
|
||||
// resume returns but before prompt.submit. Fail the readiness barrier
|
||||
// immediately so the optimistic prompt remains retryable/Not sent
|
||||
// instead of waiting for the five-minute readiness timeout.
|
||||
if (type == "error" && !eventSessionId.isNullOrBlank() &&
|
||||
(eventSessionId in lazyLiveSessions || sessionReadyWaiters.containsKey(eventSessionId))
|
||||
) {
|
||||
val message = payload?.stringField("message")
|
||||
?: "Hermes session initialization failed"
|
||||
lazyLiveSessions.remove(eventSessionId)
|
||||
readyLiveSessions.remove(eventSessionId)
|
||||
sessionReadyWaiters.remove(eventSessionId)
|
||||
?.completeExceptionally(GatewayRpcException(message))
|
||||
return
|
||||
}
|
||||
|
||||
// Upstream emits session.reclaimed process-wide, so it is identified
|
||||
// by payload rather than params.session_id. Retire only an exact live
|
||||
// runtime we own; preserve the durable id so the next send resumes it.
|
||||
@@ -3713,6 +3914,7 @@ class GatewayChatClient(
|
||||
}
|
||||
dispatchProcessEvent(type, payload, eventSessionId)
|
||||
if (consumeCancelledTurnEvent(type, eventSessionId)) return
|
||||
if (consumeSettledTurnTerminal(type, eventSessionId)) return
|
||||
var turn = activeTurn
|
||||
if (turn == null && type == "message.start") {
|
||||
// Unsolicited turns are accepted only with an explicit exact live-
|
||||
@@ -3828,6 +4030,7 @@ class GatewayChatClient(
|
||||
// id on the shared gateway stream) keeps matching after reconnect.
|
||||
val preservedLiveId = liveSessionId
|
||||
webSocket = null
|
||||
connectedSocketProfile = null
|
||||
readySignal = null
|
||||
liveSessionId = null
|
||||
attachMethodForSocket = null
|
||||
@@ -3841,6 +4044,9 @@ class GatewayChatClient(
|
||||
it.completeExceptionally(GatewayRpcException("gateway connection lost"))
|
||||
}
|
||||
pendingRpcs.clear()
|
||||
failSessionReadyWaiters("gateway connection lost")
|
||||
lazyLiveSessions.clear()
|
||||
readyLiveSessions.clear()
|
||||
failChildWatches("Child watch disconnected from the gateway")
|
||||
val turn = activeTurn
|
||||
if (turn == null) {
|
||||
@@ -4016,8 +4222,12 @@ class GatewayChatClient(
|
||||
private fun closeSocket(reason: String) {
|
||||
webSocket?.close(1000, reason)
|
||||
webSocket = null
|
||||
connectedSocketProfile = null
|
||||
readySignal = null
|
||||
liveSessionId = null
|
||||
failSessionReadyWaiters("gateway socket closed")
|
||||
lazyLiveSessions.clear()
|
||||
readyLiveSessions.clear()
|
||||
attachMethodForSocket = null
|
||||
commandsCatalogCache = null
|
||||
_processCapability.value = GatewayProcessCapability.Unknown
|
||||
@@ -4226,10 +4436,12 @@ class GatewayChatClient(
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** Per-event idle-watchdog duration — asks block server-side with no events, so they arm longer. */
|
||||
private fun watchdogTimeoutFor(eventType: String): Long = when (eventType) {
|
||||
"clarify.request", "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||
"sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||
"approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||
private fun watchdogTimeoutFor(eventType: String, payload: JsonObject? = null): Long = when {
|
||||
eventType == "clarify.request" || eventType == "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||
eventType == "sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||
eventType == "approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||
eventType == "status.update" &&
|
||||
payload?.stringField("kind") == "compacting" -> compactingTimeoutMs
|
||||
else -> turnIdleTimeoutMs
|
||||
}
|
||||
|
||||
@@ -4237,6 +4449,7 @@ class GatewayChatClient(
|
||||
val callbacks: GatewayTurnCallbacks,
|
||||
dedupeAdjacentMessageStarts: Boolean = false,
|
||||
deferEvents: Boolean = false,
|
||||
private val androidOwned: Boolean = false,
|
||||
private val onTransportAccepted: () -> Unit = { },
|
||||
) : ActiveTurnHandle {
|
||||
private val mapper = GatewayEventMapper(callbacks, dedupeAdjacentMessageStarts)
|
||||
@@ -4263,6 +4476,7 @@ class GatewayChatClient(
|
||||
|
||||
private val rejoinAttempts = java.util.concurrent.atomic.AtomicInteger(0)
|
||||
private val transportAccepted = AtomicBoolean(false)
|
||||
private val progressGeneration = java.util.concurrent.atomic.AtomicLong(0L)
|
||||
|
||||
fun markTransportAccepted() {
|
||||
if (transportAccepted.compareAndSet(false, true)) {
|
||||
@@ -4339,6 +4553,7 @@ class GatewayChatClient(
|
||||
if (settledWithoutTerminalFrame) return
|
||||
if (type != "session.info") {
|
||||
started = true
|
||||
progressGeneration.incrementAndGet()
|
||||
markTransportAccepted()
|
||||
}
|
||||
tracer.mark("ttfe")
|
||||
@@ -4348,7 +4563,7 @@ class GatewayChatClient(
|
||||
// Reset on every event — long tool runs keep the turn alive.
|
||||
// Ask requests block with no further events, so they arm with
|
||||
// their own (longer) duration via watchdogTimeoutFor.
|
||||
armWatchdog(watchdogTimeoutFor(type))
|
||||
armWatchdog(watchdogTimeoutFor(type, payload))
|
||||
// Queue this immediately before the terminal callbacks. Both are
|
||||
// marshalled through the same dispatcher, preserving callback order
|
||||
// even when the WebSocket reader and reconnect coroutine differ.
|
||||
@@ -4368,10 +4583,20 @@ class GatewayChatClient(
|
||||
* exact turn has proved it went live. A pre-start `running=false`
|
||||
* heartbeat can race `prompt.submit` and is not a completion boundary.
|
||||
*/
|
||||
fun settleFromAuthoritativeSessionState(running: Boolean?, source: String): Boolean {
|
||||
fun captureLivenessGeneration(): Long? =
|
||||
if (androidOwned && started && !ended) progressGeneration.get() else null
|
||||
|
||||
fun settleFromAuthoritativeSessionState(
|
||||
running: Boolean?,
|
||||
source: String,
|
||||
expectedProgressGeneration: Long? = null,
|
||||
): Boolean {
|
||||
if (running != false || !started) return false
|
||||
val settled = synchronized(deferredEventLock) {
|
||||
if (ended) {
|
||||
if (ended ||
|
||||
(expectedProgressGeneration != null &&
|
||||
progressGeneration.get() != expectedProgressGeneration)
|
||||
) {
|
||||
false
|
||||
} else {
|
||||
settledWithoutTerminalFrame = true
|
||||
@@ -4382,6 +4607,7 @@ class GatewayChatClient(
|
||||
if (!settled) return false
|
||||
|
||||
disarmWatchdog()
|
||||
armSettledTurnDrain()
|
||||
Log.i(TAG, "Gateway turn settled from $source after missing terminal frame")
|
||||
callbacks.onReconcileRequired()
|
||||
callbacks.onComplete()
|
||||
@@ -4402,6 +4628,7 @@ class GatewayChatClient(
|
||||
callbacks = dispatchOn(registration.callbacks),
|
||||
dedupeAdjacentMessageStarts = true,
|
||||
deferEvents = true,
|
||||
androidOwned = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4529,6 +4756,26 @@ class GatewayChatClient(
|
||||
)
|
||||
}
|
||||
|
||||
private fun armSettledTurnDrain() {
|
||||
val storedId = storedSessionId ?: return
|
||||
val liveId = liveSessionId ?: return
|
||||
settledTurnDrain = SettledTurnDrain(storedId, liveId)
|
||||
}
|
||||
|
||||
/** Consume one late terminal from a turn already settled by session state. */
|
||||
private fun consumeSettledTurnTerminal(type: String, eventSessionId: String?): Boolean {
|
||||
val drain = settledTurnDrain ?: return false
|
||||
if (eventSessionId != drain.liveSessionId) return false
|
||||
if (type == "message.start") {
|
||||
if (settledTurnDrain === drain) settledTurnDrain = null
|
||||
return false
|
||||
}
|
||||
if (type != "message.complete" && type != "error") return false
|
||||
if (settledTurnDrain === drain) settledTurnDrain = null
|
||||
Log.d(TAG, "Ignored late terminal for gateway turn settled from session state")
|
||||
return true
|
||||
}
|
||||
|
||||
private fun updateCancelledDrainLiveSession(storedId: String, liveId: String) {
|
||||
val drain = cancelledTurnDrain ?: return
|
||||
if (drain.storedSessionId == storedId) {
|
||||
@@ -4655,6 +4902,11 @@ class GatewayChatClient(
|
||||
dispatchIfCurrent(stillCurrent) { callbacks.onStatusUpdate(kind, text) }
|
||||
},
|
||||
onStatusClear = { kind -> dispatchIfCurrent(stillCurrent) { callbacks.onStatusClear(kind) } },
|
||||
onNoticeShow = { notice -> dispatchIfCurrent(stillCurrent) { callbacks.onNoticeShow(notice) } },
|
||||
onNoticeClear = { key -> dispatchIfCurrent(stillCurrent) { callbacks.onNoticeClear(key) } },
|
||||
onSubmitRejected = { message ->
|
||||
dispatchIfCurrent(stillCurrent) { callbacks.onSubmitRejected(message) }
|
||||
},
|
||||
)
|
||||
|
||||
private fun dispatchIfCurrent(stillCurrent: () -> Boolean, callback: () -> Unit) {
|
||||
@@ -4707,7 +4959,7 @@ data class GatewayAttachment(
|
||||
val sizeBytes: Long? = null,
|
||||
)
|
||||
|
||||
/** Connect/auth/submit failed before the turn started — safe to fall back to SSE. */
|
||||
/** Connect/auth/submit failed before the turn started; the caller retains transport ownership. */
|
||||
internal class GatewayPreflightException(message: String) : Exception(message)
|
||||
|
||||
/** Attachment bytes were not safely bound to a Gateway turn; never silently fall through to SSE. */
|
||||
|
||||
@@ -7,6 +7,7 @@ import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
|
||||
/**
|
||||
@@ -195,7 +196,8 @@ class GatewayEventMapper(
|
||||
|
||||
"tool.start" -> {
|
||||
clearActivityStatuses()
|
||||
val name = payload.string("name") ?: "unknown"
|
||||
val identity = payload.effectiveToolIdentity()
|
||||
val name = identity.name
|
||||
// A pending generating placeholder for this name is adopted
|
||||
// (consumed FIFO) whether or not the server sent a real id.
|
||||
val adopted = generatingIdsByName[name]?.removeFirstOrNull()
|
||||
@@ -207,7 +209,7 @@ class GatewayEventMapper(
|
||||
}
|
||||
else -> syntheticToolId(name)
|
||||
}
|
||||
val argsPreview = payload?.get("args")
|
||||
val argsPreview = identity.argsPreview ?: payload?.get("args")
|
||||
?.takeUnless { it is JsonPrimitive && it.contentOrNull.isNullOrBlank() }
|
||||
?.toString()
|
||||
?.takeIf { it.isNotBlank() && it != "null" }
|
||||
@@ -219,7 +221,7 @@ class GatewayEventMapper(
|
||||
|
||||
"tool.complete" -> {
|
||||
clearActivityStatuses()
|
||||
val name = payload.string("name") ?: "unknown"
|
||||
val name = payload.effectiveToolIdentity().name
|
||||
val toolId = payload.string("tool_id")
|
||||
?: openSyntheticIdsByName[name]?.removeFirstOrNull()
|
||||
?: return
|
||||
@@ -278,7 +280,12 @@ class GatewayEventMapper(
|
||||
|
||||
"error" -> {
|
||||
turnEnded = true
|
||||
callbacks.onError(payload.string("message") ?: "Gateway error")
|
||||
val message = payload.string("message") ?: "Gateway error"
|
||||
if (isSessionOwnershipRejection(message)) {
|
||||
callbacks.onSubmitRejected(message)
|
||||
} else {
|
||||
callbacks.onError(message)
|
||||
}
|
||||
}
|
||||
|
||||
"subagent.spawn_requested", "subagent.start", "subagent.thinking", "subagent.tool",
|
||||
@@ -397,8 +404,26 @@ class GatewayEventMapper(
|
||||
}
|
||||
}
|
||||
|
||||
// Known-but-unrendered (notification.show, …) and unknown types
|
||||
// alike: ignore.
|
||||
"notification.show" -> {
|
||||
val text = payload.string("text")?.trim().orEmpty()
|
||||
if (text.isNotEmpty()) {
|
||||
callbacks.onNoticeShow(
|
||||
GatewayAgentNotice(
|
||||
text = text,
|
||||
level = payload.string("level"),
|
||||
kind = payload.string("kind"),
|
||||
ttlMs = payload.long("ttl_ms"),
|
||||
key = payload.string("key"),
|
||||
id = payload.string("id"),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
"notification.clear" ->
|
||||
payload.string("key")?.trim()?.takeIf(String::isNotEmpty)?.let(callbacks.onNoticeClear)
|
||||
|
||||
// Unknown event types remain forward-compatible no-ops.
|
||||
else -> Unit
|
||||
}
|
||||
previousEventType = type
|
||||
@@ -450,6 +475,19 @@ class GatewayEventMapper(
|
||||
private const val MAX_MOA_REFERENCE_CHARS = 16_000
|
||||
private val OUTPUT_RISK_LEVELS = setOf("low", "medium", "high", "critical")
|
||||
private val TERMINAL_EVENTS = setOf("message.complete", "error")
|
||||
|
||||
/**
|
||||
* Isolated-turn paths can acknowledge `prompt.submit` and then emit
|
||||
* the ownership refusal as a plain terminal `error` event. That event
|
||||
* has no JSON-RPC code or structured reason, so match both stable
|
||||
* clauses from upstream's canonical message.
|
||||
*/
|
||||
internal fun isSessionOwnershipRejection(message: String): Boolean {
|
||||
val normalized = message.lowercase()
|
||||
return "already has a live owner (" in normalized &&
|
||||
"only one surface at a time may run a session" in normalized
|
||||
}
|
||||
|
||||
internal fun isFailedMoaReference(text: String): Boolean {
|
||||
val normalized = text.trimStart().lowercase()
|
||||
return normalized.startsWith("[failed:") || normalized.startsWith("[skipped:")
|
||||
@@ -590,12 +628,43 @@ private const val MAX_CLARIFY_CHOICES = 4
|
||||
private const val SUDO_TIMEOUT_SECONDS = 120
|
||||
private const val SECRET_TIMEOUT_SECONDS = 300
|
||||
|
||||
private data class GatewayToolIdentity(
|
||||
val name: String,
|
||||
val argsPreview: String?,
|
||||
)
|
||||
|
||||
/**
|
||||
* Older Tool Search gateways can expose the model-visible `tool_call` bridge
|
||||
* instead of the effective tool identity that current upstream callbacks use.
|
||||
* Unwrap only the bridge's explicit structured `{name, arguments}` envelope;
|
||||
* never infer a tool from prompt text or result content.
|
||||
*/
|
||||
private fun JsonObject?.effectiveToolIdentity(): GatewayToolIdentity {
|
||||
val outerName = string("name") ?: "unknown"
|
||||
val outerArgs = this?.get("args") as? JsonObject
|
||||
if (outerName != "tool_call" || outerArgs == null) {
|
||||
return GatewayToolIdentity(outerName, null)
|
||||
}
|
||||
val effectiveName = outerArgs.string("name")
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
?: return GatewayToolIdentity(outerName, null)
|
||||
val effectiveArgs = outerArgs["arguments"]
|
||||
?.takeUnless { it is JsonPrimitive && it.contentOrNull.isNullOrBlank() }
|
||||
?.toString()
|
||||
?.takeIf { it.isNotBlank() && it != "null" }
|
||||
return GatewayToolIdentity(effectiveName, effectiveArgs)
|
||||
}
|
||||
|
||||
private fun JsonObject?.string(key: String): String? =
|
||||
(this?.get(key) as? JsonPrimitive)?.contentOrNull
|
||||
|
||||
private fun JsonObject?.int(key: String): Int? =
|
||||
(this?.get(key) as? JsonPrimitive)?.intOrNull
|
||||
|
||||
private fun JsonObject?.long(key: String): Long? =
|
||||
(this?.get(key) as? JsonPrimitive)?.longOrNull
|
||||
|
||||
private fun JsonObject?.double(key: String): Double? =
|
||||
(this?.get(key) as? JsonPrimitive)?.doubleOrNull
|
||||
|
||||
|
||||
@@ -91,26 +91,19 @@ enum class GatewayApprovalModeCapability {
|
||||
* is unit-testable without an AndroidViewModel. ConnectionViewModel
|
||||
* delegates here with its live state.
|
||||
*
|
||||
* Manual picks pass through untouched (ChatViewModel handles per-turn
|
||||
* fallback when a "gateway" pick can't serve a send); "auto" prefers the
|
||||
* gateway while the dashboard probe is unresolved or ready. A capability-
|
||||
* preferred SSE fallback is selected only after a definitive unavailable,
|
||||
* unsupported, or sign-in-required verdict.
|
||||
* Manual picks pass through untouched. "auto" follows the saved connection's
|
||||
* stable owner: Dashboard/Gateway for a standard connection, or the
|
||||
* capability-preferred SSE surface for a true API-only compatibility record.
|
||||
* Live reachability and sign-in state never change the owner of an open chat.
|
||||
*/
|
||||
fun resolveStreamingEndpointPreference(
|
||||
preference: String,
|
||||
gateway: GatewayAvailability,
|
||||
capabilities: ServerCapabilities,
|
||||
gatewayOwned: Boolean = true,
|
||||
): String = when (preference) {
|
||||
"sessions", "completions", "runs", "gateway" -> preference
|
||||
else -> if (
|
||||
gateway == GatewayAvailability.Ready ||
|
||||
gateway == GatewayAvailability.Unknown
|
||||
) {
|
||||
"gateway"
|
||||
} else {
|
||||
capabilities.preferredChatEndpoint()
|
||||
}
|
||||
else -> if (gatewayOwned) "gateway" else capabilities.preferredChatEndpoint()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -263,6 +256,16 @@ data class GatewayToolOutputRisk(
|
||||
val redacted: Boolean,
|
||||
)
|
||||
|
||||
/** Official upstream `notification.show` AgentNotice payload. */
|
||||
data class GatewayAgentNotice(
|
||||
val text: String,
|
||||
val level: String? = null,
|
||||
val kind: String? = null,
|
||||
val ttlMs: Long? = null,
|
||||
val key: String? = null,
|
||||
val id: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One `subagent.*` lifecycle event, emitted on the PARENT session. Lifecycle
|
||||
* per task: SPAWN_REQUESTED → START → (THINKING | TOOL | PROGRESS)* →
|
||||
@@ -734,6 +737,16 @@ class GatewayTurnCallbacks(
|
||||
val onStatusUpdate: (kind: String?, text: String) -> Unit = { _, _ -> },
|
||||
/** Clear a transient status only when [kind] still owns the visible status slot. */
|
||||
val onStatusClear: (kind: String) -> Unit = { _ -> },
|
||||
/** Official upstream account/agent notice; distinct from Relay proactive messages. */
|
||||
val onNoticeShow: (GatewayAgentNotice) -> Unit = { _ -> },
|
||||
/** Exact-key dismissal for an upstream notice. */
|
||||
val onNoticeClear: (key: String) -> Unit = { _ -> },
|
||||
/**
|
||||
* The Gateway authoritatively refused `prompt.submit` before a model turn
|
||||
* began. The composed user row remains local and retryable; callers must
|
||||
* not treat this as a dropped stream or reconcile it from history.
|
||||
*/
|
||||
val onSubmitRejected: (String) -> Unit = onError,
|
||||
)
|
||||
|
||||
/**
|
||||
|
||||
@@ -726,10 +726,10 @@ class HermesApiClient(
|
||||
|
||||
suspend fun getMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): List<MessageItem> = withContext(Dispatchers.IO) {
|
||||
loadSessionMessages(mode) { page ->
|
||||
runCatching {
|
||||
try {
|
||||
val url = "$baseUrl/api/sessions/$sessionId/messages".toHttpUrlOrNull()
|
||||
?.newBuilder()
|
||||
?.addQueryParameter("limit", page.limit.toString())
|
||||
@@ -740,14 +740,20 @@ class HermesApiClient(
|
||||
val request = authRequest(url.toString()).get().build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) error("HTTP ${response.code}")
|
||||
val body = response.body?.string() ?: error("empty response body")
|
||||
val body = response.body.readUtf8Bounded(
|
||||
DashboardApiClient.MAX_JSON_RESPONSE_BYTES,
|
||||
)
|
||||
val parsed = json.decodeFromString<MessageListResponse>(body)
|
||||
SessionMessagePage(
|
||||
messages = parsed.data ?: parsed.items ?: parsed.messages ?: emptyList(),
|
||||
pagination = parsed.pagination,
|
||||
payloadChars = body.length,
|
||||
)
|
||||
}
|
||||
}.let { Result.success(it) }
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Exception) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}.getOrElse { error ->
|
||||
if (error is CancellationException) throw error
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ internal suspend fun loadSessionMessages(
|
||||
Result.success(collected)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Throwable) {
|
||||
} catch (error: Exception) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
+9
-3
@@ -195,7 +195,7 @@ class StandardHermesVoiceClient(
|
||||
.let { Result.success<VoiceSpeechStream?>(it) }
|
||||
} catch (cancelled: CancellationException) {
|
||||
throw cancelled
|
||||
} catch (error: Throwable) {
|
||||
} catch (error: Exception) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}
|
||||
@@ -222,7 +222,9 @@ class StandardHermesVoiceClient(
|
||||
if (!response.isSuccessful) {
|
||||
return Result.failure(apiFailure(response, operation))
|
||||
}
|
||||
val body = response.body.string()
|
||||
val body = response.body.readUtf8Bounded(
|
||||
DashboardApiClient.MAX_JSON_RESPONSE_BYTES,
|
||||
)
|
||||
if (body.isBlank()) {
|
||||
return Result.failure(IOException("$operation returned an empty response"))
|
||||
}
|
||||
@@ -245,7 +247,11 @@ class StandardHermesVoiceClient(
|
||||
}
|
||||
|
||||
private fun apiFailure(response: Response, operation: String): IOException {
|
||||
val body = runCatching { response.body.string() }.getOrDefault("")
|
||||
val body = try {
|
||||
response.body.readUtf8Bounded(4L * 1024L)
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
val detail = body.takeIf { it.isNotBlank() } ?: response.message
|
||||
val message = when (response.code) {
|
||||
400 -> "$operation rejected that input - ${detail.ifBlank { "bad request" }}"
|
||||
|
||||
+132
-21
@@ -3,10 +3,12 @@ package com.hermesandroid.relay.network.usage
|
||||
import com.hermesandroid.relay.network.relay.RelayHttpClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.decodeFromJsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
|
||||
/** Relay-enhanced usage with an upstream fallback for hosts without Relay support. */
|
||||
/** Upstream usage enriched by the optional Relay provider/pool surface. */
|
||||
class ProviderUsageRepository(
|
||||
private val gatewayClientProvider: () -> GatewayChatClient?,
|
||||
private val dashboardClientProvider: () -> DashboardApiClient? = { null },
|
||||
@@ -14,33 +16,142 @@ class ProviderUsageRepository(
|
||||
private val profileProvider: () -> String? = { null },
|
||||
private val sessionProvider: () -> String? = { null },
|
||||
) {
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
coerceInputValues = true
|
||||
explicitNulls = false
|
||||
}
|
||||
|
||||
suspend fun fetch(): Result<ProviderUsageResponse?> {
|
||||
val profile = profileProvider()
|
||||
val session = sessionProvider()
|
||||
val upstream: Result<ProviderUsageResponse?> = gatewayClientProvider()
|
||||
?.usageBars()
|
||||
?.mapCatching(::providerUsageFromUpstreamBars)
|
||||
?: Result.success(null)
|
||||
|
||||
val dashboard = dashboardClientProvider()
|
||||
var enhancement: Result<ProviderUsageResponse?>? = null
|
||||
if (dashboard != null) {
|
||||
val enhanced = dashboard.getProviderUsage(profile, session)
|
||||
if (enhanced.isSuccess && enhanced.getOrNull() != null) return enhanced
|
||||
enhancement = dashboard.getProviderUsage(profile, session)
|
||||
}
|
||||
|
||||
val relay = relayHttpClient.fetchProviderUsage(
|
||||
profile = profile,
|
||||
sessionId = session,
|
||||
if (enhancement?.getOrNull() == null) {
|
||||
enhancement = relayHttpClient.fetchProviderUsage(
|
||||
profile = profile,
|
||||
sessionId = session,
|
||||
)
|
||||
}
|
||||
|
||||
val merged = mergeProviderUsage(
|
||||
upstream = upstream.getOrNull(),
|
||||
enhancement = enhancement?.getOrNull(),
|
||||
)
|
||||
if (relay.isSuccess && relay.getOrNull() != null) return relay
|
||||
if (merged != null) return Result.success(merged)
|
||||
|
||||
val gateway = gatewayClientProvider()
|
||||
if (gateway != null) {
|
||||
val upstream = gateway.providerUsage()
|
||||
.mapCatching { json.decodeFromJsonElement<ProviderUsageResponse>(it) }
|
||||
if (upstream.isSuccess) return upstream
|
||||
return when {
|
||||
upstream.isFailure && enhancement?.isFailure == true ->
|
||||
Result.failure(enhancement?.exceptionOrNull()!!)
|
||||
enhancement?.isFailure == true -> Result.failure(enhancement?.exceptionOrNull()!!)
|
||||
else -> Result.success(null)
|
||||
}
|
||||
return relay
|
||||
}
|
||||
}
|
||||
|
||||
internal fun providerUsageFromUpstreamBars(root: JsonObject): ProviderUsageResponse? {
|
||||
if (root.boolean("available") != true) return null
|
||||
|
||||
val renewsAt = root.string("renews_at")
|
||||
val windows = listOfNotNull(
|
||||
root.usageWindow("plan", "Plan", renewsAt),
|
||||
root.usageWindow("topup", "Top-up", null),
|
||||
)
|
||||
val details = listOfNotNull(
|
||||
root.string("subscription_remaining_display")?.let { "Subscription remaining: $it" },
|
||||
root.string("topup_remaining_display")?.let { "Top-up remaining: $it" },
|
||||
root.string("total_spendable_display")?.let { "Total spendable: $it" },
|
||||
)
|
||||
|
||||
return ProviderUsageResponse(
|
||||
providers = listOf(
|
||||
ProviderUsageProvider(
|
||||
id = "nous",
|
||||
displayName = "Nous",
|
||||
status = ProviderUsageProvider.STATUS_AVAILABLE,
|
||||
source = "upstream:usage.bars",
|
||||
plan = root.string("plan_name"),
|
||||
windows = windows,
|
||||
details = details,
|
||||
renewsAt = renewsAt,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun mergeProviderUsage(
|
||||
upstream: ProviderUsageResponse?,
|
||||
enhancement: ProviderUsageResponse?,
|
||||
): ProviderUsageResponse? {
|
||||
if (upstream == null) return enhancement
|
||||
if (enhancement == null) return upstream
|
||||
|
||||
val providers = linkedMapOf<String, ProviderUsageProvider>()
|
||||
upstream.providers.forEach { providers[it.id] = it }
|
||||
enhancement.providers.forEach { enhanced ->
|
||||
val standard = providers[enhanced.id]
|
||||
providers[enhanced.id] = when {
|
||||
standard == null -> enhanced
|
||||
standard.available -> standard.copy(
|
||||
// Official usage.bars stays authoritative for every field it
|
||||
// supplies. Relay enriches the row with pool/balance metadata
|
||||
// and fills only gaps that upstream left absent.
|
||||
fetchedAt = standard.fetchedAt ?: enhanced.fetchedAt,
|
||||
plan = standard.plan ?: enhanced.plan,
|
||||
windows = standard.windows.ifEmpty { enhanced.windows },
|
||||
details = (standard.details + enhanced.details).distinct(),
|
||||
balances = enhanced.balances,
|
||||
renewsAt = standard.renewsAt ?: enhanced.renewsAt,
|
||||
actionUrl = standard.actionUrl ?: enhanced.actionUrl,
|
||||
credentials = enhanced.credentials,
|
||||
activeCredentialId = enhanced.activeCredentialId,
|
||||
activeCredentialState = enhanced.activeCredentialState,
|
||||
activeObservedAt = enhanced.activeObservedAt,
|
||||
message = standard.message ?: enhanced.message,
|
||||
)
|
||||
enhanced.available -> enhanced
|
||||
else -> enhanced
|
||||
}
|
||||
}
|
||||
return ProviderUsageResponse(
|
||||
schemaVersion = maxOf(upstream.schemaVersion, enhancement.schemaVersion),
|
||||
fetchedAt = enhancement.fetchedAt ?: upstream.fetchedAt,
|
||||
capabilities = upstream.capabilities + enhancement.capabilities,
|
||||
providers = providers.values.toList(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject.usageWindow(
|
||||
id: String,
|
||||
label: String,
|
||||
resetAt: String?,
|
||||
): ProviderUsageWindow? {
|
||||
val bar = this["${id}_bar"] as? JsonObject ?: return null
|
||||
val remaining = bar.string("remaining_display")
|
||||
val total = bar.string("total_display")
|
||||
val detail = when {
|
||||
remaining != null && total != null -> "$remaining remaining of $total"
|
||||
remaining != null -> "$remaining remaining"
|
||||
total != null -> "$total total"
|
||||
else -> null
|
||||
}
|
||||
return ProviderUsageWindow(
|
||||
id = id,
|
||||
label = label,
|
||||
usedPercent = bar.double("pct_used"),
|
||||
resetAt = resetAt,
|
||||
detail = detail,
|
||||
)
|
||||
}
|
||||
|
||||
private fun JsonObject.string(key: String): String? =
|
||||
(this[key] as? JsonPrimitive)?.content?.trim()?.takeIf(String::isNotEmpty)
|
||||
|
||||
private fun JsonObject.boolean(key: String): Boolean? =
|
||||
(this[key] as? JsonPrimitive)?.booleanOrNull
|
||||
|
||||
private fun JsonObject.double(key: String): Double? =
|
||||
(this[key] as? JsonPrimitive)?.doubleOrNull
|
||||
|
||||
@@ -21,6 +21,7 @@ import com.hermesandroid.relay.data.EnhancedVoiceOverrides
|
||||
import com.hermesandroid.relay.data.VoiceAudioRoute
|
||||
import com.hermesandroid.relay.data.VoiceEngineMode
|
||||
import com.hermesandroid.relay.data.VoicePreferencesRepository
|
||||
import com.hermesandroid.relay.data.VoiceProfileScope
|
||||
import com.hermesandroid.relay.data.VoiceSettings
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceAudioClientAdapter
|
||||
import com.hermesandroid.relay.network.relay.RelayVoiceClient
|
||||
@@ -170,6 +171,9 @@ internal class HermesRuntimeBinder(
|
||||
relayHttpClient = connection.relayHttpClient,
|
||||
mediaSettingsRepo = connection.mediaSettingsRepo,
|
||||
mediaCacheWriter = connection.mediaCacheWriter,
|
||||
dashboardMediaClientProvider = {
|
||||
connection.activeDashboardUrl()?.let(connection::dashboardClientForActive)
|
||||
},
|
||||
)
|
||||
chat.setSelectedProfileProvider { connection.selectedProfile.value }
|
||||
chat.setIsolatedProfileApiProvider { connection.selectedProfileUsesIsolatedApiRoute() }
|
||||
@@ -262,6 +266,11 @@ internal class HermesRuntimeBinder(
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
chat.isStreaming.collect(connection::setChatStreaming)
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
chat.conversationBinding.collect { binding ->
|
||||
connection.setActiveConversationTransport(binding.transport)
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.activeConnectionId,
|
||||
@@ -282,6 +291,36 @@ internal class HermesRuntimeBinder(
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.connectionsHydrated,
|
||||
connection.activeConnectionId,
|
||||
connection.relayConfigured,
|
||||
voiceSettingsHydrated,
|
||||
voicePreferencesRepository.activeScope,
|
||||
) { connectionsReady, connectionId, relayConfigured, settingsReady, scope ->
|
||||
VoiceRelayReconciliationInputs(
|
||||
connectionsReady = connectionsReady,
|
||||
connectionId = connectionId,
|
||||
relayConfigured = relayConfigured,
|
||||
settingsReady = settingsReady,
|
||||
scope = scope,
|
||||
)
|
||||
}.collectLatest { inputs ->
|
||||
if (
|
||||
inputs.connectionsReady &&
|
||||
inputs.settingsReady &&
|
||||
inputs.connectionId != null &&
|
||||
!inputs.relayConfigured &&
|
||||
// Default-profile storage is a legacy global layer shared
|
||||
// across connections. Keep its fallback runtime-only.
|
||||
inputs.scope.profileName != null &&
|
||||
inputs.scope.connectionId == inputs.connectionId
|
||||
) {
|
||||
voicePreferencesRepository.reconcileRelayRemoval(inputs.scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
jobs += runtime.coroutineScope.launch {
|
||||
combine(
|
||||
connection.streamingEndpoint,
|
||||
@@ -398,13 +437,22 @@ internal class HermesRuntimeBinder(
|
||||
connection.chatReady,
|
||||
connection.standardVoiceAvailability,
|
||||
connection.relayVoiceReady,
|
||||
connection.profileSelectionSettled,
|
||||
) { settings, chatReady, standard, relayReady, profileSettled ->
|
||||
connection.relayConfigured,
|
||||
) { settings, chatReady, standard, relayReady, relayConfigured ->
|
||||
VoiceReadinessInputs(
|
||||
settings = settings,
|
||||
chatReady = chatReady,
|
||||
standardAvailability = standard,
|
||||
relayReady = relayReady,
|
||||
relayConfigured = relayConfigured,
|
||||
)
|
||||
}.combine(connection.profileSelectionSettled) { inputs, profileSettled ->
|
||||
resolveVoiceActivationReadiness(
|
||||
settings,
|
||||
chatReady,
|
||||
standard,
|
||||
relayReady,
|
||||
inputs.settings,
|
||||
inputs.chatReady,
|
||||
inputs.standardAvailability,
|
||||
inputs.relayReady,
|
||||
inputs.relayConfigured,
|
||||
profileSettled,
|
||||
)
|
||||
}
|
||||
@@ -558,6 +606,22 @@ internal class HermesRuntimeBinder(
|
||||
val hiddenSources: Set<String> = emptySet(),
|
||||
)
|
||||
|
||||
private data class VoiceRelayReconciliationInputs(
|
||||
val connectionsReady: Boolean,
|
||||
val connectionId: String?,
|
||||
val relayConfigured: Boolean,
|
||||
val settingsReady: Boolean,
|
||||
val scope: VoiceProfileScope,
|
||||
)
|
||||
|
||||
private data class VoiceReadinessInputs(
|
||||
val settings: VoiceSettings,
|
||||
val chatReady: Boolean,
|
||||
val standardAvailability: StandardVoiceAvailability,
|
||||
val relayReady: Boolean,
|
||||
val relayConfigured: Boolean,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val PROFILE_SETTLE_BACKSTOP_MS = 2_500L
|
||||
const val PROFILE_CONTEXT_COALESCE_MS = 160L
|
||||
@@ -596,12 +660,14 @@ internal fun resolveVoiceActivationReadiness(
|
||||
chatReady: Boolean,
|
||||
standardAvailability: StandardVoiceAvailability,
|
||||
relayReady: Boolean,
|
||||
relayConfigured: Boolean,
|
||||
profileSettled: Boolean,
|
||||
): HermesVoiceActivationReadiness {
|
||||
if (!profileSettled) {
|
||||
return HermesVoiceActivationReadiness.Waiting("Loading the selected Hermes profile")
|
||||
}
|
||||
return when (VoiceEngineMode.fromStorage(settings.engineMode)) {
|
||||
val effectiveSettings = voiceSettingsForRelayConfiguration(settings, relayConfigured)
|
||||
return when (VoiceEngineMode.fromStorage(effectiveSettings.engineMode)) {
|
||||
VoiceEngineMode.RealtimeAgent -> {
|
||||
if (relayReady) {
|
||||
HermesVoiceActivationReadiness.Ready(HermesVoiceActivationRoute.Realtime)
|
||||
@@ -613,7 +679,7 @@ internal fun resolveVoiceActivationReadiness(
|
||||
if (!chatReady) {
|
||||
return HermesVoiceActivationReadiness.Waiting("Waiting for Hermes chat")
|
||||
}
|
||||
when (VoiceAudioRoute.fromStorage(settings.audioRoute)) {
|
||||
when (VoiceAudioRoute.fromStorage(effectiveSettings.audioRoute)) {
|
||||
VoiceAudioRoute.Relay -> if (relayReady) {
|
||||
HermesVoiceActivationReadiness.Ready(
|
||||
HermesVoiceActivationRoute.RelayAudio
|
||||
@@ -637,6 +703,24 @@ internal fun resolveVoiceActivationReadiness(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Relay absence is a topology decision, unlike a transient route outage. Only
|
||||
* the former may fall back from Relay-only persisted selections.
|
||||
*/
|
||||
internal fun voiceSettingsForRelayConfiguration(
|
||||
settings: VoiceSettings,
|
||||
relayConfigured: Boolean,
|
||||
): VoiceSettings {
|
||||
if (relayConfigured) return settings
|
||||
return settings.copy(
|
||||
engineMode = VoiceEngineMode.HermesVoiceOutput.storageValue,
|
||||
audioRoute = when (VoiceAudioRoute.fromStorage(settings.audioRoute)) {
|
||||
VoiceAudioRoute.Relay -> VoiceAudioRoute.Auto.storageValue
|
||||
else -> settings.audioRoute
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private fun standardVoiceReadiness(
|
||||
availability: StandardVoiceAvailability,
|
||||
): HermesVoiceActivationReadiness = when (availability) {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.hermesandroid.relay.ui
|
||||
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/** Width policy shared by Chat's content and persistent status surfaces. */
|
||||
internal data class ChatResponsiveLayout(
|
||||
val introMaxWidth: Dp?,
|
||||
val avatarSize: Dp?,
|
||||
val chromeMaxWidth: Dp?,
|
||||
val transcriptMaxWidth: Dp?,
|
||||
val focusVoiceMaxWidth: Dp?,
|
||||
)
|
||||
|
||||
internal fun chatResponsiveLayout(screenWidthDp: Int): ChatResponsiveLayout = when {
|
||||
screenWidthDp >= 840 -> ChatResponsiveLayout(
|
||||
introMaxWidth = 720.dp,
|
||||
avatarSize = 360.dp,
|
||||
chromeMaxWidth = 960.dp,
|
||||
transcriptMaxWidth = 960.dp,
|
||||
focusVoiceMaxWidth = 1120.dp,
|
||||
)
|
||||
screenWidthDp >= 600 -> ChatResponsiveLayout(
|
||||
introMaxWidth = 600.dp,
|
||||
avatarSize = 300.dp,
|
||||
chromeMaxWidth = 760.dp,
|
||||
transcriptMaxWidth = 760.dp,
|
||||
focusVoiceMaxWidth = 760.dp,
|
||||
)
|
||||
else -> ChatResponsiveLayout(
|
||||
introMaxWidth = null,
|
||||
avatarSize = null,
|
||||
chromeMaxWidth = null,
|
||||
transcriptMaxWidth = null,
|
||||
focusVoiceMaxWidth = null,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun useSplitVoiceLayout(screenWidthDp: Int, screenHeightDp: Int): Boolean =
|
||||
screenWidthDp >= 840 && screenWidthDp > screenHeightDp
|
||||
@@ -117,6 +117,7 @@ import com.hermesandroid.relay.ui.components.pet.PetSafeAreaRegistry
|
||||
import com.hermesandroid.relay.ui.components.pet.petPerchSurface
|
||||
import com.hermesandroid.relay.ui.components.pet.platformModalOwnsPetLayer
|
||||
import com.hermesandroid.relay.ui.components.ConnectionSwitcherSheet
|
||||
import com.hermesandroid.relay.ui.components.ChatMediaViewerHost
|
||||
import com.hermesandroid.relay.ui.components.ChatTransportStatusBadge
|
||||
import com.hermesandroid.relay.ui.components.ChatTransportTier
|
||||
import com.hermesandroid.relay.ui.components.ConnectionSecurityGlyph
|
||||
@@ -136,6 +137,8 @@ import com.hermesandroid.relay.data.BridgeSafetyPreferencesRepository
|
||||
import com.hermesandroid.relay.data.BuildFlavor
|
||||
import com.hermesandroid.relay.data.CandidateBuild
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.data.chatTransportForPreference
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.FeatureFlags
|
||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||
@@ -283,6 +286,8 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
connection: Connection?,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiHealth: ConnectionViewModel.HealthStatus,
|
||||
streamingEndpoint: String = "auto",
|
||||
conversationOwner: SessionTransport? = null,
|
||||
): ChatRuntimeStatus {
|
||||
val capabilities = connection?.capabilities
|
||||
val gateway = when {
|
||||
@@ -298,7 +303,11 @@ internal fun resolveAppChatRuntimeStatus(
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing -> ChatTransportReadiness.Connecting
|
||||
else -> ChatTransportReadiness.Unavailable
|
||||
}
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api)
|
||||
val owner = when (conversationOwner ?: connection?.chatTransportForPreference(streamingEndpoint)) {
|
||||
SessionTransport.SSE -> ChatTransportPath.ApiSse
|
||||
else -> ChatTransportPath.Gateway
|
||||
}
|
||||
return resolveChatRuntimeStatus(gateway = gateway, apiSse = api, owner = owner)
|
||||
}
|
||||
|
||||
internal fun shouldSettleStartupUnreachable(
|
||||
@@ -360,7 +369,7 @@ internal fun resolveFooterRouteCandidate(
|
||||
*
|
||||
* Endpoint roles are operator and wire metadata, so an internal role such as
|
||||
* `authenticated_dashboard` must never leak into this constrained surface.
|
||||
* Gateway labels describe how the Dashboard is reached; API fallback keeps
|
||||
* Gateway labels describe how the Dashboard is reached; Direct API keeps
|
||||
* the route's ordinary transport label.
|
||||
*/
|
||||
internal fun resolveFooterRouteLabel(
|
||||
@@ -1007,6 +1016,17 @@ fun RelayApp() {
|
||||
chatSessions.firstOrNull { it.sessionId == currentChatSessionId }
|
||||
}
|
||||
|
||||
LaunchedEffect(
|
||||
gitOwnerKey,
|
||||
activeChatSession?.gitRepoRoot,
|
||||
activeChatSession?.workingDirectory,
|
||||
) {
|
||||
gitStateViewModel.setSessionWorkspace(
|
||||
repoRoot = activeChatSession?.gitRepoRoot,
|
||||
workingDirectory = activeChatSession?.workingDirectory,
|
||||
)
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -1023,7 +1043,7 @@ fun RelayApp() {
|
||||
}
|
||||
}
|
||||
|
||||
val gitWorkspaceAvailable = gitRepoScanningEnabled &&
|
||||
val gitWorkspaceAvailable =
|
||||
(gitReposState as? GitStateUiState.Ready)?.repos?.isNotEmpty() == true
|
||||
val gitWorkspaceSummary = remember(
|
||||
gitReposState,
|
||||
@@ -1593,6 +1613,7 @@ fun RelayApp() {
|
||||
// evidence alone left a window where the reveal showed the CTA for
|
||||
// the few hundred ms until the client-based health verdict landed.
|
||||
val chatReady by connectionViewModel.chatReady.collectAsState()
|
||||
val conversationOwner by connectionViewModel.activeConversationTransport.collectAsState()
|
||||
var startupGateMinElapsed by remember { mutableStateOf(false) }
|
||||
var startupGateTimedOut by remember { mutableStateOf(false) }
|
||||
var startupGateReleased by remember { mutableStateOf(false) }
|
||||
@@ -1619,6 +1640,8 @@ fun RelayApp() {
|
||||
connection = activeConnection,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
apiHealth = apiHealth,
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
conversationOwner = conversationOwner,
|
||||
)
|
||||
// A Dashboard/Gateway-only connection is a complete standard Hermes
|
||||
// connection. Startup readiness follows the same transport-neutral
|
||||
@@ -2125,7 +2148,9 @@ fun RelayApp() {
|
||||
?: stringResource(R.string.status_no_route),
|
||||
)
|
||||
val transportStatus = resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = connectionViewModel.resolveActiveStreamingEndpoint(
|
||||
streamingEndpoint,
|
||||
),
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCapabilities,
|
||||
)
|
||||
@@ -2176,6 +2201,9 @@ fun RelayApp() {
|
||||
// Routine in-progress reconnect surfaces here (amber cue)
|
||||
// instead of a take-space banner or a floating toast.
|
||||
reconnecting = connectionReconnecting,
|
||||
maxContentWidth = chatResponsiveLayout(
|
||||
LocalConfiguration.current.screenWidthDp,
|
||||
).chromeMaxWidth,
|
||||
modifier = Modifier.petPerchSurface(
|
||||
key = APP_STATUS_PET_WALK_REGION,
|
||||
routes = APP_STATUS_PET_ROUTES,
|
||||
@@ -2448,103 +2476,110 @@ fun RelayApp() {
|
||||
|
||||
val screenChatLabel = stringResource(R.string.screen_chat_label)
|
||||
|
||||
ChatScreen(
|
||||
chatViewModel = chatViewModel,
|
||||
connectionViewModel = connectionViewModel,
|
||||
voiceViewModel = voiceViewModel,
|
||||
voiceClient = voiceClient,
|
||||
maxBubbleWidth = maxBubbleWidth,
|
||||
voicePresentationMode = voicePresentationMode,
|
||||
onVoicePresentationModeChange = { mode ->
|
||||
connectionSwitchScope.launch {
|
||||
voicePreferences.setPresentationMode(mode)
|
||||
}
|
||||
},
|
||||
openAgentSheetOnEntry = openAgentSheetArg,
|
||||
onAgentSheetArgConsumed = {
|
||||
backStackEntry.arguments?.putBoolean(
|
||||
Screen.Chat.ARG_OPEN_AGENT_SHEET, false,
|
||||
)
|
||||
},
|
||||
// AgentInfoSheet footer jumps straight into the full
|
||||
// Connections CRUD screen — saves a detour through
|
||||
// Settings → Gateways.
|
||||
onNavigateToConnections = {
|
||||
navController.navigate(Screen.ConnectionsSettings.route)
|
||||
},
|
||||
onNavigateToConnect = {
|
||||
navController.navigate(Screen.Pair.route()) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onRepairConnection = {
|
||||
navController.navigate(
|
||||
Screen.Pair.route(
|
||||
connectionId = activeConnectionId,
|
||||
autoStart = "relay",
|
||||
),
|
||||
) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
// Empty-chat "needs connection" card also offers the offline
|
||||
// demo, so a skipped / never-connected first run can explore
|
||||
// without leaving Chat. Safe here — this state only shows when
|
||||
// nothing is configured, so there's no placeholder in flight.
|
||||
onTryDemo = enterDemo,
|
||||
onNavigateToDashboardSignIn = {
|
||||
navController.navigate(Screen.DashboardSignIn.route()) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToBridge = {
|
||||
rememberBridgeReturn(
|
||||
route = Screen.Chat.route(openAgentSheet = false),
|
||||
label = screenChatLabel,
|
||||
)
|
||||
navController.navigate(Screen.Bridge.route) {
|
||||
popUpTo(navController.graph.findStartDestination().id) {
|
||||
saveState = true
|
||||
ChatMediaViewerHost(
|
||||
activeConnectionId,
|
||||
effectiveSessionProfileName,
|
||||
currentChatSessionId,
|
||||
chatSupervisedPolicy,
|
||||
) {
|
||||
ChatScreen(
|
||||
chatViewModel = chatViewModel,
|
||||
connectionViewModel = connectionViewModel,
|
||||
voiceViewModel = voiceViewModel,
|
||||
voiceClient = voiceClient,
|
||||
maxBubbleWidth = maxBubbleWidth,
|
||||
voicePresentationMode = voicePresentationMode,
|
||||
onVoicePresentationModeChange = { mode ->
|
||||
connectionSwitchScope.launch {
|
||||
voicePreferences.setPresentationMode(mode)
|
||||
}
|
||||
launchSingleTop = true
|
||||
restoreState = true
|
||||
}
|
||||
},
|
||||
onNavigateToTerminal = {
|
||||
navController.navigate(Screen.Terminal.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToSettings = {
|
||||
navController.navigate(Screen.Settings.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToAppearanceSettings = {
|
||||
navController.navigate(Screen.AppearanceSettings.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToVoiceSettings = {
|
||||
navController.navigate(Screen.VoiceSettings.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToProfileInspector = { profileName ->
|
||||
navController.navigate(Screen.ProfileInspector.route(profileName)) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
supervisedPolicy = chatSupervisedPolicy,
|
||||
onNavigateToBotMode = {
|
||||
navController.navigate(Screen.BotMode.route) { launchSingleTop = true }
|
||||
},
|
||||
gitWorkspaceAvailable = gitWorkspaceAvailable,
|
||||
gitWorkspaceSummary = gitWorkspaceSummary,
|
||||
onNavigateToGitWorkspace = {
|
||||
navController.navigate(Screen.GitState.route) { launchSingleTop = true }
|
||||
},
|
||||
)
|
||||
},
|
||||
openAgentSheetOnEntry = openAgentSheetArg,
|
||||
onAgentSheetArgConsumed = {
|
||||
backStackEntry.arguments?.putBoolean(
|
||||
Screen.Chat.ARG_OPEN_AGENT_SHEET, false,
|
||||
)
|
||||
},
|
||||
// AgentInfoSheet footer jumps straight into the full
|
||||
// Connections CRUD screen — saves a detour through
|
||||
// Settings → Gateways.
|
||||
onNavigateToConnections = {
|
||||
navController.navigate(Screen.ConnectionsSettings.route)
|
||||
},
|
||||
onNavigateToConnect = {
|
||||
navController.navigate(Screen.Pair.route()) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onRepairConnection = {
|
||||
navController.navigate(
|
||||
Screen.Pair.route(
|
||||
connectionId = activeConnectionId,
|
||||
autoStart = "relay",
|
||||
),
|
||||
) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
// Empty-chat "needs connection" card also offers the offline
|
||||
// demo, so a skipped / never-connected first run can explore
|
||||
// without leaving Chat. Safe here — this state only shows when
|
||||
// nothing is configured, so there's no placeholder in flight.
|
||||
onTryDemo = enterDemo,
|
||||
onNavigateToDashboardSignIn = {
|
||||
navController.navigate(Screen.DashboardSignIn.route()) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToBridge = {
|
||||
rememberBridgeReturn(
|
||||
route = Screen.Chat.route(openAgentSheet = false),
|
||||
label = screenChatLabel,
|
||||
)
|
||||
navController.navigate(Screen.Bridge.route) {
|
||||
popUpTo(navController.graph.findStartDestination().id) {
|
||||
saveState = true
|
||||
}
|
||||
launchSingleTop = true
|
||||
restoreState = true
|
||||
}
|
||||
},
|
||||
onNavigateToTerminal = {
|
||||
navController.navigate(Screen.Terminal.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToSettings = {
|
||||
navController.navigate(Screen.Settings.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToAppearanceSettings = {
|
||||
navController.navigate(Screen.AppearanceSettings.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToVoiceSettings = {
|
||||
navController.navigate(Screen.VoiceSettings.route) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
onNavigateToProfileInspector = { profileName ->
|
||||
navController.navigate(Screen.ProfileInspector.route(profileName)) {
|
||||
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) {
|
||||
BotModeScreen(
|
||||
|
||||
@@ -8,17 +8,38 @@ import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/** Visual tone of a transient banner message. Errors are NOT modelled here —
|
||||
* they stay on the snackbar (see [LocalSnackbarHost]); this bus is info-only. */
|
||||
enum class UiMessageSeverity { Info, Success, Status }
|
||||
/** Visual tone of a transient banner message. */
|
||||
enum class UiMessageSeverity { Info, Success, Status, Warning }
|
||||
|
||||
data class UiMessage(
|
||||
val id: Long,
|
||||
val text: String,
|
||||
val severity: UiMessageSeverity,
|
||||
val ttlMillis: Long,
|
||||
/** Stable upstream key for replace-in-place and exact dismissal. */
|
||||
val key: String? = null,
|
||||
)
|
||||
|
||||
sealed interface UiMessageEvent {
|
||||
data class Show(val message: UiMessage) : UiMessageEvent
|
||||
data class Clear(val key: String) : UiMessageEvent
|
||||
}
|
||||
|
||||
internal fun reduceUiMessages(
|
||||
current: List<UiMessage>,
|
||||
event: UiMessageEvent,
|
||||
maxRetained: Int,
|
||||
): List<UiMessage> = when (event) {
|
||||
is UiMessageEvent.Clear -> current.filterNot { it.key == event.key }
|
||||
is UiMessageEvent.Show -> {
|
||||
val incoming = event.message
|
||||
val withoutDuplicate = current.filterNot { existing ->
|
||||
if (incoming.key != null) existing.key == incoming.key else existing.text == incoming.text
|
||||
}
|
||||
(withoutDuplicate + incoming).takeLast(maxRetained)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* App-wide bus for transient, non-error status/confirmation messages that
|
||||
* surface in the top [com.hermesandroid.relay.ui.components.MessageBannerHost]
|
||||
@@ -26,8 +47,10 @@ data class UiMessage(
|
||||
* shows the newest line collapsed, expands to a few recent lines, auto-dismisses
|
||||
* and coalesces duplicates.
|
||||
*
|
||||
* Deliberately info-only: errors and persistent/actionable messages keep going
|
||||
* to the snackbar so they demand acknowledgement. Migrate frequent
|
||||
* App-owned errors and persistent/actionable messages keep going to the
|
||||
* snackbar so they demand acknowledgement. Upstream keyed AgentNotices may use
|
||||
* the warning tone here because their own sticky/clear lifecycle owns them.
|
||||
* Migrate frequent
|
||||
* `snackbarHostState.showSnackbar("…")` confirmations/status to [info] /
|
||||
* [success] / [status] here.
|
||||
*
|
||||
@@ -39,8 +62,8 @@ object UiMessageBus {
|
||||
const val STATUS_TTL_MS = 6_000L
|
||||
|
||||
private val counter = AtomicLong(0L)
|
||||
private val _events = MutableSharedFlow<UiMessage>(extraBufferCapacity = 24)
|
||||
val events: SharedFlow<UiMessage> = _events.asSharedFlow()
|
||||
private val _events = MutableSharedFlow<UiMessageEvent>(extraBufferCapacity = 24)
|
||||
val events: SharedFlow<UiMessageEvent> = _events.asSharedFlow()
|
||||
|
||||
// Number of messages currently shown by the host. Lifted here so the app
|
||||
// scaffold can fold banner visibility into its status-bar inset accounting
|
||||
@@ -52,10 +75,26 @@ object UiMessageBus {
|
||||
text: String,
|
||||
severity: UiMessageSeverity = UiMessageSeverity.Info,
|
||||
ttlMillis: Long = DEFAULT_TTL_MS,
|
||||
key: String? = null,
|
||||
) {
|
||||
val trimmed = text.trim()
|
||||
if (trimmed.isEmpty()) return
|
||||
_events.tryEmit(UiMessage(counter.incrementAndGet(), trimmed, severity, ttlMillis))
|
||||
_events.tryEmit(
|
||||
UiMessageEvent.Show(
|
||||
UiMessage(
|
||||
id = counter.incrementAndGet(),
|
||||
text = trimmed,
|
||||
severity = severity,
|
||||
ttlMillis = ttlMillis.coerceAtLeast(0L),
|
||||
key = key?.trim()?.takeIf(String::isNotEmpty),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** Dismiss only the keyed message owned by the matching upstream notice. */
|
||||
fun clear(key: String) {
|
||||
key.trim().takeIf(String::isNotEmpty)?.let { _events.tryEmit(UiMessageEvent.Clear(it)) }
|
||||
}
|
||||
|
||||
/** Neutral confirmation/info (e.g. "Pairing code copied"). */
|
||||
|
||||
+1
-1
@@ -613,7 +613,7 @@ private fun CapabilityRow(
|
||||
|
||||
/**
|
||||
* Advanced compatibility and override content:
|
||||
* - optional direct API fallback URL/key
|
||||
* - optional Direct API URL/key
|
||||
* - explicit direct Relay endpoint override/test
|
||||
* - allow-insecure-connections development toggle
|
||||
*
|
||||
|
||||
@@ -31,6 +31,7 @@ import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -128,10 +129,11 @@ fun AttachmentGallery(
|
||||
val exportAllowed = LocalImageExportAllowed.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val blurMode = LocalMediaBlurMode.current
|
||||
val viewerController = LocalChatMediaViewerController.current
|
||||
val revealed = remember { mutableStateMapOf<String, Boolean>() }
|
||||
var viewerStartIndex by remember { mutableStateOf<Int?>(null) }
|
||||
var viewerStartIndex by rememberSaveable { mutableStateOf<Int?>(null) }
|
||||
|
||||
viewerStartIndex?.let { startIndex ->
|
||||
viewerStartIndex?.takeIf { viewerController == null }?.let { startIndex ->
|
||||
AttachmentGalleryViewer(
|
||||
attachments = attachments,
|
||||
initialIndex = startIndex.coerceIn(attachments.indices),
|
||||
@@ -184,7 +186,21 @@ fun AttachmentGallery(
|
||||
.testTag("attachment-gallery-tile-$galleryIndex")
|
||||
.clip(RoundedCornerShape(GALLERY_CORNER))
|
||||
.combinedClickable(
|
||||
onClick = { viewerStartIndex = galleryIndex },
|
||||
onClick = {
|
||||
if (viewerController != null) {
|
||||
viewerController.openGallery(
|
||||
attachments = attachments,
|
||||
initialIndex = galleryIndex,
|
||||
initiallyRevealedKeys = revealed
|
||||
.filterValues { it }
|
||||
.keys,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
} else {
|
||||
viewerStartIndex = galleryIndex
|
||||
}
|
||||
},
|
||||
onLongClick = { menuExpanded = true },
|
||||
),
|
||||
)
|
||||
|
||||
@@ -9,7 +9,6 @@ import android.media.audiofx.Visualizer
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.view.SurfaceView
|
||||
import android.widget.Toast
|
||||
import androidx.annotation.OptIn
|
||||
import androidx.compose.foundation.Image
|
||||
@@ -63,10 +62,12 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -86,13 +87,13 @@ import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.ui.compose.ContentFrame
|
||||
import coil3.compose.AsyncImage
|
||||
import com.hermesandroid.relay.data.Attachment
|
||||
import com.hermesandroid.relay.data.AttachmentRenderMode
|
||||
@@ -290,7 +291,7 @@ fun Modifier.zoomable(maxScale: Float = 6f): Modifier {
|
||||
* Dispatches on [Attachment.renderMode]:
|
||||
* - IMAGE → zoomable image (Coil from the cached URI, or a decoded bitmap),
|
||||
* honoring the sensitive blur gate.
|
||||
* - VIDEO → ExoPlayer on a hand-wired [SurfaceView] with transport controls.
|
||||
* - VIDEO → ExoPlayer through Media3's lifecycle-aware Compose content frame.
|
||||
* - AUDIO → ExoPlayer mini-player with scrubber + a Visualizer amplitude meter.
|
||||
* - PDF → [PdfRenderer] paginated pages in a LazyColumn.
|
||||
* - TEXT → in-app monospace text viewer.
|
||||
@@ -384,7 +385,8 @@ fun AttachmentViewer(
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.background(Color.Black.copy(alpha = 0.96f)),
|
||||
.background(Color.Black.copy(alpha = 0.96f))
|
||||
.testTag("attachment-viewer"),
|
||||
) {
|
||||
// Body fills; toolbar floats on top. PDF/TEXT add their own top
|
||||
// inset so the first line clears the toolbar.
|
||||
@@ -737,17 +739,27 @@ private fun VideoBody(attachment: Attachment) {
|
||||
return
|
||||
}
|
||||
|
||||
var savedPosition by rememberSaveable(uri.toString()) { mutableLongStateOf(0L) }
|
||||
var wantsToPlay by rememberSaveable(uri.toString()) { mutableStateOf(true) }
|
||||
var muted by rememberSaveable(uri.toString()) { mutableStateOf(false) }
|
||||
val player = remember(uri) {
|
||||
ExoPlayer.Builder(context).build().apply {
|
||||
setMediaItem(MediaItem.fromUri(uri))
|
||||
if (savedPosition > 0L) seekTo(savedPosition)
|
||||
playWhenReady = wantsToPlay
|
||||
volume = if (muted) 0f else 1f
|
||||
prepare()
|
||||
playWhenReady = true
|
||||
}
|
||||
}
|
||||
DisposableEffect(player) { onDispose { player.release() } }
|
||||
DisposableEffect(player) {
|
||||
onDispose {
|
||||
savedPosition = player.currentPosition.coerceAtLeast(0L)
|
||||
wantsToPlay = player.playWhenReady
|
||||
player.release()
|
||||
}
|
||||
}
|
||||
|
||||
var isPlaying by remember { mutableStateOf(true) }
|
||||
var muted by remember { mutableStateOf(false) }
|
||||
var isPlaying by remember { mutableStateOf(player.isPlaying) }
|
||||
var position by remember { mutableStateOf(0L) }
|
||||
var duration by remember { mutableStateOf(0L) }
|
||||
|
||||
@@ -761,24 +773,30 @@ private fun VideoBody(attachment: Attachment) {
|
||||
LaunchedEffect(player) {
|
||||
while (true) {
|
||||
position = player.currentPosition.coerceAtLeast(0L)
|
||||
savedPosition = position
|
||||
duration = player.duration.takeIf { it > 0L } ?: 0L
|
||||
delay(250)
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center) {
|
||||
AndroidView(
|
||||
factory = { ctx ->
|
||||
SurfaceView(ctx).also { player.setVideoSurfaceView(it) }
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().weight(1f, fill = false).aspectRatio(16f / 9f),
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth().weight(1f),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
ContentFrame(
|
||||
player = player,
|
||||
modifier = Modifier.fillMaxSize().testTag("attachment-video-content"),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
PlaybackControls(
|
||||
isPlaying = isPlaying,
|
||||
position = position,
|
||||
duration = duration,
|
||||
onPlayPause = {
|
||||
if (player.isPlaying) player.pause() else player.play()
|
||||
wantsToPlay = !player.playWhenReady
|
||||
player.playWhenReady = wantsToPlay
|
||||
},
|
||||
onSeek = { player.seekTo(it) },
|
||||
trailing = {
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.hermesandroid.relay.ui.theme.appearanceTopRoundedCornerShape
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
|
||||
private val COMPOSER_TRAY_UNDERLAP = 12.dp
|
||||
|
||||
/** A separate rear surface tucked beneath the composer's foreground edge. */
|
||||
@Composable
|
||||
fun ChatComposerLayers(
|
||||
action: BusyMessageAction?,
|
||||
onActionChange: (BusyMessageAction) -> Unit,
|
||||
correctionAvailable: Boolean,
|
||||
onStop: (() -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(-COMPOSER_TRAY_UNDERLAP),
|
||||
) {
|
||||
if (action != null) {
|
||||
ChatBusyActionSelector(
|
||||
action, onActionChange,
|
||||
correctionAvailable = correctionAvailable,
|
||||
onStop = onStop,
|
||||
bottomUnderlap = COMPOSER_TRAY_UNDERLAP,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).zIndex(0f),
|
||||
)
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().zIndex(1f).testTag("chatComposerForeground")) { content() }
|
||||
}
|
||||
}
|
||||
|
||||
/** Compact current intent; optional plain-text choices slide out from behind it. */
|
||||
@Composable
|
||||
fun ChatBusyActionSelector(
|
||||
action: BusyMessageAction,
|
||||
onActionChange: (BusyMessageAction) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
correctionAvailable: Boolean = true,
|
||||
onStop: (() -> Unit)? = null,
|
||||
bottomUnderlap: Dp = 0.dp,
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
BackHandler(enabled = expanded) { expanded = false }
|
||||
Surface(
|
||||
modifier = modifier.testTag("chatBusyActionTray"),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerLow.copy(alpha = 0.82f),
|
||||
shape = appearanceTopRoundedCornerShape(12.dp),
|
||||
tonalElevation = 0.dp,
|
||||
) {
|
||||
Column(Modifier.padding(bottom = bottomUnderlap)) {
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandVertically(tween(220), expandFrom = Alignment.Bottom) +
|
||||
slideInVertically(tween(220)) { it } + fadeIn(tween(160)),
|
||||
exit = shrinkVertically(tween(180), shrinkTowards = Alignment.Bottom) +
|
||||
slideOutVertically(tween(180)) { it } + fadeOut(tween(120)),
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().testTag("chatBusyActionDrawer").padding(horizontal = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
BusyMessageAction.entries.forEach { option ->
|
||||
val available = option == BusyMessageAction.QueueNext || correctionAvailable
|
||||
Row(
|
||||
Modifier.weight(1f).heightIn(min = 48.dp)
|
||||
.testTag("chatBusyAction-${option.storedValue}")
|
||||
.selectable(selected = option == action, enabled = available, role = Role.RadioButton) {
|
||||
onActionChange(option)
|
||||
expanded = false
|
||||
}.padding(horizontal = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
if (option == action) {
|
||||
Icon(Icons.Default.Check, null, Modifier.size(14.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurface)
|
||||
} else Spacer(Modifier.size(14.dp))
|
||||
Text(
|
||||
stringResource(if (option == BusyMessageAction.CorrectNow) R.string.chat_correct_now else R.string.chat_queue_next),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = if (available) 1f else 0.38f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(
|
||||
Modifier.weight(1f).heightIn(min = 40.dp)
|
||||
.testTag("chatBusyActionTrigger")
|
||||
.clickable(role = Role.Button) { expanded = !expanded },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text(
|
||||
stringResource(if (action == BusyMessageAction.CorrectNow) R.string.chat_correct_now else R.string.chat_queue_next),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Icon(
|
||||
if (expanded) Icons.Default.ExpandMore else Icons.Default.ExpandLess,
|
||||
null, Modifier.size(14.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (onStop != null) {
|
||||
IconButton(onClick = onStop) {
|
||||
Icon(Icons.Default.Stop, stringResource(R.string.chat_input_stop_streaming), Modifier.size(18.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ChatMessageQueue(
|
||||
messages: List<String>,
|
||||
paused: Boolean,
|
||||
onResume: () -> Unit,
|
||||
onClear: () -> Unit,
|
||||
onEdit: (Int) -> Unit,
|
||||
onRemove: (Int) -> Unit,
|
||||
canEdit: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
if (messages.isEmpty()) return
|
||||
Column(modifier) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
if (paused) stringResource(R.string.chat_queue_paused)
|
||||
else pluralStringResource(R.plurals.chat_queue_count, messages.size, messages.size),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (paused) TextButton(onClick = onResume) { Text(stringResource(R.string.chat_queue_resume)) }
|
||||
TextButton(onClick = onClear) { Text(stringResource(R.string.chat_clear)) }
|
||||
}
|
||||
Column(
|
||||
Modifier.heightIn(max = 144.dp).verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
messages.forEachIndexed { index, text ->
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
text = text,
|
||||
maxLines = 2,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f)
|
||||
.clickable(enabled = canEdit, role = Role.Button) { onEdit(index) }
|
||||
.padding(vertical = 12.dp),
|
||||
)
|
||||
IconButton(onClick = { onRemove(index) }) {
|
||||
Icon(Icons.Default.Close, stringResource(R.string.chat_queue_remove))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,13 @@ fun ChatFailurePanel(
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.chat_failure_title),
|
||||
text = stringResource(
|
||||
if (isInferenceUnavailableFailure(failure.rawError)) {
|
||||
R.string.chat_failure_inference_unavailable
|
||||
} else {
|
||||
R.string.chat_failure_title
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
@@ -148,3 +154,10 @@ internal fun failureIdentity(route: String, model: String?, provider: String?):
|
||||
provider?.trim()?.takeIf { it.isNotEmpty() },
|
||||
model?.trim()?.takeIf { it.isNotEmpty() },
|
||||
).distinct().joinToString(" · ")
|
||||
|
||||
internal fun isInferenceUnavailableFailure(rawError: String): Boolean {
|
||||
val message = rawError.lowercase()
|
||||
return "agent init failed" in message ||
|
||||
"no codex credentials stored" in message ||
|
||||
"runtime resolution still failed" in message
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.ui.components
|
||||
|
||||
import android.content.Intent
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -29,6 +30,7 @@ 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.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -97,9 +99,9 @@ private fun isSensitiveAltText(alt: String): Boolean {
|
||||
|
||||
/**
|
||||
* Resolves a server-local image path — an absolute path the agent put in a
|
||||
* markdown image `` — to raw bytes, via the relay's
|
||||
* `/media/by-path` route when a relay session is paired. Returns null when no
|
||||
* relay is available or the fetch fails, so the renderer falls back to the
|
||||
* markdown image `` — to an on-disk cache URI, via the relay's
|
||||
* authenticated Dashboard route (or Relay compatibility route). Returns a
|
||||
* failure when no route is available or the fetch fails, so the renderer falls back to the
|
||||
* "this image is on the server" notice. Provided by ChatScreen from
|
||||
* [com.hermesandroid.relay.viewmodel.ChatViewModel.resolveServerImage]; the
|
||||
* default is null, which preserves the standard (no-plugin) behavior where a
|
||||
@@ -113,12 +115,12 @@ private fun isSensitiveAltText(alt: String): Boolean {
|
||||
* `RelayServerImage` on app open with a server-local image in history).
|
||||
*/
|
||||
sealed interface ServerImageResult {
|
||||
class Success(val bytes: ByteArray, val sensitive: Boolean = false) : ServerImageResult
|
||||
class Success(val cachedUri: String, val sensitive: Boolean = false) : ServerImageResult
|
||||
class Failure(val reason: String) : ServerImageResult
|
||||
}
|
||||
|
||||
fun interface RelayServerImageResolver {
|
||||
/** Fetch the server-local file's bytes over the relay, or a
|
||||
/** Fetch the server-local file into the media cache, or a
|
||||
* [ServerImageResult.Failure] whose reason explains why (unpaired /
|
||||
* sandboxed / missing / decode) so the UI can surface it instead of a
|
||||
* generic placeholder. */
|
||||
@@ -293,8 +295,10 @@ private sealed interface DataUrlImagePhase {
|
||||
@Composable
|
||||
private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
||||
var phase by remember(image.src) { mutableStateOf<DataUrlImagePhase>(DataUrlImagePhase.Loading) }
|
||||
var viewerOpen by remember(image.src) { mutableStateOf(false) }
|
||||
var viewerOpen by rememberSaveable(image.src) { mutableStateOf(false) }
|
||||
val blurMode = LocalMediaBlurMode.current
|
||||
val exportAllowed = LocalImageExportAllowed.current
|
||||
val viewerController = LocalChatMediaViewerController.current
|
||||
var revealed by remember(image.src) { mutableStateOf(false) }
|
||||
LaunchedEffect(image.src) {
|
||||
phase = withInlineImageDecodeLock {
|
||||
@@ -329,17 +333,17 @@ private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
||||
reason = "Unsupported or oversized inline image.",
|
||||
)
|
||||
is DataUrlImagePhase.Loaded -> {
|
||||
if (viewerOpen) {
|
||||
val viewerSource = ChatImageViewerSource.Bitmap(
|
||||
bitmap = current.bitmap,
|
||||
displayName = image.alt.ifBlank { "image" },
|
||||
mime = current.mime,
|
||||
// Decode the already-retained data URL only when the user
|
||||
// requests Save/Share; don't retain a second byte array.
|
||||
bytesProvider = { decodeInlineImageDataUrlOffMain(image.src)?.bytes },
|
||||
)
|
||||
if (viewerController == null && viewerOpen) {
|
||||
ChatImageViewer(
|
||||
source = ChatImageViewerSource.Bitmap(
|
||||
bitmap = current.bitmap,
|
||||
displayName = image.alt.ifBlank { "image" },
|
||||
mime = current.mime,
|
||||
// Decode the already-retained data URL only when the
|
||||
// user requests Save/Share; don't keep a second 5 MiB
|
||||
// byte array beside every thumbnail.
|
||||
bytesProvider = { decodeInlineImageDataUrlOffMain(image.src)?.bytes },
|
||||
),
|
||||
source = viewerSource,
|
||||
onDismiss = { viewerOpen = false },
|
||||
sensitive = image.sensitive,
|
||||
initiallyRevealed = revealed,
|
||||
@@ -358,7 +362,19 @@ private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
||||
.widthIn(max = maxWidth)
|
||||
.heightIn(max = 360.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.clickable { viewerOpen = true },
|
||||
.clickable {
|
||||
if (viewerController != null) {
|
||||
viewerController.openImage(
|
||||
source = viewerSource,
|
||||
sensitive = image.sensitive,
|
||||
initiallyRevealed = revealed,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
} else {
|
||||
viewerOpen = true
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -368,18 +384,21 @@ private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
||||
|
||||
@Composable
|
||||
private fun RemoteChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
||||
var viewerOpen by remember { mutableStateOf(false) }
|
||||
var viewerOpen by rememberSaveable(image.src) { mutableStateOf(false) }
|
||||
val blurMode = LocalMediaBlurMode.current
|
||||
val exportAllowed = LocalImageExportAllowed.current
|
||||
val viewerController = LocalChatMediaViewerController.current
|
||||
var revealed by remember(image.src) { mutableStateOf(false) }
|
||||
val blurred = !revealed && shouldBlurImage(blurMode, image.sensitive)
|
||||
if (viewerOpen) {
|
||||
val viewerSource = ChatImageViewerSource.Coil(
|
||||
model = image.src,
|
||||
displayName = image.alt.ifBlank { "image" },
|
||||
mime = "image/*",
|
||||
bytesProvider = { MediaSaver.fetchRemoteBytes(image.src).first },
|
||||
)
|
||||
if (viewerController == null && viewerOpen) {
|
||||
ChatImageViewer(
|
||||
source = ChatImageViewerSource.Coil(
|
||||
model = image.src,
|
||||
displayName = image.alt.ifBlank { "image" },
|
||||
mime = "image/*",
|
||||
bytesProvider = { MediaSaver.fetchRemoteBytes(image.src).first },
|
||||
),
|
||||
source = viewerSource,
|
||||
onDismiss = { viewerOpen = false },
|
||||
sensitive = image.sensitive,
|
||||
initiallyRevealed = revealed,
|
||||
@@ -395,7 +414,19 @@ private fun RemoteChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
||||
.widthIn(max = maxWidth)
|
||||
.heightIn(max = 360.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.clickable { viewerOpen = true },
|
||||
.clickable {
|
||||
if (viewerController != null) {
|
||||
viewerController.openImage(
|
||||
source = viewerSource,
|
||||
sensitive = image.sensitive,
|
||||
initiallyRevealed = revealed,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
} else {
|
||||
viewerOpen = true
|
||||
}
|
||||
},
|
||||
) {
|
||||
val state by painter.state.collectAsState()
|
||||
when (state) {
|
||||
@@ -461,6 +492,7 @@ private fun RelayServerImage(
|
||||
maxWidth: Dp,
|
||||
resolver: RelayServerImageResolver,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var phase by remember(image.src) {
|
||||
mutableStateOf<RelayImagePhase>(
|
||||
cachedInlineImage(image.src)
|
||||
@@ -473,20 +505,22 @@ private fun RelayServerImage(
|
||||
phase = withContext(Dispatchers.IO) {
|
||||
val result = try {
|
||||
resolver.fetch(image.src)
|
||||
} catch (t: Throwable) {
|
||||
ServerImageResult.Failure(t.message ?: "relay fetch failed")
|
||||
} catch (error: Exception) {
|
||||
ServerImageResult.Failure(error.message ?: "relay fetch failed")
|
||||
}
|
||||
when (result) {
|
||||
is ServerImageResult.Success -> {
|
||||
val bytes = result.bytes
|
||||
val bmp = runCatching {
|
||||
decodeOrientedBitmap(bytes)
|
||||
}.getOrNull()?.asImageBitmap()
|
||||
val cachedUri = Uri.parse(result.cachedUri)
|
||||
val bmp = try {
|
||||
decodeBoundedOrientedBitmap(context, cachedUri)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}?.asImageBitmap()
|
||||
if (bmp != null) {
|
||||
putInlineImage(image.src, bmp, result.sensitive)
|
||||
RelayImagePhase.Loaded(bmp, result.sensitive)
|
||||
} else {
|
||||
RelayImagePhase.Failed("fetched ${bytes.size} B but couldn't decode the image")
|
||||
RelayImagePhase.Failed("fetched file could not be decoded as an image")
|
||||
}
|
||||
}
|
||||
is ServerImageResult.Failure -> RelayImagePhase.Failed(result.reason)
|
||||
@@ -527,23 +561,32 @@ private fun RelayServerImageContent(
|
||||
maxWidth: Dp,
|
||||
resolver: RelayServerImageResolver,
|
||||
) {
|
||||
var viewerOpen by remember { mutableStateOf(false) }
|
||||
val context = LocalContext.current
|
||||
var viewerOpen by rememberSaveable(image.src) { mutableStateOf(false) }
|
||||
val blurMode = LocalMediaBlurMode.current
|
||||
val exportAllowed = LocalImageExportAllowed.current
|
||||
val viewerController = LocalChatMediaViewerController.current
|
||||
var revealed by remember(image.src) { mutableStateOf(false) }
|
||||
val sensitive = image.sensitive || fetchedSensitive
|
||||
val blurred = !revealed && shouldBlurImage(blurMode, sensitive)
|
||||
if (viewerOpen) {
|
||||
val viewerSource = ChatImageViewerSource.Bitmap(
|
||||
bitmap = bitmap,
|
||||
displayName = image.alt.ifBlank {
|
||||
image.src.substringAfterLast('/').ifBlank { "image" }
|
||||
},
|
||||
mime = "image/*",
|
||||
// Save/Share re-fetch the original bytes on demand so we don't hold
|
||||
// them in memory next to the decoded bitmap.
|
||||
bytesProvider = {
|
||||
(resolver.fetch(image.src) as? ServerImageResult.Success)?.let { fetched ->
|
||||
context.contentResolver.openInputStream(Uri.parse(fetched.cachedUri))
|
||||
?.use { it.readBytes() }
|
||||
}
|
||||
},
|
||||
)
|
||||
if (viewerController == null && viewerOpen) {
|
||||
ChatImageViewer(
|
||||
source = ChatImageViewerSource.Bitmap(
|
||||
bitmap = bitmap,
|
||||
displayName = image.alt.ifBlank {
|
||||
image.src.substringAfterLast('/').ifBlank { "image" }
|
||||
},
|
||||
mime = "image/*",
|
||||
// Save/Share re-fetch the original bytes on demand so we don't
|
||||
// hold them in memory next to the decoded bitmap.
|
||||
bytesProvider = { (resolver.fetch(image.src) as? ServerImageResult.Success)?.bytes },
|
||||
),
|
||||
source = viewerSource,
|
||||
onDismiss = { viewerOpen = false },
|
||||
sensitive = sensitive,
|
||||
initiallyRevealed = revealed,
|
||||
@@ -559,7 +602,19 @@ private fun RelayServerImageContent(
|
||||
.widthIn(max = maxWidth)
|
||||
.heightIn(max = 360.dp)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.clickable { viewerOpen = true },
|
||||
.clickable {
|
||||
if (viewerController != null) {
|
||||
viewerController.openImage(
|
||||
source = viewerSource,
|
||||
sensitive = sensitive,
|
||||
initiallyRevealed = revealed,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
} else {
|
||||
viewerOpen = true
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,7 +170,11 @@ fun ChatImageViewer(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
busy = true
|
||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
||||
val bytes = try {
|
||||
source.bytesProvider()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
busy = false
|
||||
if (bytes == null) {
|
||||
toast(context, errorMsg)
|
||||
@@ -195,7 +199,11 @@ fun ChatImageViewer(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
busy = true
|
||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
||||
val bytes = try {
|
||||
source.bytesProvider()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
if (bytes == null) {
|
||||
busy = false
|
||||
toast(context, errorMsg)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.tween
|
||||
@@ -191,6 +192,9 @@ fun ChatInputBar(
|
||||
physicalEnterSends: Boolean = true,
|
||||
largePasteThreshold: Int? = null,
|
||||
onLargePaste: (String) -> Unit = {},
|
||||
busyAction: BusyMessageAction? = null,
|
||||
correctionAvailable: Boolean = true,
|
||||
onBusyActionChange: (BusyMessageAction) -> Unit = {},
|
||||
) {
|
||||
val canSubmit = enabled && submitEnabled && trailing in setOf(
|
||||
ChatInputTrailing.SEND,
|
||||
@@ -236,7 +240,7 @@ fun ChatInputBar(
|
||||
// Correction and queueing are materially different actions. Keep the
|
||||
// explanation, but lead with a visible state pill so the distinction
|
||||
// does not depend on the trailing icon or accent color alone.
|
||||
AnimatedVisibility(visible = caption != null) {
|
||||
AnimatedVisibility(visible = caption != null && busyAction == null) {
|
||||
val detail = caption ?: lastCaption.orEmpty()
|
||||
val actionLabel = when (trailing) {
|
||||
ChatInputTrailing.STEER -> stringResource(R.string.chat_input_steer_response)
|
||||
@@ -319,6 +323,12 @@ fun ChatInputBar(
|
||||
)
|
||||
}
|
||||
|
||||
ChatComposerLayers(
|
||||
action = busyAction,
|
||||
onActionChange = onBusyActionChange,
|
||||
correctionAvailable = correctionAvailable,
|
||||
onStop = onStop.takeUnless { trailing == ChatInputTrailing.STOP },
|
||||
) {
|
||||
Surface(
|
||||
shape = appearanceComposerShape(),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
@@ -646,6 +656,7 @@ fun ChatInputBar(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class LargeTextInsertion(
|
||||
val insertedText: String,
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import com.hermesandroid.relay.data.Attachment
|
||||
import com.hermesandroid.relay.data.BlurMode
|
||||
|
||||
private sealed interface ChatMediaViewerRequest {
|
||||
val blurMode: BlurMode
|
||||
val exportAllowed: Boolean
|
||||
|
||||
data class SingleAttachment(
|
||||
val attachment: Attachment,
|
||||
val initiallyRevealed: Boolean,
|
||||
override val blurMode: BlurMode,
|
||||
override val exportAllowed: Boolean,
|
||||
) : ChatMediaViewerRequest
|
||||
|
||||
data class AttachmentGallery(
|
||||
val attachments: List<Attachment>,
|
||||
val initialIndex: Int,
|
||||
val initiallyRevealedKeys: Set<String>,
|
||||
override val blurMode: BlurMode,
|
||||
override val exportAllowed: Boolean,
|
||||
) : ChatMediaViewerRequest
|
||||
|
||||
data class InlineImage(
|
||||
val source: ChatImageViewerSource,
|
||||
val sensitive: Boolean,
|
||||
val initiallyRevealed: Boolean,
|
||||
override val blurMode: BlurMode,
|
||||
override val exportAllowed: Boolean,
|
||||
) : ChatMediaViewerRequest
|
||||
}
|
||||
|
||||
@Stable
|
||||
internal class ChatMediaViewerController {
|
||||
private var activeRequest by mutableStateOf<ChatMediaViewerRequest?>(null)
|
||||
|
||||
internal fun openAttachment(
|
||||
attachment: Attachment,
|
||||
initiallyRevealed: Boolean,
|
||||
blurMode: BlurMode,
|
||||
exportAllowed: Boolean,
|
||||
) {
|
||||
activeRequest = ChatMediaViewerRequest.SingleAttachment(
|
||||
attachment = attachment,
|
||||
initiallyRevealed = initiallyRevealed,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun openGallery(
|
||||
attachments: List<Attachment>,
|
||||
initialIndex: Int,
|
||||
initiallyRevealedKeys: Set<String>,
|
||||
blurMode: BlurMode,
|
||||
exportAllowed: Boolean,
|
||||
) {
|
||||
activeRequest = ChatMediaViewerRequest.AttachmentGallery(
|
||||
attachments = attachments,
|
||||
initialIndex = initialIndex,
|
||||
initiallyRevealedKeys = initiallyRevealedKeys,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun openImage(
|
||||
source: ChatImageViewerSource,
|
||||
sensitive: Boolean,
|
||||
initiallyRevealed: Boolean,
|
||||
blurMode: BlurMode,
|
||||
exportAllowed: Boolean,
|
||||
) {
|
||||
activeRequest = ChatMediaViewerRequest.InlineImage(
|
||||
source = source,
|
||||
sensitive = sensitive,
|
||||
initiallyRevealed = initiallyRevealed,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun dismiss() {
|
||||
activeRequest = null
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun RenderActiveViewer() {
|
||||
val request = activeRequest ?: return
|
||||
CompositionLocalProvider(
|
||||
LocalMediaBlurMode provides request.blurMode,
|
||||
LocalImageExportAllowed provides request.exportAllowed,
|
||||
) {
|
||||
when (request) {
|
||||
is ChatMediaViewerRequest.SingleAttachment -> AttachmentViewer(
|
||||
attachment = request.attachment,
|
||||
onDismiss = ::dismiss,
|
||||
initiallyRevealed = request.initiallyRevealed,
|
||||
)
|
||||
is ChatMediaViewerRequest.AttachmentGallery -> AttachmentGalleryViewer(
|
||||
attachments = request.attachments,
|
||||
initialIndex = request.initialIndex,
|
||||
onDismiss = ::dismiss,
|
||||
initiallyRevealedKeys = request.initiallyRevealedKeys,
|
||||
)
|
||||
is ChatMediaViewerRequest.InlineImage -> ChatImageViewer(
|
||||
source = request.source,
|
||||
onDismiss = ::dismiss,
|
||||
sensitive = request.sensitive,
|
||||
initiallyRevealed = request.initiallyRevealed,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal val LocalChatMediaViewerController =
|
||||
staticCompositionLocalOf<ChatMediaViewerController?> { null }
|
||||
|
||||
/**
|
||||
* Owns the active full-screen preview above transcript rows so responsive
|
||||
* portrait/landscape reflow cannot dispose the viewer with its source bubble.
|
||||
*/
|
||||
@Composable
|
||||
internal fun ChatMediaViewerHost(
|
||||
vararg ownerKeys: Any?,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
// A preview never follows a connection/session/policy owner change. Aside
|
||||
// from avoiding stale media, this makes export permission fail closed when
|
||||
// supervised policy changes while a viewer is open.
|
||||
val controller = remember(*ownerKeys) { ChatMediaViewerController() }
|
||||
CompositionLocalProvider(LocalChatMediaViewerController provides controller) {
|
||||
content()
|
||||
controller.RenderActiveViewer()
|
||||
}
|
||||
}
|
||||
+20
-46
@@ -21,9 +21,9 @@ import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
|
||||
enum class ChatTransportTier(val endpointId: String, val label: String) {
|
||||
Gateway("gateway", "⚡ Gateway"),
|
||||
Sessions("sessions", "📡 Sessions"),
|
||||
Completions("completions", "Completions"),
|
||||
Runs("runs", "Runs"),
|
||||
Sessions("sessions", "Direct API"),
|
||||
Completions("completions", "Direct API"),
|
||||
Runs("runs", "Direct API"),
|
||||
Offline("offline", "offline"),
|
||||
}
|
||||
|
||||
@@ -67,18 +67,6 @@ fun resolveChatTransportStatus(
|
||||
detail = "No reachable Hermes chat transport is available.",
|
||||
)
|
||||
|
||||
fun sseFallback(gatewayReason: String): ChatTransportStatus {
|
||||
if (!serverCapabilities.healthy) return offline(gatewayReason)
|
||||
val tier = preferredAvailableSseTier(serverCapabilities)
|
||||
?: return offline(gatewayReason)
|
||||
return ChatTransportStatus(
|
||||
tier = tier,
|
||||
tone = ChatTransportTone.Fallback,
|
||||
reason = "$gatewayReason → ${tier.plainName()}",
|
||||
detail = "${tier.detailText()} Using this as the fallback while Gateway is unavailable.",
|
||||
)
|
||||
}
|
||||
|
||||
fun manualSse(tier: ChatTransportTier, supported: Boolean): ChatTransportStatus {
|
||||
if (!serverCapabilities.healthy) return offline()
|
||||
return if (supported) {
|
||||
@@ -94,23 +82,17 @@ fun resolveChatTransportStatus(
|
||||
}
|
||||
|
||||
return when (preference) {
|
||||
"auto" -> when {
|
||||
"auto", "gateway" -> when {
|
||||
gatewayReady -> ChatTransportStatus(
|
||||
tier = ChatTransportTier.Gateway,
|
||||
tone = ChatTransportTone.Active,
|
||||
reason = "auto → Gateway (best)",
|
||||
reason = "Gateway connected",
|
||||
detail = ChatTransportTier.Gateway.detailText(),
|
||||
)
|
||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
||||
}
|
||||
"gateway" -> when {
|
||||
gatewayReady -> ChatTransportStatus(
|
||||
tier = ChatTransportTier.Gateway,
|
||||
tone = ChatTransportTone.Active,
|
||||
reason = "Gateway selected",
|
||||
detail = ChatTransportTier.Gateway.detailText(),
|
||||
else -> unavailable(
|
||||
ChatTransportTier.Gateway,
|
||||
gatewayFallbackReason(gatewayAvailability),
|
||||
)
|
||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
||||
}
|
||||
"sessions" -> manualSse(ChatTransportTier.Sessions, serverCapabilities.sessionsChatStream)
|
||||
"completions" -> manualSse(ChatTransportTier.Completions, serverCapabilities.portable)
|
||||
@@ -119,42 +101,34 @@ fun resolveChatTransportStatus(
|
||||
}
|
||||
}
|
||||
|
||||
private fun preferredAvailableSseTier(capabilities: ServerCapabilities): ChatTransportTier? =
|
||||
when {
|
||||
capabilities.sessionsChatStream -> ChatTransportTier.Sessions
|
||||
capabilities.portable -> ChatTransportTier.Completions
|
||||
capabilities.runs -> ChatTransportTier.Runs
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun gatewayFallbackReason(availability: GatewayAvailability): String =
|
||||
when (availability) {
|
||||
GatewayAvailability.SignInRequired -> "gateway sign-in required"
|
||||
GatewayAvailability.Unreachable -> "gateway unavailable"
|
||||
GatewayAvailability.Unsupported -> "gateway unsupported"
|
||||
GatewayAvailability.Unknown -> "checking gateway"
|
||||
GatewayAvailability.Ready -> "gateway ready"
|
||||
GatewayAvailability.SignInRequired -> "Gateway sign-in required"
|
||||
GatewayAvailability.Unreachable -> "Gateway unavailable"
|
||||
GatewayAvailability.Unsupported -> "Gateway unsupported"
|
||||
GatewayAvailability.Unknown -> "Checking Gateway"
|
||||
GatewayAvailability.Ready -> "Gateway ready"
|
||||
}
|
||||
|
||||
private fun ChatTransportTier.plainName(): String =
|
||||
when (this) {
|
||||
ChatTransportTier.Gateway -> "Gateway"
|
||||
ChatTransportTier.Sessions -> "Sessions"
|
||||
ChatTransportTier.Completions -> "Completions"
|
||||
ChatTransportTier.Runs -> "Runs"
|
||||
ChatTransportTier.Sessions -> "Direct API"
|
||||
ChatTransportTier.Completions -> "Direct API"
|
||||
ChatTransportTier.Runs -> "Direct API"
|
||||
ChatTransportTier.Offline -> "offline"
|
||||
}
|
||||
|
||||
private fun ChatTransportTier.detailText(): String =
|
||||
when (this) {
|
||||
ChatTransportTier.Gateway ->
|
||||
"Gateway uses the dashboard WebSocket /api/ws for live thinking and rich tool events."
|
||||
"Hermes Chat uses the signed-in Dashboard connection."
|
||||
ChatTransportTier.Sessions ->
|
||||
"Sessions uses /api/sessions/{id}/chat/stream with server-side session history."
|
||||
"Direct API compatibility chat with server-side session history."
|
||||
ChatTransportTier.Completions ->
|
||||
"Completions uses OpenAI-compatible SSE at /v1/chat/completions."
|
||||
"Direct API compatibility chat."
|
||||
ChatTransportTier.Runs ->
|
||||
"Runs uses /v1/runs plus streamed run events."
|
||||
"Direct API compatibility chat with streamed run events."
|
||||
ChatTransportTier.Offline ->
|
||||
"No chat transport is reachable."
|
||||
}
|
||||
|
||||
+1
-1
@@ -73,7 +73,7 @@ private const val SWIPE_DISMISS_THRESHOLD_PX = 80f
|
||||
* progress" moment (pairing, long upload, a bridge action sequence). When first
|
||||
* reused, decouple it from [ConnectionStatusSnapshot] and rename to a generic
|
||||
* `StatusToast`. It also anchors [UpdateAvailableBanner]'s visual language + the
|
||||
* shared [ConnectionStepRow]/[StepGlyph] helpers. See TODO.md.
|
||||
* shared [ConnectionStepRow]/[StepGlyph] helpers. See docs/project/TODO.md.
|
||||
*
|
||||
* Rendered as a top-aligned overlay inside a `Box` — it slides down OVER the UI
|
||||
* without shifting layout. Pair it with `AnimatedVisibility(enter =
|
||||
|
||||
@@ -741,6 +741,7 @@ fun AgentInfoSheet(
|
||||
val relayConnectionState by connectionViewModel.relayConnectionState.collectAsState()
|
||||
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||
val voiceReady by connectionViewModel.voiceReady.collectAsState()
|
||||
val standardVoiceReady by connectionViewModel.standardVoiceReady.collectAsState()
|
||||
val proactiveEnabled by connectionViewModel.proactiveEnabled.collectAsState()
|
||||
val activeEndpoint by connectionViewModel.activeEndpoint.collectAsState()
|
||||
val allConnections by connectionViewModel.connectionStore.connections.collectAsState()
|
||||
@@ -842,6 +843,7 @@ fun AgentInfoSheet(
|
||||
val sessionCaps = sessionCapabilities(
|
||||
transport = sessionTransport,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
upstreamMediaAvailable = gatewayAvailability == GatewayAvailability.Ready || standardVoiceReady,
|
||||
relayConnected = relayConnectionState == ConnectionState.Connected,
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
voiceReady = voiceReady,
|
||||
@@ -3423,6 +3425,8 @@ private fun LegacyAgentInfoSheet(
|
||||
val sessionCaps = sessionCapabilities(
|
||||
transport = sessionTransport,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
upstreamMediaAvailable = gatewayAvailability == GatewayAvailability.Ready ||
|
||||
connectionViewModel.standardVoiceReady.collectAsState().value,
|
||||
relayConnected = relayConnected,
|
||||
relayConfigured = relayUrl.isNotBlank(),
|
||||
voiceReady = voiceReady,
|
||||
|
||||
@@ -132,7 +132,7 @@ import java.net.URI
|
||||
* Settings → Gateways. Hermes setup starts with the one Dashboard address
|
||||
* the phone can open, probes public `/api/status`, and lets advertised
|
||||
* capabilities select authentication. A separate public sign-in URL is never
|
||||
* universally required. API fallback, Relay pairing, and extra LAN/Tailscale
|
||||
* universally required. Direct API, Relay pairing, and extra LAN/Tailscale
|
||||
* routes remain explicit advanced paths.
|
||||
*
|
||||
* Steps:
|
||||
|
||||
@@ -847,7 +847,7 @@ internal fun routeSurfaceSecurityPresentation(
|
||||
val label = when (surface) {
|
||||
EndpointSurface.Standard,
|
||||
EndpointSurface.Dashboard -> "Dashboard & Gateway"
|
||||
EndpointSurface.Api -> "API fallback"
|
||||
EndpointSurface.Api -> "Direct API"
|
||||
EndpointSurface.Relay -> "Relay tools"
|
||||
}
|
||||
val securityVerdict = classifySurfaceSecurity(
|
||||
|
||||
+86
-22
@@ -14,6 +14,7 @@ import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -44,6 +45,7 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -206,29 +208,49 @@ private fun FailedCard(
|
||||
modifier: Modifier,
|
||||
maxWidth: Dp
|
||||
) {
|
||||
val hostOnly = attachment.errorMessage == ChatViewModel.MEDIA_HOST_ONLY
|
||||
Surface(
|
||||
shape = appearanceRoundedCornerShape(10.dp),
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
color = if (hostOnly) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.errorContainer,
|
||||
modifier = modifier
|
||||
.widthIn(max = maxWidth)
|
||||
.clickable { onRetry() }
|
||||
.then(if (hostOnly) Modifier else Modifier.clickable { onRetry() })
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Text(text = "\u26A0\uFE0F", style = MaterialTheme.typography.titleMedium)
|
||||
Text(
|
||||
text = if (hostOnly) "\uD83D\uDCCE" else "\u26A0\uFE0F",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = attachment.errorMessage ?: stringResource(R.string.inbound_attach_failed),
|
||||
text = if (hostOnly) {
|
||||
stringResource(R.string.inbound_attach_host_only)
|
||||
} else {
|
||||
attachment.errorMessage ?: stringResource(R.string.inbound_attach_failed)
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
color = if (hostOnly) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onErrorContainer
|
||||
},
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.inbound_attach_tap_retry),
|
||||
text = if (hostOnly) {
|
||||
stringResource(R.string.inbound_attach_host_only_help)
|
||||
} else {
|
||||
stringResource(R.string.inbound_attach_tap_retry)
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.7f)
|
||||
color = if (hostOnly) {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.7f)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -282,17 +304,21 @@ private fun ImageRender(
|
||||
}
|
||||
LaunchedEffect(attachment.cachedUri, attachment.content) {
|
||||
val decoded = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val bytes: ByteArray? = when {
|
||||
try {
|
||||
when {
|
||||
!attachment.cachedUri.isNullOrBlank() ->
|
||||
context.contentResolver.openInputStream(Uri.parse(attachment.cachedUri))
|
||||
?.use { it.readBytes() }
|
||||
decodeBoundedOrientedBitmap(context, Uri.parse(attachment.cachedUri))
|
||||
?.asImageBitmap()
|
||||
attachment.content.isNotBlank() ->
|
||||
android.util.Base64.decode(attachment.content, android.util.Base64.DEFAULT)
|
||||
android.util.Base64.decode(
|
||||
attachment.content,
|
||||
android.util.Base64.DEFAULT,
|
||||
).let { decodeBoundedOrientedBitmap(it)?.asImageBitmap() }
|
||||
else -> null
|
||||
}
|
||||
bytes?.let { decodeOrientedBitmap(it)?.asImageBitmap() }
|
||||
}.getOrNull()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
if (decoded != null) bitmap = decoded else decodeFailed = true
|
||||
}
|
||||
@@ -309,9 +335,14 @@ private fun ImageRender(
|
||||
}
|
||||
|
||||
val blurMode = LocalMediaBlurMode.current
|
||||
val viewerController = LocalChatMediaViewerController.current
|
||||
var revealed by remember(attachment.cachedUri, attachment.content) { mutableStateOf(false) }
|
||||
val blurred = !revealed && shouldBlurImage(blurMode, attachment.sensitive)
|
||||
var viewerOpen by remember { mutableStateOf(false) }
|
||||
var viewerOpen by rememberSaveable(
|
||||
attachment.cachedUri,
|
||||
attachment.relayToken,
|
||||
attachment.fileName,
|
||||
) { mutableStateOf(false) }
|
||||
var menuExpanded by remember { mutableStateOf(false) }
|
||||
|
||||
val bmp = bitmap
|
||||
@@ -332,7 +363,7 @@ private fun ImageRender(
|
||||
return
|
||||
}
|
||||
|
||||
if (viewerOpen) {
|
||||
if (viewerController == null && viewerOpen) {
|
||||
AttachmentViewer(
|
||||
attachment = attachment,
|
||||
onDismiss = { viewerOpen = false },
|
||||
@@ -347,12 +378,25 @@ private fun ImageRender(
|
||||
contentDescription = attachment.fileName,
|
||||
modifier = Modifier
|
||||
.widthIn(max = maxWidth)
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(bmp.width.toFloat() / bmp.height.coerceAtLeast(1))
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.combinedClickable(
|
||||
onClick = { viewerOpen = true },
|
||||
onClick = {
|
||||
if (viewerController != null) {
|
||||
viewerController.openAttachment(
|
||||
attachment = attachment,
|
||||
initiallyRevealed = revealed,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
} else {
|
||||
viewerOpen = true
|
||||
}
|
||||
},
|
||||
onLongClick = { menuExpanded = true },
|
||||
),
|
||||
contentScale = ContentScale.FillWidth,
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
// One-tap save overlay — hidden while the blur cover is up so it
|
||||
@@ -386,15 +430,20 @@ private fun FileCardRender(
|
||||
val scope = rememberCoroutineScope()
|
||||
val (emoji, typeLabel) = emojiAndLabelFor(attachment.renderMode, attachment.contentType)
|
||||
var menuExpanded by remember { mutableStateOf(false) }
|
||||
var viewerOpen by remember { mutableStateOf(false) }
|
||||
var viewerOpen by rememberSaveable(
|
||||
attachment.cachedUri,
|
||||
attachment.relayToken,
|
||||
attachment.fileName,
|
||||
) { mutableStateOf(false) }
|
||||
|
||||
// Real thumbnail when one is cheap (video first frame, PDF first page);
|
||||
// null falls back to the type emoji.
|
||||
val thumbnail = rememberAttachmentThumbnail(attachment)
|
||||
val blurMode = LocalMediaBlurMode.current
|
||||
val viewerController = LocalChatMediaViewerController.current
|
||||
val blurThumb = thumbnail != null && shouldBlurThumb(blurMode, attachment)
|
||||
|
||||
if (viewerOpen) {
|
||||
if (viewerController == null && viewerOpen) {
|
||||
// Non-image types don't blur in the viewer; open straight through.
|
||||
AttachmentViewer(
|
||||
attachment = attachment,
|
||||
@@ -410,7 +459,18 @@ private fun FileCardRender(
|
||||
.widthIn(max = maxWidth)
|
||||
// Tap previews in-app; long-press surfaces Open-externally / Share / Save.
|
||||
.combinedClickable(
|
||||
onClick = { viewerOpen = true },
|
||||
onClick = {
|
||||
if (viewerController != null) {
|
||||
viewerController.openAttachment(
|
||||
attachment = attachment,
|
||||
initiallyRevealed = true,
|
||||
blurMode = blurMode,
|
||||
exportAllowed = exportAllowed,
|
||||
)
|
||||
} else {
|
||||
viewerOpen = true
|
||||
}
|
||||
},
|
||||
onLongClick = { menuExpanded = true },
|
||||
)
|
||||
) {
|
||||
@@ -628,7 +688,11 @@ private fun rememberAttachmentThumbnail(attachment: Attachment): ImageBitmap? {
|
||||
}
|
||||
LaunchedEffect(attachment.cachedUri, attachment.content, attachment.renderMode) {
|
||||
thumb = withContext(Dispatchers.IO) {
|
||||
runCatching { generateThumbnail(context, attachment) }.getOrNull()
|
||||
try {
|
||||
generateThumbnail(context, attachment)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
return thumb
|
||||
|
||||
@@ -46,7 +46,11 @@ internal fun decodeInlineImageDataUrl(
|
||||
// ceil(maxBytes / 3) * 4 plus at most two trailing padding characters.
|
||||
val maxEncoded = ((maxBytes.toLong() + 2L) / 3L) * 4L
|
||||
if (encoded.length.toLong() > maxEncoded) return null
|
||||
val bytes = runCatching { Base64.getDecoder().decode(encoded) }.getOrNull() ?: return null
|
||||
val bytes = try {
|
||||
Base64.getDecoder().decode(encoded)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
return null
|
||||
}
|
||||
if (bytes.isEmpty() || bytes.size > maxBytes || !matchesImageMagic(mime, bytes)) return null
|
||||
return DecodedInlineImageData(bytes, mime)
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ fun MarkdownContent(
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
ConfiguredMarkdownContent(
|
||||
content = content,
|
||||
content = markdownRenderWindow(content),
|
||||
textColor = textColor,
|
||||
modifier = modifier,
|
||||
)
|
||||
@@ -318,7 +318,7 @@ fun StreamingMarkdownContent(
|
||||
var generation by remember { mutableIntStateOf(0) }
|
||||
key(generation) {
|
||||
NativeStreamingMarkdownGeneration(
|
||||
content = content.withoutLeadingBlankLines(),
|
||||
content = markdownRenderWindow(content.withoutLeadingBlankLines()),
|
||||
textColor = textColor,
|
||||
modifier = modifier,
|
||||
onResetRequired = { generation += 1 },
|
||||
@@ -353,6 +353,17 @@ private fun NativeStreamingMarkdownGeneration(
|
||||
)
|
||||
}
|
||||
|
||||
internal const val MAX_RENDERED_MARKDOWN_CHARS = 256_000
|
||||
private const val MARKDOWN_TRUNCATION_NOTICE =
|
||||
"\n\n---\n_Response display was shortened for Android memory safety._"
|
||||
|
||||
internal fun markdownRenderWindow(content: String): String =
|
||||
if (content.length <= MAX_RENDERED_MARKDOWN_CHARS) {
|
||||
content
|
||||
} else {
|
||||
content.take(MAX_RENDERED_MARKDOWN_CHARS) + MARKDOWN_TRUNCATION_NOTICE
|
||||
}
|
||||
|
||||
internal data class StreamingMarkdownAppendPlan(
|
||||
val resetRequired: Boolean,
|
||||
val delta: String,
|
||||
|
||||
@@ -26,6 +26,7 @@ import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
@@ -53,7 +54,9 @@ import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.UiMessage
|
||||
import com.hermesandroid.relay.ui.UiMessageBus
|
||||
import com.hermesandroid.relay.ui.UiMessageEvent
|
||||
import com.hermesandroid.relay.ui.UiMessageSeverity
|
||||
import com.hermesandroid.relay.ui.reduceUiMessages
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
private const val MAX_RETAINED = 6
|
||||
@@ -68,7 +71,8 @@ private const val ROW_MIN_HEIGHT_DP = 34
|
||||
* overlay. Auto-dismisses (paused while expanded) and coalesces duplicates so a
|
||||
* burst of the same status collapses to one refreshed row.
|
||||
*
|
||||
* Errors stay on the snackbar — only post info/success/status here.
|
||||
* App-owned errors stay on the snackbar. Keyed upstream AgentNotices may also
|
||||
* use the warning tone because their sticky/clear lifecycle is server-owned.
|
||||
*/
|
||||
@Composable
|
||||
fun MessageBannerHost(
|
||||
@@ -82,18 +86,19 @@ fun MessageBannerHost(
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
UiMessageBus.events.collect { msg ->
|
||||
// Coalesce identical text so e.g. repeated "Reconnecting…" collapses
|
||||
// to a single, freshly-timed row rather than stacking.
|
||||
shown.filter { it.text == msg.text }.forEach { dup ->
|
||||
shown.remove(dup)
|
||||
expiresAt.remove(dup.id)
|
||||
}
|
||||
shown.add(msg)
|
||||
expiresAt[msg.id] = nowMs() + msg.ttlMillis
|
||||
while (shown.size > MAX_RETAINED) {
|
||||
val dropped = shown.removeAt(0)
|
||||
expiresAt.remove(dropped.id)
|
||||
UiMessageBus.events.collect { event ->
|
||||
val next = reduceUiMessages(shown, event, MAX_RETAINED)
|
||||
val retainedIds = next.mapTo(mutableSetOf()) { it.id }
|
||||
expiresAt.keys.filterNot(retainedIds::contains).forEach { expiresAt.remove(it) }
|
||||
shown.clear()
|
||||
shown.addAll(next)
|
||||
if (event is UiMessageEvent.Show) {
|
||||
val msg = event.message
|
||||
expiresAt[msg.id] = if (msg.ttlMillis == 0L) {
|
||||
Long.MAX_VALUE
|
||||
} else {
|
||||
nowMs() + msg.ttlMillis
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,6 +109,7 @@ fun MessageBannerHost(
|
||||
while (shown.isNotEmpty()) {
|
||||
val now = nowMs()
|
||||
val soonest = shown.minOfOrNull { expiresAt[it.id] ?: Long.MAX_VALUE } ?: break
|
||||
if (soonest == Long.MAX_VALUE) break
|
||||
if (soonest <= now) {
|
||||
shown.filter { (expiresAt[it.id] ?: Long.MAX_VALUE) <= now }.forEach { expired ->
|
||||
shown.remove(expired)
|
||||
@@ -281,6 +287,7 @@ private fun MessageRow(
|
||||
private fun severityContainer(severity: UiMessageSeverity): Color = when (severity) {
|
||||
UiMessageSeverity.Success -> MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.58f)
|
||||
UiMessageSeverity.Status -> MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.74f)
|
||||
UiMessageSeverity.Warning -> MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.72f)
|
||||
UiMessageSeverity.Info -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.90f)
|
||||
}
|
||||
|
||||
@@ -288,12 +295,14 @@ private fun severityContainer(severity: UiMessageSeverity): Color = when (severi
|
||||
private fun severityOnContainer(severity: UiMessageSeverity): Color = when (severity) {
|
||||
UiMessageSeverity.Success -> MaterialTheme.colorScheme.onTertiaryContainer
|
||||
UiMessageSeverity.Status -> MaterialTheme.colorScheme.onSecondaryContainer
|
||||
UiMessageSeverity.Warning -> MaterialTheme.colorScheme.onErrorContainer
|
||||
UiMessageSeverity.Info -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
|
||||
private fun severityIcon(severity: UiMessageSeverity): ImageVector = when (severity) {
|
||||
UiMessageSeverity.Success -> Icons.Filled.CheckCircle
|
||||
UiMessageSeverity.Status -> Icons.Filled.Sync
|
||||
UiMessageSeverity.Warning -> Icons.Filled.Warning
|
||||
UiMessageSeverity.Info -> Icons.Filled.Info
|
||||
}
|
||||
|
||||
|
||||
@@ -856,13 +856,13 @@ fun MessageBubble(
|
||||
}
|
||||
}
|
||||
|
||||
// Delivery status — only on agent-Thread reply bubbles (a user
|
||||
// message routed over the relay proactive channel). Null on every
|
||||
// ordinary chat message, which render nothing here.
|
||||
// Delivery status for local user messages, including steering.
|
||||
// Use the bubble's foreground: accent-on-accent hides the label.
|
||||
message.deliveryStatus?.takeIf { isUser }?.let { status ->
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
MessageDeliveryIndicator(
|
||||
status = status,
|
||||
contentColor = textColor,
|
||||
text = MessageDeliveryIndicatorText(
|
||||
sending = stringResource(R.string.msg_bubble_sending),
|
||||
queued = stringResource(R.string.msg_bubble_queued),
|
||||
|
||||
+3
-1
@@ -18,6 +18,7 @@ import androidx.compose.material3.minimumInteractiveComponentSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -57,6 +58,7 @@ fun MessageDeliveryIndicator(
|
||||
modifier: Modifier = Modifier,
|
||||
failureMessage: String? = null,
|
||||
onRetry: (() -> Unit)? = null,
|
||||
contentColor: Color? = null,
|
||||
) {
|
||||
val retryAction = onRetry.takeIf { status == MessageDeliveryStatus.FAILED }
|
||||
val retryable = retryAction != null
|
||||
@@ -67,7 +69,7 @@ fun MessageDeliveryIndicator(
|
||||
retryable = retryable,
|
||||
)
|
||||
val presentation = messageDeliveryPresentation(status)
|
||||
val tint = when (presentation.colorRole) {
|
||||
val tint = contentColor ?: when (presentation.colorRole) {
|
||||
DeliveryColorRole.NEUTRAL -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
DeliveryColorRole.ACCENT -> MaterialTheme.colorScheme.primary
|
||||
DeliveryColorRole.QUEUED -> MaterialTheme.colorScheme.tertiary
|
||||
|
||||
@@ -11,16 +11,15 @@ import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
/**
|
||||
* Temporarily allow the device to rotate (portrait or landscape, following the
|
||||
* sensor) while this composable is in the composition, overriding the app-wide
|
||||
* portrait lock declared in the manifest (`MainActivity` screenOrientation).
|
||||
* user's rotation preference) while this composable is in the composition,
|
||||
* overriding the app-wide portrait lock declared in the manifest
|
||||
* (`MainActivity` screenOrientation).
|
||||
* Restores the previous orientation (portrait) when it leaves the composition.
|
||||
*
|
||||
* Used by the full-screen media viewers ([ChatImageViewer], [AttachmentViewer])
|
||||
* so wide images and video can be viewed in landscape while the rest of the app
|
||||
* stays portrait-locked. Uses `SENSOR` (portrait + both landscapes, no
|
||||
* upside-down) so the viewer rotates with the device regardless of the system
|
||||
* auto-rotate toggle; swap to `SCREEN_ORIENTATION_USER` to instead respect that
|
||||
* toggle.
|
||||
* stays portrait-locked. Uses `USER` so the viewer follows the device only when
|
||||
* the user has enabled rotation instead of overriding their system preference.
|
||||
*/
|
||||
@Composable
|
||||
fun AllowDeviceRotation() {
|
||||
@@ -28,7 +27,7 @@ fun AllowDeviceRotation() {
|
||||
DisposableEffect(Unit) {
|
||||
val activity = context.findActivity()
|
||||
val previous = activity?.requestedOrientation
|
||||
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
|
||||
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER
|
||||
onDispose {
|
||||
activity?.requestedOrientation =
|
||||
previous ?: ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import android.net.Uri
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import java.io.ByteArrayInputStream
|
||||
|
||||
@@ -25,6 +27,11 @@ internal fun imageOrientationTransform(orientation: Int): ImageOrientationTransf
|
||||
else -> ImageOrientationTransform()
|
||||
}
|
||||
|
||||
internal fun shouldApplyExifOrientation(mimeType: String?): Boolean = when (mimeType?.lowercase()) {
|
||||
"image/png", "image/gif", "image/bmp" -> false
|
||||
else -> true
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode image bytes for display and apply their EXIF orientation. BitmapFactory
|
||||
* returns the stored pixel layout and otherwise leaves portrait phone photos
|
||||
@@ -41,14 +48,16 @@ internal fun decodeOrientedBitmap(
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||
} ?: return null
|
||||
|
||||
val orientation = runCatching {
|
||||
val orientation = try {
|
||||
ByteArrayInputStream(bytes).use { stream ->
|
||||
ExifInterface(stream).getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL,
|
||||
)
|
||||
}
|
||||
}.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
|
||||
} catch (_: Exception) {
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
}
|
||||
val transform = imageOrientationTransform(orientation)
|
||||
if (transform.rotationDegrees == 0f && !transform.flipHorizontal) return decoded
|
||||
|
||||
@@ -56,9 +65,81 @@ internal fun decodeOrientedBitmap(
|
||||
if (transform.rotationDegrees != 0f) postRotate(transform.rotationDegrees)
|
||||
if (transform.flipHorizontal) postScale(-1f, 1f)
|
||||
}
|
||||
return runCatching {
|
||||
val oriented = try {
|
||||
Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
|
||||
}.getOrNull()?.also { oriented ->
|
||||
if (oriented !== decoded) decoded.recycle()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return oriented?.also { bitmap ->
|
||||
if (bitmap !== decoded) decoded.recycle()
|
||||
} ?: decoded
|
||||
}
|
||||
|
||||
/** Decode a cached content URI without copying the encoded file into RAM. */
|
||||
internal fun decodeOrientedBitmap(context: Context, uri: Uri): Bitmap? =
|
||||
decodeBoundedOrientedBitmap(context, uri)
|
||||
|
||||
internal fun decodeBoundedOrientedBitmap(context: Context, uri: Uri): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
val boundsInput = context.contentResolver.openInputStream(uri) ?: return null
|
||||
boundsInput.use { input ->
|
||||
// Bounds-only decode deliberately returns null; the populated Options
|
||||
// are the result and must not be treated as a decode failure.
|
||||
BitmapFactory.decodeStream(input, null, bounds)
|
||||
}
|
||||
val sample = inlineImageSampleSize(bounds.outWidth, bounds.outHeight) ?: return null
|
||||
val decoded = context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
BitmapFactory.decodeStream(
|
||||
input,
|
||||
null,
|
||||
BitmapFactory.Options().apply {
|
||||
inSampleSize = sample
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
},
|
||||
)
|
||||
} ?: return null
|
||||
val orientation = if (shouldApplyExifOrientation(bounds.outMimeType)) {
|
||||
try {
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
ExifInterface(input).getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL,
|
||||
)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
} ?: ExifInterface.ORIENTATION_NORMAL
|
||||
} else {
|
||||
ExifInterface.ORIENTATION_NORMAL
|
||||
}
|
||||
val transform = imageOrientationTransform(orientation)
|
||||
if (transform.rotationDegrees == 0f && !transform.flipHorizontal) return decoded
|
||||
|
||||
val matrix = Matrix().apply {
|
||||
if (transform.rotationDegrees != 0f) postRotate(transform.rotationDegrees)
|
||||
if (transform.flipHorizontal) postScale(-1f, 1f)
|
||||
}
|
||||
val oriented = try {
|
||||
Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
return oriented?.also { bitmap ->
|
||||
if (bitmap !== decoded) decoded.recycle()
|
||||
} ?: decoded
|
||||
}
|
||||
|
||||
/** Decode an encoded chat image only after bounding its decoded pixel footprint. */
|
||||
internal fun decodeBoundedOrientedBitmap(bytes: ByteArray): Bitmap? {
|
||||
if (bytes.isEmpty()) return null
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
val sample = inlineImageSampleSize(bounds.outWidth, bounds.outHeight) ?: return null
|
||||
return decodeOrientedBitmap(
|
||||
bytes,
|
||||
BitmapFactory.Options().apply {
|
||||
inSampleSize = sample
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
+6
-4
@@ -296,12 +296,12 @@ internal fun formatAttachmentSize(bytes: Long): String {
|
||||
|
||||
private suspend fun decodePendingAttachmentImage(attachment: Attachment): ImageBitmap? =
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
try {
|
||||
val bytes = Base64.decode(attachment.content, Base64.DEFAULT)
|
||||
if (bytes.isEmpty()) return@runCatching null
|
||||
if (bytes.isEmpty()) return@withContext null
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@runCatching null
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@withContext null
|
||||
|
||||
var sample = 1
|
||||
while (
|
||||
@@ -314,7 +314,9 @@ private suspend fun decodePendingAttachmentImage(attachment: Attachment): ImageB
|
||||
bytes,
|
||||
BitmapFactory.Options().apply { inSampleSize = sample },
|
||||
)?.asImageBitmap()
|
||||
}.getOrNull()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface PendingPreviewState {
|
||||
|
||||
@@ -4,6 +4,7 @@ import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
@@ -15,6 +16,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawing
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Text
|
||||
@@ -24,7 +26,10 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
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
|
||||
@@ -41,74 +46,81 @@ fun RelayStatusStrip(
|
||||
/** Optional security marker rendered just before the route label. */
|
||||
securityGlyph: (@Composable () -> Unit)? = null,
|
||||
/**
|
||||
* When true, the strip shows an amber "Reconnecting…" cue in place of the
|
||||
* When true, the strip shows an amber "Relay reconnecting" cue in place of the
|
||||
* route label. This is where a **routine** in-progress relay reconnect
|
||||
* surfaces — the top chrome stays empty so chat content never shifts.
|
||||
*/
|
||||
reconnecting: Boolean = false,
|
||||
maxContentWidth: Dp? = null,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.windowInsetsPadding(
|
||||
WindowInsets.safeDrawing.only(
|
||||
WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom,
|
||||
),
|
||||
)
|
||||
.padding(start = 14.dp, end = 14.dp, top = 3.dp, bottom = 4.dp)
|
||||
.clip(appearanceRoundedCornerShape(16.dp))
|
||||
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
||||
.relayPanel(
|
||||
shape = appearanceRoundedCornerShape(16.dp),
|
||||
background = RelayRefresh.Navy2.copy(alpha = 0.88f),
|
||||
borderColor = RelayRefresh.Line,
|
||||
),
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
Column(
|
||||
modifier = modifier
|
||||
.then(maxContentWidth?.let { Modifier.widthIn(max = it) } ?: Modifier)
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 22.dp)
|
||||
.padding(horizontal = 14.dp, vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
.windowInsetsPadding(
|
||||
WindowInsets.safeDrawing.only(
|
||||
WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom,
|
||||
),
|
||||
)
|
||||
.padding(start = 14.dp, end = 14.dp, top = 3.dp, bottom = 4.dp)
|
||||
.clip(appearanceRoundedCornerShape(16.dp))
|
||||
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
|
||||
.relayPanel(
|
||||
shape = appearanceRoundedCornerShape(16.dp),
|
||||
background = RelayRefresh.Navy2.copy(alpha = 0.88f),
|
||||
borderColor = RelayRefresh.Line,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.weight(1f),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 22.dp)
|
||||
.padding(horizontal = 14.dp, vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
leadingBadge()
|
||||
if (securityGlyph != null) {
|
||||
securityGlyph()
|
||||
}
|
||||
// Route is in flux mid-reconnect, so the amber cue replaces the
|
||||
// route label rather than stacking beside it in the 22dp strip.
|
||||
when {
|
||||
reconnecting -> ReconnectingCue(modifier = Modifier.weight(1f))
|
||||
routeLabel.isNotBlank() -> Text(
|
||||
text = "· $routeLabel",
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.weight(1f),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
leadingBadge()
|
||||
if (securityGlyph != null) {
|
||||
securityGlyph()
|
||||
}
|
||||
// Route is in flux mid-reconnect, so the amber cue replaces the
|
||||
// route label rather than stacking beside it in the 22dp strip.
|
||||
when {
|
||||
reconnecting -> ReconnectingCue(modifier = Modifier.weight(1f))
|
||||
routeLabel.isNotBlank() -> Text(
|
||||
text = "· $routeLabel",
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Text(
|
||||
text = trailing,
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Text(
|
||||
text = trailing,
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Muted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Amber "· Reconnecting…" cue with a softly pulsing dot. This is the *only*
|
||||
* Amber "Relay reconnecting" cue with a softly pulsing dot. This is the *only*
|
||||
* surface for a routine in-progress relay reconnect — the top of the app stays
|
||||
* empty (chat/agent status rides the chat header subtitle) so nothing shifts.
|
||||
* Pulse is frame-throttled via [rememberAmbientPhase] to avoid pinning the
|
||||
@@ -132,7 +144,7 @@ private fun ReconnectingCue(modifier: Modifier = Modifier) {
|
||||
.background(RelayRefresh.Amber),
|
||||
)
|
||||
Text(
|
||||
text = "Reconnecting…",
|
||||
text = stringResource(R.string.settings_relay_reconnecting),
|
||||
style = relayMetadataStyle(),
|
||||
color = RelayRefresh.Amber,
|
||||
maxLines = 1,
|
||||
|
||||
@@ -141,8 +141,8 @@ internal data class SessionCapability(
|
||||
* live. SSE paths only get post-hoc reasoning, so this is gateway-only.
|
||||
* While the gateway is still being probed (Unknown) we surface it as a
|
||||
* "checking" reason rather than a confirmed chip.
|
||||
* - Media / Terminal → require the relay to be CONNECTED (the relay brokers
|
||||
* those channels). A configured-but-disconnected relay is not enough.
|
||||
* - Media → current upstream Dashboard managed-file delivery OR connected
|
||||
* Relay compatibility transport. Terminal remains Relay-owned.
|
||||
* - Voice → `voiceReady` (standard dashboard voice OR relay voice — whichever
|
||||
* the connection actually has).
|
||||
*/
|
||||
@@ -150,6 +150,7 @@ internal data class SessionCapability(
|
||||
internal fun sessionCapabilities(
|
||||
transport: SessionPathTransport,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
upstreamMediaAvailable: Boolean,
|
||||
relayConnected: Boolean,
|
||||
relayConfigured: Boolean,
|
||||
voiceReady: Boolean,
|
||||
@@ -170,11 +171,11 @@ internal fun sessionCapabilities(
|
||||
),
|
||||
SessionCapability(
|
||||
type = "media",
|
||||
available = relayConnected,
|
||||
available = upstreamMediaAvailable || relayConnected,
|
||||
reason = when {
|
||||
relayConnected -> null
|
||||
upstreamMediaAvailable || relayConnected -> null
|
||||
relayConfigured -> stringResource(R.string.session_path_relay_not_connected)
|
||||
else -> stringResource(R.string.session_path_pair_relay_media)
|
||||
else -> stringResource(R.string.session_path_media_not_ready)
|
||||
},
|
||||
),
|
||||
SessionCapability(
|
||||
@@ -401,7 +402,7 @@ internal fun SessionPathDetails(
|
||||
* Vertical "transport path" ladder, basic → best:
|
||||
* Completions → Runs → Sessions → Gateway. The active tier is filled +
|
||||
* highlighted; tiers the server doesn't expose render muted; the resolver's
|
||||
* reason ("auto → Gateway (best)" / "gateway unavailable → Sessions") is shown
|
||||
* owner/readiness reason ("Gateway connected" / "Gateway unavailable") is shown
|
||||
* beneath. Uses the same [resolveChatTransportStatus] the status badge does, so
|
||||
* the drawer and the badge can never disagree.
|
||||
*/
|
||||
|
||||
@@ -23,18 +23,26 @@ import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.statusBarsPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CenterFocusStrong
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
@@ -44,10 +52,11 @@ import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.GraphicEq
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
@@ -71,7 +80,9 @@ import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
@@ -81,6 +92,7 @@ import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
@@ -92,7 +104,9 @@ import com.hermesandroid.relay.ui.components.avatar.AvatarRenderState
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalAgentAvatar
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalBackgroundVisualizationEnabled
|
||||
import com.hermesandroid.relay.ui.LocalSnackbarHost
|
||||
import com.hermesandroid.relay.ui.chatResponsiveLayout
|
||||
import com.hermesandroid.relay.ui.showHumanError
|
||||
import com.hermesandroid.relay.ui.useSplitVoiceLayout
|
||||
import com.hermesandroid.relay.util.HumanError
|
||||
import kotlinx.coroutines.delay
|
||||
import com.hermesandroid.relay.viewmodel.BackgroundRunPhase
|
||||
@@ -112,6 +126,8 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
|
||||
internal const val VOICE_MODE_MIC_TEST_TAG = "voiceModeMic"
|
||||
internal const val VOICE_FOCUS_SPLIT_LAYOUT_TEST_TAG = "voiceFocusSplitLayout"
|
||||
internal const val VOICE_FOCUS_STACKED_LAYOUT_TEST_TAG = "voiceFocusStackedLayout"
|
||||
|
||||
/**
|
||||
* Full-screen voice-mode overlay. Renders the MorphingSphere in its voiceMode
|
||||
@@ -135,8 +151,7 @@ fun VoiceModeOverlay(
|
||||
onModeChange: (InteractionMode) -> Unit,
|
||||
onClearError: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
// Nullable so existing call sites compile; when wired, voice errors
|
||||
// surface as global snackbars in addition to the inline banner below.
|
||||
// Retained for callers; uiState.error owns the modal while voice is visible.
|
||||
errorEvents: SharedFlow<HumanError>? = null,
|
||||
// === PHASE3-voice-mode-transcript ===
|
||||
// Compact rolling transcript of the last N chat messages — the
|
||||
@@ -186,6 +201,56 @@ fun VoiceModeOverlay(
|
||||
val backgroundVisualizationEnabled = LocalBackgroundVisualizationEnabled.current
|
||||
val surface = MaterialTheme.colorScheme.surface
|
||||
val haptic = LocalHapticFeedback.current
|
||||
val configuration = LocalConfiguration.current
|
||||
val responsiveLayout = chatResponsiveLayout(configuration.screenWidthDp)
|
||||
val splitFocusLayout = useSplitVoiceLayout(
|
||||
screenWidthDp = configuration.screenWidthDp,
|
||||
screenHeightDp = configuration.screenHeightDp,
|
||||
)
|
||||
|
||||
val focusMicTap: () -> Unit = {
|
||||
dispatchVoiceMicTap(
|
||||
uiState = uiState,
|
||||
onStartListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicTap()
|
||||
},
|
||||
onStopListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicRelease()
|
||||
},
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
)
|
||||
}
|
||||
val focusMicHoldPress: () -> Unit = {
|
||||
dispatchVoiceMicHoldPress(
|
||||
uiState = uiState,
|
||||
onStartListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicTap()
|
||||
},
|
||||
onInterruptAndStart = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onInterrupt()
|
||||
onMicTap()
|
||||
},
|
||||
)
|
||||
}
|
||||
val focusMicHoldRelease: () -> Unit = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicRelease()
|
||||
}
|
||||
|
||||
var controlsExpanded by remember { mutableStateOf(false) }
|
||||
val focusMode = presentationMode == VoicePresentationMode.Focus
|
||||
@@ -195,7 +260,7 @@ fun VoiceModeOverlay(
|
||||
)
|
||||
}
|
||||
|
||||
// Voice errors surface ONLY on the overlay's own inline top banner
|
||||
// Voice errors surface ONLY in the overlay's dialog
|
||||
// (uiState.error) while the overlay is up — we deliberately do NOT also pipe
|
||||
// them to the app-wide bottom snackbar. Doing both duplicated the message
|
||||
// and left a retry-only, un-dismissable toast at the bottom during long /
|
||||
@@ -253,6 +318,11 @@ fun VoiceModeOverlay(
|
||||
onOpenSettings = onOpenSettings,
|
||||
onExit = onDismiss,
|
||||
modifier = Modifier
|
||||
.then(
|
||||
responsiveLayout.focusVoiceMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.statusBarsPadding()
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp)
|
||||
@@ -328,162 +398,93 @@ fun VoiceModeOverlay(
|
||||
exit = fadeOut(tween(120)),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(top = 92.dp, bottom = 160.dp, start = 20.dp, end = 20.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1.0f),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (backgroundVisualizationEnabled) {
|
||||
LocalAgentAvatar.current.Render(
|
||||
state = AvatarRenderState(
|
||||
state = voiceStateToSphereState(uiState.state),
|
||||
voiceAmplitude = uiState.amplitude,
|
||||
voiceMode = true,
|
||||
),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
if (splitFocusLayout) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.widthIn(max = responsiveLayout.focusVoiceMaxWidth ?: 1120.dp)
|
||||
.fillMaxSize()
|
||||
.navigationBarsPadding()
|
||||
.padding(top = 92.dp, bottom = 28.dp, start = 32.dp, end = 32.dp)
|
||||
.testTag(VOICE_FOCUS_SPLIT_LAYOUT_TEST_TAG),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
VoiceFocusIdentityPane(
|
||||
uiState = uiState,
|
||||
backgroundVisualizationEnabled = backgroundVisualizationEnabled,
|
||||
onMicTap = focusMicTap,
|
||||
onMicHoldPress = focusMicHoldPress,
|
||||
onMicHoldRelease = focusMicHoldRelease,
|
||||
showMic = true,
|
||||
modifier = Modifier
|
||||
.weight(0.86f)
|
||||
.fillMaxHeight(),
|
||||
)
|
||||
Spacer(Modifier.width(32.dp))
|
||||
VoiceFocusStatusAndTranscriptPane(
|
||||
uiState = uiState,
|
||||
transcriptMessages = visibleTranscriptMessages,
|
||||
pendingTranscriptText = pendingTranscriptText,
|
||||
transcriptListState = transcriptListState,
|
||||
showThinking = showThinking,
|
||||
onBackgroundRunCancel = onBackgroundRunCancel,
|
||||
onBackgroundRunTap = onBackgroundRunTap,
|
||||
onPermissionDeniedChipTap = onPermissionDeniedChipTap,
|
||||
onHermesConfirmationAnswer = onHermesConfirmationAnswer,
|
||||
onPresentationModeChange = onPresentationModeChange,
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
horizontalContentPadding = 0.dp,
|
||||
modifier = Modifier
|
||||
.weight(1.14f)
|
||||
.fillMaxHeight(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
VoiceWaveform(
|
||||
amplitude = uiState.amplitude,
|
||||
state = uiState.state,
|
||||
outputAudioActive = uiState.outputAudioActive,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 32.dp, vertical = 8.dp),
|
||||
)
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = uiState.handoffStatus != null,
|
||||
enter = fadeIn(tween(140)),
|
||||
exit = fadeOut(tween(180)),
|
||||
) {
|
||||
VoiceHandoffStrip(
|
||||
status = uiState.handoffStatus,
|
||||
} else {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
BackgroundRunChip(
|
||||
run = uiState.backgroundRun,
|
||||
onCancel = onBackgroundRunCancel,
|
||||
onTap = onBackgroundRunTap,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
DestructiveCountdownRow(
|
||||
countdown = uiState.destructiveCountdown,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp),
|
||||
)
|
||||
|
||||
PermissionDeniedChip(
|
||||
callout = uiState.permissionDeniedCallout,
|
||||
onTap = onPermissionDeniedChipTap,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
|
||||
HermesConfirmationCard(
|
||||
confirmation = uiState.hermesConfirmation,
|
||||
onAnswer = onHermesConfirmationAnswer,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(4.dp))
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1.25f, fill = true),
|
||||
) {
|
||||
val hasTranscript = visibleTranscriptMessages.isNotEmpty() ||
|
||||
pendingTranscriptText != null
|
||||
if (hasTranscript) {
|
||||
val latestId = visibleTranscriptMessages.lastOrNull()?.id
|
||||
LazyColumn(
|
||||
state = transcriptListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
// Match ChatScreen's identity contract. A history
|
||||
// reconcile can adopt the same authoritative server
|
||||
// id into a live row while Compose still holds the
|
||||
// pre-reconcile row for a frame. uiKey remains stable
|
||||
// and unique across that transition.
|
||||
items(visibleTranscriptMessages, key = ::voiceTranscriptItemKey) { msg ->
|
||||
CompactTranscriptRow(
|
||||
message = msg,
|
||||
showThinking = showThinking,
|
||||
expanded = msg.id == latestId || msg.isStreaming,
|
||||
onViewConversation = {
|
||||
onPresentationModeChange(VoicePresentationMode.Conversation)
|
||||
},
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
)
|
||||
}
|
||||
if (pendingTranscriptText != null) {
|
||||
item(key = "aux:pending-voice-transcript") {
|
||||
CompactTranscriptRow(
|
||||
message = ChatMessage(
|
||||
id = "pending-voice-transcript",
|
||||
role = MessageRole.USER,
|
||||
content = pendingTranscriptText,
|
||||
timestamp = System.currentTimeMillis(),
|
||||
isStreaming = true,
|
||||
),
|
||||
showThinking = showThinking,
|
||||
expanded = true,
|
||||
onViewConversation = {
|
||||
onPresentationModeChange(VoicePresentationMode.Conversation)
|
||||
},
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
)
|
||||
}
|
||||
}
|
||||
item { Spacer(Modifier.height(12.dp)) }
|
||||
}
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = stateHint(uiState.state),
|
||||
transitionSpec = {
|
||||
fadeIn(tween(200)) togetherWith fadeOut(tween(200))
|
||||
},
|
||||
label = "stateHint",
|
||||
) { hint ->
|
||||
Text(
|
||||
text = hint,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
.then(
|
||||
responsiveLayout.focusVoiceMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxSize()
|
||||
.padding(top = 92.dp, bottom = 160.dp, start = 20.dp, end = 20.dp)
|
||||
.testTag(VOICE_FOCUS_STACKED_LAYOUT_TEST_TAG),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
VoiceFocusIdentityPane(
|
||||
uiState = uiState,
|
||||
backgroundVisualizationEnabled = backgroundVisualizationEnabled,
|
||||
onMicTap = focusMicTap,
|
||||
onMicHoldPress = focusMicHoldPress,
|
||||
onMicHoldRelease = focusMicHoldRelease,
|
||||
showMic = false,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
)
|
||||
VoiceFocusStatusAndTranscriptPane(
|
||||
uiState = uiState,
|
||||
transcriptMessages = visibleTranscriptMessages,
|
||||
pendingTranscriptText = pendingTranscriptText,
|
||||
transcriptListState = transcriptListState,
|
||||
showThinking = showThinking,
|
||||
onBackgroundRunCancel = onBackgroundRunCancel,
|
||||
onBackgroundRunTap = onBackgroundRunTap,
|
||||
onPermissionDeniedChipTap = onPermissionDeniedChipTap,
|
||||
onHermesConfirmationAnswer = onHermesConfirmationAnswer,
|
||||
onPresentationModeChange = onPresentationModeChange,
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
horizontalContentPadding = 24.dp,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1.25f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -498,6 +499,12 @@ fun VoiceModeOverlay(
|
||||
exit = fadeOut(tween(180)),
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.then(
|
||||
responsiveLayout.chromeMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 176.dp, start = 24.dp, end = 24.dp),
|
||||
) {
|
||||
BackgroundRunChip(
|
||||
@@ -508,53 +515,15 @@ fun VoiceModeOverlay(
|
||||
)
|
||||
}
|
||||
|
||||
// Error banner
|
||||
AnimatedVisibility(
|
||||
visible = uiState.error != null,
|
||||
enter = fadeIn(),
|
||||
exit = fadeOut(),
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopCenter)
|
||||
.padding(top = 64.dp, start = 16.dp, end = 16.dp),
|
||||
) {
|
||||
Surface(
|
||||
shape = appearanceRoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.errorContainer,
|
||||
tonalElevation = 2.dp,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = uiState.error.orEmpty(),
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// Dismiss clears the error and returns to Idle without
|
||||
// retrying, so a failed/timed-out turn never traps the user
|
||||
// on a retry-only banner.
|
||||
TextButton(onClick = { onClearError() }) {
|
||||
Text(stringResource(R.string.common_dismiss))
|
||||
}
|
||||
TextButton(
|
||||
onClick = {
|
||||
onClearError()
|
||||
onMicTap()
|
||||
},
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Refresh,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Spacer(Modifier.size(4.dp))
|
||||
Text(stringResource(R.string.voice_overlay_retry))
|
||||
}
|
||||
}
|
||||
}
|
||||
uiState.error?.let { error ->
|
||||
VoiceErrorDialog(
|
||||
error = error,
|
||||
onDismiss = onClearError,
|
||||
onRetry = {
|
||||
onClearError()
|
||||
onMicTap()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Mic button — dispatch by current voice state.
|
||||
@@ -570,57 +539,259 @@ fun VoiceModeOverlay(
|
||||
// that visually said "Stop" but was actually wired to "Start."
|
||||
VoiceMicButton(
|
||||
uiState = uiState,
|
||||
onTap = {
|
||||
dispatchVoiceMicTap(
|
||||
uiState = uiState,
|
||||
onStartListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicTap()
|
||||
},
|
||||
onStopListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicRelease()
|
||||
},
|
||||
onInterrupt = onInterrupt,
|
||||
onPauseAutoMode = onPauseAutoMode,
|
||||
)
|
||||
},
|
||||
onHoldPress = {
|
||||
dispatchVoiceMicHoldPress(
|
||||
uiState = uiState,
|
||||
onStartListening = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicTap()
|
||||
},
|
||||
onInterruptAndStart = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onInterrupt()
|
||||
onMicTap()
|
||||
},
|
||||
)
|
||||
},
|
||||
onHoldRelease = {
|
||||
try {
|
||||
haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove)
|
||||
} catch (_: Exception) { /* ignore */ }
|
||||
onMicRelease()
|
||||
},
|
||||
onTap = focusMicTap,
|
||||
onHoldPress = focusMicHoldPress,
|
||||
onHoldRelease = focusMicHoldRelease,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(bottom = 48.dp),
|
||||
visible = focusMode,
|
||||
visible = focusMode && !splitFocusLayout,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceErrorDialog(
|
||||
error: String,
|
||||
onDismiss: () -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
) {
|
||||
val keyboard = LocalSoftwareKeyboardController.current
|
||||
LaunchedEffect(error) { keyboard?.hide() }
|
||||
|
||||
// Match ChatFailureDetailsDialog: keep provider detail selectable and inside
|
||||
// a bounded surface, with actions outside the scroll area. A real dialog
|
||||
// owns focus and blocks the underlying chat in both voice presentations.
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Default.ErrorOutline,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
},
|
||||
title = { Text(stringResource(R.string.voice_overlay_error_title)) },
|
||||
text = {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
shape = MaterialTheme.shapes.small,
|
||||
) {
|
||||
SelectionContainer {
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 320.dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = onRetry) {
|
||||
Text(stringResource(R.string.voice_overlay_retry))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text(stringResource(R.string.common_dismiss))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceFocusIdentityPane(
|
||||
uiState: VoiceUiState,
|
||||
backgroundVisualizationEnabled: Boolean,
|
||||
onMicTap: () -> Unit,
|
||||
onMicHoldPress: () -> Unit,
|
||||
onMicHoldRelease: () -> Unit,
|
||||
showMic: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.testTag("voiceFocusIdentityPane"),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (backgroundVisualizationEnabled) {
|
||||
LocalAgentAvatar.current.Render(
|
||||
state = AvatarRenderState(
|
||||
state = voiceStateToSphereState(uiState.state),
|
||||
voiceAmplitude = uiState.amplitude,
|
||||
voiceMode = true,
|
||||
),
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
VoiceWaveform(
|
||||
amplitude = uiState.amplitude,
|
||||
state = uiState.state,
|
||||
outputAudioActive = uiState.outputAudioActive,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 8.dp),
|
||||
)
|
||||
if (showMic) {
|
||||
Spacer(Modifier.height(16.dp))
|
||||
VoiceMicButton(
|
||||
uiState = uiState,
|
||||
onTap = onMicTap,
|
||||
onHoldPress = onMicHoldPress,
|
||||
onHoldRelease = onMicHoldRelease,
|
||||
visible = true,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceFocusStatusAndTranscriptPane(
|
||||
uiState: VoiceUiState,
|
||||
transcriptMessages: List<ChatMessage>,
|
||||
pendingTranscriptText: String?,
|
||||
transcriptListState: LazyListState,
|
||||
showThinking: Boolean,
|
||||
onBackgroundRunCancel: () -> Unit,
|
||||
onBackgroundRunTap: () -> Unit,
|
||||
onPermissionDeniedChipTap: (PermissionDeniedCallout) -> Unit,
|
||||
onHermesConfirmationAnswer: (String) -> Unit,
|
||||
onPresentationModeChange: (VoicePresentationMode) -> Unit,
|
||||
onCardAction: (messageId: String, cardKey: String, action: HermesCardAction) -> Unit,
|
||||
onCardInput: (messageId: String, cardKey: String, value: String) -> Unit,
|
||||
horizontalContentPadding: Dp,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(modifier = modifier.testTag("voiceFocusTranscriptPane")) {
|
||||
AnimatedVisibility(
|
||||
visible = uiState.handoffStatus != null,
|
||||
enter = fadeIn(tween(140)),
|
||||
exit = fadeOut(tween(180)),
|
||||
) {
|
||||
VoiceHandoffStrip(
|
||||
status = uiState.handoffStatus,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
BackgroundRunChip(
|
||||
run = uiState.backgroundRun,
|
||||
onCancel = onBackgroundRunCancel,
|
||||
onTap = onBackgroundRunTap,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding, vertical = 4.dp),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
DestructiveCountdownRow(
|
||||
countdown = uiState.destructiveCountdown,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding),
|
||||
)
|
||||
PermissionDeniedChip(
|
||||
callout = uiState.permissionDeniedCallout,
|
||||
onTap = onPermissionDeniedChipTap,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding, vertical = 4.dp),
|
||||
)
|
||||
HermesConfirmationCard(
|
||||
confirmation = uiState.hermesConfirmation,
|
||||
onAnswer = onHermesConfirmationAnswer,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = horizontalContentPadding, vertical = 4.dp),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f, fill = true),
|
||||
) {
|
||||
val hasTranscript = transcriptMessages.isNotEmpty() || pendingTranscriptText != null
|
||||
if (hasTranscript) {
|
||||
val latestId = transcriptMessages.lastOrNull()?.id
|
||||
LazyColumn(
|
||||
state = transcriptListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
// uiKey remains stable while Gateway reconciliation adopts
|
||||
// an authoritative server id into a live transcript row.
|
||||
items(transcriptMessages, key = ::voiceTranscriptItemKey) { msg ->
|
||||
CompactTranscriptRow(
|
||||
message = msg,
|
||||
showThinking = showThinking,
|
||||
expanded = msg.id == latestId || msg.isStreaming,
|
||||
onViewConversation = {
|
||||
onPresentationModeChange(VoicePresentationMode.Conversation)
|
||||
},
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
)
|
||||
}
|
||||
if (pendingTranscriptText != null) {
|
||||
item(key = "aux:pending-voice-transcript") {
|
||||
CompactTranscriptRow(
|
||||
message = ChatMessage(
|
||||
id = "pending-voice-transcript",
|
||||
role = MessageRole.USER,
|
||||
content = pendingTranscriptText,
|
||||
timestamp = System.currentTimeMillis(),
|
||||
isStreaming = true,
|
||||
),
|
||||
showThinking = showThinking,
|
||||
expanded = true,
|
||||
onViewConversation = {
|
||||
onPresentationModeChange(VoicePresentationMode.Conversation)
|
||||
},
|
||||
onCardAction = onCardAction,
|
||||
onCardInput = onCardInput,
|
||||
)
|
||||
}
|
||||
}
|
||||
item { Spacer(Modifier.height(12.dp)) }
|
||||
}
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = stateHint(uiState.state),
|
||||
transitionSpec = {
|
||||
fadeIn(tween(200)) togetherWith fadeOut(tween(200))
|
||||
},
|
||||
label = "stateHint",
|
||||
) { hint ->
|
||||
Text(
|
||||
text = hint,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun VoiceMicButton(
|
||||
uiState: VoiceUiState,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import com.hermesandroid.relay.data.canCorrectBusyMessage
|
||||
import com.hermesandroid.relay.ui.components.ChatComposerLayers
|
||||
import com.hermesandroid.relay.ui.components.ChatMessageQueue
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -58,6 +62,7 @@ import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.ui.components.ChatMediaViewerHost
|
||||
import com.hermesandroid.relay.ui.components.MessageBubble
|
||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
import com.hermesandroid.relay.viewmodel.ChatViewModel
|
||||
@@ -84,24 +89,28 @@ fun BotChatScreen(
|
||||
connectionViewModel: ConnectionViewModel,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
BotChatScreen(
|
||||
route = route,
|
||||
bot = bot,
|
||||
sessionId = sessionId,
|
||||
gatewayClient = gatewayClient,
|
||||
dashboardClient = dashboardClient,
|
||||
chatViewModel = chatViewModel,
|
||||
onBack = onBack,
|
||||
handlerFactory = ::ChatHandler,
|
||||
historyLoader = { profileName, storedSessionId, mode ->
|
||||
dashboardClient.getSessionMessages(
|
||||
sessionId = storedSessionId,
|
||||
profile = profileName,
|
||||
mode = mode,
|
||||
)
|
||||
},
|
||||
profileIconFlow = connectionViewModel::profileIconFlow,
|
||||
)
|
||||
val busyMessageAction by connectionViewModel.busyMessageAction.collectAsState()
|
||||
ChatMediaViewerHost(route.key, sessionId) {
|
||||
BotChatScreen(
|
||||
route = route,
|
||||
bot = bot,
|
||||
sessionId = sessionId,
|
||||
gatewayClient = gatewayClient,
|
||||
dashboardClient = dashboardClient,
|
||||
chatViewModel = chatViewModel,
|
||||
onBack = onBack,
|
||||
handlerFactory = ::ChatHandler,
|
||||
historyLoader = { profileName, storedSessionId, mode ->
|
||||
dashboardClient.getSessionMessages(
|
||||
sessionId = storedSessionId,
|
||||
profile = profileName,
|
||||
mode = mode,
|
||||
)
|
||||
},
|
||||
profileIconFlow = connectionViewModel::profileIconFlow,
|
||||
busyMessageAction = busyMessageAction,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@@ -117,6 +126,7 @@ internal fun BotChatScreen(
|
||||
handlerFactory: () -> ChatHandler,
|
||||
historyLoader: BotChatHistoryLoader,
|
||||
profileIconFlow: BotChatProfileIconFlow,
|
||||
busyMessageAction: BusyMessageAction = BusyMessageAction.CorrectNow,
|
||||
) {
|
||||
val handler = remember(route.key) { handlerFactory() }
|
||||
val context = LocalContext.current
|
||||
@@ -133,6 +143,21 @@ internal fun BotChatScreen(
|
||||
.collectAsState(initial = null)
|
||||
val listState = rememberLazyListState()
|
||||
var composer by remember(route.key, sessionId) { mutableStateOf("") }
|
||||
var editingQueuedMessage by remember(route.key, sessionId) { mutableStateOf(false) }
|
||||
var busyActionOverride by remember(route.key, sessionId, busyMessageAction) {
|
||||
mutableStateOf<BusyMessageAction?>(null)
|
||||
}
|
||||
val steerable by chatViewModel.steerableTurn.collectAsState()
|
||||
val attachments by chatViewModel.pendingAttachments.collectAsState()
|
||||
val pendingAsk by chatViewModel.pendingAsk.collectAsState()
|
||||
val turnStatus by handler.turnStatus.collectAsState()
|
||||
val queue by chatViewModel.queuedMessages.collectAsState()
|
||||
val queuePaused by chatViewModel.queuePaused.collectAsState()
|
||||
val correctionAvailable = canCorrectBusyMessage(
|
||||
steerable, attachments.isNotEmpty(), pendingAsk != null, turnStatus, composer,
|
||||
)
|
||||
val effectiveBusyAction = if (correctionAvailable && !editingQueuedMessage) busyActionOverride ?: busyMessageAction
|
||||
else BusyMessageAction.QueueNext
|
||||
|
||||
DisposableEffect(chatViewModel, gatewayClient, dashboardClient, route.key) {
|
||||
chatViewModel.initialize(apiClient = null, chatHandler = handler)
|
||||
@@ -234,49 +259,82 @@ internal fun BotChatScreen(
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
ChatComposerLayers(
|
||||
action = effectiveBusyAction.takeIf { isStreaming },
|
||||
onActionChange = {
|
||||
editingQueuedMessage = false
|
||||
busyActionOverride = it
|
||||
},
|
||||
correctionAvailable = correctionAvailable,
|
||||
onStop = if (composer.isNotBlank()) chatViewModel::cancelStream else null,
|
||||
modifier = Modifier.imePadding(),
|
||||
) {
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||
shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp),
|
||||
modifier = Modifier.imePadding(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.Bottom,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = composer,
|
||||
onValueChange = { composer = it },
|
||||
placeholder = { Text(stringResource(R.string.chat_placeholder_message)) },
|
||||
modifier = Modifier.weight(1f),
|
||||
minLines = 1,
|
||||
maxLines = 6,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (isStreaming) {
|
||||
chatViewModel.cancelStream()
|
||||
} else {
|
||||
val text = composer.trim()
|
||||
if (text.isNotEmpty()) {
|
||||
composer = ""
|
||||
chatViewModel.sendMessage(text)
|
||||
}
|
||||
Column {
|
||||
ChatMessageQueue(
|
||||
messages = queue,
|
||||
paused = queuePaused,
|
||||
onResume = chatViewModel::resumeQueue,
|
||||
onClear = chatViewModel::clearQueue,
|
||||
onRemove = chatViewModel::removeQueuedAt,
|
||||
canEdit = composer.isBlank() && attachments.isEmpty(),
|
||||
onEdit = { index ->
|
||||
chatViewModel.takeQueuedForEdit(index)?.let {
|
||||
composer = it
|
||||
editingQueuedMessage = true
|
||||
}
|
||||
},
|
||||
enabled = isStreaming || composer.isNotBlank(),
|
||||
modifier = Modifier.padding(horizontal = 12.dp),
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.Bottom,
|
||||
) {
|
||||
Icon(
|
||||
if (isStreaming) Icons.Filled.Stop else Icons.AutoMirrored.Filled.Send,
|
||||
contentDescription = stringResource(
|
||||
if (isStreaming) R.string.chat_input_stop_streaming
|
||||
else R.string.chat_input_send_message,
|
||||
),
|
||||
OutlinedTextField(
|
||||
value = composer,
|
||||
onValueChange = { composer = it },
|
||||
placeholder = { Text(stringResource(R.string.chat_placeholder_message)) },
|
||||
modifier = Modifier.weight(1f),
|
||||
minLines = 1,
|
||||
maxLines = 6,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
IconButton(
|
||||
onClick = {
|
||||
if (isStreaming && composer.isBlank()) {
|
||||
chatViewModel.cancelStream()
|
||||
} else {
|
||||
val text = composer.trim()
|
||||
if (text.isNotEmpty()) {
|
||||
composer = ""
|
||||
chatViewModel.sendMessage(text, effectiveBusyAction)
|
||||
editingQueuedMessage = false
|
||||
busyActionOverride = null
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = isStreaming || composer.isNotBlank(),
|
||||
) {
|
||||
Icon(
|
||||
if (isStreaming && composer.isBlank()) Icons.Filled.Stop else Icons.AutoMirrored.Filled.Send,
|
||||
contentDescription = stringResource(
|
||||
when {
|
||||
isStreaming && composer.isBlank() -> R.string.chat_input_stop_streaming
|
||||
isStreaming && effectiveBusyAction == BusyMessageAction.CorrectNow -> R.string.chat_correct_now
|
||||
isStreaming -> R.string.chat_queue_next
|
||||
else -> R.string.chat_input_send_message
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Box(
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import com.hermesandroid.relay.data.canCorrectBusyMessage
|
||||
import com.hermesandroid.relay.ui.components.ChatMessageQueue
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.foundation.Canvas
|
||||
@@ -98,6 +101,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.clipToBounds
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
@@ -119,6 +123,7 @@ import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.zIndex
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.chatResponsiveLayout
|
||||
import com.hermesandroid.relay.ui.theme.radialNavyBackground
|
||||
import com.hermesandroid.relay.network.upstream.ApiModelOption
|
||||
import com.hermesandroid.relay.network.upstream.ChatMode
|
||||
@@ -749,6 +754,7 @@ fun ChatScreen(
|
||||
gitWorkspaceAvailable: Boolean = gitWorkspaceSummary != null,
|
||||
onNavigateToGitWorkspace: () -> Unit = {},
|
||||
) {
|
||||
val responsiveLayout = chatResponsiveLayout(LocalConfiguration.current.screenWidthDp)
|
||||
val supervised = supervisedPolicy.enabled
|
||||
val supervisedVisibility = supervisedPolicy.visibility.resolved()
|
||||
LaunchedEffect(supervisedPolicy) {
|
||||
@@ -1135,6 +1141,12 @@ fun ChatScreen(
|
||||
|
||||
val availableSkills by chatViewModel.availableSkills.collectAsState()
|
||||
val queuedMessages by chatViewModel.queuedMessages.collectAsState()
|
||||
val queuePaused by chatViewModel.queuePaused.collectAsState()
|
||||
val busyMessageAction by connectionViewModel.busyMessageAction.collectAsState()
|
||||
var busyActionOverride by remember(currentSessionId, busyMessageAction) {
|
||||
mutableStateOf<BusyMessageAction?>(null)
|
||||
}
|
||||
var editingQueuedMessage by remember(currentSessionId) { mutableStateOf(false) }
|
||||
val recentPrompts by chatViewModel.recentPrompts.collectAsState()
|
||||
val recentPromptsEnabled by connectionViewModel.chatRecentPromptsEnabled.collectAsState()
|
||||
// Effective approval-bypass (server-computed: ORs global approvals.mode=off,
|
||||
@@ -1395,7 +1407,11 @@ fun ChatScreen(
|
||||
}
|
||||
var showCommandPalette by remember { mutableStateOf(false) }
|
||||
var showTranscriptSearch by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingAttachmentPreview by remember { mutableStateOf<Attachment?>(null) }
|
||||
var pendingAttachmentPreviewIndex by rememberSaveable(
|
||||
composerDraftKey.connectionId,
|
||||
composerDraftKey.profileId,
|
||||
composerDraftKey.sessionId,
|
||||
) { mutableStateOf<Int?>(null) }
|
||||
var showModelSheet by remember { mutableStateOf(false) }
|
||||
var showEffortSheet by remember { mutableStateOf(false) }
|
||||
var showAgentInfo by remember { mutableStateOf(false) }
|
||||
@@ -3311,7 +3327,13 @@ fun ChatScreen(
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier.padding(horizontal = 32.dp)
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 32.dp)
|
||||
.then(
|
||||
responsiveLayout.introMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
),
|
||||
) {
|
||||
Spacer(modifier = Modifier.weight(0.15f))
|
||||
|
||||
@@ -3320,12 +3342,15 @@ fun ChatScreen(
|
||||
LocalBackgroundVisualizationEnabled.current &&
|
||||
(!supervised || supervisedVisibility.showAgentIdentity)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(1f)
|
||||
.weight(0.7f, fill = false)
|
||||
) {
|
||||
val avatarModifier = responsiveLayout.avatarSize?.let { size ->
|
||||
Modifier
|
||||
.size(size)
|
||||
.clipToBounds()
|
||||
} ?: Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(1f)
|
||||
.weight(0.7f, fill = false)
|
||||
Box(modifier = avatarModifier) {
|
||||
LocalAgentAvatar.current.Render(
|
||||
state = AvatarRenderState(
|
||||
state = if (error != null) SphereState.Error else SphereState.Idle,
|
||||
@@ -3568,7 +3593,14 @@ fun ChatScreen(
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.align(Alignment.Center)
|
||||
.fillMaxHeight()
|
||||
.then(
|
||||
responsiveLayout.transcriptMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.padding(top = if (showTranscriptSearch) 112.dp else 0.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp)
|
||||
@@ -4091,69 +4123,21 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
AnimatedVisibility(visible = queuedMessages.isNotEmpty()) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = pluralStringResource(
|
||||
R.plurals.chat_queue_count,
|
||||
queuedMessages.size,
|
||||
queuedMessages.size,
|
||||
),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
TextButton(
|
||||
onClick = { chatViewModel.clearQueue() },
|
||||
modifier = Modifier.height(28.dp)
|
||||
) {
|
||||
Text(
|
||||
stringResource(R.string.chat_clear),
|
||||
style = MaterialTheme.typography.labelSmall
|
||||
)
|
||||
}
|
||||
ChatMessageQueue(
|
||||
messages = queuedMessages,
|
||||
paused = queuePaused,
|
||||
onResume = chatViewModel::resumeQueue,
|
||||
onClear = chatViewModel::clearQueue,
|
||||
onRemove = chatViewModel::removeQueuedAt,
|
||||
canEdit = inputText.isBlank() && pendingAttachments.isEmpty(),
|
||||
onEdit = { index ->
|
||||
chatViewModel.takeQueuedForEdit(index)?.let {
|
||||
inputText = it
|
||||
editingQueuedMessage = true
|
||||
}
|
||||
// Per-item: tap the text to pull it back into the composer
|
||||
// for editing; ✕ to drop just that one. (Reorder omitted —
|
||||
// low value vs. drag-handle complexity on a transient queue.)
|
||||
queuedMessages.forEachIndexed { index, msg ->
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = msg,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clickable {
|
||||
chatViewModel.takeQueuedForEdit(index)?.let { t ->
|
||||
inputText = if (inputText.isBlank()) t else "$inputText $t"
|
||||
}
|
||||
}
|
||||
.padding(vertical = 4.dp),
|
||||
)
|
||||
TextButton(
|
||||
onClick = { chatViewModel.removeQueuedAt(index) },
|
||||
modifier = Modifier.height(28.dp),
|
||||
) {
|
||||
Text("✕", style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp),
|
||||
)
|
||||
|
||||
val quoteYouLabel = stringResource(R.string.chat_quote_you)
|
||||
val quoteHermesLabel = stringResource(R.string.chat_quote_hermes)
|
||||
@@ -4199,15 +4183,17 @@ fun ChatScreen(
|
||||
|
||||
PendingAttachmentComposer(
|
||||
attachments = pendingAttachments,
|
||||
onPreview = { attachment, _ -> pendingAttachmentPreview = attachment },
|
||||
onPreview = { _, index -> pendingAttachmentPreviewIndex = index },
|
||||
onRemove = chatViewModel::removeAttachment,
|
||||
onMove = chatViewModel::moveAttachment,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
)
|
||||
pendingAttachmentPreview?.let { attachment ->
|
||||
pendingAttachmentPreviewIndex
|
||||
?.let(pendingAttachments::getOrNull)
|
||||
?.let { attachment ->
|
||||
AttachmentViewer(
|
||||
attachment = attachment,
|
||||
onDismiss = { pendingAttachmentPreview = null },
|
||||
onDismiss = { pendingAttachmentPreviewIndex = null },
|
||||
initiallyRevealed = true,
|
||||
)
|
||||
}
|
||||
@@ -4260,25 +4246,32 @@ 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 = canCorrectBusyMessage(
|
||||
steerableTurn, pendingAttachments.isNotEmpty(), pendingAsk != null, turnStatus, inputText,
|
||||
) &&
|
||||
(!supervised || supervisedPolicy.capabilities.steerResponse)
|
||||
val effectiveBusyAction = if (canSteerCurrentMessage && !editingQueuedMessage) busyActionOverride ?: busyMessageAction
|
||||
else BusyMessageAction.QueueNext
|
||||
val correctCurrentMessage = canSteerCurrentMessage &&
|
||||
effectiveBusyAction == BusyMessageAction.CorrectNow
|
||||
val trailing = when {
|
||||
!isStreaming && hasContent -> ChatInputTrailing.SEND
|
||||
!isStreaming -> ChatInputTrailing.VOICE
|
||||
isStreaming && !hasContent -> ChatInputTrailing.STOP
|
||||
canSteerCurrentMessage -> ChatInputTrailing.STEER
|
||||
correctCurrentMessage -> ChatInputTrailing.STEER
|
||||
else -> ChatInputTrailing.QUEUE
|
||||
}
|
||||
val inputCaption = when {
|
||||
isStreaming && hasContent && canSteerCurrentMessage ->
|
||||
isStreaming && hasContent && correctCurrentMessage ->
|
||||
stringResource(R.string.chat_sends_now)
|
||||
isStreaming && hasContent && queuePaused -> stringResource(R.string.chat_queue_paused)
|
||||
isStreaming && hasContent -> stringResource(R.string.chat_delivered_after_turn)
|
||||
isStreaming && steerNotice != null -> steerNotice
|
||||
else -> null
|
||||
}
|
||||
val inputPlaceholder = when {
|
||||
editingMessage != null -> stringResource(R.string.chat_placeholder_edit)
|
||||
isStreaming && canSteerCurrentMessage -> stringResource(R.string.chat_placeholder_steer)
|
||||
isStreaming && correctCurrentMessage -> stringResource(R.string.chat_placeholder_steer)
|
||||
isStreaming -> stringResource(R.string.chat_placeholder_queue)
|
||||
else -> stringResource(R.string.chat_placeholder_message)
|
||||
}
|
||||
@@ -4530,6 +4523,12 @@ fun ChatScreen(
|
||||
}
|
||||
|
||||
ChatInputBar(
|
||||
busyAction = effectiveBusyAction.takeIf { isStreaming },
|
||||
correctionAvailable = canSteerCurrentMessage,
|
||||
onBusyActionChange = {
|
||||
editingQueuedMessage = false
|
||||
busyActionOverride = it
|
||||
},
|
||||
value = inputText,
|
||||
onValueChange = { inputText = it },
|
||||
placeholder = inputPlaceholder,
|
||||
@@ -4558,7 +4557,9 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
} else {
|
||||
chatViewModel.sendMessage(outboundText)
|
||||
chatViewModel.sendMessage(outboundText, effectiveBusyAction)
|
||||
editingQueuedMessage = false
|
||||
busyActionOverride = null
|
||||
inputText = ""
|
||||
finishSuccessfulSend()
|
||||
}
|
||||
@@ -4650,6 +4651,13 @@ fun ChatScreen(
|
||||
supervisedPolicy.capabilities.attachmentCategories
|
||||
)) pasteImageFromClipboard else ({ }),
|
||||
onLongPressAttach = { if (!supervised) showCommandPalette = true },
|
||||
modifier = Modifier
|
||||
.align(Alignment.CenterHorizontally)
|
||||
.then(
|
||||
responsiveLayout.chromeMaxWidth?.let {
|
||||
Modifier.widthIn(max = it)
|
||||
} ?: Modifier,
|
||||
),
|
||||
charLimit = charLimit,
|
||||
caption = turnStatus ?: inputCaption,
|
||||
voiceReady = voiceReady,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import com.hermesandroid.relay.ui.components.ChatBusyActionSelector
|
||||
import android.os.Build
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -499,6 +500,22 @@ fun ChatSettingsScreen(
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
val busyMessageAction by connectionViewModel.busyMessageAction.collectAsState()
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.chat_busy_default_title), style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
stringResource(R.string.chat_busy_default_description),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
ChatBusyActionSelector(
|
||||
action = busyMessageAction,
|
||||
onActionChange = connectionViewModel::setBusyMessageAction,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
HorizontalDivider()
|
||||
|
||||
val physicalKeyboardEnterBehavior by
|
||||
connectionViewModel.physicalKeyboardEnterBehavior.collectAsState()
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
@@ -706,8 +723,9 @@ fun ChatSettingsScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// Live preview of the exact text that will be sent.
|
||||
// Rebuilds on every toggle change via remember(key1..key5).
|
||||
// Representative preview of each enabled block.
|
||||
// The chat context audit remains the exact selected-
|
||||
// session preview. Rebuilds on every toggle change.
|
||||
val previewText = remember(
|
||||
appContextEnabled,
|
||||
appContextBridgeState,
|
||||
@@ -735,6 +753,14 @@ fun ChatSettingsScreen(
|
||||
destructiveVerbCount = 5,
|
||||
autoDisableMinutes = 15,
|
||||
),
|
||||
// This card is an explanatory fixture, not
|
||||
// the active session audit. Supply one
|
||||
// representative Relay tool so the bridge
|
||||
// and safety toggles remain visible; the
|
||||
// real send path uses the selected
|
||||
// session/profile's authoritative catalog.
|
||||
availableTools =
|
||||
com.hermesandroid.relay.util.PHONE_CONTEXT_PREVIEW_TOOLS,
|
||||
)
|
||||
}
|
||||
Card(
|
||||
@@ -778,7 +804,7 @@ fun ChatSettingsScreen(
|
||||
serverCaps,
|
||||
) {
|
||||
resolveChatTransportStatus(
|
||||
streamingEndpoint = streamingEndpoint,
|
||||
streamingEndpoint = resolvedStreamingEndpoint,
|
||||
gatewayAvailability = gatewayAvailability,
|
||||
serverCapabilities = serverCaps,
|
||||
)
|
||||
|
||||
@@ -66,6 +66,7 @@ import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
@@ -83,6 +84,7 @@ import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import com.hermesandroid.relay.viewmodel.RelayUiState
|
||||
import com.hermesandroid.relay.viewmodel.StandardVoiceAvailability
|
||||
import com.hermesandroid.relay.viewmodel.resolveActiveChatTransport
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
@@ -476,12 +478,16 @@ private fun ActiveOverview(
|
||||
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
||||
val relayConfigured by connectionViewModel.relayConfigured.collectAsState()
|
||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||
val usingApiFallback = apiReachable && gatewayAvailability in setOf(
|
||||
GatewayAvailability.SignInRequired,
|
||||
GatewayAvailability.Unreachable,
|
||||
GatewayAvailability.Unsupported,
|
||||
)
|
||||
val currentRouteUrl = if (usingApiFallback) {
|
||||
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||
// Observe the binding as well as the saved preference so a restored
|
||||
// conversation immediately presents its actual owner.
|
||||
val activeConversationTransport by connectionViewModel.activeConversationTransport.collectAsState()
|
||||
val usingDirectApi = resolveActiveChatTransport(
|
||||
boundOwner = activeConversationTransport,
|
||||
connection = connection,
|
||||
preference = streamingEndpoint,
|
||||
) == SessionTransport.SSE
|
||||
val currentRouteUrl = if (usingDirectApi) {
|
||||
activeEndpoint?.api?.url ?: connection.apiServerUrl
|
||||
} else {
|
||||
effectiveDashboardUrl
|
||||
@@ -492,23 +498,29 @@ private fun ActiveOverview(
|
||||
effectiveDashboardUrl = currentRouteUrl,
|
||||
)
|
||||
val routeStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
usingDirectApi && apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unknown ||
|
||||
apiHealth == ConnectionViewModel.HealthStatus.Probing ->
|
||||
(!usingDirectApi && gatewayAvailability == GatewayAvailability.Unknown) ||
|
||||
(usingDirectApi && apiHealth == ConnectionViewModel.HealthStatus.Probing) ->
|
||||
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
gatewayAvailability == GatewayAvailability.Unsupported ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unsupported ->
|
||||
OverviewStatus(stringResource(R.string.active_section_unsupported), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_unreachable), OverviewTone.Warning)
|
||||
}
|
||||
val chatStatus = when {
|
||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
||||
usingDirectApi && apiReachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Ready ->
|
||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.SignInRequired ->
|
||||
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||
gatewayAvailability == GatewayAvailability.Unreachable && !apiReachable ->
|
||||
!usingDirectApi && gatewayAvailability == GatewayAvailability.Unreachable ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
usingDirectApi && !apiReachable && apiHealth != ConnectionViewModel.HealthStatus.Probing ->
|
||||
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||
else -> OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||
}
|
||||
|
||||
+22
-7
@@ -62,6 +62,7 @@ import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.EndpointCandidate
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.displayLabel
|
||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
||||
import com.hermesandroid.relay.data.isDashboardOnlyRoute
|
||||
@@ -386,6 +387,12 @@ private fun ConnectionListCard(
|
||||
} else {
|
||||
connection.resolvedDashboardUrl
|
||||
}
|
||||
val selectedProfile: Profile? = if (activeConnectionViewModel != null) {
|
||||
val profile by activeConnectionViewModel.selectedProfile.collectAsState()
|
||||
profile
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val presentedConnection = activeConnection ?: connection
|
||||
val presentation = resolveGatewayCardPresentation(
|
||||
connection = presentedConnection,
|
||||
@@ -429,13 +436,7 @@ private fun ConnectionListCard(
|
||||
modifier = Modifier
|
||||
.size(10.dp)
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(
|
||||
if (presentation.status == GatewayCardStatus.Online) {
|
||||
com.hermesandroid.relay.ui.theme.RelayRefresh.Green
|
||||
} else {
|
||||
MaterialTheme.colorScheme.outline
|
||||
},
|
||||
),
|
||||
.background(gatewayStatusColor(presentation.status)),
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Dns,
|
||||
@@ -484,6 +485,20 @@ private fun ConnectionListCard(
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (isActive) {
|
||||
Text(
|
||||
text = listOfNotNull(
|
||||
stringResource(R.string.conn_info_profile),
|
||||
selectedProfile?.name?.takeIf { it.isNotBlank() }
|
||||
?: stringResource(R.string.settings_server_default),
|
||||
selectedProfile?.model?.takeIf { it.isNotBlank() },
|
||||
).joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (onSwitch != null || isSwitching || justSwitched) {
|
||||
OutlinedButton(
|
||||
|
||||
@@ -544,19 +544,24 @@ internal fun buildStatusChecks(
|
||||
)
|
||||
}
|
||||
|
||||
// A healthy standard-only connection should not read like three missing
|
||||
// dependencies. Collapse the absent optional extension to one neutral row;
|
||||
// configured Relay keeps the detailed auth/server/plugin troubleshooting.
|
||||
if (!relayConfigured) {
|
||||
checks += StatusCheck(
|
||||
context.getString(R.string.diag_relay_tools_optional),
|
||||
CheckStatus.Unknown,
|
||||
reason = context.getString(R.string.diag_relay_tools_not_paired),
|
||||
category = DiagnosticCategory.Relay,
|
||||
)
|
||||
}
|
||||
// 6) Optional Relay / pairing auth.
|
||||
val authLabel = context.getString(R.string.diag_check_pairing_auth)
|
||||
val authRelayActive = context.getString(R.string.diag_check_relay_active)
|
||||
val authPairingProg = context.getString(R.string.diag_check_pairing_progress)
|
||||
val authNotPaired = context.getString(R.string.diag_check_not_paired)
|
||||
val authErr = recentError(DiagnosticCategory.Auth)
|
||||
checks += when {
|
||||
!relayConfigured ->
|
||||
StatusCheck(
|
||||
authLabel, CheckStatus.Unknown,
|
||||
reason = context.getString(R.string.active_section_optional),
|
||||
category = DiagnosticCategory.Auth,
|
||||
)
|
||||
if (relayConfigured) checks += when {
|
||||
authState is AuthState.Paired ->
|
||||
StatusCheck(
|
||||
authLabel, CheckStatus.Pass,
|
||||
@@ -586,18 +591,11 @@ internal fun buildStatusChecks(
|
||||
|
||||
// 7) Relay server (optional — Unknown when not paired/configured).
|
||||
val relayLabel = context.getString(R.string.active_section_optional_relay)
|
||||
val relayNotConfigured = context.getString(R.string.diag_check_relay_not_configured)
|
||||
val relayConnected = context.getString(R.string.diag_check_connected)
|
||||
val relayReachableNotReady = context.getString(R.string.diag_check_reachable_not_ready)
|
||||
val relayConfiguredNotReachable = context.getString(R.string.diag_check_configured_not_reachable)
|
||||
val relayErr = recentError(DiagnosticCategory.Relay)
|
||||
checks += when {
|
||||
!relayConfigured ->
|
||||
StatusCheck(
|
||||
relayLabel, CheckStatus.Unknown,
|
||||
reason = relayNotConfigured,
|
||||
category = DiagnosticCategory.Relay,
|
||||
)
|
||||
if (relayConfigured) checks += when {
|
||||
relayReady ->
|
||||
StatusCheck(
|
||||
relayLabel, CheckStatus.Pass,
|
||||
@@ -629,7 +627,7 @@ internal fun buildStatusChecks(
|
||||
relayReady = relayReady,
|
||||
relayUpdateInfo = relayUpdateInfo,
|
||||
)
|
||||
checks += when (pluginState) {
|
||||
if (relayConfigured) checks += when (pluginState) {
|
||||
RelayPluginDiagnosticState.NotConfigured ->
|
||||
StatusCheck(
|
||||
pluginLabel, CheckStatus.Unknown,
|
||||
|
||||
@@ -98,7 +98,7 @@ private data class DisplayFile(
|
||||
val deletions: Int?,
|
||||
)
|
||||
|
||||
/** First-class native Git workspace backed by the optional Relay contribution. */
|
||||
/** Native Git workspace: upstream current-session reads plus optional Relay enhancements. */
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun GitStateScreen(
|
||||
@@ -131,7 +131,7 @@ fun GitStateScreen(
|
||||
var pendingConfirm by remember { mutableStateOf<ConfirmationRequest?>(null) }
|
||||
|
||||
LaunchedEffect(scanningEnabled) {
|
||||
if (scanningEnabled) viewModel.loadRepos()
|
||||
viewModel.loadRepos()
|
||||
}
|
||||
|
||||
val repos = (reposState as? GitStateUiState.Ready)?.repos.orEmpty()
|
||||
@@ -202,29 +202,27 @@ fun GitStateScreen(
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (scanningEnabled) {
|
||||
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 })
|
||||
}
|
||||
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 (scanningEnabled && detail != null) {
|
||||
if (detail != null) {
|
||||
Surface(shadowElevation = 8.dp, tonalElevation = 2.dp) {
|
||||
Column {
|
||||
if (selection.isNotEmpty()) {
|
||||
SelectionRail(
|
||||
count = selection.size,
|
||||
canWrite = hasGrant,
|
||||
canWrite = hasGrant && scanningEnabled,
|
||||
allStaged = selection.all { it.filter == FileFilter.Staged },
|
||||
onStage = stageSelection,
|
||||
onDiscard = discardSelection,
|
||||
@@ -234,7 +232,7 @@ fun GitStateScreen(
|
||||
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)) {
|
||||
Button(onClick = { showCommit = true }, enabled = scanningEnabled && 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))
|
||||
}
|
||||
}
|
||||
@@ -248,21 +246,21 @@ fun GitStateScreen(
|
||||
enabled = scanningEnabled,
|
||||
onEnabledChange = onScanningEnabledChange,
|
||||
)
|
||||
if (scanningEnabled) {
|
||||
when (val state = reposState) {
|
||||
GitStateUiState.Loading -> FullState(Modifier.weight(1f), true, "Finding repositories")
|
||||
is GitStateUiState.Unavailable -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Error -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Ready -> when {
|
||||
state.repos.isEmpty() -> FullState(Modifier.weight(1f), false, "No Git repositories found", "Add a repository to the host's configured Git roots, then refresh.")
|
||||
selectedRepo == null -> RepositoryPrompt(Modifier.weight(1f), state.repos, viewModel::selectRepo)
|
||||
else -> WorkspaceBody(
|
||||
when (val state = reposState) {
|
||||
GitStateUiState.Loading -> FullState(Modifier.weight(1f), true, "Finding repositories")
|
||||
is GitStateUiState.Unavailable -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Error -> UnavailableState(Modifier.weight(1f), state.message, viewModel::loadRepos)
|
||||
is GitStateUiState.Ready -> when {
|
||||
state.repos.isEmpty() -> FullState(Modifier.weight(1f), false, "No current-session Git repository", "Open a Hermes coding session with repository context, or enable host repository discovery above.")
|
||||
selectedRepo == null -> RepositoryPrompt(Modifier.weight(1f), state.repos, viewModel::selectRepo)
|
||||
else -> WorkspaceBody(
|
||||
modifier = Modifier.weight(1f),
|
||||
repo = selectedRepo,
|
||||
reposNotice = state.notice,
|
||||
detailState = detailState,
|
||||
mutation = mutation,
|
||||
stashNotice = stashNotice,
|
||||
relayEnhancementsEnabled = scanningEnabled,
|
||||
hasGrant = hasGrant,
|
||||
filter = filter,
|
||||
onFilter = { filter = it },
|
||||
@@ -289,8 +287,7 @@ fun GitStateScreen(
|
||||
onPush = { viewModel.currentTarget()?.let { pendingConfirm = ConfirmationRequest.Push(it) } },
|
||||
onClearMutation = viewModel::clearMutationError,
|
||||
onRetry = { viewModel.selectRepo(selectedRepo.id) },
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,7 +308,7 @@ fun GitStateScreen(
|
||||
onCreate = { name, track -> showBranches = false; viewModel.checkout("", newBranch = name, track = track) },
|
||||
)
|
||||
}
|
||||
if (showCommit && detail != null) {
|
||||
if (showCommit && scanningEnabled && detail != null) {
|
||||
val stagedPaths = detail.status.staged.map { it.path }
|
||||
CommitDialog(
|
||||
hasStaged = stagedPaths.isNotEmpty(),
|
||||
@@ -392,6 +389,7 @@ private fun WorkspaceBody(
|
||||
detailState: GitRepoDetailState,
|
||||
mutation: GitMutationState,
|
||||
stashNotice: String?,
|
||||
relayEnhancementsEnabled: Boolean,
|
||||
hasGrant: Boolean,
|
||||
filter: FileFilter,
|
||||
onFilter: (FileFilter) -> Unit,
|
||||
@@ -421,9 +419,11 @@ private fun WorkspaceBody(
|
||||
LazyColumn(modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 18.dp)) {
|
||||
item {
|
||||
SummaryRail(repo, detailState)
|
||||
RemoteActions(hasGrant, status, onFetch, onPull, onPush)
|
||||
if (relayEnhancementsEnabled) {
|
||||
RemoteActions(hasGrant, status, onFetch, onPull, onPush)
|
||||
}
|
||||
reposNotice?.let { NoticeCard(it) }
|
||||
if (!hasGrant) WriteGrantNotice()
|
||||
if (relayEnhancementsEnabled && !hasGrant) WriteGrantNotice()
|
||||
MutationBanner(mutation, onClearMutation)
|
||||
stashNotice?.let { NoticeCard(it) }
|
||||
if (status.truncated) NoticeCard(stringResource(R.string.git_state_truncated), error = true)
|
||||
@@ -438,6 +438,7 @@ private fun WorkspaceBody(
|
||||
FileRow(
|
||||
file = file,
|
||||
selected = file in selection,
|
||||
selectionEnabled = relayEnhancementsEnabled,
|
||||
expanded = expandedPath == file.path,
|
||||
mode = contentMode,
|
||||
contentState = contentState,
|
||||
@@ -554,6 +555,7 @@ private fun GitStatus.uniqueChangeCount(): Int = counts.changes.takeIf { it >= 0
|
||||
private fun FileRow(
|
||||
file: DisplayFile,
|
||||
selected: Boolean,
|
||||
selectionEnabled: Boolean,
|
||||
expanded: Boolean,
|
||||
mode: ContentMode,
|
||||
contentState: GitContentViewState,
|
||||
@@ -572,7 +574,7 @@ private fun FileRow(
|
||||
) {
|
||||
Checkbox(
|
||||
checked = selected,
|
||||
onCheckedChange = { onToggleSelected() },
|
||||
onCheckedChange = if (selectionEnabled) ({ _ -> onToggleSelected() }) else null,
|
||||
modifier = Modifier.semantics {
|
||||
contentDescription = "Select ${file.path}"
|
||||
},
|
||||
@@ -602,7 +604,9 @@ private fun FileRow(
|
||||
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") })
|
||||
if (selectionEnabled) {
|
||||
FilterChip(mode == ContentMode.File, { onOpen(ContentMode.File) }, label = { Text("File") })
|
||||
}
|
||||
}
|
||||
InlineContent(contentState, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 10.dp))
|
||||
}
|
||||
|
||||
@@ -355,7 +355,7 @@ fun SettingsScreen(
|
||||
)
|
||||
else -> null
|
||||
}
|
||||
// The Power tools below all ride the relay plugin. Rather than stamp an
|
||||
// The Relay tools below all ride the optional plugin. Rather than stamp an
|
||||
// identical badge on every card (noise, not signal), the dependency is
|
||||
// surfaced ONCE on the section header as a single plugin-state badge.
|
||||
val pluginBadge = when (relayUiState) {
|
||||
@@ -629,6 +629,14 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Image,
|
||||
title = stringResource(R.string.settings_media),
|
||||
subtitle = stringResource(R.string.settings_media_desc),
|
||||
onClick = onNavigateToMediaSettings,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.GraphicEq,
|
||||
title = stringResource(R.string.settings_voice_mode),
|
||||
@@ -637,6 +645,8 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsSectionHeader(stringResource(R.string.settings_power_tools), trailing = pluginBadge)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.AutoMirrored.Filled.Message,
|
||||
title = stringResource(R.string.settings_threads),
|
||||
@@ -645,8 +655,6 @@ fun SettingsScreen(
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
SettingsSectionHeader(stringResource(R.string.settings_power_tools), trailing = pluginBadge)
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Code,
|
||||
title = stringResource(R.string.settings_terminal),
|
||||
@@ -681,13 +689,6 @@ fun SettingsScreen(
|
||||
)
|
||||
// === END PHASE3-notif-listener-followup ===
|
||||
|
||||
SettingsCategoryRow(
|
||||
icon = Icons.Filled.Image,
|
||||
title = stringResource(R.string.settings_media),
|
||||
subtitle = stringResource(R.string.settings_media_desc), onClick = onNavigateToMediaSettings,
|
||||
isDarkTheme = isDarkTheme,
|
||||
)
|
||||
|
||||
if (BuildFlavor.isSideload) {
|
||||
// === PHASE3-safety-rails: bridge safety entry-point ===
|
||||
SettingsCategoryRow(
|
||||
|
||||
@@ -957,25 +957,6 @@ private fun VoiceForThisProfileCard(
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
// Auto-repair when Relay disappears out from under a Relay-only selection:
|
||||
// a persisted RealtimeAgent engine (Relay-only) or Relay route can't run
|
||||
// without a paired Relay, so fall back to the always-available defaults.
|
||||
LaunchedEffect(relayVoiceReady, currentEngine, currentAudioRoute) {
|
||||
if (!relayVoiceReady) {
|
||||
if (currentEngine == VoiceEngineMode.RealtimeAgent) {
|
||||
prefsRepo.setEngineMode(VoiceEngineMode.HermesVoiceOutput)
|
||||
}
|
||||
val coerced = coerceAudioRoute(
|
||||
engine = VoiceEngineMode.HermesVoiceOutput,
|
||||
route = currentAudioRoute,
|
||||
relayVoiceReady = false,
|
||||
)
|
||||
if (coerced != currentAudioRoute) {
|
||||
prefsRepo.setAudioRoute(coerced)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SectionCard(title = stringResource(R.string.voice_settings_for_profile_title)) {
|
||||
Text(
|
||||
text = stringResource(R.string.voice_settings_engine_label),
|
||||
|
||||
@@ -6,6 +6,7 @@ import androidx.core.content.FileProvider
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
@@ -98,7 +99,7 @@ class MediaCacheWriter(
|
||||
suspend fun cache(bytes: ByteArray, contentType: String, fileName: String?): Uri =
|
||||
withContext(Dispatchers.IO) {
|
||||
val dir = cacheRoot
|
||||
val targetName = buildFilename(bytes, contentType, fileName)
|
||||
val targetName = buildFilename(bytes.sha1(), contentType, fileName)
|
||||
val file = File(dir, targetName)
|
||||
file.writeBytes(bytes)
|
||||
// Best-effort LRU enforcement — never fatal on a cache operation.
|
||||
@@ -113,6 +114,45 @@ class MediaCacheWriter(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a completed streaming download into the media cache without ever
|
||||
* materializing the file as a ByteArray. The caller retains ownership of
|
||||
* [source] when this throws; successful calls consume or copy it.
|
||||
*/
|
||||
suspend fun cache(source: File, contentType: String, fileName: String?): Uri {
|
||||
val target = cacheFile(source, contentType, fileName)
|
||||
return withContext(Dispatchers.IO) {
|
||||
FileProvider.getUriForFile(
|
||||
context,
|
||||
"${context.packageName}.fileprovider",
|
||||
target,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun cacheFile(source: File, contentType: String, fileName: String?): File =
|
||||
withContext(Dispatchers.IO) {
|
||||
require(source.isFile) { "Media cache source does not exist" }
|
||||
val dir = cacheRoot
|
||||
val target = File(dir, buildFilename(source.sha1(), contentType, fileName))
|
||||
if (source.canonicalFile != target.canonicalFile) {
|
||||
if (target.exists()) {
|
||||
source.delete()
|
||||
target.setLastModified(System.currentTimeMillis())
|
||||
} else if (!source.renameTo(target)) {
|
||||
source.inputStream().use { input ->
|
||||
target.outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
source.delete()
|
||||
}
|
||||
}
|
||||
try {
|
||||
enforceCap()
|
||||
} catch (_: Exception) { /* swallow */ }
|
||||
|
||||
target
|
||||
}
|
||||
|
||||
/**
|
||||
* Wipe the entire `hermes-media/` directory. Returns the number of bytes
|
||||
* freed so the caller can show a "Freed X MB" snackbar/toast.
|
||||
@@ -133,15 +173,8 @@ class MediaCacheWriter(
|
||||
|
||||
// --- internals ---
|
||||
|
||||
private fun buildFilename(bytes: ByteArray, contentType: String, fileName: String?): String {
|
||||
private fun buildFilename(sha1: String, contentType: String, fileName: String?): String {
|
||||
val ext = mimeToExt[contentType.lowercase().substringBefore(';').trim()] ?: "bin"
|
||||
// SHA-1 of the bytes — stable + collision-resistant enough for cache keys.
|
||||
val sha1 = try {
|
||||
MessageDigest.getInstance("SHA-1").digest(bytes).joinToString("") { "%02x".format(it) }
|
||||
} catch (_: Exception) {
|
||||
// fallback to a weaker but always-available hash
|
||||
bytes.contentHashCode().toUInt().toString(16)
|
||||
}
|
||||
|
||||
// If the server supplied a filename, keep the base (sanitized) but
|
||||
// force the extension we derived from the MIME. This keeps the
|
||||
@@ -162,6 +195,33 @@ class MediaCacheWriter(
|
||||
}
|
||||
}
|
||||
|
||||
private fun ByteArray.sha1(): String = try {
|
||||
MessageDigest.getInstance("SHA-1").digest(this).toHexString()
|
||||
} catch (_: Exception) {
|
||||
contentHashCode().toUInt().toString(16)
|
||||
}
|
||||
|
||||
private fun File.sha1(): String = try {
|
||||
inputStream().use { input ->
|
||||
val digest = MessageDigest.getInstance("SHA-1")
|
||||
input.updateDigest(digest)
|
||||
digest.digest().toHexString()
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
"${length().toUInt().toString(16)}-${lastModified().toUInt().toString(16)}"
|
||||
}
|
||||
|
||||
private fun InputStream.updateDigest(digest: MessageDigest) {
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
while (true) {
|
||||
val read = read(buffer)
|
||||
if (read < 0) return
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
|
||||
private fun ByteArray.toHexString(): String = joinToString("") { "%02x".format(it) }
|
||||
|
||||
/**
|
||||
* Delete oldest-mtime files until the cache directory fits under the cap.
|
||||
* Called after every write; safe to call more often.
|
||||
|
||||
@@ -14,6 +14,9 @@ import kotlinx.coroutines.withContext
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.File
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
@@ -39,6 +42,7 @@ object MediaSaver {
|
||||
|
||||
private const val SAVE_SUBDIR = "Hermes-Relay"
|
||||
private const val SHARE_CACHE_DIR = "hermes-media"
|
||||
private const val MAX_IN_MEMORY_MEDIA_BYTES = 25L * 1024L * 1024L
|
||||
|
||||
private val httpClient: OkHttpClient by lazy {
|
||||
OkHttpClient.Builder()
|
||||
@@ -70,7 +74,10 @@ object MediaSaver {
|
||||
httpClient.newCall(request).execute().use { resp ->
|
||||
if (!resp.isSuccessful) error("HTTP ${resp.code}")
|
||||
val contentType = resp.header("Content-Type")?.substringBefore(';')?.trim()
|
||||
val body = resp.body.bytes()
|
||||
val responseBody = resp.body
|
||||
val body = responseBody.byteStream().use { input ->
|
||||
readBoundedBytes(input, responseBody.contentLength())
|
||||
}
|
||||
body to contentType
|
||||
}
|
||||
}
|
||||
@@ -78,11 +85,42 @@ object MediaSaver {
|
||||
/** Read the bytes behind a `content://` (or `file://`) [uri]. */
|
||||
suspend fun readUriBytes(context: Context, uri: Uri): ByteArray? =
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
}.getOrNull()
|
||||
try {
|
||||
val declaredLength = context.contentResolver.openAssetFileDescriptor(uri, "r")
|
||||
?.use { it.length }
|
||||
?.takeIf { it >= 0L }
|
||||
?: -1L
|
||||
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||
readBoundedBytes(input, declaredLength)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun readBoundedBytes(input: InputStream, declaredLength: Long): ByteArray {
|
||||
if (declaredLength > MAX_IN_MEMORY_MEDIA_BYTES) {
|
||||
throw IOException("Media exceeds Android's in-memory export limit")
|
||||
}
|
||||
val initialSize = when {
|
||||
declaredLength in 1..MAX_IN_MEMORY_MEDIA_BYTES -> declaredLength.toInt()
|
||||
else -> DEFAULT_BUFFER_SIZE
|
||||
}
|
||||
val output = ByteArrayOutputStream(initialSize)
|
||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
total += read
|
||||
if (total > MAX_IN_MEMORY_MEDIA_BYTES) {
|
||||
throw IOException("Media exceeds Android's in-memory export limit")
|
||||
}
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
// --- Save ---------------------------------------------------------------
|
||||
|
||||
suspend fun saveImage(
|
||||
|
||||
@@ -99,8 +99,14 @@ private const val PREAMBLE =
|
||||
"The user is chatting via the Hermes-Relay Android app. " +
|
||||
"Keep responses mobile-friendly and concise when possible."
|
||||
|
||||
/** Representative capability used only by the Settings preview fixture. */
|
||||
internal val PHONE_CONTEXT_PREVIEW_TOOLS = setOf("android_phone_status")
|
||||
|
||||
/**
|
||||
* Build the system-prompt block from [settings] + [snapshot].
|
||||
* Build the system-prompt block from [settings] + [snapshot]. Relay-only
|
||||
* bridge guidance is emitted only when [availableTools] proves that this exact
|
||||
* selected session/profile can call at least one `android_*` tool. A missing
|
||||
* catalog fails closed for tool claims while preserving neutral mobile context.
|
||||
*
|
||||
* Returns `null` iff:
|
||||
* 1. [AppContextSettings.master] is false, OR
|
||||
@@ -112,14 +118,27 @@ private const val PREAMBLE =
|
||||
* itself is useful (it's the original v0.1.0 behavior). The "everything
|
||||
* off → null" case in the brief is the `master=false` branch.
|
||||
*/
|
||||
fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): String? {
|
||||
fun buildPromptBlock(
|
||||
settings: AppContextSettings,
|
||||
snapshot: PhoneSnapshot,
|
||||
availableTools: Set<String>? = null,
|
||||
): String? {
|
||||
if (!settings.master) return null
|
||||
|
||||
val lines = mutableListOf<String>()
|
||||
lines += PREAMBLE
|
||||
|
||||
if (settings.bridgeState) {
|
||||
lines += buildBridgeLine(snapshot)
|
||||
val phoneControlTools = availableTools
|
||||
?.filterTo(mutableSetOf()) {
|
||||
it.startsWith("android_") && it != "android_setup"
|
||||
}
|
||||
.orEmpty()
|
||||
|
||||
if (settings.bridgeState && phoneControlTools.isNotEmpty()) {
|
||||
lines += buildBridgeLine(
|
||||
snapshot = snapshot,
|
||||
phoneStatusToolAvailable = "android_phone_status" in phoneControlTools,
|
||||
)
|
||||
}
|
||||
|
||||
if (settings.currentApp && snapshot.currentApp != null) {
|
||||
@@ -130,7 +149,7 @@ fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): Str
|
||||
lines += "Battery: ${snapshot.batteryPercent}%."
|
||||
}
|
||||
|
||||
if (settings.safetyStatus) {
|
||||
if (settings.safetyStatus && phoneControlTools.isNotEmpty()) {
|
||||
buildSafetyLine(snapshot)?.let { lines += it }
|
||||
}
|
||||
|
||||
@@ -151,7 +170,10 @@ fun buildPromptBlock(settings: AppContextSettings, snapshot: PhoneSnapshot): Str
|
||||
* the bridge isn't bound — "Phone bridge: not installed" is itself useful
|
||||
* context (tells the agent not to try tool calls into the phone).
|
||||
*/
|
||||
private fun buildBridgeLine(snapshot: PhoneSnapshot): String {
|
||||
private fun buildBridgeLine(
|
||||
snapshot: PhoneSnapshot,
|
||||
phoneStatusToolAvailable: Boolean,
|
||||
): String {
|
||||
if (!snapshot.bridgeBound) {
|
||||
return "Phone bridge: not connected. Tool calls into the phone are unavailable."
|
||||
}
|
||||
@@ -189,8 +211,12 @@ private fun buildBridgeLine(snapshot: PhoneSnapshot): String {
|
||||
|
||||
val screenText = if (snapshot.screenOn) "Screen: on." else "Screen: off."
|
||||
|
||||
return "Phone bridge: enabled. $permsText. $screenText $unattendedText " +
|
||||
"For full phone status (current app, battery, blocklist), call the android_phone_status tool."
|
||||
val statusToolHint = if (phoneStatusToolAvailable) {
|
||||
" For full phone status (current app, battery, blocklist), call the android_phone_status tool."
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "Phone bridge: enabled. $permsText. $screenText $unattendedText$statusToolHint"
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -28,25 +28,26 @@ sealed interface ChatRuntimeStatus {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve chat health in product priority order:
|
||||
* Gateway primary, API/SSE fallback, pending connection, then unavailable.
|
||||
* Resolve chat health for the active conversation owner only. A reachable
|
||||
* sibling endpoint cannot make a signed-out or unreachable conversation look
|
||||
* connected.
|
||||
*/
|
||||
fun resolveChatRuntimeStatus(
|
||||
gateway: ChatTransportReadiness,
|
||||
apiSse: ChatTransportReadiness,
|
||||
): ChatRuntimeStatus = when {
|
||||
gateway == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = ChatTransportPath.Gateway,
|
||||
fallback = false,
|
||||
)
|
||||
|
||||
apiSse == ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = ChatTransportPath.ApiSse,
|
||||
fallback = true,
|
||||
)
|
||||
|
||||
gateway == ChatTransportReadiness.Connecting ||
|
||||
apiSse == ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
|
||||
|
||||
else -> ChatRuntimeStatus.Unavailable
|
||||
owner: ChatTransportPath = ChatTransportPath.Gateway,
|
||||
): ChatRuntimeStatus {
|
||||
val readiness = when (owner) {
|
||||
ChatTransportPath.Gateway -> gateway
|
||||
ChatTransportPath.ApiSse -> apiSse
|
||||
}
|
||||
return when (readiness) {
|
||||
ChatTransportReadiness.Ready -> ChatRuntimeStatus.Connected(
|
||||
transport = owner,
|
||||
fallback = false,
|
||||
)
|
||||
ChatTransportReadiness.Connecting -> ChatRuntimeStatus.Connecting
|
||||
ChatTransportReadiness.NotConfigured,
|
||||
ChatTransportReadiness.Unavailable -> ChatRuntimeStatus.Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.BusyMessageAction
|
||||
import android.app.Application
|
||||
import android.os.Build
|
||||
import android.content.Context
|
||||
@@ -55,6 +56,8 @@ import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.capabilities
|
||||
import com.hermesandroid.relay.data.automaticChatTransport
|
||||
import com.hermesandroid.relay.data.chatTransportForPreference
|
||||
import com.hermesandroid.relay.data.ConnectionSecurity
|
||||
import com.hermesandroid.relay.data.ConnectionStore
|
||||
import com.hermesandroid.relay.data.LEGACY_AUTHENTICATED_DASHBOARD_ROUTE_ROLE
|
||||
@@ -348,16 +351,16 @@ internal fun resolveChatConnectState(
|
||||
ready: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
apiHealth: ConnectionViewModel.HealthStatus,
|
||||
chatOwner: SessionTransport = connection?.automaticChatTransport ?: SessionTransport.GATEWAY,
|
||||
): ChatConnectState {
|
||||
if (ready) return ChatConnectState.Ready
|
||||
if (!hydrated) return ChatConnectState.Connecting
|
||||
val active = connection ?: return ChatConnectState.NeedsConnection
|
||||
val gatewayStillSettling = active.capabilities.dashboardGatewayConfigured &&
|
||||
if (connection == null) return ChatConnectState.NeedsConnection
|
||||
val gatewayStillSettling = chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability in setOf(
|
||||
GatewayAvailability.Unknown,
|
||||
GatewayAvailability.SignInRequired,
|
||||
)
|
||||
val apiStillSettling = active.capabilities.apiServerConfigured &&
|
||||
val apiStillSettling = chatOwner == SessionTransport.SSE &&
|
||||
apiHealth in setOf(
|
||||
ConnectionViewModel.HealthStatus.Unknown,
|
||||
ConnectionViewModel.HealthStatus.Probing,
|
||||
@@ -374,9 +377,20 @@ internal fun isChatTransportReady(
|
||||
apiClientPresent: Boolean,
|
||||
apiReachable: Boolean,
|
||||
gatewayAvailability: GatewayAvailability,
|
||||
chatOwner: SessionTransport = SessionTransport.GATEWAY,
|
||||
): Boolean =
|
||||
gatewayAvailability == GatewayAvailability.Ready ||
|
||||
(apiClientPresent && apiReachable)
|
||||
when (chatOwner) {
|
||||
SessionTransport.GATEWAY -> gatewayAvailability == GatewayAvailability.Ready
|
||||
SessionTransport.SSE -> apiClientPresent && apiReachable
|
||||
}
|
||||
|
||||
internal fun resolveActiveChatTransport(
|
||||
boundOwner: SessionTransport?,
|
||||
connection: Connection?,
|
||||
preference: String,
|
||||
): SessionTransport = boundOwner
|
||||
?: connection?.chatTransportForPreference(preference)
|
||||
?: SessionTransport.GATEWAY
|
||||
|
||||
/** Startup transport timeouts are retryable evidence, not an offline verdict. */
|
||||
internal fun isTransientDashboardTransportFailure(error: Throwable?): Boolean =
|
||||
@@ -1325,7 +1339,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
upstreamTransport.dashboardSessionClientFor(cid, url)
|
||||
},
|
||||
streamingEndpointProvider = { streamingEndpoint.value },
|
||||
gatewayAvailabilityProvider = { upstreamTransport.gatewayAvailability.value },
|
||||
automaticTransportProvider = {
|
||||
activeConnection.value?.automaticChatTransport ?: SessionTransport.GATEWAY
|
||||
},
|
||||
setLastSessionId = { _lastSessionId.value = it },
|
||||
legacyDefaultSessionId = {
|
||||
getApplication<Application>().relayDataStore.data.first()[KEY_LAST_SESSION_ID]
|
||||
@@ -1667,10 +1683,17 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
private val _chatApiClient = MutableStateFlow<HermesApiClient?>(null)
|
||||
val chatApiClient: StateFlow<HermesApiClient?> = _chatApiClient.asStateFlow()
|
||||
private val _activeConversationTransport = MutableStateFlow<SessionTransport?>(null)
|
||||
val activeConversationTransport: StateFlow<SessionTransport?> =
|
||||
_activeConversationTransport.asStateFlow()
|
||||
private var profileChatApiClient: HermesApiClient? = null
|
||||
private var profileChatApiClientUrl: String? = null
|
||||
private var profileChatApiClientKey: String? = null
|
||||
|
||||
fun setActiveConversationTransport(transport: SessionTransport?) {
|
||||
_activeConversationTransport.value = transport
|
||||
}
|
||||
|
||||
// Chat mode + per-endpoint capability snapshot — owned by
|
||||
// [upstreamTransport]; getters delegate. `rebuildApiClient()` pushes the
|
||||
// freshly-probed snapshot via `setCapabilitiesAndMode`.
|
||||
@@ -1863,16 +1886,24 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
return upstreamTransport.dashboardClientFor(connectionId, dashboardUrl).getConfig()
|
||||
}
|
||||
|
||||
// Gateway/Dashboard is the standard path; API remains an optional fallback.
|
||||
private val streamingEndpointPreference: StateFlow<String> =
|
||||
application.relayDataStore.data
|
||||
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
|
||||
// Readiness follows the active conversation owner, not any reachable sibling route.
|
||||
val chatReady: StateFlow<Boolean> = combine(
|
||||
_chatApiClient,
|
||||
_apiServerReachable,
|
||||
combine(_chatApiClient, _apiServerReachable) { client, reachable -> client to reachable },
|
||||
upstreamTransport.gatewayAvailability,
|
||||
) { client, apiReachable, gateway ->
|
||||
activeConnection,
|
||||
streamingEndpointPreference,
|
||||
activeConversationTransport,
|
||||
) { (client, apiReachable), gateway, connection, preference, boundOwner ->
|
||||
isChatTransportReady(
|
||||
apiClientPresent = client != null,
|
||||
apiReachable = apiReachable,
|
||||
gatewayAvailability = gateway,
|
||||
chatOwner = resolveActiveChatTransport(boundOwner, connection, preference),
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, false)
|
||||
|
||||
@@ -1892,13 +1923,22 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
* before any flow emits — is the neutral state, not the CTA.
|
||||
*/
|
||||
val chatConnectState: StateFlow<ChatConnectState> = combine(
|
||||
connectionStore.isHydrated,
|
||||
activeConnection,
|
||||
chatReady,
|
||||
combine(connectionStore.isHydrated, activeConnection, chatReady) { hydrated, active, ready ->
|
||||
Triple(hydrated, active, ready)
|
||||
},
|
||||
upstreamTransport.gatewayAvailability,
|
||||
_apiServerHealth,
|
||||
) { hydrated, active, ready, gateway, apiHealth ->
|
||||
resolveChatConnectState(hydrated, active, ready, gateway, apiHealth)
|
||||
streamingEndpointPreference,
|
||||
activeConversationTransport,
|
||||
) { (hydrated, active, ready), gateway, apiHealth, preference, boundOwner ->
|
||||
resolveChatConnectState(
|
||||
hydrated,
|
||||
active,
|
||||
ready,
|
||||
gateway,
|
||||
apiHealth,
|
||||
resolveActiveChatTransport(boundOwner, active, preference),
|
||||
)
|
||||
}.stateIn(viewModelScope, SharingStarted.Eagerly, ChatConnectState.Connecting)
|
||||
// NOTE: [relayReady] / [voiceReady] are declared below the [_relayUrl]
|
||||
// MutableStateFlow,
|
||||
@@ -2348,13 +2388,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
suspend fun loadProfileScopedMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>>? = profileController.loadProfileScopedMessages(sessionId, mode)
|
||||
|
||||
suspend fun loadProfileScopedMessages(
|
||||
profileName: String?,
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>>? =
|
||||
profileController.loadProfileScopedMessages(profileName, sessionId, mode)
|
||||
|
||||
@@ -2749,9 +2789,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
//
|
||||
// Existing users keep whatever they previously chose. Only fresh installs
|
||||
// (no value persisted yet) get the new "auto" default.
|
||||
val streamingEndpoint: StateFlow<String> = application.relayDataStore.data
|
||||
.map { it[KEY_STREAMING_ENDPOINT] ?: "auto" }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
val streamingEndpoint: StateFlow<String> = streamingEndpointPreference
|
||||
|
||||
fun setStreamingEndpoint(endpoint: String) {
|
||||
viewModelScope.launch {
|
||||
@@ -2833,14 +2871,28 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
|
||||
*/
|
||||
fun resolveStreamingEndpoint(preference: String): String =
|
||||
upstreamTransport.resolveStreamingEndpoint(preference)
|
||||
upstreamTransport.resolveStreamingEndpoint(
|
||||
preference = preference,
|
||||
gatewayOwned = activeConnection.value
|
||||
?.chatTransportForPreference(preference) == SessionTransport.GATEWAY,
|
||||
)
|
||||
|
||||
/**
|
||||
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
|
||||
* [ChatViewModel.sseFallbackEndpoint] for per-turn gateway fallbacks.
|
||||
* [ChatViewModel.sseFallbackEndpoint] only for an API-owned compatibility
|
||||
* binding.
|
||||
*/
|
||||
fun resolveSseStreamingEndpoint(): String = upstreamTransport.resolveSseStreamingEndpoint()
|
||||
|
||||
fun resolveActiveStreamingEndpoint(preference: String): String =
|
||||
when (activeConversationTransport.value) {
|
||||
SessionTransport.GATEWAY -> "gateway"
|
||||
SessionTransport.SSE -> resolveStreamingEndpoint(preference)
|
||||
.takeUnless { it == "gateway" }
|
||||
?: resolveSseStreamingEndpoint()
|
||||
null -> resolveStreamingEndpoint(preference)
|
||||
}
|
||||
|
||||
// Parse tool annotations from text markers toggle
|
||||
val parseToolAnnotations: StateFlow<Boolean> = application.relayDataStore.data
|
||||
.map { it[KEY_PARSE_TOOL_ANNOTATIONS] ?: false }
|
||||
@@ -3039,6 +3091,13 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
}
|
||||
|
||||
val busyMessageAction = chatInputPreferencesRepository.busyMessageAction
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, BusyMessageAction.CorrectNow)
|
||||
|
||||
fun setBusyMessageAction(action: BusyMessageAction) {
|
||||
viewModelScope.launch { chatInputPreferencesRepository.setBusyMessageAction(action) }
|
||||
}
|
||||
|
||||
val physicalKeyboardEnterBehavior: StateFlow<PhysicalKeyboardEnterBehavior> =
|
||||
chatInputPreferencesRepository.physicalKeyboardEnterBehavior
|
||||
.stateIn(
|
||||
@@ -3674,11 +3733,18 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
val dashboardConfigured = activeConnection?.capabilities?.dashboardGatewayConfigured == true
|
||||
val apiConfigured = activeConnection?.capabilities?.apiServerConfigured == true
|
||||
// This helper runs from an eager StateFlow during construction. Read
|
||||
// the earlier-declared backing preference, not its later public alias.
|
||||
val chatOwner = resolveActiveChatTransport(
|
||||
boundOwner = activeConversationTransport.value,
|
||||
connection = activeConnection,
|
||||
preference = streamingEndpointPreference.value,
|
||||
)
|
||||
|
||||
if (
|
||||
dashboardConfigured &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired &&
|
||||
(!apiConfigured || apiHealth != HealthStatus.Reachable)
|
||||
chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability == GatewayAvailability.SignInRequired
|
||||
) {
|
||||
return ConnectionStatusSnapshot(
|
||||
title = ctx.getString(R.string.cw_dashboard_sign_in_required),
|
||||
@@ -3695,8 +3761,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
if (
|
||||
dashboardConfigured &&
|
||||
gatewayAvailability == GatewayAvailability.Unreachable &&
|
||||
(!apiConfigured || apiHealth != HealthStatus.Reachable)
|
||||
chatOwner == SessionTransport.GATEWAY &&
|
||||
gatewayAvailability == GatewayAvailability.Unreachable
|
||||
) {
|
||||
return ConnectionStatusSnapshot(
|
||||
title = ctx.getString(R.string.cw_dashboard_not_reachable),
|
||||
@@ -3712,7 +3778,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
|
||||
return when {
|
||||
apiConfigured &&
|
||||
chatOwner == SessionTransport.SSE &&
|
||||
apiConfigured &&
|
||||
apiHealth == HealthStatus.Unreachable &&
|
||||
gatewayAvailability != GatewayAvailability.Ready -> {
|
||||
// Diagnose, don't just report: for a single-route connection
|
||||
|
||||
+13
-2
@@ -2,6 +2,7 @@ package com.hermesandroid.relay.viewmodel
|
||||
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.SessionTransport
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
@@ -23,6 +24,7 @@ internal data class ConversationBinding(
|
||||
val contextKey: String? = null,
|
||||
val profileName: String? = null,
|
||||
val sessionId: String? = null,
|
||||
val transport: SessionTransport? = null,
|
||||
val displayProfile: Profile? = null,
|
||||
val origin: ConversationBindingOrigin = ConversationBindingOrigin.GlobalSelection,
|
||||
val revision: Long = 0L,
|
||||
@@ -46,6 +48,7 @@ internal class ConversationBindingController {
|
||||
sessionId: String?,
|
||||
displayProfile: Profile?,
|
||||
lockedProfileToken: String?,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
): Boolean {
|
||||
if (!profileAllowed(profileName, lockedProfileToken)) return false
|
||||
reduce(
|
||||
@@ -54,6 +57,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
transport = transport,
|
||||
)
|
||||
return true
|
||||
}
|
||||
@@ -63,6 +67,7 @@ internal class ConversationBindingController {
|
||||
profileName: String?,
|
||||
sessionId: String?,
|
||||
displayProfile: Profile? = null,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
) {
|
||||
reduce(
|
||||
contextKey = contextKey,
|
||||
@@ -70,6 +75,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = ConversationBindingOrigin.GlobalSelection,
|
||||
transport = transport,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -79,6 +85,7 @@ internal class ConversationBindingController {
|
||||
profileName: String?,
|
||||
sessionId: String?,
|
||||
displayProfile: Profile? = null,
|
||||
transport: SessionTransport? = sessionId?.let(SessionTransport::forSessionId),
|
||||
): Boolean {
|
||||
val current = _state.value
|
||||
if (
|
||||
@@ -89,7 +96,7 @@ internal class ConversationBindingController {
|
||||
current.sessionId != sessionId
|
||||
)
|
||||
) return false
|
||||
forceGlobal(contextKey, profileName, sessionId, displayProfile)
|
||||
forceGlobal(contextKey, profileName, sessionId, displayProfile, transport)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -98,17 +105,19 @@ internal class ConversationBindingController {
|
||||
if (current.sessionId == sessionId) return
|
||||
_state.value = current.copy(
|
||||
sessionId = sessionId,
|
||||
transport = sessionId?.let(SessionTransport::forSessionId) ?: current.transport,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
}
|
||||
|
||||
/** A user-requested draft keeps its owner and fences persisted-session reconciliation. */
|
||||
fun startFreshDraft() {
|
||||
fun startFreshDraft(transport: SessionTransport? = _state.value.transport) {
|
||||
val current = _state.value
|
||||
if (!current.isBound) return
|
||||
if (current.sessionId == null && current.hasExplicitOwner) return
|
||||
_state.value = current.copy(
|
||||
sessionId = null,
|
||||
transport = transport,
|
||||
origin = ConversationBindingOrigin.ExplicitSession,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
@@ -130,6 +139,7 @@ internal class ConversationBindingController {
|
||||
sessionId: String?,
|
||||
displayProfile: Profile?,
|
||||
origin: ConversationBindingOrigin,
|
||||
transport: SessionTransport?,
|
||||
) {
|
||||
val current = _state.value
|
||||
val next = ConversationBinding(
|
||||
@@ -138,6 +148,7 @@ internal class ConversationBindingController {
|
||||
sessionId = sessionId,
|
||||
displayProfile = displayProfile,
|
||||
origin = origin,
|
||||
transport = transport,
|
||||
revision = current.revision + 1,
|
||||
)
|
||||
if (current.copy(revision = next.revision) != next) {
|
||||
|
||||
@@ -72,8 +72,9 @@ data class GitTarget(
|
||||
/**
|
||||
* 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/
|
||||
* Loads the active session repository from upstream first and adds repositories
|
||||
* discovered by the Hermes-Relay plugin. On selection it 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
|
||||
@@ -119,12 +120,12 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
private var mutationJob: Job? = null
|
||||
private var messageJob: Job? = null
|
||||
private var scopeKey: String? = null
|
||||
private var sessionRepoPath: String? = null
|
||||
private var targetGeneration: Long = 0
|
||||
|
||||
fun selectedRepoIdForDisplay(): String? = _selectedRepoId.value
|
||||
|
||||
fun currentTarget(): GitTarget? {
|
||||
if (!_scanningEnabled.value) return null
|
||||
val owner = scopeKey ?: return null
|
||||
val repo = _selectedRepoId.value ?: return null
|
||||
return GitTarget(owner, repo, targetGeneration)
|
||||
@@ -143,10 +144,34 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
api = dashboard?.let(::GitStateApiClient)
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind standard Git to the active upstream session workspace.
|
||||
*
|
||||
* An exact `git_repo_root` wins; `cwd` is the official Desktop-compatible
|
||||
* fallback. Changing sessions invalidates every selected repository target
|
||||
* before starting a fresh, owner-bound discovery pass.
|
||||
*/
|
||||
fun setSessionWorkspace(repoRoot: String?, workingDirectory: String?) {
|
||||
val next = repoRoot?.trim()?.takeIf { it.isNotBlank() }
|
||||
?: workingDirectory?.trim()?.takeIf { it.isNotBlank() }
|
||||
if (sessionRepoPath == next) return
|
||||
val workspaceWasLoaded = _repos.value !is GitStateUiState.Loading
|
||||
sessionRepoPath = next
|
||||
targetGeneration += 1
|
||||
clearWorkspaceState()
|
||||
// Preserve lazy discovery: the first host scan still starts only when
|
||||
// the Git workspace asks for it. Once visible/loaded, a session switch
|
||||
// refreshes immediately against the new exact workspace.
|
||||
if (workspaceWasLoaded) loadRepos()
|
||||
}
|
||||
|
||||
fun setScanningEnabled(enabled: Boolean) {
|
||||
if (_scanningEnabled.value == enabled) return
|
||||
val workspaceWasLoaded = _repos.value !is GitStateUiState.Loading
|
||||
_scanningEnabled.value = enabled
|
||||
if (!enabled) clearWorkspaceState()
|
||||
targetGeneration += 1
|
||||
clearWorkspaceState()
|
||||
if (workspaceWasLoaded) loadRepos()
|
||||
}
|
||||
|
||||
/** Grants the plugin.api.write capability for this connection/profile. */
|
||||
@@ -158,7 +183,6 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
fun hasWriteGrant(): Boolean = _writeGrant.value
|
||||
|
||||
fun loadRepos() {
|
||||
if (!_scanningEnabled.value) return
|
||||
val client = api ?: run {
|
||||
_repos.value = GitStateUiState.Error("Dashboard connection unavailable")
|
||||
return
|
||||
@@ -167,7 +191,10 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
reposJob?.cancel()
|
||||
reposJob = viewModelScope.launch {
|
||||
_repos.value = GitStateUiState.Loading
|
||||
client.repos().fold(
|
||||
client.repos(
|
||||
sessionRepoPath = sessionRepoPath,
|
||||
includeRelayDiscovery = _scanningEnabled.value,
|
||||
).fold(
|
||||
onSuccess = { list ->
|
||||
if (scopeKey == expectedScope) {
|
||||
_repos.value = GitStateUiState.Ready(list, null)
|
||||
@@ -208,7 +235,6 @@ class GitStateViewModel(application: Application) : AndroidViewModel(application
|
||||
}
|
||||
|
||||
fun selectRepo(repoId: String) {
|
||||
if (!_scanningEnabled.value) return
|
||||
val client = api ?: return
|
||||
targetGeneration += 1
|
||||
_selectedRepoId.value = repoId
|
||||
|
||||
+8
-13
@@ -130,8 +130,8 @@ class ProfileController(
|
||||
private val dashboardClientFactory: (connectionId: String, dashboardUrl: String) -> DashboardApiClient,
|
||||
/** Current `streamingEndpoint` preference (for [activeSessionTransport]). */
|
||||
private val streamingEndpointProvider: () -> String,
|
||||
/** Current gateway availability tier (for [activeSessionTransport]). */
|
||||
private val gatewayAvailabilityProvider: () -> GatewayAvailability,
|
||||
/** Stable Auto owner for the active saved connection. */
|
||||
private val automaticTransportProvider: () -> SessionTransport,
|
||||
/** Writes `ConnectionViewModel._lastSessionId`. */
|
||||
private val setLastSessionId: (String?) -> Unit,
|
||||
/** Legacy default (untransported) session id for the server-default profile. */
|
||||
@@ -909,7 +909,7 @@ class ProfileController(
|
||||
*/
|
||||
suspend fun loadProfileScopedMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>>? = loadProfileScopedMessages(
|
||||
profileName = resolveSessionProfileName(),
|
||||
sessionId = sessionId,
|
||||
@@ -919,7 +919,7 @@ class ProfileController(
|
||||
suspend fun loadProfileScopedMessages(
|
||||
profileName: String?,
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||
): Result<List<MessageItem>>? {
|
||||
val connectionId = activeConnectionId.value ?: return null
|
||||
val dashboardUrl = activeDashboardUrlProvider() ?: return null
|
||||
@@ -1517,19 +1517,14 @@ class ProfileController(
|
||||
|
||||
/**
|
||||
* Which transport's session slot to restore right now — or `null` when the
|
||||
* decision is still pending (the gateway probe hasn't landed). A manual
|
||||
* streaming-endpoint override resolves immediately; under `"auto"`, Unknown
|
||||
* remains Gateway-owned because the transport resolver also chooses Gateway
|
||||
* until a definitive fallback verdict exists.
|
||||
* decision is still pending. A manual streaming-endpoint override resolves
|
||||
* immediately; under `"auto"`, the saved connection contract owns the
|
||||
* choice, never a transient reachability or authentication verdict.
|
||||
*/
|
||||
fun activeSessionTransport(): SessionTransport? {
|
||||
val preference = streamingEndpointProvider()
|
||||
if (preference != "auto") return SessionTransport.forEndpoint(preference)
|
||||
return when (gatewayAvailabilityProvider()) {
|
||||
GatewayAvailability.Ready -> SessionTransport.GATEWAY
|
||||
GatewayAvailability.Unknown -> SessionTransport.GATEWAY
|
||||
else -> SessionTransport.SSE
|
||||
}
|
||||
return automaticTransportProvider()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+6
-2
@@ -667,17 +667,21 @@ class UpstreamTransportController(
|
||||
* - "sessions" / "completions" / "runs" pass through unchanged (manual override wins).
|
||||
* - "auto" → reads `serverCapabilities.value.preferredChatEndpoint()`.
|
||||
*/
|
||||
fun resolveStreamingEndpoint(preference: String): String =
|
||||
fun resolveStreamingEndpoint(
|
||||
preference: String,
|
||||
gatewayOwned: Boolean,
|
||||
): String =
|
||||
resolveStreamingEndpointPreference(
|
||||
preference = preference,
|
||||
gateway = _gatewayAvailability.value,
|
||||
capabilities = _serverCapabilities.value,
|
||||
gatewayOwned = gatewayOwned,
|
||||
)
|
||||
|
||||
/**
|
||||
* Capability-resolved SSE endpoint, ignoring the gateway tier — wired to
|
||||
* [com.hermesandroid.relay.viewmodel.ChatViewModel.sseFallbackEndpoint] for
|
||||
* per-turn gateway fallbacks.
|
||||
* explicit API-owned compatibility conversations.
|
||||
*/
|
||||
fun resolveSseStreamingEndpoint(): String =
|
||||
_serverCapabilities.value.preferredChatEndpoint()
|
||||
|
||||
@@ -122,6 +122,7 @@
|
||||
<string name="chat_retry">Tentar novamente</string>
|
||||
<string name="chat_dismiss">Dispensar</string>
|
||||
<string name="chat_failure_title">O Hermes não conseguiu concluir esta resposta</string>
|
||||
<string name="chat_failure_inference_unavailable">Inferência indisponível</string>
|
||||
<string name="chat_failure_details">Detalhes</string>
|
||||
<string name="chat_failure_details_title">Falha na resposta</string>
|
||||
<string name="chat_failure_details_guidance">O Hermes relatou este erro. O app não mudará de rota nem de modelo automaticamente.</string>
|
||||
@@ -288,7 +289,7 @@
|
||||
<string name="cw_cloud_subtitle">Conecte ao seu agente hospedado</string>
|
||||
<string name="cw_server_vps_title">Gateway remoto</string>
|
||||
<string name="cw_server_vps_subtitle">Informe o endereço do Dashboard</string>
|
||||
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e fallback da API são opcionais.</string>
|
||||
<string name="cw_relay_optional_note">Endereços privados LAN e Tailscale podem usar HTTP ou HTTPS. Endereços públicos exigem HTTPS. Relay e API direta são opcionais.</string>
|
||||
<string name="cw_cloud_entry_title">Conectar ao Hermes hospedado pela Nous</string>
|
||||
<string name="cw_cloud_entry_description">Insira o endereço do agente mostrado no Nous Portal. Você entrará com segurança depois que o Hermes for encontrado.</string>
|
||||
<string name="cw_cloud_agent_name">Endereço do agente</string>
|
||||
@@ -373,7 +374,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 ou http://your-server:8642</string>
|
||||
<string name="cw_api_url_supporting">API do Hermes usada pelo Chat e pelas sessões — a porta 8642 da API e http:// são presumidos para hosts sem esquema (a porta 9119 do painel é determinada separadamente)</string>
|
||||
<string name="cw_scan_message">Procurando o painel/a API do Hermes nesta LAN…</string>
|
||||
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas no fallback opcional pela API direta.</string>
|
||||
<string name="cw_dashboard_signin_hint">Entre pelo painel para liberar Gerenciar e voz — a chave da API é usada apenas em conexões explícitas pela API direta.</string>
|
||||
<string name="cw_pair_relay_section">Parear o Relay (opcional)</string>
|
||||
<string name="cw_pair_relay_section_desc">O plugin do Relay já está em execução? Faça o pareamento aqui para ativar Terminal, Bridge e permissões de canais.</string>
|
||||
<string name="cw_pair_relay_url_label">URL do Relay</string>
|
||||
@@ -665,12 +666,12 @@
|
||||
<string name="settings_hermes_management">Gerenciamento do Hermes</string>
|
||||
<string name="settings_hermes_management_desc">Recursos do painel: habilidades, cron, MCP, perfis e modelos</string>
|
||||
<string name="settings_chat">Chat</string>
|
||||
<string name="settings_chat_desc">Comportamento do chat, Gateway, fallback da API, exibição de ferramentas e tamanho das mensagens</string>
|
||||
<string name="settings_chat_desc">Comportamento do chat, Gateway, API direta, exibição de ferramentas e tamanho das mensagens</string>
|
||||
<string name="settings_voice_mode">Modo de voz</string>
|
||||
<string name="settings_voice_mode_desc">Voz do painel, opções de relay em tempo real e provedores</string>
|
||||
<string name="settings_threads">Threads</string>
|
||||
<string name="settings_threads_desc">Permita que o agente inicie conversas com você (desativado por padrão)</string>
|
||||
<string name="settings_power_tools">Ferramentas avançadas</string>
|
||||
<string name="settings_threads_desc">Conversas iniciadas pelo Relay e entrega proativa (desativado por padrão)</string>
|
||||
<string name="settings_power_tools">Ferramentas do Relay</string>
|
||||
<string name="settings_terminal">Terminal</string>
|
||||
<string name="settings_terminal_desc">Acesso ao shell do servidor por uma sessão pareada do relay</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -682,7 +683,7 @@
|
||||
<string name="settings_notification_companion">Assistente de notificações</string>
|
||||
<string name="settings_notification_companion_desc">Notificações compartilhadas do celular para ferramentas pareadas do relay</string>
|
||||
<string name="settings_media">Mídia</string>
|
||||
<string name="settings_media_desc">Anexos recebidos pelo Relay, busca automática e limite do cache</string>
|
||||
<string name="settings_media_desc">Anexos do chat, downloads, privacidade e cache</string>
|
||||
<string name="settings_bridge_safety">Segurança do Bridge</string>
|
||||
<string name="settings_bridge_safety_desc">Lista de bloqueio, confirmação de verbos destrutivos e desativação automática</string>
|
||||
<string name="settings_sideload">Sideload</string>
|
||||
@@ -775,11 +776,11 @@
|
||||
<string name="chat_settings_debug">Depuração</string>
|
||||
<string name="chat_settings_show_system_messages_desc">Mostre os marcadores ocultos \"[System: …]\" do servidor (alterações de modelo/personalidade). Desativado corresponde ao desktop/TUI.</string>
|
||||
<string name="chat_settings_streaming_endpoint">Endpoint de streaming</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: escolhe o melhor caminho com base no que seu servidor oferece. Em uso no momento: </string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">Automático: conexões padrão usam o Gateway; conexões somente API usam a API direta. Em uso no momento: </string>
|
||||
<string name="chat_settings_gateway_suffix"> (pensamento ao vivo pelo WebSocket do painel)</string>
|
||||
<string name="chat_settings_chat_completions_suffix"> (chat por /v1/chat/completions)</string>
|
||||
<string name="chat_settings_runs_suffix"> (chat transmitido explicitamente por /v1/runs)</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, usa SSE como alternativa em cada turno.</string>
|
||||
<string name="chat_settings_gateway_desc">Gateway: pensamento ao vivo + eventos avançados de ferramentas pelo WebSocket do painel (/api/ws) — o mesmo usado pelo app para desktop. Exige login em Gerenciar; quando indisponível, este chat permanece no Gateway e oferece login ou nova tentativa.</string>
|
||||
<string name="chat_settings_sessions_desc">Sessões: fluxo nativo do Hermes em /api/sessions/{id}/chat/stream.</string>
|
||||
<string name="chat_settings_chat_desc">Chat: SSE compatível com OpenAI por /v1/chat/completions.</string>
|
||||
<string name="chat_settings_runs_desc">Runs: use somente quando seu servidor transmitir /v1/runs diretamente.</string>
|
||||
@@ -1162,8 +1163,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">Mídia</string>
|
||||
<string name="media_back">Voltar</string>
|
||||
<string name="media_intro_1">Controla como o app lida com arquivos enviados pelos resultados de ferramentas (capturas de tela, PDFs etc.) pelo relay.</string>
|
||||
<string name="media_intro_2">Somente Relay — estas configurações não afetam as imagens que você anexa no chat nem nada em uma conexão padrão (sem Relay).</string>
|
||||
<string name="media_intro_1">Controla como o app baixa, protege e armazena em cache os arquivos enviados pelo Hermes no chat.</string>
|
||||
<string name="media_intro_2">A mídia padrão do Dashboard é priorizada. Quando pareado, o Relay pode acrescentar entrega de compatibilidade e metadados de sensibilidade.</string>
|
||||
<string name="media_max_inbound">Tamanho máximo dos anexos recebidos</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">Arquivos maiores que isso são rejeitados após o download.</string>
|
||||
@@ -2080,7 +2081,8 @@
|
||||
<string name="session_path_signin_for_gateway">Entre em Gerenciar para usar o Gateway com pensamento ao vivo.</string>
|
||||
<string name="session_path_gateway_api_server">Disponível no transporte do Gateway — esta sessão transmite pelo servidor API.</string>
|
||||
<string name="session_path_relay_not_connected">Relay pareado, mas desconectado.</string>
|
||||
<string name="session_path_pair_relay_media">Pareie o relay para enviar e receber mídia.</string>
|
||||
<string name="session_path_pair_relay_media">Pareie o Relay para compatibilidade de mídia em hosts Hermes mais antigos.</string>
|
||||
<string name="session_path_media_not_ready">Atualize o Hermes para entrega de mídia padrão ou pareie o Relay para compatibilidade.</string>
|
||||
<string name="session_path_pair_relay_terminal">Pareie o relay para acessar o terminal.</string>
|
||||
<string name="session_path_voice_not_ready">A voz não está pronta nesta conexão.</string>
|
||||
<string name="session_path_threads_pair_relay">Pareie o relay e ative \"Permitir que o Hermes me envie mensagens\" para o agente poder abrir Threads.</string>
|
||||
@@ -2678,6 +2680,8 @@
|
||||
<string name="inbound_attach_downloading">Baixando…%1$s</string>
|
||||
<string name="inbound_attach_failed">Falha no anexo</string>
|
||||
<string name="inbound_attach_tap_retry">Toque para tentar novamente</string>
|
||||
<string name="inbound_attach_host_only">O arquivo está no seu host Hermes</string>
|
||||
<string name="inbound_attach_host_only_help">Atualize o Hermes para downloads padrão ou pareie o Relay para compatibilidade.</string>
|
||||
<string name="inbound_attach_open">Abrir externamente</string>
|
||||
<string name="inbound_attach_share">Compartilhar</string>
|
||||
<string name="inbound_attach_save">Salvar no dispositivo</string>
|
||||
@@ -3151,6 +3155,8 @@
|
||||
<string name="diag_check_ready_with">Pronto com %s</string>
|
||||
<string name="diag_check_relay_active">Relay ativo</string>
|
||||
<string name="diag_check_relay_not_configured">Relay não configurado</string>
|
||||
<string name="diag_relay_tools_optional">Ferramentas do Relay (opcionais)</string>
|
||||
<string name="diag_relay_tools_not_paired">Não pareado</string>
|
||||
<string name="diag_check_relay_server">Verificar servidor relay</string>
|
||||
<string name="diag_check_relay_plugin">Plugin do Relay</string>
|
||||
<string name="diag_plugin_not_configured">O plugin opcional não está configurado</string>
|
||||
@@ -3180,8 +3186,8 @@
|
||||
<string name="inbound_attach_cd_cancel">Cancelar</string>
|
||||
<string name="inbound_attach_open_failed">Não foi possível abrir o anexo</string>
|
||||
<string name="inbound_attach_share_failed">Não foi possível compartilhar o anexo</string>
|
||||
<string name="injected_context_media_no_relay">A mídia exige uma conexão ativa com o Relay</string>
|
||||
<string name="injected_context_media_relay_active">Relay ativo para mídia</string>
|
||||
<string name="injected_context_media_no_relay">Nenhuma instrução extra de mídia — a entrega padrão continua sob responsabilidade do servidor</string>
|
||||
<string name="injected_context_media_relay_active">Aprimoramento de mídia do Relay disponível</string>
|
||||
<string name="injected_context_media_title">Compartilhamento de mídia</string>
|
||||
<string name="injected_context_persona_not_set">Nenhuma persona definida</string>
|
||||
<string name="injected_context_persona_server_side">Persona no servidor</string>
|
||||
@@ -3339,7 +3345,7 @@
|
||||
<string name="active_section_dashboard_unreachable">Inacessível</string>
|
||||
<string name="active_section_no_fallback_routes">Ainda não há rotas alternativas</string>
|
||||
<string name="active_section_no_fallback_routes_desc">Adicione uma rota de API opcional para chat direto alternativo e troca de rede.</string>
|
||||
<string name="active_section_add_api_fallback">Adicionar rota alternativa</string>
|
||||
<string name="active_section_add_api_fallback">Adicionar rota de API direta</string>
|
||||
<string name="active_section_security_authentication">Autenticação</string>
|
||||
<string name="active_section_dashboard_session">Sessão do Dashboard</string>
|
||||
<string name="active_section_credential_storage">Armazenamento de credenciais</string>
|
||||
@@ -3364,7 +3370,7 @@
|
||||
<string name="cw_timeline_authenticated">Autenticação verificada</string>
|
||||
<string name="cw_timeline_ready">Conexão pronta</string>
|
||||
<string name="cw_timeline_ready_detail">Chat, Manage e Voice podem usar este Dashboard</string>
|
||||
<string name="active_section_optional_api_fallback">Fallback opcional pela API direta</string>
|
||||
<string name="active_section_optional_api_fallback">API direta opcional</string>
|
||||
<string name="active_section_api_not_required">Não é necessário quando esta conexão usa o Hermes Dashboard.</string>
|
||||
<string name="active_section_where_api_key">Onde obtenho essa chave?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY é criada no seu servidor Hermes; este aplicativo não fornece a chave. Configure-a somente ao ativar o servidor de API opcional, que exige uma chave utilizável, e insira aqui o mesmo valor.</string>
|
||||
@@ -4332,7 +4338,7 @@
|
||||
<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>
|
||||
<string name="settings_git_workspace_desc">Git da sessão atual primeiro, com descoberta opcional do host</string>
|
||||
<string name="current_chat_activity_title">Atividade atual do chat</string>
|
||||
<string name="current_chat_activity_subtitle">Detalhes ao vivo e somente leitura deste chat</string>
|
||||
<string name="current_chat_activity_open">Visualizar atividade atual do chat</string>
|
||||
@@ -4367,7 +4373,7 @@
|
||||
<string name="agent_activity_child_role_task">Tarefa</string>
|
||||
<string name="agent_activity_child_role_agent">Agente</string>
|
||||
<string name="agent_activity_child_role_system">Sistema</string>
|
||||
<string name="settings_git_workspace_off_desc">Desativado · A verificação de repositórios no host é opcional</string>
|
||||
<string name="settings_git_workspace_off_desc">Somente repositório da sessão · A descoberta do host é opcional</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4378,7 +4384,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">API direta</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">Defina o endereço do Dashboard e do Gateway que este telefone deve usar. Rotas privadas de LAN e Tailscale podem usar HTTP ou HTTPS; rotas públicas exigem HTTPS.</string>
|
||||
<string name="dashboard_address_editor_title">Endereço do gateway</string>
|
||||
@@ -4395,7 +4401,7 @@
|
||||
<string name="dashboard_oauth_canonical_origin">Hermes is signing in through %1$s. You’ll review this address before it is saved.</string>
|
||||
<string name="network_routes_empty">No additional network routes</string>
|
||||
<string name="network_routes_empty_desc">Add a LAN, Tailscale, public, API, or Relay address when this phone needs another path to Hermes.</string>
|
||||
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. O fallback da API e as extensões Relay são opcionais.</string>
|
||||
<string name="network_routes_summary">Rotas LAN, Tailscale e públicas são formas de acessar este Gateway. A API direta e as extensões Relay são opcionais.</string>
|
||||
<string name="network_routes_title">Network routes</string>
|
||||
<string name="security_sheet_available_mechanism">Available fallback · %1$s</string>
|
||||
<string name="security_sheet_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
@@ -4415,4 +4421,12 @@
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="voice_overlay_error_title">Erro de voz</string>
|
||||
<string name="chat_correct_now">Corrigir agora</string>
|
||||
<string name="chat_queue_next">Enviar depois</string>
|
||||
<string name="chat_busy_default_title">Durante a resposta</string>
|
||||
<string name="chat_busy_default_description">Escolha o que Enviar faz enquanto o Hermes trabalha. Este padrão do dispositivo também vale no campo de mensagem. Anexos e correções indisponíveis entram na fila.</string>
|
||||
<string name="chat_queue_paused">Fila pausada</string>
|
||||
<string name="chat_queue_resume">Retomar</string>
|
||||
<string name="chat_queue_remove">Remover mensagem da fila</string>
|
||||
</resources>
|
||||
|
||||
@@ -136,12 +136,13 @@
|
||||
<string name="chat_retry">重试</string>
|
||||
<string name="chat_dismiss">关闭</string>
|
||||
<string name="chat_failure_title">Hermes 无法完成此回复</string>
|
||||
<string name="chat_failure_inference_unavailable">推理服务不可用</string>
|
||||
<string name="chat_failure_details">详情</string>
|
||||
<string name="chat_failure_details_title">回复失败</string>
|
||||
<string name="chat_failure_details_guidance">Hermes 报告了此错误。应用不会自动切换路由或模型。</string>
|
||||
<string name="chat_failure_copy_details">复制详情</string>
|
||||
<string name="chat_failure_route_gateway">网关</string>
|
||||
<string name="chat_failure_route_api">API 回退</string>
|
||||
<string name="chat_failure_route_api">Direct API</string>
|
||||
<string name="chat_open_settings">打开设置</string>
|
||||
<string name="chat_connect_hermes">连接 Hermes</string>
|
||||
<string name="chat_try_demo">体验演示</string>
|
||||
@@ -396,7 +397,7 @@
|
||||
<string name="cw_api_url_placeholder">192.168.1.10 或 http://你的服务器:8642</string>
|
||||
<string name="cw_api_url_supporting">聊天和会话使用的 Hermes API——裸主机名默认使用 API 端口 8642 和 http://(仪表盘的 9119 端口单独推导)</string>
|
||||
<string name="cw_scan_message">正在扫描本局域网寻找 Hermes 仪表盘/API…</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于可选的直接 API 回退。</string>
|
||||
<string name="cw_dashboard_signin_hint">通过仪表盘登录以解锁管理和语音——API 密钥仅用于明确配置的 Direct API 连接。</string>
|
||||
<string name="cw_pair_relay_section">配对 Relay(可选)</string>
|
||||
<string name="cw_pair_relay_for">为 %1$s 配对 Relay</string>
|
||||
<string name="cw_pair_relay_scoped_desc">为这个已保存的 Hermes 连接添加可选的 Relay 扩展。这不会添加或替换服务器。</string>
|
||||
@@ -703,12 +704,12 @@
|
||||
<string name="settings_hermes_management">Hermes 管理</string>
|
||||
<string name="settings_hermes_management_desc">仪表盘功能:技能、定时任务、MCP、配置文件、模型</string>
|
||||
<string name="settings_chat">聊天</string>
|
||||
<string name="settings_chat_desc">聊天行为、Gateway、API 回退、工具显示、消息长度</string>
|
||||
<string name="settings_chat_desc">聊天行为、Gateway、Direct API、工具显示、消息长度</string>
|
||||
<string name="settings_voice_mode">语音模式</string>
|
||||
<string name="settings_voice_mode_desc">仪表盘语音、实时 Relay 选项、提供商</string>
|
||||
<string name="settings_threads">话题</string>
|
||||
<string name="settings_threads_desc">允许代理主动与你对话(默认关闭)</string>
|
||||
<string name="settings_power_tools">高级工具</string>
|
||||
<string name="settings_threads_desc">由 Relay 发起的对话和主动推送(默认关闭)</string>
|
||||
<string name="settings_power_tools">Relay 工具</string>
|
||||
<string name="settings_terminal">终端</string>
|
||||
<string name="settings_terminal_desc">通过已配对的 Relay 会话访问服务器 shell</string>
|
||||
<string name="settings_bridge">Bridge</string>
|
||||
@@ -720,7 +721,7 @@
|
||||
<string name="settings_notification_companion">通知助手</string>
|
||||
<string name="settings_notification_companion_desc">为已配对的 Relay 工具共享手机通知</string>
|
||||
<string name="settings_media">媒体</string>
|
||||
<string name="settings_media_desc">Relay 入站附件、自动获取、缓存上限</string>
|
||||
<string name="settings_media_desc">聊天附件、下载行为、隐私和缓存</string>
|
||||
<string name="settings_bridge_safety">Bridge 安全</string>
|
||||
<string name="settings_bridge_safety_desc">黑名单、破坏性动词确认、自动禁用</string>
|
||||
<string name="settings_sideload">Sideload</string>
|
||||
@@ -814,11 +815,11 @@
|
||||
<string name="chat_settings_debug">调试</string>
|
||||
<string name="chat_settings_show_system_messages_desc">显示服务器隐藏的 \"[System: …]\" 标记(模型/人格更改)。关闭则与桌面/TUI 一致。</string>
|
||||
<string name="chat_settings_streaming_endpoint">流式端点</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:根据服务器暴露的内容选择最佳路径。当前使用:</string>
|
||||
<string name="chat_settings_streaming_endpoint_auto_prefix">自动:标准连接使用网关;仅 API 连接使用直接 API。当前使用:</string>
|
||||
<string name="chat_settings_gateway_suffix">(通过仪表盘 WebSocket 实时思考)</string>
|
||||
<string name="chat_settings_chat_completions_suffix">(通过 /v1/chat/completions 聊天)</string>
|
||||
<string name="chat_settings_runs_suffix">(通过显式流式 /v1/runs 聊天)</string>
|
||||
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)实时思考+丰富工具事件——桌面应用使用的方式。需要管理登录;不可用时每轮回退到 SSE。</string>
|
||||
<string name="chat_settings_gateway_desc">网关:通过仪表盘 WebSocket(/api/ws)提供实时思考和丰富工具事件——桌面应用也使用此路径。需要“管理”登录;不可用时,此聊天仍保留在网关,并提示登录或重试。</string>
|
||||
<string name="chat_settings_sessions_desc">会话:Hermes 原生 /api/sessions/{id}/chat/stream。</string>
|
||||
<string name="chat_settings_chat_desc">聊天:通过 /v1/chat/completions 的 OpenAI 兼容 SSE。</string>
|
||||
<string name="chat_settings_runs_desc">Runs:仅在服务器直接流式传输 /v1/runs 时使用。</string>
|
||||
@@ -1212,8 +1213,8 @@
|
||||
<!-- P1: MediaSettingsScreen -->
|
||||
<string name="media_title">媒体</string>
|
||||
<string name="media_back">返回</string>
|
||||
<string name="media_intro_1">控制应用如何处理通过 Relay 传来的工具结果文件(截图、PDF 等)。</string>
|
||||
<string name="media_intro_2">仅限 Relay——这些设置不影响你在聊天中附加的图片或标准(无 Relay)连接上的任何内容。</string>
|
||||
<string name="media_intro_1">控制应用如何下载、保护和缓存 Hermes 在聊天中发送的文件。</string>
|
||||
<string name="media_intro_2">优先使用标准 Dashboard 媒体。配对后,Relay 可补充兼容性传输和敏感度元数据。</string>
|
||||
<string name="media_max_inbound">最大入站附件大小</string>
|
||||
<string name="media_max_inbound_value">%1$d MB</string>
|
||||
<string name="media_max_inbound_desc">超过此大小的文件在下载后被拒绝。</string>
|
||||
@@ -2166,7 +2167,8 @@
|
||||
<string name="session_path_signin_for_gateway">请在管理页面登录以使用实时思考 Gateway。</string>
|
||||
<string name="session_path_gateway_api_server">Gateway 传输可用——此会话通过 API 服务器传输。</string>
|
||||
<string name="session_path_relay_not_connected">Relay 已配对但未连接。</string>
|
||||
<string name="session_path_pair_relay_media">配对 Relay 以发送和接收媒体。</string>
|
||||
<string name="session_path_pair_relay_media">配对 Relay,以兼容较旧 Hermes 主机上的媒体。</string>
|
||||
<string name="session_path_media_not_ready">更新 Hermes 以使用标准媒体传输,或配对 Relay 以获得兼容性。</string>
|
||||
<string name="session_path_pair_relay_terminal">配对 Relay 以使用终端。</string>
|
||||
<string name="session_path_voice_not_ready">此连接的语音未就绪。</string>
|
||||
<string name="session_path_threads_pair_relay">配对 Relay 并开启"让 Hermes 联系我",代理才能打开话题。</string>
|
||||
@@ -2791,6 +2793,8 @@
|
||||
<string name="inbound_attach_downloading">正在下载…%1$s</string>
|
||||
<string name="inbound_attach_failed">附件失败</string>
|
||||
<string name="inbound_attach_tap_retry">点击重试</string>
|
||||
<string name="inbound_attach_host_only">文件位于你的 Hermes 主机上</string>
|
||||
<string name="inbound_attach_host_only_help">更新 Hermes 以使用标准下载,或配对 Relay 以获得兼容性。</string>
|
||||
<string name="inbound_attach_open">外部打开</string>
|
||||
<string name="inbound_attach_share">分享</string>
|
||||
<string name="inbound_attach_save">保存到设备</string>
|
||||
@@ -3250,6 +3254,8 @@
|
||||
<string name="diag_check_ready_with">已就绪(%s)</string>
|
||||
<string name="diag_check_relay_active">Relay 活跃</string>
|
||||
<string name="diag_check_relay_not_configured">Relay 未配置</string>
|
||||
<string name="diag_relay_tools_optional">Relay 工具(可选)</string>
|
||||
<string name="diag_relay_tools_not_paired">未配对</string>
|
||||
<string name="diag_check_relay_server">检查 Relay 服务器</string>
|
||||
<string name="diag_check_relay_plugin">Relay 插件</string>
|
||||
<string name="diag_plugin_not_configured">未配置可选插件</string>
|
||||
@@ -3279,8 +3285,8 @@
|
||||
<string name="inbound_attach_cd_cancel">取消</string>
|
||||
<string name="inbound_attach_open_failed">无法打开附件</string>
|
||||
<string name="inbound_attach_share_failed">无法分享附件</string>
|
||||
<string name="injected_context_media_no_relay">媒体需要活跃的 Relay 连接</string>
|
||||
<string name="injected_context_media_relay_active">Relay 已为媒体激活</string>
|
||||
<string name="injected_context_media_no_relay">没有额外媒体指令——标准传输仍由服务器负责</string>
|
||||
<string name="injected_context_media_relay_active">Relay 媒体增强可用</string>
|
||||
<string name="injected_context_media_title">媒体共享</string>
|
||||
<string name="injected_context_persona_not_set">未设置角色</string>
|
||||
<string name="injected_context_persona_server_side">服务端角色</string>
|
||||
@@ -3450,7 +3456,7 @@
|
||||
<string name="active_section_dashboard_unreachable">无法访问</string>
|
||||
<string name="active_section_no_fallback_routes">尚无备用路由</string>
|
||||
<string name="active_section_no_fallback_routes_desc">可添加 API 路由,用于直接聊天回退和网络切换。</string>
|
||||
<string name="active_section_add_api_fallback">添加备用路由</string>
|
||||
<string name="active_section_add_api_fallback">添加 Direct API 路由</string>
|
||||
<string name="active_section_security_authentication">身份验证</string>
|
||||
<string name="active_section_dashboard_session">Dashboard 会话</string>
|
||||
<string name="active_section_credential_storage">凭据存储</string>
|
||||
@@ -3516,7 +3522,7 @@
|
||||
<string name="cw_timeline_authenticated">身份验证已确认</string>
|
||||
<string name="cw_timeline_ready">连接已就绪</string>
|
||||
<string name="cw_timeline_ready_detail">Chat、Manage 和 Voice 可以使用此 Dashboard</string>
|
||||
<string name="active_section_optional_api_fallback">可选的直接 API 回退</string>
|
||||
<string name="active_section_optional_api_fallback">可选 Direct API</string>
|
||||
<string name="active_section_api_not_required">此连接使用 Hermes Dashboard 时不需要配置。</string>
|
||||
<string name="active_section_where_api_key">从哪里获取此密钥?</string>
|
||||
<string name="active_section_api_key_explainer">API_SERVER_KEY 需要在 Hermes 服务器上创建,并非由此应用提供。仅在启用可选 API 服务器时配置;该服务器需要可用密钥,并在此输入相同的值。</string>
|
||||
@@ -4413,7 +4419,7 @@
|
||||
<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>
|
||||
<string name="settings_git_workspace_desc">优先使用当前会话的 Git,可选择发现主机仓库</string>
|
||||
<string name="current_chat_activity_title">当前聊天活动</string>
|
||||
<string name="current_chat_activity_subtitle">此聊天中的只读实时详情</string>
|
||||
<string name="current_chat_activity_open">预览当前聊天活动</string>
|
||||
@@ -4448,7 +4454,7 @@
|
||||
<string name="agent_activity_child_role_task">任务</string>
|
||||
<string name="agent_activity_child_role_agent">代理</string>
|
||||
<string name="agent_activity_child_role_system">系统</string>
|
||||
<string name="settings_git_workspace_off_desc">关闭 · 主机仓库扫描需手动启用</string>
|
||||
<string name="settings_git_workspace_off_desc">仅会话仓库 · 主机发现需手动启用</string>
|
||||
<string name="active_section_available_fallback">Available fallback</string>
|
||||
<string name="active_section_available_fallback_mechanism">Available fallback · %1$s</string>
|
||||
<string name="active_section_in_use">In use</string>
|
||||
@@ -4459,7 +4465,7 @@
|
||||
<string name="active_section_not_checked_separately">Not checked separately</string>
|
||||
<string name="active_section_protection_unavailable">Protection unavailable</string>
|
||||
<string name="active_section_unavailable_mechanism">Unavailable · %1$s</string>
|
||||
<string name="api_fallback_title">API fallback</string>
|
||||
<string name="api_fallback_title">直接 API</string>
|
||||
<string name="current_surface_paths_title">Current paths</string>
|
||||
<string name="dashboard_address_editor_body">设置此手机使用的 Dashboard 和 Gateway 地址。私有 LAN 与 Tailscale 路由可使用 HTTP 或 HTTPS;公共路由必须使用 HTTPS。</string>
|
||||
<string name="dashboard_address_editor_title">网关地址</string>
|
||||
@@ -4496,4 +4502,12 @@
|
||||
<string name="active_section_unavailable">Unavailable</string>
|
||||
<string name="detail_inactive_badge">Not active</string>
|
||||
<string name="detail_overview_clarity_summary">What works now, the path this phone is using, and what can take over if it becomes unavailable.</string>
|
||||
<string name="voice_overlay_error_title">语音错误</string>
|
||||
<string name="chat_correct_now">立即纠正</string>
|
||||
<string name="chat_queue_next">稍后发送</string>
|
||||
<string name="chat_busy_default_title">回复期间</string>
|
||||
<string name="chat_busy_default_description">选择 Hermes 工作时发送按钮的行为。此设备默认设置与输入框共用。附件及无法立即纠正的消息将进入队列。</string>
|
||||
<string name="chat_queue_paused">队列已暂停</string>
|
||||
<string name="chat_queue_resume">继续</string>
|
||||
<string name="chat_queue_remove">移除队列消息</string>
|
||||
</resources>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user