Compare commits
130
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6395e73927 | ||
|
|
0c337c9384 | ||
|
|
179080d6d9 | ||
|
|
ac1f42b7d5 | ||
|
|
88591fca89 | ||
|
|
00c5f5daa2 | ||
|
|
69b6c005cd | ||
|
|
c902215a15 | ||
|
|
d39368bc51 | ||
|
|
414dc08b9f | ||
|
|
3b78a17bd7 | ||
|
|
a5efb9ec96 | ||
|
|
e5228f2089 | ||
|
|
c738a2c2c0 | ||
|
|
8ed6b35e76 | ||
|
|
c6d4a15226 | ||
|
|
22c8f76c72 | ||
|
|
a0161f51ef | ||
|
|
7aa3b1c697 | ||
|
|
e7112dda9e | ||
|
|
c1413c494f | ||
|
|
bb23e6ab48 | ||
|
|
816638b46a | ||
|
|
df0fe59b0b | ||
|
|
df4d4c8f2a | ||
|
|
398ad253f1 | ||
|
|
ad4bbb2c86 | ||
|
|
7c5894213d | ||
|
|
82c088aa89 | ||
|
|
ed599995d6 | ||
|
|
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 | ||
|
|
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 |
@@ -4,6 +4,7 @@ function classifyCiPaths(paths) {
|
|||||||
const forceAll = paths.some((path) => [
|
const forceAll = paths.some((path) => [
|
||||||
'.github/workflows/ci-required.yml',
|
'.github/workflows/ci-required.yml',
|
||||||
'.github/workflows/release-backmerge.yml',
|
'.github/workflows/release-backmerge.yml',
|
||||||
|
'.github/workflows/approve-release-train.yml',
|
||||||
'.github/scripts/classify-ci-paths.cjs',
|
'.github/scripts/classify-ci-paths.cjs',
|
||||||
'.github/scripts/classify-ci-paths.test.cjs',
|
'.github/scripts/classify-ci-paths.test.cjs',
|
||||||
'scripts/plan_release_backmerge.py',
|
'scripts/plan_release_backmerge.py',
|
||||||
@@ -13,15 +14,17 @@ function classifyCiPaths(paths) {
|
|||||||
const under = (prefixes) => paths.some((path) => prefixes.some((prefix) => path.startsWith(prefix)));
|
const under = (prefixes) => paths.some((path) => prefixes.some((prefix) => path.startsWith(prefix)));
|
||||||
|
|
||||||
return {
|
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',
|
'build.gradle.kts', 'settings.gradle.kts', 'gradle.properties', 'gradlew', 'gradlew.bat',
|
||||||
'scripts/check-android-locales.py', 'scripts/android-locale-harness.py',
|
'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-collection-apis.py', 'scripts/check-android-native-compat.py',
|
||||||
'scripts/check-android-release-notes.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/android-lane.ps1', 'scripts/android-prepush.py', 'scripts/dev.bat', 'scripts/dev.sh',
|
||||||
'scripts/tests/android_prepush_test.py',
|
'scripts/tests/android_prepush_test.py',
|
||||||
'scripts/tests/check_android_native_compat_test.py',
|
'scripts/tests/check_android_native_compat_test.py',
|
||||||
'scripts/tests/check_android_release_notes_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/android-on-demand.yml', '.github/workflows/ci-android.yml',
|
||||||
'.github/workflows/play-preflight-android.yml',
|
'.github/workflows/play-preflight-android.yml',
|
||||||
'.github/workflows/approve-release-android.yml',
|
'.github/workflows/approve-release-android.yml',
|
||||||
@@ -29,12 +32,16 @@ function classifyCiPaths(paths) {
|
|||||||
]),
|
]),
|
||||||
desktop: forceAll || under(['desktop/']) || exact([
|
desktop: forceAll || under(['desktop/']) || exact([
|
||||||
'.github/workflows/ci-desktop.yml',
|
'.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)) ||
|
plugin: forceAll || paths.some((path) => /^plugin\/[^/]+\.py$/.test(path)) ||
|
||||||
under(['plugin/relay/', 'plugin/tools/', 'plugin/tests/', 'relay_server/', 'hermes_relay_bootstrap/']) || exact([
|
under(['plugin/relay/', 'plugin/tools/', 'plugin/tests/', 'relay_server/', 'hermes_relay_bootstrap/']) || exact([
|
||||||
'plugin/plugin.yaml', 'pyproject.toml', 'scripts/check-plugin-version-sync.py',
|
'plugin/plugin.yaml', 'pyproject.toml', 'scripts/check-plugin-version-sync.py',
|
||||||
'scripts/check-server-version-sync.py', 'scripts/bump-plugin-version.sh',
|
'scripts/check-server-version-sync.py', 'scripts/bump-plugin-version.sh',
|
||||||
'scripts/bump-server-version.sh', '.github/workflows/ci-plugin.yml',
|
'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([
|
dashboard: forceAll || under(['plugin/dashboard/']) || exact([
|
||||||
'.github/workflows/ci-dashboard.yml',
|
'.github/workflows/ci-dashboard.yml',
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const assert = require('node:assert/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 { classifyCiPaths } = require('./classify-ci-paths.cjs');
|
||||||
|
|
||||||
const none = {
|
const none = {
|
||||||
@@ -14,9 +16,11 @@ const none = {
|
|||||||
|
|
||||||
assert.deepEqual(classifyCiPaths(['README.md']), none);
|
assert.deepEqual(classifyCiPaths(['README.md']), none);
|
||||||
assert.deepEqual(classifyCiPaths(['desktop/src/cli.ts']), { ...none, desktop: true });
|
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-release-notes.py']), { ...none, android: true });
|
||||||
assert.deepEqual(classifyCiPaths(['scripts/check-android-native-compat.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/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-lane.ps1']), { ...none, android: true });
|
||||||
assert.deepEqual(classifyCiPaths(['scripts/android-prepush.py']), { ...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/dev.sh']), { ...none, android: true });
|
||||||
assert.deepEqual(classifyCiPaths(['scripts/tests/android_prepush_test.py']), { ...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/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/relay/server.py']), { ...none, plugin: true });
|
||||||
assert.deepEqual(classifyCiPaths(['plugin/dashboard/src/App.tsx']), { ...none, dashboard: true });
|
assert.deepEqual(classifyCiPaths(['plugin/dashboard/src/App.tsx']), { ...none, dashboard: true });
|
||||||
assert.deepEqual(classifyCiPaths(['user-docs/index.md']), { ...none, docs: 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,
|
contract: true,
|
||||||
docs: 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@v6/);
|
||||||
|
assert.match(desktopCiWorkflow, /name: Restore exact-source tray build cache[\s\S]*?actions\/cache@v6/);
|
||||||
|
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.');
|
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"
|
echo "::error::Hermes-Relay Android Release Approval must run from main, not $GITHUB_REF"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
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)
|
TOML_VERSION=$(grep -oP 'appVersionName\s*=\s*"\K[^"]+' gradle/libs.versions.toml)
|
||||||
if [ "$REQUESTED_VERSION" != "$TOML_VERSION" ]; then
|
if [ "$REQUESTED_VERSION" != "$TOML_VERSION" ]; then
|
||||||
echo "::error::Requested version $REQUESTED_VERSION does not match appVersionName $TOML_VERSION"
|
echo "::error::Requested version $REQUESTED_VERSION does not match appVersionName $TOML_VERSION"
|
||||||
@@ -56,13 +60,21 @@ jobs:
|
|||||||
RELEASE_TREE: ${{ steps.metadata.outputs.tree }}
|
RELEASE_TREE: ${{ steps.metadata.outputs.tree }}
|
||||||
run: |
|
run: |
|
||||||
ARTIFACT_NAME="play-preflight-${VERSION}-${RELEASE_TREE}"
|
ARTIFACT_NAME="play-preflight-${VERSION}-${RELEASE_TREE}"
|
||||||
COUNT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
ARTIFACT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||||
--jq '[.artifacts[] | select(.expired == false)] | length')
|
--jq '[.artifacts[] | select(.expired == false)] | sort_by(.created_at) | last')
|
||||||
if [ "$COUNT" -lt 1 ]; then
|
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"
|
echo "::error::No successful Play preflight found for version $VERSION with tree $RELEASE_TREE"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
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
|
- name: Ensure release tag does not already exist
|
||||||
env:
|
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]
|
branches: [main, dev]
|
||||||
paths:
|
paths:
|
||||||
- "app/**"
|
- "app/**"
|
||||||
- "relay-core/**"
|
|
||||||
- "relay-ui/**"
|
|
||||||
- "ui-preview/**"
|
|
||||||
- "quest/**"
|
|
||||||
- "gradle/**"
|
- "gradle/**"
|
||||||
- "build.gradle.kts"
|
- "build.gradle.kts"
|
||||||
- "settings.gradle.kts"
|
- "settings.gradle.kts"
|
||||||
|
|||||||
@@ -107,6 +107,18 @@ jobs:
|
|||||||
- name: Setup Rust
|
- name: Setup Rust
|
||||||
uses: dtolnay/rust-toolchain@stable
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
|
||||||
|
- name: Restore exact-source tray build cache
|
||||||
|
uses: actions/cache@v6
|
||||||
|
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
|
- name: Install deps
|
||||||
run: npm ci && npm --prefix tray ci
|
run: npm ci && npm --prefix tray ci
|
||||||
|
|
||||||
|
|||||||
@@ -101,6 +101,7 @@ jobs:
|
|||||||
- name: Run focused Plugin tests
|
- name: Run focused Plugin tests
|
||||||
run: |
|
run: |
|
||||||
python -m pytest \
|
python -m pytest \
|
||||||
|
plugin/tests/test_manifest_compatibility.py \
|
||||||
plugin/tests/test_relay_security.py \
|
plugin/tests/test_relay_security.py \
|
||||||
plugin/tests/test_voice_routes.py \
|
plugin/tests/test_voice_routes.py \
|
||||||
plugin/tests/test_session_grants.py \
|
plugin/tests/test_session_grants.py \
|
||||||
@@ -110,4 +111,8 @@ jobs:
|
|||||||
plugin/tests/test_git_state.py \
|
plugin/tests/test_git_state.py \
|
||||||
plugin/tests/test_git_state_write.py \
|
plugin/tests/test_git_state_write.py \
|
||||||
plugin/tests/test_git_state_extras.py \
|
plugin/tests/test_git_state_extras.py \
|
||||||
plugin/tests/test_mobile_plugin_store.py
|
plugin/tests/test_mobile_plugin_store.py \
|
||||||
|
plugin/tests/test_android_tool.py \
|
||||||
|
plugin/tests/test_android_navigate.py \
|
||||||
|
plugin/tests/test_phone_platform.py \
|
||||||
|
plugin/tests/test_desktop_tool_availability.py
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ on:
|
|||||||
- all-final
|
- all-final
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
|
actions: read
|
||||||
contents: read
|
contents: read
|
||||||
pull-requests: read
|
pull-requests: read
|
||||||
|
|
||||||
@@ -52,6 +53,8 @@ jobs:
|
|||||||
dashboard: ${{ steps.filter.outputs.dashboard }}
|
dashboard: ${{ steps.filter.outputs.dashboard }}
|
||||||
contract: ${{ steps.filter.outputs.contract }}
|
contract: ${{ steps.filter.outputs.contract }}
|
||||||
docs: ${{ steps.filter.outputs.docs }}
|
docs: ${{ steps.filter.outputs.docs }}
|
||||||
|
release_pr: ${{ steps.release.outputs.release_pr }}
|
||||||
|
tree: ${{ steps.tree.outputs.tree }}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout pull request merge
|
- name: Checkout pull request merge
|
||||||
if: github.event_name == 'pull_request'
|
if: github.event_name == 'pull_request'
|
||||||
@@ -69,6 +72,26 @@ jobs:
|
|||||||
- name: Test path classifier
|
- name: Test path classifier
|
||||||
run: node .github/scripts/classify-ci-paths.test.cjs
|
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
|
- name: Classify changed files
|
||||||
id: filter
|
id: filter
|
||||||
uses: actions/github-script@v8
|
uses: actions/github-script@v8
|
||||||
@@ -123,43 +146,117 @@ jobs:
|
|||||||
core.notice(`Changed paths: ${paths.join(', ')}`);
|
core.notice(`Changed paths: ${paths.join(', ')}`);
|
||||||
core.notice(`Selected checks: ${Object.entries(outputs).filter(([, value]) => value).map(([key]) => key).join(', ') || 'none'}`);
|
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
|
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
|
uses: ./.github/workflows/ci-android.yml
|
||||||
|
|
||||||
android_on_demand:
|
android_on_demand:
|
||||||
needs: changes
|
needs: [changes, release-proof]
|
||||||
if: github.event_name == 'workflow_dispatch' && inputs.android_preset != 'auto'
|
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
|
uses: ./.github/workflows/android-on-demand.yml
|
||||||
with:
|
with:
|
||||||
head_sha: ${{ inputs.head_sha }}
|
head_sha: ${{ inputs.head_sha }}
|
||||||
preset: ${{ inputs.android_preset }}
|
preset: ${{ inputs.android_preset }}
|
||||||
|
|
||||||
desktop:
|
desktop:
|
||||||
needs: changes
|
needs: [changes, release-proof]
|
||||||
if: needs.changes.outputs.desktop == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
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
|
uses: ./.github/workflows/ci-desktop.yml
|
||||||
|
|
||||||
plugin:
|
plugin:
|
||||||
needs: changes
|
needs: [changes, release-proof]
|
||||||
if: needs.changes.outputs.plugin == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
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
|
uses: ./.github/workflows/ci-plugin.yml
|
||||||
|
|
||||||
dashboard:
|
dashboard:
|
||||||
needs: changes
|
needs: [changes, release-proof]
|
||||||
if: needs.changes.outputs.dashboard == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
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
|
uses: ./.github/workflows/ci-dashboard.yml
|
||||||
|
|
||||||
contract:
|
contract:
|
||||||
needs: changes
|
needs: [changes, release-proof]
|
||||||
if: needs.changes.outputs.contract == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
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
|
uses: ./.github/workflows/ci-contract.yml
|
||||||
|
|
||||||
docs:
|
docs:
|
||||||
name: Build public docs
|
name: Build public docs
|
||||||
needs: changes
|
needs: [changes, release-proof]
|
||||||
if: needs.changes.outputs.docs == 'true' && (github.event_name != 'workflow_dispatch' || inputs.android_preset == 'auto')
|
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
|
runs-on: ubuntu-latest
|
||||||
defaults:
|
defaults:
|
||||||
run:
|
run:
|
||||||
@@ -181,10 +278,12 @@ jobs:
|
|||||||
guard:
|
guard:
|
||||||
name: Required checks
|
name: Required checks
|
||||||
if: always()
|
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
|
runs-on: ubuntu-latest
|
||||||
env:
|
env:
|
||||||
CHANGES_RESULT: ${{ needs.changes.result }}
|
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_RESULT: ${{ needs.android.result }}
|
||||||
ANDROID_ON_DEMAND_RESULT: ${{ needs.android_on_demand.result }}
|
ANDROID_ON_DEMAND_RESULT: ${{ needs.android_on_demand.result }}
|
||||||
DESKTOP_RESULT: ${{ needs.desktop.result }}
|
DESKTOP_RESULT: ${{ needs.desktop.result }}
|
||||||
@@ -197,7 +296,7 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
failed=0
|
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_var="${check}_RESULT"
|
||||||
result="${!result_var}"
|
result="${!result_var}"
|
||||||
echo "$check: $result"
|
echo "$check: $result"
|
||||||
@@ -207,3 +306,26 @@ jobs:
|
|||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
exit "$failed"
|
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
|
# Run manually from the final dev or untagged main tree before creating
|
||||||
# android-v*. The job
|
# android-v*. The job
|
||||||
# builds the same signed release artifacts, scans final DEX, and uploads the
|
# builds the signed release artifacts once, scans the final packages, and uploads
|
||||||
# Google Play bundle as a production DRAFT. A successful upload is the automated
|
# the Google Play bundle as a production DRAFT. The exact signed APK/AAB,
|
||||||
# Play gate while no public GitHub Release or sideload APK exists. Console-only
|
# mappings, manifest, and checksums remain private Actions artifacts until
|
||||||
# pre-review and pre-launch reports are informational and do not block release.
|
# 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
|
name: Hermes-Relay Android Play Preflight
|
||||||
|
|
||||||
@@ -98,7 +99,12 @@ jobs:
|
|||||||
HERMES_KEYSTORE_PASSWORD: ${{ secrets.HERMES_KEYSTORE_PASSWORD }}
|
HERMES_KEYSTORE_PASSWORD: ${{ secrets.HERMES_KEYSTORE_PASSWORD }}
|
||||||
HERMES_KEY_ALIAS: ${{ secrets.HERMES_KEY_ALIAS }}
|
HERMES_KEY_ALIAS: ${{ secrets.HERMES_KEY_ALIAS }}
|
||||||
HERMES_KEY_PASSWORD: ${{ secrets.HERMES_KEY_PASSWORD }}
|
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
|
- name: Scan final release DEX
|
||||||
run: |
|
run: |
|
||||||
@@ -106,6 +112,12 @@ jobs:
|
|||||||
--apk app/build/outputs/apk/googlePlay/release/*.apk \
|
--apk app/build/outputs/apk/googlePlay/release/*.apk \
|
||||||
--apk app/build/outputs/apk/sideload/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
|
- name: Upload private production draft to Play
|
||||||
env:
|
env:
|
||||||
PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
|
PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}
|
||||||
@@ -121,27 +133,27 @@ jobs:
|
|||||||
--resolution-strategy=ignore \
|
--resolution-strategy=ignore \
|
||||||
--release-name="Hermes-Relay Android v${{ steps.metadata.outputs.version }}"
|
--release-name="Hermes-Relay Android v${{ steps.metadata.outputs.version }}"
|
||||||
|
|
||||||
- name: Record successful preflight for the exact commit
|
- name: Package immutable preflight artifacts
|
||||||
run: |
|
run: |
|
||||||
mkdir -p app/build/reports
|
python3 scripts/android_release_artifacts.py package \
|
||||||
cat > app/build/reports/play-preflight.json <<EOF
|
--version "${{ steps.metadata.outputs.version }}" \
|
||||||
{
|
--version-code "${{ steps.metadata.outputs.version_code }}" \
|
||||||
"version": "${{ steps.metadata.outputs.version }}",
|
--commit "$GITHUB_SHA" \
|
||||||
"versionCode": "${{ steps.metadata.outputs.version_code }}",
|
--tree "${{ steps.metadata.outputs.tree }}" \
|
||||||
"commit": "$GITHUB_SHA",
|
--sideload-apk app/build/outputs/apk/sideload/release/*.apk \
|
||||||
"tree": "${{ steps.metadata.outputs.tree }}",
|
--google-play-aab app/build/outputs/bundle/googlePlayRelease/*.aab \
|
||||||
"track": "production",
|
--sideload-mapping app/build/outputs/mapping/sideloadRelease/mapping.txt \
|
||||||
"status": "draft"
|
--google-play-mapping app/build/outputs/mapping/googlePlayRelease/mapping.txt \
|
||||||
}
|
--output app/build/preflight-artifacts
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Upload preflight proof
|
- name: Upload immutable preflight artifacts
|
||||||
uses: actions/upload-artifact@v7
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
name: play-preflight-${{ steps.metadata.outputs.version }}-${{ steps.metadata.outputs.tree }}
|
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
|
if-no-files-found: error
|
||||||
retention-days: 30
|
retention-days: 30
|
||||||
|
compression-level: 0
|
||||||
|
|
||||||
- name: Preflight summary
|
- name: Preflight summary
|
||||||
run: |
|
run: |
|
||||||
@@ -152,4 +164,4 @@ jobs:
|
|||||||
echo "- Release tree: \`${{ steps.metadata.outputs.tree }}\`" >> "$GITHUB_STEP_SUMMARY"
|
echo "- Release tree: \`${{ steps.metadata.outputs.tree }}\`" >> "$GITHUB_STEP_SUMMARY"
|
||||||
echo "- Play track/status: **Production draft**" >> "$GITHUB_STEP_SUMMARY"
|
echo "- Play track/status: **Production draft**" >> "$GITHUB_STEP_SUMMARY"
|
||||||
echo "" >> "$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: ${{ steps.version.outputs.version }}
|
||||||
version_code: ${{ steps.version.outputs.version_code }}
|
version_code: ${{ steps.version.outputs.version_code }}
|
||||||
prerelease: ${{ steps.version.outputs.prerelease }}
|
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:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
with:
|
with:
|
||||||
@@ -66,6 +69,7 @@ jobs:
|
|||||||
echo "version=$REF_VERSION" >> "$GITHUB_OUTPUT"
|
echo "version=$REF_VERSION" >> "$GITHUB_OUTPUT"
|
||||||
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
|
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
|
||||||
echo "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"
|
echo "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "release_tree=$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Verify version sync
|
- name: Verify version sync
|
||||||
run: |
|
run: |
|
||||||
@@ -110,25 +114,38 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Require successful Play preflight for this exact release tree
|
- name: Require successful Play preflight for this exact release tree
|
||||||
|
id: preflight
|
||||||
if: ${{ !contains(steps.version.outputs.version, '-') }}
|
if: ${{ !contains(steps.version.outputs.version, '-') }}
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
VERSION: ${{ steps.version.outputs.version }}
|
VERSION: ${{ steps.version.outputs.version }}
|
||||||
run: |
|
run: |
|
||||||
RELEASE_TREE=$(git rev-parse 'HEAD^{tree}')
|
RELEASE_TREE="${{ steps.version.outputs.release_tree }}"
|
||||||
ARTIFACT_NAME="play-preflight-${VERSION}-${RELEASE_TREE}"
|
ARTIFACT_NAME="play-preflight-${VERSION}-${RELEASE_TREE}"
|
||||||
COUNT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
ARTIFACT=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${ARTIFACT_NAME}" \
|
||||||
--jq '[.artifacts[] | select(.expired == false)] | length')
|
--jq '[.artifacts[] | select(.expired == false)] | sort_by(.created_at) | last')
|
||||||
if [ "$COUNT" -lt 1 ]; then
|
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 "::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."
|
echo "Run Hermes-Relay Android Play Preflight from the final dev tree, merge that unchanged tree to main, then approve the release."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
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:
|
ci:
|
||||||
name: CI Checks
|
name: CI Checks (prerelease only)
|
||||||
needs: validate
|
needs: validate
|
||||||
|
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
steps:
|
steps:
|
||||||
@@ -168,6 +185,7 @@ jobs:
|
|||||||
release:
|
release:
|
||||||
name: Build & Publish Release
|
name: Build & Publish Release
|
||||||
needs: [validate, ci]
|
needs: [validate, ci]
|
||||||
|
if: ${{ always() && needs.validate.result == 'success' && (needs.ci.result == 'success' || needs.ci.result == 'skipped') }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 30
|
timeout-minutes: 30
|
||||||
steps:
|
steps:
|
||||||
@@ -186,31 +204,33 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
cache-read-only: false
|
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:
|
env:
|
||||||
HERMES_KEYSTORE_BASE64: ${{ secrets.HERMES_KEYSTORE_BASE64 }}
|
HERMES_KEYSTORE_BASE64: ${{ secrets.HERMES_KEYSTORE_BASE64 }}
|
||||||
if: env.HERMES_KEYSTORE_BASE64 != ''
|
if: ${{ needs.validate.outputs.prerelease == 'true' && env.HERMES_KEYSTORE_BASE64 != '' }}
|
||||||
run: |
|
run: |
|
||||||
echo "$HERMES_KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.keystore"
|
echo "$HERMES_KEYSTORE_BASE64" | base64 -d > "$RUNNER_TEMP/release.keystore"
|
||||||
echo "HERMES_KEYSTORE_PATH=$RUNNER_TEMP/release.keystore" >> "$GITHUB_ENV"
|
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
|
- name: Build side-by-side release candidate APK
|
||||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||||
env:
|
env:
|
||||||
@@ -234,10 +254,10 @@ jobs:
|
|||||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||||
uses: actions/upload-artifact@v7
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
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: |
|
path: |
|
||||||
app/build/outputs/mapping/googlePlayRelease/mapping.txt
|
app/build/preflight-artifacts/mapping-googlePlayRelease.txt
|
||||||
app/build/outputs/mapping/sideloadRelease/mapping.txt
|
app/build/preflight-artifacts/mapping-sideloadRelease.txt
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
retention-days: 90
|
retention-days: 90
|
||||||
|
|
||||||
@@ -254,8 +274,7 @@ jobs:
|
|||||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||||
run: |
|
run: |
|
||||||
python3 scripts/check-android-collection-apis.py \
|
python3 scripts/check-android-collection-apis.py \
|
||||||
--apk app/build/outputs/apk/googlePlay/release/*.apk \
|
--apk app/build/preflight-artifacts/*-sideload-release.apk
|
||||||
--apk app/build/outputs/apk/sideload/release/*.apk
|
|
||||||
|
|
||||||
- name: Scan candidate DEX for unsupported collection APIs
|
- name: Scan candidate DEX for unsupported collection APIs
|
||||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||||
@@ -267,8 +286,7 @@ jobs:
|
|||||||
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
if: ${{ needs.validate.outputs.prerelease != 'true' }}
|
||||||
run: |
|
run: |
|
||||||
python3 scripts/check-android-native-compat.py \
|
python3 scripts/check-android-native-compat.py \
|
||||||
app/build/outputs/apk/googlePlay/release/*.apk \
|
app/build/preflight-artifacts/*-sideload-release.apk
|
||||||
app/build/outputs/apk/sideload/release/*.apk
|
|
||||||
|
|
||||||
- name: Verify candidate packaged ONNX Runtime compatibility
|
- name: Verify candidate packaged ONNX Runtime compatibility
|
||||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||||
@@ -278,23 +296,10 @@ jobs:
|
|||||||
|
|
||||||
- name: List produced artifacts (debug aid)
|
- name: List produced artifacts (debug aid)
|
||||||
run: |
|
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
|
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
|
- name: Generate candidate checksums
|
||||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||||
@@ -340,9 +345,9 @@ jobs:
|
|||||||
# Deliberate 2-asset policy (#144): attach ONLY the installable
|
# Deliberate 2-asset policy (#144): attach ONLY the installable
|
||||||
# sideload APK and Play AAB, plus checksums covering those files.
|
# sideload APK and Play AAB, plus checksums covering those files.
|
||||||
files: |
|
files: |
|
||||||
app/build/outputs/apk/sideload/release/*.apk
|
app/build/preflight-artifacts/*-sideload-release.apk
|
||||||
app/build/outputs/bundle/googlePlayRelease/*.aab
|
app/build/preflight-artifacts/*-googlePlay-release.aab
|
||||||
app/build/outputs/SHA256SUMS.txt
|
app/build/preflight-artifacts/SHA256SUMS.txt
|
||||||
|
|
||||||
- name: Create candidate GitHub prerelease
|
- name: Create candidate GitHub prerelease
|
||||||
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
if: ${{ needs.validate.outputs.prerelease == 'true' }}
|
||||||
@@ -364,18 +369,17 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
echo "## Hermes-Relay Android v${{ needs.validate.outputs.version }}" >> "$GITHUB_STEP_SUMMARY"
|
echo "## Hermes-Relay Android v${{ needs.validate.outputs.version }}" >> "$GITHUB_STEP_SUMMARY"
|
||||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||||
if [ "$PRERELEASE" = "true" ] && [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
if [ "$PRERELEASE" != "true" ]; then
|
||||||
echo "✅ **Release-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
echo "✅ **Published the exact signed Play-preflight artifacts**" >> "$GITHUB_STEP_SUMMARY"
|
||||||
elif [ "$PRERELEASE" = "true" ]; then
|
|
||||||
echo "⚠️ **Debug-signed HR Candidate app** — separate package ID; never uploaded to Play" >> "$GITHUB_STEP_SUMMARY"
|
|
||||||
elif [ -n "$HERMES_KEYSTORE_BASE64" ]; then
|
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
|
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
|
fi
|
||||||
echo "" >> "$GITHUB_STEP_SUMMARY"
|
echo "" >> "$GITHUB_STEP_SUMMARY"
|
||||||
echo "### Artifacts" >> "$GITHUB_STEP_SUMMARY"
|
echo "### Artifacts" >> "$GITHUB_STEP_SUMMARY"
|
||||||
echo '```' >> "$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/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
|
find app/build/outputs/bundle -name '*.aab' -exec ls -la {} + >> "$GITHUB_STEP_SUMMARY" 2>/dev/null || true
|
||||||
echo '```' >> "$GITHUB_STEP_SUMMARY"
|
echo '```' >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|||||||
@@ -3,6 +3,12 @@ name: Hermes-Relay CLI+UI Release
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
tags: ['desktop-v*']
|
tags: ['desktop-v*']
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
description: "Approved CLI+UI version"
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -20,6 +26,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
@@ -34,10 +41,16 @@ jobs:
|
|||||||
- name: Extract and validate tag version
|
- name: Extract and validate tag version
|
||||||
id: version
|
id: version
|
||||||
shell: bash
|
shell: bash
|
||||||
|
env:
|
||||||
|
DISPATCHED_VERSION: ${{ inputs.version }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
version="${GITHUB_REF_NAME#desktop-v}"
|
if [ -n "$DISPATCHED_VERSION" ]; then
|
||||||
if [[ -z "$version" || "$version" == "$GITHUB_REF_NAME" ]]; 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
|
echo "Expected a desktop-v* tag, got $GITHUB_REF_NAME" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
@@ -51,11 +64,12 @@ jobs:
|
|||||||
- name: Verify tag belongs to the correct integration branch
|
- name: Verify tag belongs to the correct integration branch
|
||||||
shell: bash
|
shell: bash
|
||||||
working-directory: .
|
working-directory: .
|
||||||
|
env:
|
||||||
|
TAG_VERSION: ${{ steps.version.outputs.version }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
version="${GITHUB_REF_NAME#desktop-v}"
|
tag_commit="$(git rev-parse HEAD)"
|
||||||
tag_commit="$(git rev-parse "${GITHUB_REF_NAME}^{commit}")"
|
if [[ "$TAG_VERSION" == *-* ]]; then
|
||||||
if [[ "$version" == *-* ]]; then
|
|
||||||
git fetch origin dev --no-tags
|
git fetch origin dev --no-tags
|
||||||
if ! git merge-base --is-ancestor "$tag_commit" origin/dev; then
|
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
|
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
|
working-directory: desktop
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- 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)
|
- name: Setup Node.js (for npm ci + tsc)
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
@@ -271,6 +287,8 @@ jobs:
|
|||||||
working-directory: desktop
|
working-directory: desktop
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
@@ -289,6 +307,18 @@ jobs:
|
|||||||
- name: Setup Rust
|
- name: Setup Rust
|
||||||
uses: dtolnay/rust-toolchain@stable
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
|
||||||
|
- name: Restore exact-source tray build cache
|
||||||
|
uses: actions/cache@v6
|
||||||
|
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
|
- name: Install deps
|
||||||
run: npm ci && npm --prefix tray ci
|
run: npm ci && npm --prefix tray ci
|
||||||
|
|
||||||
@@ -411,6 +441,11 @@ jobs:
|
|||||||
if ($versionOutput -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
|
if ($versionOutput -ne "hermes-relay $env:EXPECTED_DESKTOP_VERSION") {
|
||||||
throw "installed CLI version mismatch: expected $env:EXPECTED_DESKTOP_VERSION, got '$versionOutput'"
|
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)
|
$helpOutput = (& $cli --help | Out-String)
|
||||||
if ($LASTEXITCODE -ne 0 -or $helpOutput -notmatch 'Usage:') {
|
if ($LASTEXITCODE -ne 0 -or $helpOutput -notmatch 'Usage:') {
|
||||||
throw 'installed CLI --help smoke failed'
|
throw 'installed CLI --help smoke failed'
|
||||||
@@ -451,7 +486,7 @@ jobs:
|
|||||||
throw "installer lifecycle changed the pre-existing tray startup preference"
|
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 {
|
} finally {
|
||||||
Get-Process -Name 'hermes-relay-tray' -ErrorAction SilentlyContinue |
|
Get-Process -Name 'hermes-relay-tray' -ErrorAction SilentlyContinue |
|
||||||
Stop-Process -Force -ErrorAction SilentlyContinue
|
Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
@@ -483,6 +518,7 @@ jobs:
|
|||||||
name: Publish GitHub Release
|
name: Publish GitHub Release
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs:
|
needs:
|
||||||
|
- validate-release
|
||||||
- build-cli-binaries
|
- build-cli-binaries
|
||||||
- smoke-windows-cli-release-asset
|
- smoke-windows-cli-release-asset
|
||||||
- smoke-macos-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
|
# Needed so CLI_RELEASE_NOTES.md is available to render into the release body
|
||||||
# (the other publish-release steps only consume downloaded build artifacts).
|
# (the other publish-release steps only consume downloaded build artifacts).
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
- name: Extract CLI+UI version
|
ref: ${{ github.event_name == 'workflow_dispatch' && format('desktop-v{0}', inputs.version) || github.ref }}
|
||||||
id: version
|
|
||||||
run: echo "version=${GITHUB_REF_NAME#desktop-v}" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- uses: actions/download-artifact@v8
|
- uses: actions/download-artifact@v8
|
||||||
with:
|
with:
|
||||||
@@ -515,8 +549,8 @@ jobs:
|
|||||||
# (desktop-v0.3.0) so install/pin commands stay accurate without manual edits.
|
# (desktop-v0.3.0) so install/pin commands stay accurate without manual edits.
|
||||||
- name: Render release notes
|
- name: Render release notes
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ steps.version.outputs.version }}
|
VERSION: ${{ needs.validate-release.outputs.version }}
|
||||||
TAG: ${{ github.ref_name }}
|
TAG: desktop-v${{ needs.validate-release.outputs.version }}
|
||||||
run: |
|
run: |
|
||||||
sed -e "s/__VERSION__/${VERSION}/g" -e "s/__TAG__/${TAG}/g" \
|
sed -e "s/__VERSION__/${VERSION}/g" -e "s/__TAG__/${TAG}/g" \
|
||||||
CLI_RELEASE_NOTES.md > cli_release_notes_rendered.md
|
CLI_RELEASE_NOTES.md > cli_release_notes_rendered.md
|
||||||
@@ -525,10 +559,10 @@ jobs:
|
|||||||
- name: Publish GitHub Release
|
- name: Publish GitHub Release
|
||||||
uses: softprops/action-gh-release@v3
|
uses: softprops/action-gh-release@v3
|
||||||
with:
|
with:
|
||||||
name: Hermes-Relay CLI+UI v${{ steps.version.outputs.version }}
|
name: Hermes-Relay CLI+UI v${{ needs.validate-release.outputs.version }}
|
||||||
tag_name: ${{ github.ref_name }}
|
tag_name: desktop-v${{ needs.validate-release.outputs.version }}
|
||||||
draft: false
|
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
|
fail_on_unmatched_files: true
|
||||||
body_path: cli_release_notes_rendered.md
|
body_path: cli_release_notes_rendered.md
|
||||||
files: |
|
files: |
|
||||||
|
|||||||
@@ -4,6 +4,12 @@ on:
|
|||||||
push:
|
push:
|
||||||
tags:
|
tags:
|
||||||
- "server-v*"
|
- "server-v*"
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
description: "Approved Plugin version"
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -19,10 +25,19 @@ jobs:
|
|||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
ref: ${{ github.event_name == 'workflow_dispatch' && format('server-v{0}', inputs.version) || github.ref }}
|
||||||
|
|
||||||
- name: Extract version from tag
|
- name: Extract version from tag
|
||||||
id: version
|
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
|
- name: Verify Plugin version sync and changelog
|
||||||
run: |
|
run: |
|
||||||
@@ -61,6 +76,8 @@ jobs:
|
|||||||
timeout-minutes: 15
|
timeout-minutes: 15
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- 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
|
- name: Set up Python 3.11
|
||||||
uses: actions/setup-python@v7
|
uses: actions/setup-python@v7
|
||||||
@@ -85,11 +102,16 @@ jobs:
|
|||||||
- name: Run focused Plugin tests
|
- name: Run focused Plugin tests
|
||||||
run: |
|
run: |
|
||||||
python -m pytest \
|
python -m pytest \
|
||||||
|
plugin/tests/test_manifest_compatibility.py \
|
||||||
plugin/tests/test_relay_security.py \
|
plugin/tests/test_relay_security.py \
|
||||||
plugin/tests/test_voice_routes.py \
|
plugin/tests/test_voice_routes.py \
|
||||||
plugin/tests/test_session_grants.py \
|
plugin/tests/test_session_grants.py \
|
||||||
plugin/tests/test_proactive_channel.py \
|
plugin/tests/test_proactive_channel.py \
|
||||||
plugin/tests/test_android_phone_status.py
|
plugin/tests/test_android_phone_status.py \
|
||||||
|
plugin/tests/test_android_tool.py \
|
||||||
|
plugin/tests/test_android_navigate.py \
|
||||||
|
plugin/tests/test_phone_platform.py \
|
||||||
|
plugin/tests/test_desktop_tool_availability.py
|
||||||
|
|
||||||
package:
|
package:
|
||||||
name: Build and publish Plugin package
|
name: Build and publish Plugin package
|
||||||
@@ -98,6 +120,8 @@ jobs:
|
|||||||
timeout-minutes: 15
|
timeout-minutes: 15
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- 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
|
- name: Set up Python 3.11
|
||||||
uses: actions/setup-python@v7
|
uses: actions/setup-python@v7
|
||||||
|
|||||||
+1
-4
@@ -24,10 +24,7 @@ Thumbs.db
|
|||||||
local.properties
|
local.properties
|
||||||
/build/
|
/build/
|
||||||
/app/build/
|
/app/build/
|
||||||
/relay-core/build/
|
/experiments/quest/**/build/
|
||||||
/relay-ui/build/
|
|
||||||
/ui-preview/build/
|
|
||||||
/quest/build/
|
|
||||||
/app/release/
|
/app/release/
|
||||||
*.apk
|
*.apk
|
||||||
*.aab
|
*.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 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 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)**
|
- `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
|
## 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
|
- **Vanilla Hermes path = upstream-only.** The standard (no-plugin) connection
|
||||||
uses the upstream Dashboard/Gateway for chat, authentication, Manage, sessions,
|
uses the upstream Dashboard/Gateway for chat, authentication, Manage, sessions,
|
||||||
and Vanilla Hermes voice. The API server is an optional automatic fallback and
|
and Vanilla Hermes voice. The API server is an explicit API-only/headless
|
||||||
advanced headless-compatibility surface; Relay adds optional extensions. This
|
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
|
path must work against unmodified upstream hermes-agent. Server-side needs go
|
||||||
through upstream PRs or the optional relay plugin, never fork patches.
|
through upstream PRs or the optional relay plugin, never fork patches.
|
||||||
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
|
- **Verify endpoints against upstream** (`gateway/platforms/api_server.py` /
|
||||||
|
|||||||
+58
-3
@@ -6,18 +6,73 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Android Dashboard sign-in removes pasted line breaks from username and password fields, matching the browser login while preserving every other credential character. (#541)
|
||||||
|
- **Relay tool availability avoids repeated Windows loopback delays and preserves multi-PC capabilities.** Host-local Android, Desktop, and Phone paths use explicit IPv4 loopback, while Desktop checks share a bounded health snapshot that preserves per-client advertisements and fails closed when Hermes-Relay is unavailable. (#562, #563)
|
||||||
|
- Android keeps saved Dashboard sign-ins bound to their connection when switching gateways, rather than letting a stale resolver route invalidate another connection's session.
|
||||||
|
- Bot Mode no longer crashes when different connections have bots with the same profile name. Both the conversation list and Active Now strip preserve each bot's connection, and opening progress appears only on the selected bot.
|
||||||
|
- Android feedback uses themed banners and action cards instead of platform toasts and default snackbars. Dashboard errors no longer misidentify missing resources as an outdated Relay. Developer settings includes local-only message previews.
|
||||||
|
- Missing chat attachments show their error and retry in the attachment card without repeated global popups. Global action messages occupy the top message area instead of covering the composer.
|
||||||
|
- Chat distinguishes session preparation from response streaming and retains initialization errors that arrive before the session acknowledgement. Long-press the agent header to open a live session-diagnostics drawer.
|
||||||
|
- Delegated-agent activity survives parent replies and leaves compact history entries for later read-only review. The activity strip appears only while work runs; historical process views cannot stop or dismiss live work. (#447)
|
||||||
|
- **`android_*` tools resolve bridge credentials written after host startup.** Requests retry profile-scoped env and active bridge-session credentials after a stale token is rejected, and vision navigation now shares the same current Relay transport instead of the retired standalone default.
|
||||||
|
- **`android_setup` accepts both its canonical and legacy schema keys.** `bridge_session_token` and `pairing_code` are accepted, while a missing token returns a structured error.
|
||||||
|
- **Android tool setup tests use a temporary Hermes home.** Test runs no longer write bridge settings into a developer environment.
|
||||||
|
|
||||||
|
## [Android 1.15.1] - 2026-09-02
|
||||||
|
|
||||||
### Changed
|
### 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 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.
|
- **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
|
### 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 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 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.
|
- **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.
|
- **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
|
## [Android 1.14.0] - 2026-08-30
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
@@ -66,7 +121,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.
|
- **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.
|
- **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
|
### Changed
|
||||||
|
|
||||||
@@ -1254,7 +1309,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.
|
- **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`.
|
- **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.
|
- **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.
|
- **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 +2126,7 @@ picker.
|
|||||||
- **`CLAUDE.md`** — updated Git section with the new branching policy,
|
- **`CLAUDE.md`** — updated Git section with the new branching policy,
|
||||||
added file-table entries for `hermes-relay-update`,
|
added file-table entries for `hermes-relay-update`,
|
||||||
`register_code_command`, and the expanded `install.sh`
|
`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
|
Hermes plugin/skill/tool distribution
|
||||||
- **`user-docs` vitepress site** — new "For AI Agents" copy-paste
|
- **`user-docs` vitepress site** — new "For AI Agents" copy-paste
|
||||||
block on the home view, Feature Matrix component, two-track explainer,
|
block on the home view, Feature Matrix component, two-track explainer,
|
||||||
|
|||||||
@@ -1,22 +1,18 @@
|
|||||||
# Hermes-Relay CLI+UI v__VERSION__
|
# 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.
|
**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
|
## 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
|
### 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.
|
- `hermes-relay update` detects an installed management UI beside the CLI and reports both installed versions.
|
||||||
- **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.
|
- 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
|
## 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
|
5. `scripts/dev.bat prepush` only when full local verification is explicitly
|
||||||
wanted or cloud execution is unavailable.
|
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
|
`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
|
sideload debug APK or when the target ABI is not arm64. Release builds remain
|
||||||
universal and are unaffected unless `-Phermes.devAbi` is explicitly supplied.
|
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
|
review reference is recorded. Focused correction PRs from fluent contributors
|
||||||
are the canonical way to improve wording and can advance a locale to
|
are the canonical way to improve wording and can advance a locale to
|
||||||
`community-reviewed` or `verified` under `docs/translation-playbook.md`.
|
`community-reviewed` or `verified` under `docs/translation-playbook.md`.
|
||||||
Translated READMEs use separate `README.<locale>.md` files; `README.md` remains
|
Translated README entrypoints live under `docs/readme/` as
|
||||||
the canonical project description. User docs may be added incrementally under
|
`README.<locale>.md`; root `README.md` remains the canonical project
|
||||||
`user-docs/<locale>/`, with links back to canonical English reference material.
|
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
|
## 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.
|
- **`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.
|
||||||
- **`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.
|
- **`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.
|
- **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.
|
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__
|
# Hermes-Relay Plugin v__VERSION__
|
||||||
|
|
||||||
**Release Date:** August 30, 2026
|
**Release Date:** August 31, 2026
|
||||||
|
|
||||||
## Summary
|
## 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.
|
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.
|
||||||
|
|
||||||
## 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.
|
|
||||||
|
|
||||||
## Fixed
|
## Fixed
|
||||||
|
|
||||||
- Public and roaming invites no longer synthesize closed direct Relay `:8767` or wrong Dashboard `:9119` routes.
|
- **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.
|
||||||
- Ambiguous, credential-bearing, or plaintext public candidates fail closed before an invite is exposed.
|
- **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.
|
||||||
- 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.
|
|
||||||
|
|
||||||
## Install / update
|
## Install / update
|
||||||
|
|
||||||
@@ -35,7 +21,7 @@ This release lets one authenticated Hermes Dashboard origin carry Gateway plus o
|
|||||||
# or, if already installed:
|
# or, if already installed:
|
||||||
hermes-relay-update
|
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
|
## Verify
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<p align="center">
|
<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>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
@@ -21,7 +21,13 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<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://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/releases">Releases</a> ·
|
||||||
<a href="https://github.com/Codename-11/hermes-relay/discussions">Discussions</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.
|
- **📱 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.
|
- **⌨️ 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">
|
<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>
|
</p>
|
||||||
|
|
||||||
## Quick Start (Android)
|
## Quick Start (Android)
|
||||||
@@ -50,7 +56,7 @@ Install → connect → talk, in about two minutes.
|
|||||||
|
|
||||||
### 1 · Install the app
|
### 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).
|
- **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.
|
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
|
### 2 · Have the Hermes Dashboard running
|
||||||
|
|
||||||
The normal Android connection uses the upstream Hermes Dashboard/Gateway for
|
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:
|
provider is vanilla Hermes setup:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -77,16 +83,15 @@ the [remote-access guide](https://hermes-relay.dev/docs/guide/remote-access/).
|
|||||||
|
|
||||||
### 3 · Connect and talk
|
### 3 · Connect and talk
|
||||||
|
|
||||||
For a plugin-enabled host, open the Web Dashboard's **Relay** page, click
|
Use **Find Hermes on LAN** or enter the Dashboard address manually
|
||||||
**Connect mobile app**, and scan that tokenless QR from Android **Connect → Scan
|
(conventionally `http://<host>:9119`). Sign in through the
|
||||||
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
|
|
||||||
Dashboard's configured provider when prompted. The app probes the available
|
Dashboard's configured provider when prompted. The app probes the available
|
||||||
upstream capabilities and finishes with a connection summary.
|
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
|
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
|
**Advanced** as a chat fallback or for a headless compatibility setup. Its API
|
||||||
key is requested only when that optional endpoint is configured. Existing
|
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 |
|
| **Chat** | Dashboard/Gateway ready — you can talk |
|
||||||
| **Manage** | Models, keys, skills, and profiles are available from the phone |
|
| **Manage** | Models, keys, skills, and profiles are available from the phone |
|
||||||
| **Voice** | Speech ready via your server (or one Manage sign-in away) |
|
| **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 |
|
| **Relay** | Recommended extensions paired/unpaired; never blocks the upstream path |
|
||||||
|
|
||||||
One dashboard sign-in unlocks Chat, Manage, sessions, and standard voice. That's
|
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
|
### 4 · Recommended: pair Relay for the complete experience
|
||||||
|
|
||||||
Install Relay for Terminal/TUI, notifications, media handoff, desktop tools,
|
Install Relay for Terminal/TUI, notifications, desktop tools, enhanced voice,
|
||||||
enhanced voice, Relay sessions, approval-gated page drafts, and optional Device
|
Relay sessions, approval-gated page drafts, optional Device Control, and media
|
||||||
Control:
|
compatibility or sensitivity metadata:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
hermes plugins install Codename-11/hermes-relay/plugin --enable
|
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) ·
|
[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)
|
[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
|
## Screenshots
|
||||||
|
|
||||||
@@ -161,7 +166,7 @@ manual fallbacks when QR or clipboard transfer is unavailable.
|
|||||||
|
|
||||||
<p align="center">
|
<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>
|
<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>
|
</p>
|
||||||
|
|
||||||
### Simplified Chinese
|
### 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*`.
|
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>
|
<table>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -239,17 +244,17 @@ remote tool surface. See the [desktop tools guide](https://hermes-relay.dev/docs
|
|||||||
## How It Works
|
## How It Works
|
||||||
|
|
||||||
```
|
```
|
||||||
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice]
|
Phone (HTTP/WSS) --> Hermes Dashboard (:9119) [chat gateway, manage, vanilla voice, inbound files]
|
||||||
Phone (HTTP/SSE) --> Hermes API Server (:8642) [chat fallback, sessions, runs]
|
Phone (HTTP/SSE) --> Hermes API Server (:8642) [Direct API chat, sessions, runs]
|
||||||
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media, relay voice, sessions]
|
Phone (WSS/HTTP) --> Relay (:8767) [terminal, bridge, media enhancements, relay voice, sessions]
|
||||||
CLI (WSS) --> Relay (:8767) [machine tools, tui, terminal]
|
CLI (WSS) --> Relay (:8767) [machine tools, tui, terminal]
|
||||||
```
|
```
|
||||||
|
|
||||||
Chat prefers the Hermes dashboard gateway when Manage auth is ready, then falls
|
Standard connections keep Chat on the Hermes Dashboard/Gateway. Explicit API-only
|
||||||
back to the upstream API server SSE path with the API key. Manage and Vanilla Hermes
|
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
|
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
|
install needs no plugin for those surfaces or ordinary inbound files. The optional relay on `:8767` adds
|
||||||
surfaces: terminal, bridge phone control, media handoff, machine tools, and
|
terminal, bridge phone control, media compatibility/metadata, machine tools, and
|
||||||
relay-side voice, which is preferred automatically when paired. One QR can
|
relay-side voice, which is preferred automatically when paired. One QR can
|
||||||
configure API, dashboard, and relay routes without merging their auth models.
|
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
|
### 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
|
```bat
|
||||||
scripts\dev.bat bundle
|
scripts\dev.bat bundle
|
||||||
keytool -printcert -jarfile app\build\outputs\bundle\googlePlayRelease\hermes-relay-*-googlePlay-release.aab
|
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;
|
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;
|
4. scans the final minified APK DEX for unsupported collection calls;
|
||||||
5. uploads the Google Play AAB as a private **Production draft**; and
|
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
|
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
|
build, final package scans, and Production-draft upload is the automated Play
|
||||||
gate. Play Console pre-review and pre-launch reports are informational and
|
release gate. The private artifact is immutable and hash-verified again before
|
||||||
non-blocking because their detailed results are not exposed through the release
|
publication; the stable release workflow does not rebuild those bytes. Play
|
||||||
automation API. If the release source changes after preflight, rerun it—the
|
Console pre-review and pre-launch reports are informational and non-blocking
|
||||||
approval workflow matches the complete Git tree, not just the version number.
|
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
|
GitHub exposes manual workflows only after their workflow file exists on the
|
||||||
default branch. For the first release that introduces this process, merge 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
|
an existing tag or changing its artifact tree. Manual stable tags are still
|
||||||
guarded by the same preflight proof in the tag workflow.
|
guarded by the same preflight proof in the tag workflow.
|
||||||
|
|
||||||
The tag-triggered `.github/workflows/release-android.yml` rebuilds and scans the
|
The tag-triggered `.github/workflows/release-android.yml` downloads the exact
|
||||||
artifacts, changes the existing Play Production draft to `completed` (submitting
|
private preflight artifact by ID, verifies its source workflow, manifest, tree,
|
||||||
it for review), and only after Play accepts that operation creates the public
|
version, sizes, and hashes, reruns the package scanners, then changes the
|
||||||
GitHub Release with the sideload APK. A missing preflight, changed release tree,
|
existing Play Production draft to `completed` (submitting it for review). Only
|
||||||
missing Play credential, or Play submission failure prevents public GitHub
|
after Play accepts that operation does it publish those same APK/AAB bytes on
|
||||||
publication.
|
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
|
Plugin/Python version files are intentionally not part of an Android app
|
||||||
release unless the plugin package itself is also being released.
|
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
|
git push origin dev
|
||||||
|
|
||||||
# Open the release PR (dev -> main) and merge with --no-ff.
|
# Open the release PR (dev -> main) and merge with --no-ff.
|
||||||
# After merge, tag from the new main tip:
|
# Then run "Hermes-Relay Plugin and CLI+UI Release Approval" from main,
|
||||||
git checkout main
|
# select plugin, and enter 0.6.2. The workflow selects and validates main
|
||||||
git pull --ff-only origin main
|
# before it creates server-v0.6.2 and starts the immutable-tag release workflow.
|
||||||
git tag server-v0.6.2
|
|
||||||
git push origin server-v0.6.2
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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
|
validates all plugin-owned version metadata with
|
||||||
`scripts/check-plugin-version-sync.py`. Run
|
`scripts/check-plugin-version-sync.py`. Run
|
||||||
`python scripts/check-version-tracks.py` locally before tagging when a change
|
`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 commit -m "release(desktop): desktop-v0.4.0-alpha.2"
|
||||||
git push origin dev
|
git push origin dev
|
||||||
|
|
||||||
# Open the release PR (dev -> main) and merge with --no-ff.
|
# This is a prerelease: run "Hermes-Relay Plugin and CLI+UI Release Approval"
|
||||||
# After merge, tag from main:
|
# from main, select desktop, and enter 0.4.0-alpha.2. The workflow validates dev
|
||||||
git switch main
|
# before it creates the tag and starts the immutable-tag release workflow.
|
||||||
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
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The tag workflow rejects version drift and tags whose commit is not in
|
For a stable CLI+UI version, first merge the release PR from `dev` to `main`,
|
||||||
`origin/main`, reruns CLI tests, builds all four standalone binaries, tests and
|
then run the approval workflow from `main`. The version determines the source:
|
||||||
packages the Windows tray, generates checksums, and publishes the GitHub Release.
|
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
|
### 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
|
(This step was only needed as a retrofit for v0.1.0 — v0.1.1+ inherit
|
||||||
the Download section automatically from `RELEASE_NOTES.md`.)
|
the Download section automatically from `RELEASE_NOTES.md`.)
|
||||||
- Confirm Play Console shows the new versionCode on the target track.
|
- 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
|
## 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
|
This keeps a dashboard CSS fix from running the full server suite, and keeps
|
||||||
plugin changes from forcing an Android app `versionCode` bump.
|
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`:
|
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
|
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
|
prerelease tag resolves to a commit contained in `dev`, and that the tag matches `appVersionName` in
|
||||||
`gradle/libs.versions.toml` (mismatches fail the workflow).
|
`gradle/libs.versions.toml` (mismatches fail the workflow).
|
||||||
2. Runs the Android debug build and the stable sideload pairing/connection
|
2. For stable releases, verifies and downloads the exact immutable Play
|
||||||
regression slice with explicit timeouts.
|
preflight artifact; prereleases run the focused CI slice and build the
|
||||||
3. Decodes `HERMES_KEYSTORE_BASE64` into `$RUNNER_TEMP/release.keystore`
|
side-by-side `sideloadCandidate` APK.
|
||||||
and exports `HERMES_KEYSTORE_PATH` (skipped if the secret is unset).
|
3. Revalidates stable artifact hashes, DEX collection compatibility, packaged
|
||||||
4. For stable releases, builds all four flavored release artifacts
|
native compatibility, and retained R8 mappings without recompiling.
|
||||||
(`./gradlew bundleRelease assembleRelease`); only the sideload APK and
|
4. Generates candidate checksums when applicable; stable checksums come from
|
||||||
googlePlay AAB are attached. For prereleases, builds only the side-by-side
|
the verified preflight artifact and cover the two public files.
|
||||||
`sideloadCandidate` APK.
|
5. For stable releases only, promotes the exact preflighted Production draft to
|
||||||
5. Generates `SHA256SUMS.txt` covering the two attached files.
|
|
||||||
6. For stable releases only, promotes the exact preflighted Production draft to
|
|
||||||
`completed`; prereleases never upload to Play.
|
`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
|
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.
|
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`:
|
`.github/workflows/release-plugin.yml`:
|
||||||
|
|
||||||
1. Verifies a stable tag commit is contained in `main`, or a prerelease tag is
|
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,
|
5. Creates a GitHub Release named `Hermes-Relay Plugin v<version>` with the wheel,
|
||||||
sdist, and checksum file attached.
|
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
|
`.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`
|
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
|
(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
|
## 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.
|
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
|
## 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.
|
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.
|
||||||
|
|
||||||
## 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.
|
|
||||||
|
|
||||||
## Changed
|
## 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)
|
- 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.
|
||||||
- **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.
|
- Chat and Voice use readable centered layouts on wider screens, including landscape Voice Focus.
|
||||||
|
|
||||||
## Fixed
|
## Fixed
|
||||||
|
|
||||||
- Wake-word detection packages one compatible ONNX Runtime for sherpa and Java JNI on every supported ABI. (#444)
|
- Correction and delivery labels remain visible inside user-message bubbles.
|
||||||
- Continuous voice waits for barge-in microphone teardown before listening again. (#464)
|
- Voice errors open in a scrollable dialog with separate Retry and Dismiss actions.
|
||||||
- Fresh chats retain their selected profile without reopening a previous session or carrying a proactive Thread route across profiles. (#436)
|
- Attachment previews remain open through rotation, and video previews preserve their proportions.
|
||||||
- Provisional Threads can be removed locally and reconcile with promoted sessions without deleting server history. (#461)
|
- Release optimization preserves the native speech configuration required for wake-word startup.
|
||||||
- Clarify cards expose a reachable Other answer, keyboard Send, and authoritative expiry behavior. (#446)
|
- Standard Hermes attachments download directly to disk with bounded size checks.
|
||||||
- Passive Android browsing no longer claims or interrupts a turn owned by another client. (Related: #365)
|
- Session refresh avoids repeated request loops; history loads, Markdown, image previews, and media exports keep memory use bounded.
|
||||||
- Assistant sessions show retryable no-speech feedback, recover their active state after recreation, and redact conversation details behind the keyguard. (Related: #424)
|
- Image-generation progress stays visible through gaps between interim replies and returned media.
|
||||||
- Protected Relay ingress `401/403` responses are recognized as authentication boundaries rather than outages; malformed, different-origin, and direct unauthorized routes still fail closed.
|
- The first prompt waits for Gateway session readiness. Ownership refusals retain the prompt for retry and show the original server error.
|
||||||
|
|
||||||
## Install / Verify
|
## Install / Verify
|
||||||
|
|
||||||
- App version: **1.14.0** (versionCode **52**).
|
- App version: **1.15.1** (versionCode **54**).
|
||||||
- Standard Chat, sessions, profiles, Manage, and standard voice continue to work against unmodified upstream Hermes without the optional Relay plugin.
|
- Standard Chat, sessions, profiles, Manage, voice, and ordinary media use current upstream Hermes. Speech-to-text still requires a configured provider on the host.
|
||||||
- Install Hermes-Relay Plugin v1.11.0 for same-origin Relay extensions, Git workspace actions, Bridge, media, proactive features, and enhanced voice.
|
- Hermes-Relay Plugin **1.11.1** remains the current optional plugin release; this Android patch does not require a new plugin version.
|
||||||
- Granular Device Control and the system Voice Focus overlay remain sideload-only; the Google Play build does not declare their restricted permissions.
|
- Paused text queues can be restored. Attachment bytes are not persisted in preferences; unrestorable attachment queues must be reviewed and sent again.
|
||||||
- Existing connections, drafts, sessions, profile ownership, and legacy direct Relay routes remain data-preserving compatibility paths.
|
- 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)
|
||||||
implementation(libs.okhttp.sse)
|
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.exoplayer)
|
||||||
|
implementation(libs.media3.ui.compose)
|
||||||
|
|
||||||
// android-vad Silero — on-device VAD for barge-in (B2)
|
// android-vad Silero — on-device VAD for barge-in (B2)
|
||||||
// Bundled ONNX Silero model (~2.2 MB); pulled from JitPack.
|
// Bundled ONNX Silero model (~2.2 MB); pulled from JitPack.
|
||||||
|
|||||||
Vendored
+3
@@ -55,6 +55,9 @@
|
|||||||
-keep class androidx.camera.** { *; }
|
-keep class androidx.camera.** { *; }
|
||||||
-dontwarn androidx.camera.**
|
-dontwarn androidx.camera.**
|
||||||
|
|
||||||
|
# sherpa-onnx JNI resolves Kotlin configuration classes and fields by name.
|
||||||
|
-keep class com.k2fsa.sherpa.onnx.** { *; }
|
||||||
|
|
||||||
# ── General ──────────────────────────────────────────────────────────
|
# ── General ──────────────────────────────────────────────────────────
|
||||||
-keepattributes SourceFile,LineNumberTable
|
-keepattributes SourceFile,LineNumberTable
|
||||||
-renamesourcefileattribute SourceFile
|
-renamesourcefileattribute SourceFile
|
||||||
|
|||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
package com.hermesandroid.relay.ui.screens
|
||||||
|
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.testTag
|
||||||
|
import androidx.compose.ui.test.assertIsDisplayed
|
||||||
|
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||||
|
import androidx.compose.ui.test.longClick
|
||||||
|
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||||
|
import androidx.compose.ui.test.onNodeWithTag
|
||||||
|
import androidx.compose.ui.test.onNodeWithText
|
||||||
|
import androidx.compose.ui.test.performClick
|
||||||
|
import androidx.compose.ui.test.performTouchInput
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.hermesandroid.relay.network.upstream.GatewayConnectionState
|
||||||
|
import com.hermesandroid.relay.ui.components.ChatDebugDrawer
|
||||||
|
import com.hermesandroid.relay.ui.components.ChatDebugOverlay
|
||||||
|
import com.hermesandroid.relay.ui.components.chatDebugHeaderGesture
|
||||||
|
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class ChatDebugDrawerInstrumentedTest {
|
||||||
|
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun longPressOpensDiagnosticsBelowHeaderAndCloseRestoresChat() {
|
||||||
|
compose.setContent {
|
||||||
|
var open by remember { mutableStateOf(false) }
|
||||||
|
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||||
|
Box(Modifier.fillMaxSize()) {
|
||||||
|
Text("Hermes", Modifier.fillMaxWidth().height(64.dp).testTag("header")
|
||||||
|
.chatDebugHeaderGesture(true, onClick = {}, onHold = { open = true }))
|
||||||
|
ChatDebugOverlay(open, 64.dp, onClose = { open = false }) {
|
||||||
|
ChatDebugDrawer(
|
||||||
|
profile = "Server Default", model = "Example", sessionId = "session",
|
||||||
|
gateway = true, signedIn = true, signInRequired = false,
|
||||||
|
socketState = GatewayConnectionState.Ready, preparing = false,
|
||||||
|
streaming = false, loadingHistory = false, directoryUnavailable = false,
|
||||||
|
failure = null, onClose = { open = false }, onConnections = {},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val header = compose.onNodeWithTag("header")
|
||||||
|
val before = header.fetchSemanticsNode().boundsInRoot
|
||||||
|
header.performTouchInput { longClick() }
|
||||||
|
compose.onNodeWithText("Session diagnostics").assertIsDisplayed()
|
||||||
|
assertEquals(before, header.fetchSemanticsNode().boundsInRoot)
|
||||||
|
compose.onNodeWithContentDescription("Close session diagnostics").performClick()
|
||||||
|
compose.onNodeWithText("Session diagnostics").assertDoesNotExist()
|
||||||
|
header.assertIsDisplayed()
|
||||||
|
}
|
||||||
|
}
|
||||||
+183
@@ -0,0 +1,183 @@
|
|||||||
|
package com.hermesandroid.relay.viewmodel
|
||||||
|
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.testTag
|
||||||
|
import androidx.compose.ui.test.assertIsDisplayed
|
||||||
|
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||||
|
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||||
|
import androidx.compose.ui.test.onNodeWithTag
|
||||||
|
import androidx.compose.ui.test.onNodeWithText
|
||||||
|
import androidx.compose.ui.test.performClick
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.hermesandroid.relay.data.AgentDisplay
|
||||||
|
import com.hermesandroid.relay.data.ChatActivityPhase
|
||||||
|
import com.hermesandroid.relay.data.InMemoryChatActivityStore
|
||||||
|
import com.hermesandroid.relay.data.projectChatActivityReceipts
|
||||||
|
import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||||
|
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||||
|
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||||
|
import com.hermesandroid.relay.network.upstream.HermesApiClient
|
||||||
|
import com.hermesandroid.relay.ui.components.ChatActivityReceipt
|
||||||
|
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessSheet
|
||||||
|
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessStrip
|
||||||
|
import com.hermesandroid.relay.ui.components.SubagentPreviewVisibility
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.serialization.json.buildJsonObject
|
||||||
|
import kotlinx.serialization.json.put
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.WebSocket
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/** Real Gateway callbacks drive production activity surfaces through Android lifecycle changes. */
|
||||||
|
class ChatActivityReceiptInstrumentedTest {
|
||||||
|
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
|
||||||
|
|
||||||
|
private lateinit var fixture: AndroidGatewayContractFixture
|
||||||
|
private lateinit var gatewayScope: CoroutineScope
|
||||||
|
private lateinit var gateway: GatewayChatClient
|
||||||
|
private lateinit var handler: ChatHandler
|
||||||
|
private lateinit var viewModel: ChatViewModel
|
||||||
|
private lateinit var socket: WebSocket
|
||||||
|
private val owner = AgentDisplay.profileContextKey("fixture-connection", "research")
|
||||||
|
|
||||||
|
@Before
|
||||||
|
fun setUp() {
|
||||||
|
fixture = AndroidGatewayContractFixture().also { it.profileName = "research" }
|
||||||
|
gatewayScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
val http = OkHttpClient()
|
||||||
|
gateway = GatewayChatClient(
|
||||||
|
initialDashboardClient = DashboardApiClient(fixture.server.url("/").toString().trimEnd('/'), okHttpClient = http),
|
||||||
|
okHttpClient = http,
|
||||||
|
callbackDispatcher = { block -> Handler(Looper.getMainLooper()).post(block) },
|
||||||
|
scope = gatewayScope,
|
||||||
|
reconnectJitterUnit = { 0.0 },
|
||||||
|
)
|
||||||
|
handler = ChatHandler().also { it.setSessionId(STORED_SESSION_ID) }
|
||||||
|
viewModel = ChatViewModel().also {
|
||||||
|
it.initialize(HermesApiClient(fixture.server.url("/").toString(), "fixture-key"), handler)
|
||||||
|
it.streamingEndpoint = "gateway"
|
||||||
|
it.setSessionProfileNameProvider { "research" }
|
||||||
|
it.setProfileMessageLoader { Result.success(emptyList()) }
|
||||||
|
it.setChatActivityStore(InMemoryChatActivityStore())
|
||||||
|
it.switchProfileContext(owner, STORED_SESSION_ID)
|
||||||
|
it.updateGatewayClient(gateway)
|
||||||
|
it.setChatVisible(true)
|
||||||
|
}
|
||||||
|
compose.setContent {
|
||||||
|
val messages by viewModel.messages.collectAsStateWithLifecycle()
|
||||||
|
val records by viewModel.activityRecords.collectAsStateWithLifecycle()
|
||||||
|
val children by viewModel.subagentActivities.collectAsStateWithLifecycle()
|
||||||
|
val retained by viewModel.retainedActivityPreview.collectAsStateWithLifecycle()
|
||||||
|
val childPreview by viewModel.subagentChildPreview.collectAsStateWithLifecycle()
|
||||||
|
val session by viewModel.currentSessionId.collectAsStateWithLifecycle()
|
||||||
|
var sheetOpen by remember { mutableStateOf(false) }
|
||||||
|
MaterialTheme {
|
||||||
|
Column {
|
||||||
|
GatewayBackgroundProcessStrip(
|
||||||
|
processes = emptyList(), subagentActivities = children,
|
||||||
|
subagentPreviewVisibility = SubagentPreviewVisibility(), loading = false,
|
||||||
|
onClick = { viewModel.openCurrentActivityPreview(); sheetOpen = true },
|
||||||
|
modifier = Modifier.testTag("active-activity"),
|
||||||
|
)
|
||||||
|
projectChatActivityReceipts(messages, records, owner, session).forEach { message ->
|
||||||
|
message.activityRecord?.let { record ->
|
||||||
|
ChatActivityReceipt(
|
||||||
|
record = record,
|
||||||
|
onClick = { sheetOpen = viewModel.openRetainedActivity(record) },
|
||||||
|
modifier = Modifier.testTag("activity-receipt"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sheetOpen) {
|
||||||
|
GatewayBackgroundProcessSheet(
|
||||||
|
processes = retained?.processes.orEmpty(),
|
||||||
|
subagentActivities = retained?.record?.previewActivities() ?: children,
|
||||||
|
subagentChildPreview = childPreview,
|
||||||
|
subagentPreviewVisibility = SubagentPreviewVisibility(),
|
||||||
|
loading = false, stoppingProcessIds = emptySet(),
|
||||||
|
onRefresh = viewModel::refreshBackgroundProcesses,
|
||||||
|
onStop = viewModel::stopBackgroundProcess,
|
||||||
|
onDismissProcess = viewModel::dismissBackgroundProcess,
|
||||||
|
onOpenSubagentChild = viewModel::openSubagentChildPreview,
|
||||||
|
onDismiss = { viewModel.closeActivityPreview(); sheetOpen = false },
|
||||||
|
readOnlyHistory = retained != null,
|
||||||
|
historyNotice = "Recorded activity. Available child history is read-only.",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue(runBlocking { gateway.prewarmAwait(STORED_SESSION_ID) })
|
||||||
|
socket = fixture.awaitServerSocket()
|
||||||
|
fixture.awaitRpc("session.resume")
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
fun tearDown() {
|
||||||
|
viewModel.updateGatewayClient(null)
|
||||||
|
gateway.shutdown()
|
||||||
|
gatewayScope.cancel()
|
||||||
|
fixture.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun detachedCompletionLeavesReopenableReceiptAcrossActivityResume() {
|
||||||
|
viewModel.sendMessage("Delegate a background task")
|
||||||
|
fixture.awaitRpc("prompt.submit")
|
||||||
|
socket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||||
|
socket.send(fixture.event("subagent.start", buildJsonObject {
|
||||||
|
put("subagent_id", "receipt-child")
|
||||||
|
put("delegation_id", "receipt-delegation")
|
||||||
|
put("task_count", 1)
|
||||||
|
put("goal", "Inspect activity lifecycle")
|
||||||
|
}, LIVE_SESSION_ID))
|
||||||
|
compose.waitUntil(5_000) { viewModel.subagentActivities.value.size == 1 }
|
||||||
|
compose.onNodeWithTag("active-activity").assertIsDisplayed()
|
||||||
|
socket.send(fixture.event("message.complete", buildJsonObject { put("text", "Launched") }, LIVE_SESSION_ID))
|
||||||
|
compose.waitUntil(5_000) { !handler.isStreaming.value }
|
||||||
|
compose.onNodeWithTag("active-activity").assertIsDisplayed()
|
||||||
|
|
||||||
|
socket.send(fixture.event("subagent.complete", buildJsonObject {
|
||||||
|
put("subagent_id", "receipt-child")
|
||||||
|
put("delegation_id", "receipt-delegation")
|
||||||
|
put("status", "completed")
|
||||||
|
}, LIVE_SESSION_ID))
|
||||||
|
compose.waitUntil(5_000) { viewModel.activityRecords.value.singleOrNull()?.phase == ChatActivityPhase.COMPLETE }
|
||||||
|
compose.onNodeWithTag("active-activity").assertDoesNotExist()
|
||||||
|
compose.onNodeWithTag("activity-receipt").assertIsDisplayed().performClick()
|
||||||
|
compose.onNodeWithText("Chat activity").assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Recorded activity. Available child history is read-only.").assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Stop").assertDoesNotExist()
|
||||||
|
compose.onNodeWithContentDescription("Close activity preview").performClick()
|
||||||
|
compose.onNodeWithTag("activity-receipt").assertIsDisplayed()
|
||||||
|
|
||||||
|
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||||
|
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||||
|
compose.onNodeWithTag("active-activity").assertDoesNotExist()
|
||||||
|
compose.onNodeWithTag("activity-receipt").assertIsDisplayed().performClick()
|
||||||
|
compose.onNodeWithText("Chat activity").assertIsDisplayed()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val STORED_SESSION_ID = "20260821_120000_fixture"
|
||||||
|
const val LIVE_SESSION_ID = "fixture-live-1"
|
||||||
|
}
|
||||||
|
}
|
||||||
+79
@@ -15,6 +15,10 @@ import androidx.compose.ui.test.assertTextEquals
|
|||||||
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
|
||||||
import androidx.compose.ui.test.onAllNodesWithText
|
import androidx.compose.ui.test.onAllNodesWithText
|
||||||
import androidx.compose.ui.test.onNodeWithTag
|
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.test.platform.app.InstrumentationRegistry
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
import com.hermesandroid.relay.data.MessageRole
|
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 ->
|
private fun JsonArray.rpcCount(method: String): Int = count { element ->
|
||||||
val entry = element as? JsonObject ?: return@count false
|
val entry = element as? JsonObject ?: return@count false
|
||||||
entry["kind"]?.jsonString() == "rpc" && entry["method"]?.jsonString() == method
|
entry["kind"]?.jsonString() == "rpc" && entry["method"]?.jsonString() == method
|
||||||
|
|||||||
+82
@@ -28,6 +28,8 @@ import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
|||||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||||
import com.hermesandroid.relay.network.upstream.HermesApiClient
|
import com.hermesandroid.relay.network.upstream.HermesApiClient
|
||||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||||
|
import com.hermesandroid.relay.ui.components.GatewayBackgroundProcessStrip
|
||||||
|
import com.hermesandroid.relay.ui.components.SubagentPreviewVisibility
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
@@ -115,9 +117,18 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
|||||||
compose.setContent {
|
compose.setContent {
|
||||||
val messages by viewModel.messages.collectAsStateWithLifecycle()
|
val messages by viewModel.messages.collectAsStateWithLifecycle()
|
||||||
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
|
val streaming by viewModel.isStreaming.collectAsStateWithLifecycle()
|
||||||
|
val children by viewModel.subagentActivities.collectAsStateWithLifecycle()
|
||||||
val signInRequired by historySignInRequired.collectAsStateWithLifecycle()
|
val signInRequired by historySignInRequired.collectAsStateWithLifecycle()
|
||||||
MaterialTheme {
|
MaterialTheme {
|
||||||
Column(Modifier.testTag("contract-transcript")) {
|
Column(Modifier.testTag("contract-transcript")) {
|
||||||
|
GatewayBackgroundProcessStrip(
|
||||||
|
processes = emptyList(),
|
||||||
|
subagentActivities = children,
|
||||||
|
subagentPreviewVisibility = SubagentPreviewVisibility(),
|
||||||
|
loading = false,
|
||||||
|
onClick = {},
|
||||||
|
modifier = Modifier.testTag("child-activity"),
|
||||||
|
)
|
||||||
Text(
|
Text(
|
||||||
text = if (streaming) "STREAMING" else "IDLE",
|
text = if (streaming) "STREAMING" else "IDLE",
|
||||||
modifier = Modifier.testTag("stream-state"),
|
modifier = Modifier.testTag("stream-state"),
|
||||||
@@ -153,6 +164,37 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
|||||||
fixture.shutdown()
|
fixture.shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun detachedChildActivity_survivesParentTerminalAndActivityResume() {
|
||||||
|
viewModel.sendMessage("Delegate a background task")
|
||||||
|
fixture.awaitRpc("prompt.submit")
|
||||||
|
serverSocket.send(fixture.event("message.start", null, LIVE_SESSION_ID))
|
||||||
|
serverSocket.send(fixture.event("subagent.start", buildJsonObject {
|
||||||
|
put("subagent_id", "detached-child")
|
||||||
|
put("goal", "Inspect")
|
||||||
|
}, LIVE_SESSION_ID))
|
||||||
|
compose.waitUntil(5_000) { viewModel.subagentActivities.value.size == 1 }
|
||||||
|
compose.onNodeWithTag("child-activity").assertIsDisplayed()
|
||||||
|
serverSocket.send(fixture.event("message.complete", buildJsonObject { put("text", "Launched") }, LIVE_SESSION_ID))
|
||||||
|
compose.waitUntil(5_000) { !handler.isStreaming.value }
|
||||||
|
compose.activityRule.scenario.moveToState(Lifecycle.State.STARTED)
|
||||||
|
serverSocket.send(fixture.event("subagent.progress", buildJsonObject {
|
||||||
|
put("subagent_id", "detached-child")
|
||||||
|
put("text", "Still working")
|
||||||
|
}, LIVE_SESSION_ID))
|
||||||
|
compose.activityRule.scenario.moveToState(Lifecycle.State.RESUMED)
|
||||||
|
compose.waitUntil(5_000) { viewModel.subagentActivities.value.single().events.last().text == "Still working" }
|
||||||
|
compose.onNodeWithTag("child-activity").assertIsDisplayed()
|
||||||
|
assertFalse(viewModel.subagentActivities.value.single().isTerminal)
|
||||||
|
compose.onNodeWithTag("stream-state").assertTextEquals("IDLE")
|
||||||
|
serverSocket.send(fixture.event("subagent.complete", buildJsonObject {
|
||||||
|
put("subagent_id", "detached-child")
|
||||||
|
put("status", "completed")
|
||||||
|
}, LIVE_SESSION_ID))
|
||||||
|
compose.waitUntil(5_000) { viewModel.subagentActivities.value.single().isTerminal }
|
||||||
|
compose.onNodeWithTag("child-activity").assertDoesNotExist()
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun terminalGapActivate_recoversForegroundTurnWithoutNavigationOrCrossSessionLeak() {
|
fun terminalGapActivate_recoversForegroundTurnWithoutNavigationOrCrossSessionLeak() {
|
||||||
viewModel.sendMessage("Run a long foreground task")
|
viewModel.sendMessage("Run a long foreground task")
|
||||||
@@ -258,6 +300,46 @@ class GatewayForegroundRecoveryInstrumentedTest {
|
|||||||
assertEquals(0, fixture.requestsTo("/v1/chat/completions"))
|
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
|
@Test
|
||||||
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
fun desktopOwnedTurn_remainsReadOnlyAcrossAndroidForegroundLifecycle() {
|
||||||
viewModel.setChatVisible(false)
|
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,
|
"schema": 3,
|
||||||
"versions": [
|
"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",
|
"version": "1.14.0",
|
||||||
"title": "Connections, delegated work, Git, and voice",
|
"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
|
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
|
Highlights
|
||||||
* Connections recover independently — Move between LAN, Tailscale, and public HTTPS without mixing Dashboard and Relay authentication.
|
* 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.
|
||||||
* Follow delegated-agent activity — See lifecycle, progress, tool previews, and available read-only child history from the parent chat.
|
* 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.
|
||||||
* Work with repositories from Android — Review status, diffs, branches, staging, commits, and remotes from Chat or Settings.
|
* 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.
|
||||||
* Steer voice at any time — Stop or redirect Hermes while it is Thinking, Transcribing, or Speaking, including with accessibility controls.
|
|
||||||
|
|
||||||
Improved
|
Improved
|
||||||
* Release notes stay out of your way — A dismissible post-update notice keeps startup usable and leaves the complete history available from Settings.
|
* 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.
|
||||||
* Chat uses one consistent presentation — The overlapping clean-focus mode was removed while the separate Voice Focus experience remains available.
|
|
||||||
|
|
||||||
Fixed
|
Fixed
|
||||||
* Wake-word detection starts reliably — Compatible native voice components are now packaged for every supported phone architecture.
|
* Read message delivery status clearly — Correction and delivery labels use contrasting text instead of disappearing into the message bubble.
|
||||||
* The visible Sphere keeps moving smoothly — Foreground animation no longer falls back to a stepped ambient pulse.
|
* 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.
|
||||||
* Continuous voice keeps the microphone — The next listening turn waits for barge-in recording to release cleanly.
|
* Fix wake-word startup in release builds — Release optimization now preserves the native speech configuration names needed to initialize wake-word detection.
|
||||||
* New chats keep the selected profile — Fresh drafts no longer reopen an older session or carry a Thread route into another profile.
|
* Download attachments with less memory — Standard Hermes attachments stream into the on-disk cache while download size limits remain enforced.
|
||||||
* Provisional Threads can be removed safely — Local removal and later session promotion no longer risk duplicate rows or server history.
|
* Keep image-generation progress visible — The working indicator stays visible between interim replies and the generated image, including gateways that omit tool activity events.
|
||||||
* Clarify keeps custom answers reachable — Other answers, keyboard Send, and expired prompts now behave consistently.
|
* 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.
|
||||||
* 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.
|
|
||||||
|
|
||||||
Compatibility
|
Compatibility
|
||||||
* Standard Chat, sessions, profiles, Manage, and standard voice continue to work without the optional Hermes-Relay Plugin.
|
* 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.
|
||||||
* The Git workspace and same-origin Relay extensions require Hermes-Relay Plugin 1.11.0.
|
* 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.
|
||||||
* Granular Device Control and the system Voice Focus overlay remain available only in the sideload build.
|
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package com.hermesandroid.relay.data
|
||||||
|
|
||||||
|
/** Presentation only: canonical rows retain their wire identity, role and content. */
|
||||||
|
internal fun projectChatActivityReceipts(
|
||||||
|
messages: List<ChatMessage>,
|
||||||
|
records: List<ChatActivityRecord>,
|
||||||
|
scopeKey: String?,
|
||||||
|
sessionId: String?,
|
||||||
|
): List<ChatMessage> {
|
||||||
|
val originals = messages.filterNot {
|
||||||
|
it.clientOnly && it.id.startsWith("activity:") && it.activityRecord != null
|
||||||
|
}
|
||||||
|
if (scopeKey.isNullOrBlank() || sessionId.isNullOrBlank()) {
|
||||||
|
return originals.map { it.copy(activityRecord = null) }
|
||||||
|
}
|
||||||
|
val owned = records.filter { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||||
|
.sortedByDescending { it.updatedAt }
|
||||||
|
.distinctBy { it.id }
|
||||||
|
val represented = mutableSetOf<String>()
|
||||||
|
val canonical = originals.map { message ->
|
||||||
|
val process = message.hermesProcessNotificationOrNull()
|
||||||
|
val delegation = message.activitySourceId?.takeIf { it.startsWith("delegation:") }
|
||||||
|
?.removePrefix("delegation:")?.takeIf { it.isNotBlank() }
|
||||||
|
val kind = when {
|
||||||
|
message.activitySourceId != null -> ChatActivityKind.SUBAGENTS
|
||||||
|
process != null -> ChatActivityKind.PROCESS
|
||||||
|
else -> return@map message.copy(activityRecord = null)
|
||||||
|
}
|
||||||
|
val sourceId = delegation ?: process?.processId
|
||||||
|
val processTerminal = process?.let { notice ->
|
||||||
|
PROCESS_TERMINAL_HEADLINE.matchEntire(notice.headline)?.let { match ->
|
||||||
|
match.groupValues[2].toIntOrNull()?.let { code ->
|
||||||
|
val phase = when {
|
||||||
|
match.groupValues[1].startsWith("terminated by ") -> ChatActivityPhase.CANCELLED
|
||||||
|
code == 0 -> ChatActivityPhase.COMPLETE
|
||||||
|
else -> ChatActivityPhase.FAILED
|
||||||
|
}
|
||||||
|
phase to code
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A process id can be reused after a registry restart. A canonical row has
|
||||||
|
// no start-generation field, so multiple generations must remain unmatched.
|
||||||
|
val matching = if (sourceId == null) emptyList() else owned.filter {
|
||||||
|
it.kind == kind && it.sourceId == sourceId
|
||||||
|
}
|
||||||
|
val record = matching.singleOrNull()?.also { represented += it.id }
|
||||||
|
?: ChatActivityRecord(
|
||||||
|
id = "canonical:${message.id}",
|
||||||
|
scopeKey = scopeKey,
|
||||||
|
sessionId = sessionId,
|
||||||
|
kind = kind,
|
||||||
|
sourceId = sourceId ?: "unavailable:${message.id}",
|
||||||
|
title = process?.headline ?: message.content,
|
||||||
|
phase = when {
|
||||||
|
kind == ChatActivityKind.PROCESS -> processTerminal?.first ?: ChatActivityPhase.UNKNOWN
|
||||||
|
(message.activityFailedCount ?: 0) > 0 ->
|
||||||
|
if (message.activityFailedCount == message.activityTaskCount) {
|
||||||
|
ChatActivityPhase.FAILED
|
||||||
|
} else ChatActivityPhase.UNKNOWN
|
||||||
|
(message.activityTaskCount ?: 0) > 0 -> ChatActivityPhase.COMPLETE
|
||||||
|
else -> ChatActivityPhase.UNKNOWN
|
||||||
|
},
|
||||||
|
createdAt = message.timestamp,
|
||||||
|
updatedAt = message.timestamp,
|
||||||
|
taskCount = message.activityTaskCount?.coerceAtLeast(0) ?: 0,
|
||||||
|
processId = process?.processId,
|
||||||
|
exitCode = processTerminal?.second,
|
||||||
|
)
|
||||||
|
// Aggregate completion metadata never rewrites captured child phases.
|
||||||
|
message.copy(activityRecord = record)
|
||||||
|
}
|
||||||
|
val pending = owned.filter { it.phase != ChatActivityPhase.RUNNING && it.id !in represented }
|
||||||
|
.sortedWith(compareBy<ChatActivityRecord> { it.updatedAt }.thenBy { it.id })
|
||||||
|
.map { record ->
|
||||||
|
ChatMessage(
|
||||||
|
id = "activity:${record.id}",
|
||||||
|
role = MessageRole.SYSTEM,
|
||||||
|
content = record.title,
|
||||||
|
timestamp = record.updatedAt,
|
||||||
|
clientOnly = true,
|
||||||
|
activityRecord = record,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// Stable merge: history order is authoritative even if server timestamps
|
||||||
|
// regress. Only insert local receipts; never sort canonical messages.
|
||||||
|
var next = 0
|
||||||
|
return buildList {
|
||||||
|
canonical.forEach { message ->
|
||||||
|
while (next < pending.size && pending[next].timestamp < message.timestamp) {
|
||||||
|
add(pending[next++])
|
||||||
|
}
|
||||||
|
add(message)
|
||||||
|
}
|
||||||
|
while (next < pending.size) add(pending[next++])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Upstream completion envelope only; never search arbitrary command/output text. */
|
||||||
|
private val PROCESS_TERMINAL_HEADLINE = Regex(
|
||||||
|
"""Background process \S+ (completed normally|exited|terminated by [^\r\n]+|marked lost because the process backend disappeared|failed to start) \(exit code (-?\d+)(?:, SIGTERM)?\)\.""",
|
||||||
|
)
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
package com.hermesandroid.relay.data
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.datastore.core.DataStore
|
||||||
|
import androidx.datastore.preferences.core.Preferences
|
||||||
|
import androidx.datastore.preferences.core.edit
|
||||||
|
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||||
|
import java.io.IOException
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlinx.serialization.encodeToString
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.JsonArray
|
||||||
|
import kotlinx.serialization.json.JsonObject
|
||||||
|
import kotlinx.serialization.json.jsonPrimitive
|
||||||
|
import kotlinx.serialization.json.intOrNull
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
enum class ChatActivityKind { SUBAGENTS, PROCESS }
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
enum class ChatActivityPhase { RUNNING, COMPLETE, FAILED, CANCELLED, UNKNOWN }
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ChatActivityChild(
|
||||||
|
val id: String,
|
||||||
|
val childSessionId: String? = null,
|
||||||
|
val goal: String = "",
|
||||||
|
val phase: ChatActivityPhase = ChatActivityPhase.UNKNOWN,
|
||||||
|
val summary: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Local presentation metadata and exact references, never transcripts or process output. */
|
||||||
|
@Serializable
|
||||||
|
data class ChatActivityRecord(
|
||||||
|
val id: String,
|
||||||
|
val scopeKey: String,
|
||||||
|
val sessionId: String,
|
||||||
|
val kind: ChatActivityKind,
|
||||||
|
val sourceId: String,
|
||||||
|
val title: String,
|
||||||
|
val phase: ChatActivityPhase,
|
||||||
|
val createdAt: Long,
|
||||||
|
val updatedAt: Long,
|
||||||
|
val children: List<ChatActivityChild> = emptyList(),
|
||||||
|
val taskCount: Int = 0,
|
||||||
|
val processId: String? = null,
|
||||||
|
val processStartedAt: String? = null,
|
||||||
|
val exitCode: Int? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
interface ChatActivityStore {
|
||||||
|
/** Recovery is not live evidence: RUNNING becomes UNKNOWN, including child phases. */
|
||||||
|
suspend fun read(scopeKey: String, sessionId: String): List<ChatActivityRecord>
|
||||||
|
suspend fun upsert(record: ChatActivityRecord)
|
||||||
|
suspend fun removeRecord(scopeKey: String, sessionId: String, id: String)
|
||||||
|
suspend fun removeSession(scopeKey: String, sessionId: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bounded app-private history references in the shared settings DataStore.
|
||||||
|
* Retains 30 days, 128 records overall, 32 per exact owner/session, and 32 children
|
||||||
|
* per record. Titles are 160 characters; goals/summaries 512. Identity fields are
|
||||||
|
* rejected above 512 characters (scope 2048), never truncated into another owner.
|
||||||
|
* The complete encoded envelope is capped at 1 MiB, evicting oldest records first.
|
||||||
|
* Five minutes of future skew allows monotonic local revisions within one clock tick.
|
||||||
|
* All read/modify/write operations occur inside DataStore's serialized edit.
|
||||||
|
*/
|
||||||
|
class DataStoreChatActivityStore(
|
||||||
|
private val dataStore: DataStore<Preferences>,
|
||||||
|
private val now: () -> Long = System::currentTimeMillis,
|
||||||
|
) : ChatActivityStore {
|
||||||
|
constructor(context: Context) : this(context.applicationContext.relayDataStore)
|
||||||
|
|
||||||
|
override suspend fun read(scopeKey: String, sessionId: String): List<ChatActivityRecord> {
|
||||||
|
val raw = try {
|
||||||
|
dataStore.data.first()[CHAT_ACTIVITY_KEY]
|
||||||
|
} catch (_: IOException) {
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
return boundChatActivities(decodeChatActivities(raw), now())
|
||||||
|
.filter { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||||
|
.map(ChatActivityRecord::recovered)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun upsert(record: ChatActivityRecord) {
|
||||||
|
dataStore.edit { preferences ->
|
||||||
|
val records = mergeChatActivity(decodeChatActivities(preferences[CHAT_ACTIVITY_KEY]), record, now())
|
||||||
|
preferences[CHAT_ACTIVITY_KEY] = encodeChatActivities(records)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun removeSession(scopeKey: String, sessionId: String) {
|
||||||
|
dataStore.edit { preferences ->
|
||||||
|
val remaining = boundChatActivities(decodeChatActivities(preferences[CHAT_ACTIVITY_KEY]), now())
|
||||||
|
.filterNot { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||||
|
if (remaining.isEmpty()) preferences.remove(CHAT_ACTIVITY_KEY)
|
||||||
|
else preferences[CHAT_ACTIVITY_KEY] = encodeChatActivities(remaining)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun removeRecord(scopeKey: String, sessionId: String, id: String) {
|
||||||
|
dataStore.edit { preferences ->
|
||||||
|
val remaining = boundChatActivities(decodeChatActivities(preferences[CHAT_ACTIVITY_KEY]), now())
|
||||||
|
.filterNot { it.scopeKey == scopeKey && it.sessionId == sessionId && it.id == id }
|
||||||
|
if (remaining.isEmpty()) preferences.remove(CHAT_ACTIVITY_KEY)
|
||||||
|
else preferences[CHAT_ACTIVITY_KEY] = encodeChatActivities(remaining)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Test/ephemeral implementation with the same bounds and recovery semantics. */
|
||||||
|
class InMemoryChatActivityStore(
|
||||||
|
private val now: () -> Long = System::currentTimeMillis,
|
||||||
|
) : ChatActivityStore {
|
||||||
|
private val mutex = Mutex()
|
||||||
|
private var records = emptyList<ChatActivityRecord>()
|
||||||
|
|
||||||
|
override suspend fun read(scopeKey: String, sessionId: String): List<ChatActivityRecord> = mutex.withLock {
|
||||||
|
records = boundChatActivities(records, now())
|
||||||
|
records.filter { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||||
|
.map(ChatActivityRecord::recovered)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun upsert(record: ChatActivityRecord) = mutex.withLock {
|
||||||
|
records = mergeChatActivity(records, record, now())
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun removeSession(scopeKey: String, sessionId: String) = mutex.withLock {
|
||||||
|
records = boundChatActivities(records, now())
|
||||||
|
.filterNot { it.scopeKey == scopeKey && it.sessionId == sessionId }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun removeRecord(scopeKey: String, sessionId: String, id: String) = mutex.withLock {
|
||||||
|
records = boundChatActivities(records, now())
|
||||||
|
.filterNot { it.scopeKey == scopeKey && it.sessionId == sessionId && it.id == id }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal const val CHAT_ACTIVITY_MAX_AGE_MS = 30L * 24L * 60L * 60L * 1_000L
|
||||||
|
private const val MAX_RECORDS = 128
|
||||||
|
private const val MAX_SESSION_RECORDS = 32
|
||||||
|
private const val MAX_PAYLOAD_BYTES = 1_048_576
|
||||||
|
private val CHAT_ACTIVITY_KEY = stringPreferencesKey("chat_activity_records_v1")
|
||||||
|
private val activityJson = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
private data class ChatActivityEnvelope(val version: Int = 1, val records: List<ChatActivityRecord>)
|
||||||
|
|
||||||
|
private fun encodeChatActivities(records: List<ChatActivityRecord>): String =
|
||||||
|
activityJson.encodeToString(ChatActivityEnvelope(records = records))
|
||||||
|
|
||||||
|
internal fun decodeChatActivities(raw: String?): List<ChatActivityRecord> {
|
||||||
|
if (raw == null || raw.length > MAX_PAYLOAD_BYTES || raw.toByteArray().size > MAX_PAYLOAD_BYTES) {
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
val envelope = runCatching { activityJson.parseToJsonElement(raw) as? JsonObject }.getOrNull()
|
||||||
|
?: return emptyList()
|
||||||
|
val version = runCatching { envelope["version"]?.jsonPrimitive?.intOrNull }.getOrNull()
|
||||||
|
if (version != 1) return emptyList()
|
||||||
|
val rows = envelope["records"] as? JsonArray ?: return emptyList()
|
||||||
|
// One corrupt or newer row must not hide independently valid records.
|
||||||
|
return rows.mapNotNull { row ->
|
||||||
|
runCatching { activityJson.decodeFromJsonElement(ChatActivityRecord.serializer(), row) }.getOrNull()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ChatActivityRecord.identity() = Triple(scopeKey, sessionId, id)
|
||||||
|
|
||||||
|
private fun mergeChatActivity(
|
||||||
|
existing: List<ChatActivityRecord>,
|
||||||
|
record: ChatActivityRecord,
|
||||||
|
now: Long,
|
||||||
|
): List<ChatActivityRecord> {
|
||||||
|
// Sorting first also rejects a late write for an older generation of the same record.
|
||||||
|
return boundChatActivities(listOf(record) + existing, now)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun boundChatActivities(records: List<ChatActivityRecord>, now: Long): List<ChatActivityRecord> {
|
||||||
|
val counts = mutableMapOf<Pair<String, String>, Int>()
|
||||||
|
val bounded = records.mapNotNull { it.bounded(now) }
|
||||||
|
.sortedByDescending(ChatActivityRecord::updatedAt)
|
||||||
|
.distinctBy { it.identity() }
|
||||||
|
.filter {
|
||||||
|
val owner = it.scopeKey to it.sessionId
|
||||||
|
val count = counts.getOrDefault(owner, 0)
|
||||||
|
counts[owner] = count + 1
|
||||||
|
count < MAX_SESSION_RECORDS
|
||||||
|
}.take(MAX_RECORDS).toMutableList()
|
||||||
|
while (bounded.isNotEmpty() && encodeChatActivities(bounded).toByteArray().size > MAX_PAYLOAD_BYTES) {
|
||||||
|
bounded.removeAt(bounded.lastIndex)
|
||||||
|
}
|
||||||
|
return bounded
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validIdentity(value: String, max: Int = 512) = value.isNotBlank() && value.length <= max
|
||||||
|
|
||||||
|
private fun ChatActivityRecord.bounded(now: Long): ChatActivityRecord? {
|
||||||
|
if (!validIdentity(scopeKey, 2048) || !validIdentity(sessionId) || !validIdentity(id) ||
|
||||||
|
!validIdentity(sourceId) || (processId != null && !validIdentity(processId)) ||
|
||||||
|
(processStartedAt != null && !validIdentity(processStartedAt)) ||
|
||||||
|
createdAt < 0 || updatedAt < createdAt || updatedAt > now + 300_000L ||
|
||||||
|
now - updatedAt > CHAT_ACTIVITY_MAX_AGE_MS
|
||||||
|
) return null
|
||||||
|
return copy(
|
||||||
|
title = title.take(160),
|
||||||
|
taskCount = taskCount.coerceIn(0, 10_000),
|
||||||
|
children = children.asSequence().filter {
|
||||||
|
validIdentity(it.id) && (it.childSessionId == null || validIdentity(it.childSessionId))
|
||||||
|
}.distinctBy(ChatActivityChild::id).take(32)
|
||||||
|
.map { it.copy(goal = it.goal.take(512), summary = it.summary?.take(512)) }.toList(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ChatActivityRecord.recovered() = copy(
|
||||||
|
phase = if (phase == ChatActivityPhase.RUNNING) ChatActivityPhase.UNKNOWN else phase,
|
||||||
|
children = children.map {
|
||||||
|
if (it.phase == ChatActivityPhase.RUNNING) it.copy(phase = ChatActivityPhase.UNKNOWN) else it
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -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. */
|
/** Device-level chat input preferences shared by every Hermes profile. */
|
||||||
class ChatInputPreferencesRepository(
|
class ChatInputPreferencesRepository(
|
||||||
private val dataStore: DataStore<Preferences>,
|
private val dataStore: DataStore<Preferences>,
|
||||||
@@ -29,6 +49,7 @@ class ChatInputPreferencesRepository(
|
|||||||
constructor(context: Context) : this(context.relayDataStore)
|
constructor(context: Context) : this(context.relayDataStore)
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
internal val KEY_BUSY_MESSAGE_ACTION = stringPreferencesKey("busy_message_action")
|
||||||
internal val KEY_PHYSICAL_KEYBOARD_ENTER =
|
internal val KEY_PHYSICAL_KEYBOARD_ENTER =
|
||||||
stringPreferencesKey("physical_keyboard_enter_behavior")
|
stringPreferencesKey("physical_keyboard_enter_behavior")
|
||||||
internal val KEY_CONVERT_LARGE_PASTES =
|
internal val KEY_CONVERT_LARGE_PASTES =
|
||||||
@@ -45,6 +66,14 @@ class ChatInputPreferencesRepository(
|
|||||||
}
|
}
|
||||||
.distinctUntilChanged()
|
.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
|
val convertLargePastesToAttachments: Flow<Boolean> = dataStore.data
|
||||||
.map { preferences -> preferences[KEY_CONVERT_LARGE_PASTES] ?: true }
|
.map { preferences -> preferences[KEY_CONVERT_LARGE_PASTES] ?: true }
|
||||||
.distinctUntilChanged()
|
.distinctUntilChanged()
|
||||||
|
|||||||
@@ -170,6 +170,12 @@ data class ChatMessage(
|
|||||||
* but server history never owns these presentation blocks.
|
* but server history never owns these presentation blocks.
|
||||||
*/
|
*/
|
||||||
val moaReferences: List<MoaReference> = emptyList(),
|
val moaReferences: List<MoaReference> = emptyList(),
|
||||||
|
/** Exact upstream identity on a persisted activity-completion marker. */
|
||||||
|
val activitySourceId: String? = null,
|
||||||
|
val activityTaskCount: Int? = null,
|
||||||
|
val activityFailedCount: Int? = null,
|
||||||
|
/** Read-only UI projection; never sent as model history or voice input. */
|
||||||
|
val activityRecord: ChatActivityRecord? = null,
|
||||||
)
|
)
|
||||||
|
|
||||||
data class MessageReaction(
|
data class MessageReaction(
|
||||||
|
|||||||
@@ -35,6 +35,9 @@ data class ChatTurnCheckpoint(
|
|||||||
val baselineAssistantCount: Int,
|
val baselineAssistantCount: Int,
|
||||||
val pendingAsk: ChatTurnAskCheckpoint? = null,
|
val pendingAsk: ChatTurnAskCheckpoint? = null,
|
||||||
val queuedMessages: List<ChatQueuedMessageCheckpoint> = emptyList(),
|
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 startedAt: Long,
|
||||||
val updatedAt: Long,
|
val updatedAt: Long,
|
||||||
) {
|
) {
|
||||||
|
|||||||
@@ -29,3 +29,24 @@ val Connection.capabilities: ConnectionCapabilities
|
|||||||
apiServerConfigured = apiServerUrl.isNotBlank(),
|
apiServerConfigured = apiServerUrl.isNotBlank(),
|
||||||
relayConfigured = relayUrl.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 normalized = url.trim().trimEnd('/')
|
||||||
val service = when (label) {
|
val service = when (label) {
|
||||||
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
|
"Chat & Manage", "Dashboard & Gateway" -> "dashboard"
|
||||||
"API / sessions", "API fallback" -> "api"
|
"API / sessions", "API fallback", "Direct API" -> "api"
|
||||||
"Relay tools" -> "relay"
|
"Relay tools" -> "relay"
|
||||||
else -> return false
|
else -> return false
|
||||||
}
|
}
|
||||||
@@ -170,7 +170,7 @@ fun computeConnectionSecurity(
|
|||||||
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
|
apiUrl.trim().takeIf { it.isNotBlank() }?.let {
|
||||||
add(
|
add(
|
||||||
classifySurfaceSecurity(
|
classifySurfaceSecurity(
|
||||||
label = "API fallback",
|
label = "Direct API",
|
||||||
url = it,
|
url = it,
|
||||||
activeEndpoint = apiEndpoint,
|
activeEndpoint = apiEndpoint,
|
||||||
isTailscaleDetected = isTailscaleDetected,
|
isTailscaleDetected = isTailscaleDetected,
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
package com.hermesandroid.relay.data
|
package com.hermesandroid.relay.data
|
||||||
|
|
||||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||||
|
import com.hermesandroid.relay.network.upstream.DashboardHttpException
|
||||||
import com.hermesandroid.relay.plugins.runtime.ScopedPluginApiClient
|
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.Json
|
||||||
import kotlinx.serialization.json.JsonPrimitive
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
import kotlinx.serialization.json.buildJsonArray
|
import kotlinx.serialization.json.buildJsonArray
|
||||||
@@ -9,113 +15,178 @@ import kotlinx.serialization.json.buildJsonObject
|
|||||||
import kotlinx.serialization.json.decodeFromJsonElement
|
import kotlinx.serialization.json.decodeFromJsonElement
|
||||||
import kotlinx.serialization.json.put
|
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)) } }
|
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(
|
class GitStateApiClient(
|
||||||
dashboard: DashboardApiClient,
|
private val dashboard: DashboardApiClient,
|
||||||
) {
|
) {
|
||||||
private val scoped = ScopedPluginApiClient("hermes-relay", dashboard)
|
private val scoped = ScopedPluginApiClient("hermes-relay", dashboard)
|
||||||
private val json = Json { ignoreUnknownKeys = true }
|
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
|
suspend fun repos(
|
||||||
.get("git/repos")
|
sessionRepoPath: String? = null,
|
||||||
.mapCatching { element ->
|
includeRelayDiscovery: Boolean = true,
|
||||||
json.decodeFromJsonElement<ReposResponse>(element).repos
|
): 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
|
val upstream = upstreamStatus(path)
|
||||||
.get("git/status", mapOf("repo" to repo))
|
if (upstream.isFailure) {
|
||||||
.mapCatching { element -> json.decodeFromJsonElement<GitStatus>(element) }
|
val error = upstream.exceptionOrNull()!!
|
||||||
|
if (!error.isUnsupportedGitRoute()) return Result.failure(error)
|
||||||
suspend fun branches(repo: String): Result<List<GitBranch>> = scoped
|
return if (includeRelayDiscovery) relayRepos().onSuccess(::rememberRepos)
|
||||||
.get("git/branches", mapOf("repo" to repo))
|
else Result.failure(error)
|
||||||
.mapCatching { element ->
|
}
|
||||||
json.decodeFromJsonElement<BranchesResponse>(element).branches
|
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
|
val standardRepo = GitRepo(
|
||||||
.get("git/diff", mapOf("repo" to repo, "path" to path, "kind" to kind))
|
id = UPSTREAM_SESSION_REPO_ID,
|
||||||
.mapCatching { element -> json.decodeFromJsonElement<GitDiff>(element) }
|
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
|
// Plugin discovery is an enhancement. Once upstream answered, plugin
|
||||||
.get("git/file", mapOf("repo" to repo, "path" to path))
|
// absence or breakage cannot take the standard session repository down.
|
||||||
.mapCatching { element -> json.decodeFromJsonElement<GitFile>(element) }
|
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 ───────────────────────────────────────────────────
|
suspend fun status(repo: String): Result<GitStatus> {
|
||||||
// Every write requires the plugin.api.write grant, which the app enforces
|
val target = reposById[repo]
|
||||||
// (see GitStateViewModel: a POST is never sent without the grant). The
|
if (target?.route != GitRepositoryRoute.UPSTREAM) return relayStatus(repo)
|
||||||
// server additionally enforces per-use confirmation strings for destructive
|
return fallbackOnUnsupported(target, upstreamStatusWithFiles(target.root), ::relayStatus)
|
||||||
// ops (discard/push/dirty-checkout) — the caller passes the echoed token.
|
}
|
||||||
|
|
||||||
|
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> =
|
suspend fun stage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||||
scoped.post("git/stage", buildJsonObject {
|
relayWrite(repo) { relay -> scoped.post("git/stage", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("paths", pathsArray(paths))
|
put("paths", pathsArray(paths))
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
}).decodeMutation() }
|
||||||
|
|
||||||
suspend fun unstage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
suspend fun unstage(repo: String, paths: List<String>): Result<GitMutationResult> =
|
||||||
scoped.post("git/unstage", buildJsonObject {
|
relayWrite(repo) { relay -> scoped.post("git/unstage", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("paths", pathsArray(paths))
|
put("paths", pathsArray(paths))
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
}).decodeMutation() }
|
||||||
|
|
||||||
suspend fun discard(
|
suspend fun discard(
|
||||||
repo: String,
|
repo: String,
|
||||||
paths: List<String>,
|
paths: List<String>,
|
||||||
confirmation: String,
|
confirmation: String,
|
||||||
deleteUntracked: Boolean = false,
|
deleteUntracked: Boolean = false,
|
||||||
): Result<GitMutationResult> = scoped.post("git/discard", buildJsonObject {
|
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/discard", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("paths", pathsArray(paths))
|
put("paths", pathsArray(paths))
|
||||||
put("confirmation", confirmation)
|
put("confirmation", confirmation)
|
||||||
put("delete_untracked", deleteUntracked)
|
put("delete_untracked", deleteUntracked)
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
}).decodeMutation() }
|
||||||
|
|
||||||
suspend fun commit(repo: String, message: String): Result<GitMutationResult> =
|
suspend fun commit(repo: String, message: String): Result<GitMutationResult> =
|
||||||
scoped.post("git/commit", buildJsonObject {
|
relayWrite(repo) { relay -> scoped.post("git/commit", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("message", message)
|
put("message", message)
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
}).decodeMutation() }
|
||||||
|
|
||||||
suspend fun commitSelected(
|
suspend fun commitSelected(
|
||||||
repo: String,
|
repo: String,
|
||||||
message: String,
|
message: String,
|
||||||
paths: List<String>,
|
paths: List<String>,
|
||||||
): Result<GitMutationResult> = scoped.post("git/commit_selected", buildJsonObject {
|
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/commit_selected", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("message", message)
|
put("message", message)
|
||||||
put("paths", pathsArray(paths))
|
put("paths", pathsArray(paths))
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
}).decodeMutation() }
|
||||||
|
|
||||||
suspend fun fetch(repo: String, remote: String = "origin"): Result<GitMutationResult> =
|
suspend fun fetch(repo: String, remote: String = "origin"): Result<GitMutationResult> =
|
||||||
scoped.post("git/fetch", buildJsonObject {
|
relayWrite(repo) { relay -> scoped.post("git/fetch", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("remote", remote)
|
put("remote", remote)
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
}).decodeMutation() }
|
||||||
|
|
||||||
suspend fun pull(repo: String, remote: String = "origin", branch: String = ""): Result<GitMutationResult> =
|
suspend fun pull(repo: String, remote: String = "origin", branch: String = ""): Result<GitMutationResult> =
|
||||||
scoped.post("git/pull", buildJsonObject {
|
relayWrite(repo) { relay -> scoped.post("git/pull", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("remote", remote)
|
put("remote", remote)
|
||||||
put("branch", branch)
|
put("branch", branch)
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
}).decodeMutation() }
|
||||||
|
|
||||||
suspend fun push(
|
suspend fun push(
|
||||||
repo: String,
|
repo: String,
|
||||||
confirmation: String,
|
confirmation: String,
|
||||||
remote: String = "origin",
|
remote: String = "origin",
|
||||||
branch: String = "",
|
branch: String = "",
|
||||||
): Result<GitMutationResult> = scoped.post("git/push", buildJsonObject {
|
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/push", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("remote", remote)
|
put("remote", remote)
|
||||||
put("branch", branch)
|
put("branch", branch)
|
||||||
put("confirmation", confirmation)
|
put("confirmation", confirmation)
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitMutationResult>(it) }
|
}).decodeMutation() }
|
||||||
|
|
||||||
suspend fun checkout(
|
suspend fun checkout(
|
||||||
repo: String,
|
repo: String,
|
||||||
@@ -123,41 +194,217 @@ class GitStateApiClient(
|
|||||||
confirmation: String? = null,
|
confirmation: String? = null,
|
||||||
newBranch: String = "",
|
newBranch: String = "",
|
||||||
track: Boolean = false,
|
track: Boolean = false,
|
||||||
): Result<GitMutationResult> = scoped.post("git/checkout", buildJsonObject {
|
): Result<GitMutationResult> = relayWrite(repo) { relay -> scoped.post("git/checkout", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("ref", ref)
|
put("ref", ref)
|
||||||
if (confirmation != null) put("confirmation", confirmation)
|
if (confirmation != null) put("confirmation", confirmation)
|
||||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||||
put("track", track)
|
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 commitMessageSelected(repo: String, paths: List<String>): Result<GitCommitMessage> =
|
||||||
suspend fun commitMessage(repo: String): Result<GitCommitMessage> =
|
relayWrite(repo) { relay -> scoped.post("git/commit_message_selected", buildJsonObject {
|
||||||
scoped.post("git/commit_message", buildJsonObject {
|
put("repo", relay)
|
||||||
put("repo", repo)
|
put("paths", pathsArray(paths))
|
||||||
}).mapCatching { json.decodeFromJsonElement<GitCommitMessage>(it) }
|
}).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(
|
suspend fun stashCheckout(
|
||||||
repo: String,
|
repo: String,
|
||||||
ref: String,
|
ref: String,
|
||||||
newBranch: String = "",
|
newBranch: String = "",
|
||||||
track: Boolean = false,
|
track: Boolean = false,
|
||||||
): Result<GitStashCheckoutResult> = scoped.post("git/stash_checkout", buildJsonObject {
|
): Result<GitStashCheckoutResult> = relayWrite(repo) { relay -> scoped.post("git/stash_checkout", buildJsonObject {
|
||||||
put("repo", repo)
|
put("repo", relay)
|
||||||
put("ref", ref)
|
put("ref", ref)
|
||||||
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
if (newBranch.isNotEmpty()) put("new_branch", newBranch)
|
||||||
put("track", track)
|
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.SerialName
|
||||||
import kotlinx.serialization.Serializable
|
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
|
@Serializable
|
||||||
data class GitRepo(
|
data class GitRepo(
|
||||||
val id: String,
|
val id: String,
|
||||||
@@ -11,9 +11,19 @@ data class GitRepo(
|
|||||||
val root: String,
|
val root: String,
|
||||||
@SerialName("current_branch") val currentBranch: String? = null,
|
@SerialName("current_branch") val currentBranch: String? = null,
|
||||||
val dirty: Boolean = false,
|
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
|
@Serializable
|
||||||
data class GitStatus(
|
data class GitStatus(
|
||||||
val counts: GitStatusCounts = GitStatusCounts(),
|
val counts: GitStatusCounts = GitStatusCounts(),
|
||||||
|
|||||||
@@ -344,6 +344,46 @@ class VoicePreferencesRepository(private val dataStore: DataStore<Preferences>)
|
|||||||
dataStore.edit { it[key] = route.storageValue }
|
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). */
|
/** "" clears the override (relay falls back to the server's saved voice). */
|
||||||
suspend fun setEnhancedVoice(voice: String) {
|
suspend fun setEnhancedVoice(voice: String) {
|
||||||
val key = stringPreferencesKey(scopedName(KEY_ENH_VOICE, _scope.value))
|
val key = stringPreferencesKey(scopedName(KEY_ENH_VOICE, _scope.value))
|
||||||
|
|||||||
@@ -348,7 +348,7 @@ class BridgeCommandHandler(
|
|||||||
* the multiplexer. The two paths are fully independent.
|
* the multiplexer. The two paths are fully independent.
|
||||||
*
|
*
|
||||||
* Caught by Bailey's on-device test 2026-04-14 — see the v0.4.1
|
* 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 {
|
suspend fun handleLocalCommand(envelope: Envelope): LocalDispatchResult {
|
||||||
if (envelope.type != "bridge.command") {
|
if (envelope.type != "bridge.command") {
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import okhttp3.OkHttpClient
|
|||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
|
||||||
internal const val RELAY_SESSION_HEADER: String = "X-Hermes-Relay-Session"
|
internal const val RELAY_SESSION_HEADER: String = "X-Hermes-Relay-Session"
|
||||||
|
|
||||||
@@ -88,6 +89,7 @@ class RelayHttpClient(
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val TAG = "RelayHttpClient"
|
private const val TAG = "RelayHttpClient"
|
||||||
|
private const val DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES = 100L * 1024L * 1024L
|
||||||
const val MAX_MODEL_CAPABILITY_ROWS = 64
|
const val MAX_MODEL_CAPABILITY_ROWS = 64
|
||||||
private const val MAX_MODEL_CAPABILITY_PROVIDER_CHARS = 128
|
private const val MAX_MODEL_CAPABILITY_PROVIDER_CHARS = 128
|
||||||
private const val MAX_MODEL_CAPABILITY_MODEL_CHARS = 512
|
private const val MAX_MODEL_CAPABILITY_MODEL_CHARS = 512
|
||||||
@@ -257,7 +259,10 @@ class RelayHttpClient(
|
|||||||
* underlying exception with a human-readable message suitable for
|
* underlying exception with a human-readable message suitable for
|
||||||
* surfacing in the attachment's `errorMessage` field.
|
* 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()
|
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||||
if (relayUrl.isEmpty()) {
|
if (relayUrl.isEmpty()) {
|
||||||
return@withContext Result.failure(
|
return@withContext Result.failure(
|
||||||
@@ -318,7 +323,7 @@ class RelayHttpClient(
|
|||||||
if (body == null) {
|
if (body == null) {
|
||||||
return@withContext Result.failure(IOException("Empty response body"))
|
return@withContext Result.failure(IOException("Empty response body"))
|
||||||
}
|
}
|
||||||
val bytes = body.bytes()
|
val bytes = body.readBytesBounded(maxBytes)
|
||||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||||
}
|
}
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
@@ -352,6 +357,7 @@ class RelayHttpClient(
|
|||||||
suspend fun fetchMediaByPath(
|
suspend fun fetchMediaByPath(
|
||||||
path: String,
|
path: String,
|
||||||
contentTypeHint: String? = null,
|
contentTypeHint: String? = null,
|
||||||
|
maxBytes: Long = DEFAULT_MEDIA_DOWNLOAD_LIMIT_BYTES,
|
||||||
): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
): Result<FetchedMedia> = withContext(Dispatchers.IO) {
|
||||||
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
val relayUrl = relayUrlProvider()?.trim().orEmpty()
|
||||||
if (relayUrl.isEmpty()) {
|
if (relayUrl.isEmpty()) {
|
||||||
@@ -427,12 +433,16 @@ class RelayHttpClient(
|
|||||||
if (body == null) {
|
if (body == null) {
|
||||||
return@withContext Result.failure(IOException("Empty response body"))
|
return@withContext Result.failure(IOException("Empty response body"))
|
||||||
}
|
}
|
||||||
val bytes = body.bytes()
|
val bytes = body.readBytesBounded(maxBytes)
|
||||||
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
Result.success(FetchedMedia(contentType, bytes, fileName, sensitive))
|
||||||
}
|
}
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
Log.w(TAG, "fetchMediaByPath failed for $path: ${e.message}")
|
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) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "fetchMediaByPath unexpected error for $path: ${e.message}")
|
Log.w(TAG, "fetchMediaByPath unexpected error for $path: ${e.message}")
|
||||||
Result.failure(e)
|
Result.failure(e)
|
||||||
@@ -1456,6 +1466,33 @@ class RelayHttpClient(
|
|||||||
return match?.groupValues?.get(1)?.trim()?.ifBlank { null }
|
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.
|
* Parse the relay's `X-Media-Sensitive` response header into a bool.
|
||||||
*
|
*
|
||||||
@@ -1468,7 +1505,7 @@ class RelayHttpClient(
|
|||||||
return value == "1" || value == "true"
|
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(
|
suspend fun fetchProviderUsage(
|
||||||
profile: String? = null,
|
profile: String? = null,
|
||||||
sessionId: String? = null,
|
sessionId: String? = null,
|
||||||
|
|||||||
@@ -1451,6 +1451,12 @@ class ChatHandler {
|
|||||||
val loaded = renderedItems.mapNotNull { item ->
|
val loaded = renderedItems.mapNotNull { item ->
|
||||||
val displayKind = item.displayKind?.trim()?.lowercase()
|
val displayKind = item.displayKind?.trim()?.lowercase()
|
||||||
if (displayKind == "hidden") return@mapNotNull null
|
if (displayKind == "hidden") return@mapNotNull null
|
||||||
|
val activitySourceId = if (displayKind == "async_delegation_complete") {
|
||||||
|
item.displayMetadata.stringField("delegation_id")?.let { "delegation:$it" }
|
||||||
|
?: "unavailable:${item.id}"
|
||||||
|
} else null
|
||||||
|
val activityTaskCount = if (activitySourceId != null) item.displayMetadata.intField("task_count") else null
|
||||||
|
val activityFailedCount = if (activitySourceId != null) item.displayMetadata.intField("failed_count") else null
|
||||||
val role = when {
|
val role = when {
|
||||||
displayKind == "model_switch" ||
|
displayKind == "model_switch" ||
|
||||||
displayKind == "async_delegation_complete" ||
|
displayKind == "async_delegation_complete" ||
|
||||||
@@ -1540,19 +1546,28 @@ class ChatHandler {
|
|||||||
val prior = priorById[messageId]
|
val prior = priorById[messageId]
|
||||||
// Outbound attachments: prefer an id-match (covers any future
|
// Outbound attachments: prefer an id-match (covers any future
|
||||||
// user-message id reconciliation), else fall back to the
|
// user-message id reconciliation), else fall back to the
|
||||||
// content-keyed queue. Inbound attachments normally come back via
|
// content-keyed queue. Exact inbound marker attachments are also
|
||||||
// marker re-dispatch. One narrow exception retains a completed
|
// carried by id: a history refresh must not replace a successfully
|
||||||
// image_generate result when the immediate post-turn history read
|
// loaded image/file with a fresh LOADING placeholder. A process
|
||||||
// still lacks its MEDIA marker; otherwise the rendered image
|
// restart has no prior attachment, so the marker still dispatches
|
||||||
// disappears during the persistence-lag window.
|
// 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 carriedAttachments = run {
|
||||||
val persistedImagePaths = persistedImages.paths.toHashSet()
|
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 ->
|
val priorGeneratedImage = prior?.toolCalls.orEmpty().any { tool ->
|
||||||
isImageGenerationToolName(tool.name) &&
|
isImageGenerationToolName(tool.name) &&
|
||||||
tool.isComplete && tool.success != false
|
tool.isComplete && tool.success != false
|
||||||
}
|
}
|
||||||
val byId = prior?.attachments.orEmpty().filter { attachment ->
|
val byId = prior?.attachments.orEmpty().filter { attachment ->
|
||||||
attachment.relayToken == null ||
|
attachment.relayToken == null ||
|
||||||
|
attachment.relayToken in persistedMediaKeys ||
|
||||||
(role == MessageRole.USER && attachment.relayToken in persistedImagePaths) ||
|
(role == MessageRole.USER && attachment.relayToken in persistedImagePaths) ||
|
||||||
(
|
(
|
||||||
role == MessageRole.ASSISTANT &&
|
role == MessageRole.ASSISTANT &&
|
||||||
@@ -1602,6 +1617,9 @@ class ChatHandler {
|
|||||||
// this as the same visible row across the post-turn reload.
|
// this as the same visible row across the post-turn reload.
|
||||||
prior.copy(
|
prior.copy(
|
||||||
id = messageId,
|
id = messageId,
|
||||||
|
activitySourceId = activitySourceId,
|
||||||
|
activityTaskCount = activityTaskCount,
|
||||||
|
activityFailedCount = activityFailedCount,
|
||||||
rowId = item.resolvedRowId,
|
rowId = item.resolvedRowId,
|
||||||
reactions = item.reactions,
|
reactions = item.reactions,
|
||||||
role = role,
|
role = role,
|
||||||
@@ -1634,6 +1652,9 @@ class ChatHandler {
|
|||||||
// nothing local to carry).
|
// nothing local to carry).
|
||||||
ChatMessage(
|
ChatMessage(
|
||||||
id = messageId,
|
id = messageId,
|
||||||
|
activitySourceId = activitySourceId,
|
||||||
|
activityTaskCount = activityTaskCount,
|
||||||
|
activityFailedCount = activityFailedCount,
|
||||||
rowId = item.resolvedRowId,
|
rowId = item.resolvedRowId,
|
||||||
reactions = item.reactions,
|
reactions = item.reactions,
|
||||||
role = role,
|
role = role,
|
||||||
@@ -1708,15 +1729,27 @@ class ChatHandler {
|
|||||||
is MediaMarkerHit.RelayToken -> {
|
is MediaMarkerHit.RelayToken -> {
|
||||||
val dedupeKey = "$messageId:relay:${hit.token}"
|
val dedupeKey = "$messageId:relay:${hit.token}"
|
||||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||||
Log.d(TAG, "Media marker accepted from reloaded Relay history")
|
val alreadyHydrated = _messages.value
|
||||||
onMediaAttachmentRequested(messageId, hit.token)
|
.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 -> {
|
is MediaMarkerHit.BarePath -> {
|
||||||
val dedupeKey = "$messageId:bare:${hit.path}"
|
val dedupeKey = "$messageId:bare:${hit.path}"
|
||||||
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
if (dispatchedMediaMarkers.add(dedupeKey)) {
|
||||||
Log.d(TAG, "Media marker (bare-path, reload): ${hit.path}")
|
val alreadyHydrated = _messages.value
|
||||||
onMediaBarePathRequested(messageId, hit.path)
|
.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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+180
-6
@@ -49,6 +49,7 @@ import okhttp3.Request
|
|||||||
import okhttp3.RequestBody
|
import okhttp3.RequestBody
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import okhttp3.Response
|
import okhttp3.Response
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
import java.io.OutputStream
|
import java.io.OutputStream
|
||||||
@@ -293,6 +294,34 @@ internal fun copyBounded(
|
|||||||
return written
|
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. */
|
/** One entry from `GET /api/audio/elevenlabs/voices` — non-secret voice metadata. */
|
||||||
data class ElevenLabsVoice(
|
data class ElevenLabsVoice(
|
||||||
val voiceId: String,
|
val voiceId: String,
|
||||||
@@ -310,6 +339,19 @@ data class ElevenLabsVoices(
|
|||||||
val voices: List<ElevenLabsVoice>,
|
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).
|
* Native client for the Hermes dashboard/admin server (:9119).
|
||||||
*
|
*
|
||||||
@@ -381,6 +423,58 @@ class DashboardApiClient(
|
|||||||
executeJsonElement(request, normalized)
|
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(
|
suspend fun postJsonObject(
|
||||||
path: String,
|
path: String,
|
||||||
payload: JsonObject = JsonObject(emptyMap()),
|
payload: JsonObject = JsonObject(emptyMap()),
|
||||||
@@ -1262,7 +1356,7 @@ class DashboardApiClient(
|
|||||||
suspend fun getSessionMessages(
|
suspend fun getSessionMessages(
|
||||||
sessionId: String,
|
sessionId: String,
|
||||||
profile: String? = null,
|
profile: String? = null,
|
||||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||||
): Result<List<MessageItem>> = withContext(Dispatchers.IO) {
|
): Result<List<MessageItem>> = withContext(Dispatchers.IO) {
|
||||||
val name = profile?.trim().orEmpty()
|
val name = profile?.trim().orEmpty()
|
||||||
loadSessionMessages(mode) { page ->
|
loadSessionMessages(mode) { page ->
|
||||||
@@ -1431,10 +1525,14 @@ class DashboardApiClient(
|
|||||||
password: String,
|
password: String,
|
||||||
next: String = "/",
|
next: String = "/",
|
||||||
): Result<DashboardLoginResponse> = withContext(Dispatchers.IO) {
|
): Result<DashboardLoginResponse> = withContext(Dispatchers.IO) {
|
||||||
|
// Match the Dashboard's single-line HTML username/password controls:
|
||||||
|
// remove only forbidden line breaks and preserve every other code point.
|
||||||
|
val normalizedUsername = username.replace("\r", "").replace("\n", "")
|
||||||
|
val normalizedPassword = password.replace("\r", "").replace("\n", "")
|
||||||
val payload = buildJsonObject {
|
val payload = buildJsonObject {
|
||||||
put("provider", provider)
|
put("provider", provider)
|
||||||
put("username", username)
|
put("username", normalizedUsername)
|
||||||
put("password", password)
|
put("password", normalizedPassword)
|
||||||
put("next", next)
|
put("next", next)
|
||||||
}
|
}
|
||||||
val httpUrl = resolveUrl("/auth/password-login")
|
val httpUrl = resolveUrl("/auth/password-login")
|
||||||
@@ -1666,6 +1764,7 @@ class DashboardApiClient(
|
|||||||
// Mirrors current upstream `_MANAGED_FILE_MAX_BYTES`; enforcing it
|
// Mirrors current upstream `_MANAGED_FILE_MAX_BYTES`; enforcing it
|
||||||
// client-side avoids uploading a body the Dashboard will reject.
|
// client-side avoids uploading a body the Dashboard will reject.
|
||||||
internal const val MAX_BACKUP_TRANSFER_BYTES = 100L * 1024L * 1024L
|
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 =
|
fun pathSegment(value: String): String =
|
||||||
URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
||||||
@@ -2394,17 +2493,61 @@ data class StoredDashboardCookie(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun Response.readJsonObject(json: Json): JsonObject {
|
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())
|
if (raw.isBlank()) return JsonObject(emptyMap())
|
||||||
return json.parseToJsonElement(raw).jsonObject
|
return json.parseToJsonElement(raw).jsonObject
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun Response.readJsonElement(json: Json): JsonElement {
|
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())
|
if (raw.isBlank()) return JsonObject(emptyMap())
|
||||||
return json.parseToJsonElement(raw)
|
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(
|
internal class DashboardHttpException(
|
||||||
val statusCode: Int,
|
val statusCode: Int,
|
||||||
message: String,
|
message: String,
|
||||||
@@ -2448,8 +2591,39 @@ internal fun Throwable.isDashboardSignInRequiredFailure(): Boolean {
|
|||||||
return false
|
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 {
|
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 }
|
val detail = bodyDetail.take(240).ifBlank { response.message }
|
||||||
return DashboardHttpException(
|
return DashboardHttpException(
|
||||||
statusCode = response.code,
|
statusCode = response.code,
|
||||||
|
|||||||
+320
-24
@@ -119,6 +119,10 @@ class GatewayChatClient(
|
|||||||
private val promptSubmitTimeoutMs: Long = PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,
|
private val promptSubmitTimeoutMs: Long = PROMPT_SUBMIT_REQUEST_TIMEOUT_MS,
|
||||||
/** Test seam — idle-progress watchdog base. Production keeps [TURN_TIMEOUT_MS]. */
|
/** Test seam — idle-progress watchdog base. Production keeps [TURN_TIMEOUT_MS]. */
|
||||||
private val turnIdleTimeoutMs: Long = 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. */
|
/** Random source for ordinary reconnect full-jitter. */
|
||||||
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
|
private val reconnectJitterUnit: () -> Double = { kotlin.random.Random.nextDouble() },
|
||||||
) : GatewayProfileEditorClient {
|
) : GatewayProfileEditorClient {
|
||||||
@@ -159,6 +163,19 @@ class GatewayChatClient(
|
|||||||
private const val ASK_SUDO_TIMEOUT_MS = 150_000L
|
private const val ASK_SUDO_TIMEOUT_MS = 150_000L
|
||||||
private const val ASK_UNBOUNDED_TIMEOUT_MS = 600_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
|
private const val RPC_TIMEOUT_MS = 15_000L
|
||||||
const val PROFILE_AVATAR_MAX_BYTES = 2_000_000
|
const val PROFILE_AVATAR_MAX_BYTES = 2_000_000
|
||||||
|
|
||||||
@@ -176,6 +193,7 @@ class GatewayChatClient(
|
|||||||
* would have been abandoned server-side anyway.
|
* would have been abandoned server-side anyway.
|
||||||
*/
|
*/
|
||||||
private const val PROMPT_SUBMIT_REQUEST_TIMEOUT_MS = 1_800_000L
|
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
|
private const val CONNECT_TIMEOUT_MS = 20_000L
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -263,7 +281,7 @@ class GatewayChatClient(
|
|||||||
.newBuilder()
|
.newBuilder()
|
||||||
// The 10s default connectTimeout is LAN-tuned; a remote dashboard
|
// The 10s default connectTimeout is LAN-tuned; a remote dashboard
|
||||||
// reached over Tailscale (DERP cold start) can take longer to complete
|
// 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.
|
// 5s cooldown, so give the first remote handshake room.
|
||||||
.connectTimeout(20, TimeUnit.SECONDS)
|
.connectTimeout(20, TimeUnit.SECONDS)
|
||||||
.pingInterval(30, TimeUnit.SECONDS)
|
.pingInterval(30, TimeUnit.SECONDS)
|
||||||
@@ -384,12 +402,24 @@ class GatewayChatClient(
|
|||||||
private val _serverProject = MutableStateFlow<GatewaySessionProject?>(null)
|
private val _serverProject = MutableStateFlow<GatewaySessionProject?>(null)
|
||||||
val serverProject: StateFlow<GatewaySessionProject?> = _serverProject.asStateFlow()
|
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. */
|
/** Serializes connect / session-establish so concurrent sends share one socket. */
|
||||||
private val connectMutex = Mutex()
|
private val connectMutex = Mutex()
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var webSocket: WebSocket? = null
|
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. */
|
/** Completed when the server's `gateway.ready` event arrives for the current socket. */
|
||||||
@Volatile
|
@Volatile
|
||||||
private var readySignal: CompletableDeferred<Unit>? = null
|
private var readySignal: CompletableDeferred<Unit>? = null
|
||||||
@@ -398,6 +428,12 @@ class GatewayChatClient(
|
|||||||
/** Invalidates an older async prewarm when a newer session selection wins. */
|
/** Invalidates an older async prewarm when a newer session selection wins. */
|
||||||
private val prewarmRequestGeneration = AtomicLong(0)
|
private val prewarmRequestGeneration = AtomicLong(0)
|
||||||
private val pendingRpcs = ConcurrentHashMap<Long, CompletableDeferred<JsonObject>>()
|
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>>()
|
||||||
|
private val sessionReadyFailures = ConcurrentHashMap<String, String>()
|
||||||
|
private val _preparingSessionId = MutableStateFlow<String?>(null)
|
||||||
|
val preparingSessionId: StateFlow<String?> = _preparingSessionId.asStateFlow()
|
||||||
|
|
||||||
/** Monotonic client-local fence for lazy child watch open/close races. */
|
/** Monotonic client-local fence for lazy child watch open/close races. */
|
||||||
private val childWatchGeneration = AtomicLong(0)
|
private val childWatchGeneration = AtomicLong(0)
|
||||||
@@ -548,6 +584,28 @@ class GatewayChatClient(
|
|||||||
val terminalRequired: Boolean,
|
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
|
* Creates UI callbacks when the server starts a turn that has no matching
|
||||||
* [sendTurn] call (for example a background-process completion). The
|
* [sendTurn] call (for example a background-process completion). The
|
||||||
@@ -578,6 +636,13 @@ class GatewayChatClient(
|
|||||||
@Volatile
|
@Volatile
|
||||||
private var processEventListener: ((GatewayProcessEvent) -> Unit)? = null
|
private var processEventListener: ((GatewayProcessEvent) -> Unit)? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var subagentEventListener: ((String, String?, GatewaySubagentEvent) -> Unit)? = null
|
||||||
|
|
||||||
|
fun setSubagentEventListener(listener: ((String, String?, GatewaySubagentEvent) -> Unit)?) {
|
||||||
|
subagentEventListener = listener
|
||||||
|
}
|
||||||
|
|
||||||
/** Process-wide durable-session invalidation/liveness edge. */
|
/** Process-wide durable-session invalidation/liveness edge. */
|
||||||
@Volatile
|
@Volatile
|
||||||
private var sessionDirectoryInvalidationListener: (() -> Unit)? = null
|
private var sessionDirectoryInvalidationListener: (() -> Unit)? = null
|
||||||
@@ -677,6 +742,7 @@ class GatewayChatClient(
|
|||||||
): ActiveTurnHandle {
|
): ActiveTurnHandle {
|
||||||
val turn = GatewayTurn(
|
val turn = GatewayTurn(
|
||||||
callbacks = dispatchOn(callbacks),
|
callbacks = dispatchOn(callbacks),
|
||||||
|
androidOwned = true,
|
||||||
onTransportAccepted = onTransportAccepted,
|
onTransportAccepted = onTransportAccepted,
|
||||||
)
|
)
|
||||||
// Warm = the connection-establish phases are skipped this turn (socket
|
// Warm = the connection-establish phases are skipped this turn (socket
|
||||||
@@ -724,6 +790,10 @@ class GatewayChatClient(
|
|||||||
cleanupStagedAttachments(stagedImagePaths)
|
cleanupStagedAttachments(stagedImagePaths)
|
||||||
return@launch
|
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
|
activeTurn = turn
|
||||||
turn.armWatchdog()
|
turn.armWatchdog()
|
||||||
// Generic `file.attach` uploads are staged artifacts, not
|
// Generic `file.attach` uploads are staged artifacts, not
|
||||||
@@ -758,7 +828,7 @@ class GatewayChatClient(
|
|||||||
// Once this turn's own events are flowing (or it already
|
// Once this turn's own events are flowing (or it already
|
||||||
// finished), the prompt provably reached the server — a
|
// finished), the prompt provably reached the server — a
|
||||||
// slow, lost, or socket-severed ack must NOT preflight-fail
|
// 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
|
// prompt as a duplicate turn. Recovery belongs to the
|
||||||
// stream: the watchdog and mid-turn rejoin own it.
|
// stream: the watchdog and mid-turn rejoin own it.
|
||||||
if (turn.started || turn.ended || turn.transportRecoveryStarted) {
|
if (turn.started || turn.ended || turn.transportRecoveryStarted) {
|
||||||
@@ -782,7 +852,7 @@ class GatewayChatClient(
|
|||||||
// through the normal failed-turn callback instead.
|
// through the normal failed-turn callback instead.
|
||||||
cleanupStagedAttachments(stagedImagePaths)
|
cleanupStagedAttachments(stagedImagePaths)
|
||||||
turn.tracer.done("submit-rejected")
|
turn.tracer.done("submit-rejected")
|
||||||
turn.callbacks.onError(
|
turn.callbacks.onSubmitRejected(
|
||||||
submitError?.message ?: "Hermes rejected the new session",
|
submitError?.message ?: "Hermes rejected the new session",
|
||||||
)
|
)
|
||||||
return@launch
|
return@launch
|
||||||
@@ -849,7 +919,11 @@ class GatewayChatClient(
|
|||||||
liveSessionId = null
|
liveSessionId = null
|
||||||
storedSessionId = null
|
storedSessionId = null
|
||||||
liveSessionProfile = null
|
liveSessionProfile = null
|
||||||
|
failSessionReadyWaiters("gateway session cleared")
|
||||||
|
lazyLiveSessions.clear()
|
||||||
|
readyLiveSessions.clear()
|
||||||
cancelledTurnDrain = null
|
cancelledTurnDrain = null
|
||||||
|
_serverTools.value = null
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1363,6 +1437,7 @@ class GatewayChatClient(
|
|||||||
callbacks = dispatchOn(callbacks),
|
callbacks = dispatchOn(callbacks),
|
||||||
dedupeAdjacentMessageStarts = true,
|
dedupeAdjacentMessageStarts = true,
|
||||||
deferEvents = true,
|
deferEvents = true,
|
||||||
|
androidOwned = true,
|
||||||
).also { turn ->
|
).also { turn ->
|
||||||
turn.markRecoveredStarted()
|
turn.markRecoveredStarted()
|
||||||
activeTurn = turn
|
activeTurn = turn
|
||||||
@@ -1486,6 +1561,7 @@ class GatewayChatClient(
|
|||||||
boundTurn = GatewayTurn(
|
boundTurn = GatewayTurn(
|
||||||
callbacks = dispatchOn(callbacks),
|
callbacks = dispatchOn(callbacks),
|
||||||
dedupeAdjacentMessageStarts = true,
|
dedupeAdjacentMessageStarts = true,
|
||||||
|
androidOwned = true,
|
||||||
).also { turn ->
|
).also { turn ->
|
||||||
turn.markRecoveredStarted()
|
turn.markRecoveredStarted()
|
||||||
activeTurn = turn
|
activeTurn = turn
|
||||||
@@ -1497,7 +1573,10 @@ class GatewayChatClient(
|
|||||||
.orEmpty()
|
.orEmpty()
|
||||||
.also { recoveryEvents = null }
|
.also { recoveryEvents = null }
|
||||||
}
|
}
|
||||||
buffered.forEach { event -> boundTurn?.onEvent(event.type, event.payload) }
|
buffered.forEach { event ->
|
||||||
|
dispatchSubagentEvent(event.type, event.payload, event.sessionId)
|
||||||
|
boundTurn.onEvent(event.type, event.payload)
|
||||||
|
}
|
||||||
queued?.let { queuedTurn ->
|
queued?.let { queuedTurn ->
|
||||||
queuedTurnProvider?.invoke(queuedTurn)?.let { registration ->
|
queuedTurnProvider?.invoke(queuedTurn)?.let { registration ->
|
||||||
boundTurn.installQueuedSuccessor(registration)
|
boundTurn.installQueuedSuccessor(registration)
|
||||||
@@ -1519,6 +1598,7 @@ class GatewayChatClient(
|
|||||||
val queuedTurn = GatewayTurn(
|
val queuedTurn = GatewayTurn(
|
||||||
callbacks = dispatchOn(registration.callbacks),
|
callbacks = dispatchOn(registration.callbacks),
|
||||||
dedupeAdjacentMessageStarts = true,
|
dedupeAdjacentMessageStarts = true,
|
||||||
|
androidOwned = true,
|
||||||
)
|
)
|
||||||
// recoverTurn is resumed on its caller's coroutine context;
|
// recoverTurn is resumed on its caller's coroutine context;
|
||||||
// ChatViewModel calls it from Main, so this admission runs
|
// ChatViewModel calls it from Main, so this admission runs
|
||||||
@@ -1765,18 +1845,17 @@ class GatewayChatClient(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Provider-neutral account limits owned by upstream Hermes. Current hosts
|
* Official upstream Nous usage bars. Current hosts may not expose this
|
||||||
* may not expose this additive method yet; callers should treat JSON-RPC
|
* additive method yet; callers should treat JSON-RPC method-not-found as
|
||||||
* method-not-found as capability absence and use the optional Relay
|
* capability absence and use the optional Relay enhancement when paired.
|
||||||
* compatibility surface when paired.
|
|
||||||
*/
|
*/
|
||||||
suspend fun providerUsage(): Result<JsonObject> {
|
suspend fun usageBars(): Result<JsonObject> {
|
||||||
try {
|
try {
|
||||||
connectMutex.withLock { ensureConnected() }
|
connectMutex.withLock { ensureConnected() }
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
return Result.failure(e)
|
return Result.failure(e)
|
||||||
}
|
}
|
||||||
return rpc("account.usage", JsonObject(emptyMap()))
|
return rpc("usage.bars", JsonObject(emptyMap()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -2414,6 +2493,7 @@ class GatewayChatClient(
|
|||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
return GatewayActiveSessionsResult.TransientFailure(error)
|
return GatewayActiveSessionsResult.TransientFailure(error)
|
||||||
}
|
}
|
||||||
|
val livenessProbe = captureActiveTurnLivenessProbe()
|
||||||
val result = rpc(
|
val result = rpc(
|
||||||
"session.active_list",
|
"session.active_list",
|
||||||
buildJsonObject {
|
buildJsonObject {
|
||||||
@@ -2433,12 +2513,58 @@ class GatewayChatClient(
|
|||||||
val payload = result.getOrThrow()
|
val payload = result.getOrThrow()
|
||||||
val rows = payload["sessions"] as? JsonArray
|
val rows = payload["sessions"] as? JsonArray
|
||||||
?: throw GatewayRpcException("session.active_list returned no sessions array")
|
?: 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) {
|
} catch (parseError: Exception) {
|
||||||
GatewayActiveSessionsResult.TransientFailure(parseError)
|
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. */
|
/** Stop one process owned by the current live gateway session. */
|
||||||
suspend fun killProcess(processId: String): Result<Unit> {
|
suspend fun killProcess(processId: String): Result<Unit> {
|
||||||
if (processId.isBlank()) {
|
if (processId.isBlank()) {
|
||||||
@@ -2831,11 +2957,13 @@ class GatewayChatClient(
|
|||||||
activeTurn = null
|
activeTurn = null
|
||||||
backgroundTurns.clear()
|
backgroundTurns.clear()
|
||||||
cancelledTurnDrain = null
|
cancelledTurnDrain = null
|
||||||
|
settledTurnDrain = null
|
||||||
unsolicitedTurnProvider = null
|
unsolicitedTurnProvider = null
|
||||||
coldPrewarmSessionReadyListener = null
|
coldPrewarmSessionReadyListener = null
|
||||||
unmatchedTurnCompleteListener = null
|
unmatchedTurnCompleteListener = null
|
||||||
backgroundInteractionListener = null
|
backgroundInteractionListener = null
|
||||||
processEventListener = null
|
processEventListener = null
|
||||||
|
subagentEventListener = null
|
||||||
sessionDirectoryInvalidationListener = null
|
sessionDirectoryInvalidationListener = null
|
||||||
closeSocket("client shutdown")
|
closeSocket("client shutdown")
|
||||||
backgroundCloseJob?.cancel()
|
backgroundCloseJob?.cancel()
|
||||||
@@ -2956,9 +3084,10 @@ class GatewayChatClient(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
val ticketMs = (System.nanoTime() - connectStart) / 1_000_000
|
val ticketMs = (System.nanoTime() - connectStart) / 1_000_000
|
||||||
|
val socketProfile = currentSessionProfile()
|
||||||
val url = dashboardClient.gatewayWebSocketUrl(
|
val url = dashboardClient.gatewayWebSocketUrl(
|
||||||
ticket = ticket.ticket,
|
ticket = ticket.ticket,
|
||||||
profile = currentSessionProfile(),
|
profile = socketProfile,
|
||||||
)
|
)
|
||||||
?: throw GatewayConnectAttemptException(
|
?: throw GatewayConnectAttemptException(
|
||||||
"could not build /api/ws URL",
|
"could not build /api/ws URL",
|
||||||
@@ -2992,6 +3121,7 @@ class GatewayChatClient(
|
|||||||
if (readyFailure != null) {
|
if (readyFailure != null) {
|
||||||
socket.cancel()
|
socket.cancel()
|
||||||
webSocket = null
|
webSocket = null
|
||||||
|
connectedSocketProfile = null
|
||||||
throw (readyFailure as? GatewayConnectAttemptException
|
throw (readyFailure as? GatewayConnectAttemptException
|
||||||
?: GatewayConnectAttemptException(
|
?: GatewayConnectAttemptException(
|
||||||
"gateway connection failed: ${readyFailure.message}",
|
"gateway connection failed: ${readyFailure.message}",
|
||||||
@@ -3004,6 +3134,7 @@ class GatewayChatClient(
|
|||||||
val wsMs = (System.nanoTime() - connectStart) / 1_000_000 - ticketMs
|
val wsMs = (System.nanoTime() - connectStart) / 1_000_000 - ticketMs
|
||||||
Log.i(TAG, "Gateway connected (/api/ws ready) — ticket=${ticketMs}ms ws=${wsMs}ms")
|
Log.i(TAG, "Gateway connected (/api/ws ready) — ticket=${ticketMs}ms ws=${wsMs}ms")
|
||||||
hasEverReachedReady = true
|
hasEverReachedReady = true
|
||||||
|
connectedSocketProfile = socketProfile
|
||||||
coldStartFailureEpisodes = 0
|
coldStartFailureEpisodes = 0
|
||||||
_reconnectDisposition.value = GatewayReconnectDisposition.None
|
_reconnectDisposition.value = GatewayReconnectDisposition.None
|
||||||
_connectionState.value = GatewayConnectionState.Ready
|
_connectionState.value = GatewayConnectionState.Ready
|
||||||
@@ -3134,6 +3265,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
|
// Context usage: require used > 0 — a COLD resume resets counters and
|
||||||
// reports 0 until the first turn rebuilds the prompt; painting 0 would
|
// reports 0 until the first turn rebuilds the prompt; painting 0 would
|
||||||
// mislead on a session that actually has history.
|
// mislead on a session that actually has history.
|
||||||
@@ -3149,6 +3292,7 @@ class GatewayChatClient(
|
|||||||
/** Apply a session create/resume result without leaking metadata from the prior session. */
|
/** Apply a session create/resume result without leaking metadata from the prior session. */
|
||||||
private fun applySessionResultInfo(result: JsonObject) {
|
private fun applySessionResultInfo(result: JsonObject) {
|
||||||
_serverProject.value = null
|
_serverProject.value = null
|
||||||
|
_serverTools.value = null
|
||||||
(result["info"] as? JsonObject)?.let { applySessionInfo(it) }
|
(result["info"] as? JsonObject)?.let { applySessionInfo(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3165,7 +3309,8 @@ class GatewayChatClient(
|
|||||||
?.stringField("profile_name")
|
?.stringField("profile_name")
|
||||||
?.trim()
|
?.trim()
|
||||||
?.takeIf { it.isNotEmpty() }
|
?.takeIf { it.isNotEmpty() }
|
||||||
if (actual != expected) {
|
val socketConfirmed = actual == null && connectedSocketProfile == expected
|
||||||
|
if (actual != expected && !socketConfirmed) {
|
||||||
val detail = actual?.let { "Hermes returned profile '$it'" }
|
val detail = actual?.let { "Hermes returned profile '$it'" }
|
||||||
?: "Hermes did not confirm profile ownership"
|
?: "Hermes did not confirm profile ownership"
|
||||||
throw GatewayPreflightException(
|
throw GatewayPreflightException(
|
||||||
@@ -3267,6 +3412,7 @@ class GatewayChatClient(
|
|||||||
val requestedProfile = currentSessionProfile()
|
val requestedProfile = currentSessionProfile()
|
||||||
if (requestedStoredId != null && requestedStoredId != storedSessionId) {
|
if (requestedStoredId != null && requestedStoredId != storedSessionId) {
|
||||||
cancelledTurnDrain = null
|
cancelledTurnDrain = null
|
||||||
|
settledTurnDrain = null
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
liveSessionId != null &&
|
liveSessionId != null &&
|
||||||
@@ -3274,6 +3420,7 @@ class GatewayChatClient(
|
|||||||
requestedStoredId != null &&
|
requestedStoredId != null &&
|
||||||
liveSessionProfile == requestedProfile
|
liveSessionProfile == requestedProfile
|
||||||
) {
|
) {
|
||||||
|
awaitSessionReadyIfRequired(liveSessionId!!)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3303,6 +3450,7 @@ class GatewayChatClient(
|
|||||||
liveSessionProfile = requestedProfile
|
liveSessionProfile = requestedProfile
|
||||||
updateCancelledDrainLiveSession(requestedStoredId, live)
|
updateCancelledDrainLiveSession(requestedStoredId, live)
|
||||||
applySessionResultInfo(result)
|
applySessionResultInfo(result)
|
||||||
|
awaitSessionReadyIfRequired(live, result)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
throw GatewayAuthoritativeResumeException(
|
throw GatewayAuthoritativeResumeException(
|
||||||
@@ -3336,7 +3484,54 @@ class GatewayChatClient(
|
|||||||
storedSessionId = stored
|
storedSessionId = stored
|
||||||
liveSessionProfile = requestedProfile
|
liveSessionProfile = requestedProfile
|
||||||
if (cancelledTurnDrain?.storedSessionId != stored) cancelledTurnDrain = null
|
if (cancelledTurnDrain?.storedSessionId != stored) cancelledTurnDrain = null
|
||||||
|
if (settledTurnDrain?.storedSessionId != stored) settledTurnDrain = null
|
||||||
turn.callbacks.onSessionId(stored)
|
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,
|
||||||
|
) {
|
||||||
|
sessionReadyFailures[liveId]?.let { throw GatewayPreflightException(it) }
|
||||||
|
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)
|
||||||
|
sessionReadyFailures[liveId]?.let { waiter.completeExceptionally(GatewayRpcException(it)) }
|
||||||
|
val preparingStoredId = storedSessionId
|
||||||
|
_preparingSessionId.value = preparingStoredId
|
||||||
|
try {
|
||||||
|
withTimeout(sessionReadyTimeoutMs) { waiter.await() }
|
||||||
|
lazyLiveSessions.remove(liveId)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
throw GatewayPreflightException(
|
||||||
|
error.message ?: "Hermes session initialization timed out",
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
if (_preparingSessionId.value == preparingStoredId) _preparingSessionId.value = null
|
||||||
|
sessionReadyWaiters.remove(liveId, waiter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun failSessionReadyWaiters(message: String) {
|
||||||
|
_preparingSessionId.value = null
|
||||||
|
sessionReadyFailures.clear()
|
||||||
|
sessionReadyWaiters.values.forEach {
|
||||||
|
it.completeExceptionally(GatewayRpcException(message))
|
||||||
|
}
|
||||||
|
sessionReadyWaiters.clear()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun createListener(ready: CompletableDeferred<Unit>) = object : WebSocketListener() {
|
private fun createListener(ready: CompletableDeferred<Unit>) = object : WebSocketListener() {
|
||||||
@@ -3515,6 +3710,40 @@ class GatewayChatClient(
|
|||||||
return
|
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
|
||||||
|
) {
|
||||||
|
sessionReadyFailures.remove(eventSessionId)
|
||||||
|
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) ||
|
||||||
|
payload?.stringField("message")?.startsWith("agent init failed:") == true)
|
||||||
|
) {
|
||||||
|
val message = payload?.stringField("message")
|
||||||
|
?: "Hermes session initialization failed"
|
||||||
|
// A fast deferred build can fail before the lazy RPC acknowledgement.
|
||||||
|
// Retain the exact runtime failure so the subsequent readiness wait
|
||||||
|
// cannot lose that edge and hang until its deadline.
|
||||||
|
if (sessionReadyFailures.size >= 64) sessionReadyFailures.keys.firstOrNull()?.let(sessionReadyFailures::remove)
|
||||||
|
sessionReadyFailures[eventSessionId] = message.take(2_000)
|
||||||
|
lazyLiveSessions.remove(eventSessionId)
|
||||||
|
readyLiveSessions.remove(eventSessionId)
|
||||||
|
sessionReadyWaiters.remove(eventSessionId)
|
||||||
|
?.completeExceptionally(GatewayRpcException(message))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Upstream emits session.reclaimed process-wide, so it is identified
|
// Upstream emits session.reclaimed process-wide, so it is identified
|
||||||
// by payload rather than params.session_id. Retire only an exact live
|
// 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.
|
// runtime we own; preserve the durable id so the next send resumes it.
|
||||||
@@ -3713,6 +3942,8 @@ class GatewayChatClient(
|
|||||||
}
|
}
|
||||||
dispatchProcessEvent(type, payload, eventSessionId)
|
dispatchProcessEvent(type, payload, eventSessionId)
|
||||||
if (consumeCancelledTurnEvent(type, eventSessionId)) return
|
if (consumeCancelledTurnEvent(type, eventSessionId)) return
|
||||||
|
if (consumeSettledTurnTerminal(type, eventSessionId)) return
|
||||||
|
dispatchSubagentEvent(type, payload, eventSessionId)
|
||||||
var turn = activeTurn
|
var turn = activeTurn
|
||||||
if (turn == null && type == "message.start") {
|
if (turn == null && type == "message.start") {
|
||||||
// Unsolicited turns are accepted only with an explicit exact live-
|
// Unsolicited turns are accepted only with an explicit exact live-
|
||||||
@@ -3774,10 +4005,25 @@ class GatewayChatClient(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deliver session-scoped process events before the active-turn gate. The
|
* Detached child updates belong to the session even between parent turns.
|
||||||
* gateway socket is process-wide, so an exact non-blank live id match is
|
* Recheck socket, session, profile and listener ownership on UI dispatch.
|
||||||
* required; missing/foreign ids must never leak another window's process.
|
|
||||||
*/
|
*/
|
||||||
|
private fun dispatchSubagentEvent(type: String, payload: JsonObject?, eventSessionId: String?) {
|
||||||
|
val liveId = liveSessionId ?: return
|
||||||
|
val storedId = storedSessionId ?: return
|
||||||
|
if (eventSessionId.isNullOrBlank() || eventSessionId != liveId) return
|
||||||
|
val event = GatewayEventMapper.parseSubagentEvent(type, payload) ?: return
|
||||||
|
val profile = liveSessionProfile
|
||||||
|
val socket = webSocket
|
||||||
|
val listener = subagentEventListener ?: return
|
||||||
|
callbackDispatcher {
|
||||||
|
if (webSocket === socket && liveSessionId == liveId && storedSessionId == storedId &&
|
||||||
|
liveSessionProfile == profile && subagentEventListener === listener
|
||||||
|
) listener(storedId, profile, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Process updates likewise require an exact live-session match before turn admission. */
|
||||||
private fun dispatchProcessEvent(type: String, payload: JsonObject?, eventSessionId: String?) {
|
private fun dispatchProcessEvent(type: String, payload: JsonObject?, eventSessionId: String?) {
|
||||||
val liveId = liveSessionId ?: return
|
val liveId = liveSessionId ?: return
|
||||||
if (eventSessionId.isNullOrBlank() || eventSessionId != liveId) return
|
if (eventSessionId.isNullOrBlank() || eventSessionId != liveId) return
|
||||||
@@ -3828,6 +4074,7 @@ class GatewayChatClient(
|
|||||||
// id on the shared gateway stream) keeps matching after reconnect.
|
// id on the shared gateway stream) keeps matching after reconnect.
|
||||||
val preservedLiveId = liveSessionId
|
val preservedLiveId = liveSessionId
|
||||||
webSocket = null
|
webSocket = null
|
||||||
|
connectedSocketProfile = null
|
||||||
readySignal = null
|
readySignal = null
|
||||||
liveSessionId = null
|
liveSessionId = null
|
||||||
attachMethodForSocket = null
|
attachMethodForSocket = null
|
||||||
@@ -3841,6 +4088,9 @@ class GatewayChatClient(
|
|||||||
it.completeExceptionally(GatewayRpcException("gateway connection lost"))
|
it.completeExceptionally(GatewayRpcException("gateway connection lost"))
|
||||||
}
|
}
|
||||||
pendingRpcs.clear()
|
pendingRpcs.clear()
|
||||||
|
failSessionReadyWaiters("gateway connection lost")
|
||||||
|
lazyLiveSessions.clear()
|
||||||
|
readyLiveSessions.clear()
|
||||||
failChildWatches("Child watch disconnected from the gateway")
|
failChildWatches("Child watch disconnected from the gateway")
|
||||||
val turn = activeTurn
|
val turn = activeTurn
|
||||||
if (turn == null) {
|
if (turn == null) {
|
||||||
@@ -4016,8 +4266,12 @@ class GatewayChatClient(
|
|||||||
private fun closeSocket(reason: String) {
|
private fun closeSocket(reason: String) {
|
||||||
webSocket?.close(1000, reason)
|
webSocket?.close(1000, reason)
|
||||||
webSocket = null
|
webSocket = null
|
||||||
|
connectedSocketProfile = null
|
||||||
readySignal = null
|
readySignal = null
|
||||||
liveSessionId = null
|
liveSessionId = null
|
||||||
|
failSessionReadyWaiters("gateway socket closed")
|
||||||
|
lazyLiveSessions.clear()
|
||||||
|
readyLiveSessions.clear()
|
||||||
attachMethodForSocket = null
|
attachMethodForSocket = null
|
||||||
commandsCatalogCache = null
|
commandsCatalogCache = null
|
||||||
_processCapability.value = GatewayProcessCapability.Unknown
|
_processCapability.value = GatewayProcessCapability.Unknown
|
||||||
@@ -4226,10 +4480,12 @@ class GatewayChatClient(
|
|||||||
// ------------------------------------------------------------------
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
/** Per-event idle-watchdog duration — asks block server-side with no events, so they arm longer. */
|
/** Per-event idle-watchdog duration — asks block server-side with no events, so they arm longer. */
|
||||||
private fun watchdogTimeoutFor(eventType: String): Long = when (eventType) {
|
private fun watchdogTimeoutFor(eventType: String, payload: JsonObject? = null): Long = when {
|
||||||
"clarify.request", "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
eventType == "clarify.request" || eventType == "secret.request" -> ASK_CLARIFY_SECRET_TIMEOUT_MS
|
||||||
"sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
eventType == "sudo.request" -> ASK_SUDO_TIMEOUT_MS
|
||||||
"approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
eventType == "approval.request" -> ASK_UNBOUNDED_TIMEOUT_MS
|
||||||
|
eventType == "status.update" &&
|
||||||
|
payload?.stringField("kind") == "compacting" -> compactingTimeoutMs
|
||||||
else -> turnIdleTimeoutMs
|
else -> turnIdleTimeoutMs
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4237,6 +4493,7 @@ class GatewayChatClient(
|
|||||||
val callbacks: GatewayTurnCallbacks,
|
val callbacks: GatewayTurnCallbacks,
|
||||||
dedupeAdjacentMessageStarts: Boolean = false,
|
dedupeAdjacentMessageStarts: Boolean = false,
|
||||||
deferEvents: Boolean = false,
|
deferEvents: Boolean = false,
|
||||||
|
private val androidOwned: Boolean = false,
|
||||||
private val onTransportAccepted: () -> Unit = { },
|
private val onTransportAccepted: () -> Unit = { },
|
||||||
) : ActiveTurnHandle {
|
) : ActiveTurnHandle {
|
||||||
private val mapper = GatewayEventMapper(callbacks, dedupeAdjacentMessageStarts)
|
private val mapper = GatewayEventMapper(callbacks, dedupeAdjacentMessageStarts)
|
||||||
@@ -4263,6 +4520,7 @@ class GatewayChatClient(
|
|||||||
|
|
||||||
private val rejoinAttempts = java.util.concurrent.atomic.AtomicInteger(0)
|
private val rejoinAttempts = java.util.concurrent.atomic.AtomicInteger(0)
|
||||||
private val transportAccepted = AtomicBoolean(false)
|
private val transportAccepted = AtomicBoolean(false)
|
||||||
|
private val progressGeneration = java.util.concurrent.atomic.AtomicLong(0L)
|
||||||
|
|
||||||
fun markTransportAccepted() {
|
fun markTransportAccepted() {
|
||||||
if (transportAccepted.compareAndSet(false, true)) {
|
if (transportAccepted.compareAndSet(false, true)) {
|
||||||
@@ -4339,6 +4597,7 @@ class GatewayChatClient(
|
|||||||
if (settledWithoutTerminalFrame) return
|
if (settledWithoutTerminalFrame) return
|
||||||
if (type != "session.info") {
|
if (type != "session.info") {
|
||||||
started = true
|
started = true
|
||||||
|
progressGeneration.incrementAndGet()
|
||||||
markTransportAccepted()
|
markTransportAccepted()
|
||||||
}
|
}
|
||||||
tracer.mark("ttfe")
|
tracer.mark("ttfe")
|
||||||
@@ -4348,7 +4607,7 @@ class GatewayChatClient(
|
|||||||
// Reset on every event — long tool runs keep the turn alive.
|
// Reset on every event — long tool runs keep the turn alive.
|
||||||
// Ask requests block with no further events, so they arm with
|
// Ask requests block with no further events, so they arm with
|
||||||
// their own (longer) duration via watchdogTimeoutFor.
|
// their own (longer) duration via watchdogTimeoutFor.
|
||||||
armWatchdog(watchdogTimeoutFor(type))
|
armWatchdog(watchdogTimeoutFor(type, payload))
|
||||||
// Queue this immediately before the terminal callbacks. Both are
|
// Queue this immediately before the terminal callbacks. Both are
|
||||||
// marshalled through the same dispatcher, preserving callback order
|
// marshalled through the same dispatcher, preserving callback order
|
||||||
// even when the WebSocket reader and reconnect coroutine differ.
|
// even when the WebSocket reader and reconnect coroutine differ.
|
||||||
@@ -4368,10 +4627,20 @@ class GatewayChatClient(
|
|||||||
* exact turn has proved it went live. A pre-start `running=false`
|
* exact turn has proved it went live. A pre-start `running=false`
|
||||||
* heartbeat can race `prompt.submit` and is not a completion boundary.
|
* 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
|
if (running != false || !started) return false
|
||||||
val settled = synchronized(deferredEventLock) {
|
val settled = synchronized(deferredEventLock) {
|
||||||
if (ended) {
|
if (ended ||
|
||||||
|
(expectedProgressGeneration != null &&
|
||||||
|
progressGeneration.get() != expectedProgressGeneration)
|
||||||
|
) {
|
||||||
false
|
false
|
||||||
} else {
|
} else {
|
||||||
settledWithoutTerminalFrame = true
|
settledWithoutTerminalFrame = true
|
||||||
@@ -4382,6 +4651,7 @@ class GatewayChatClient(
|
|||||||
if (!settled) return false
|
if (!settled) return false
|
||||||
|
|
||||||
disarmWatchdog()
|
disarmWatchdog()
|
||||||
|
armSettledTurnDrain()
|
||||||
Log.i(TAG, "Gateway turn settled from $source after missing terminal frame")
|
Log.i(TAG, "Gateway turn settled from $source after missing terminal frame")
|
||||||
callbacks.onReconcileRequired()
|
callbacks.onReconcileRequired()
|
||||||
callbacks.onComplete()
|
callbacks.onComplete()
|
||||||
@@ -4402,6 +4672,7 @@ class GatewayChatClient(
|
|||||||
callbacks = dispatchOn(registration.callbacks),
|
callbacks = dispatchOn(registration.callbacks),
|
||||||
dedupeAdjacentMessageStarts = true,
|
dedupeAdjacentMessageStarts = true,
|
||||||
deferEvents = true,
|
deferEvents = true,
|
||||||
|
androidOwned = true,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4529,6 +4800,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) {
|
private fun updateCancelledDrainLiveSession(storedId: String, liveId: String) {
|
||||||
val drain = cancelledTurnDrain ?: return
|
val drain = cancelledTurnDrain ?: return
|
||||||
if (drain.storedSessionId == storedId) {
|
if (drain.storedSessionId == storedId) {
|
||||||
@@ -4655,6 +4946,11 @@ class GatewayChatClient(
|
|||||||
dispatchIfCurrent(stillCurrent) { callbacks.onStatusUpdate(kind, text) }
|
dispatchIfCurrent(stillCurrent) { callbacks.onStatusUpdate(kind, text) }
|
||||||
},
|
},
|
||||||
onStatusClear = { kind -> dispatchIfCurrent(stillCurrent) { callbacks.onStatusClear(kind) } },
|
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) {
|
private fun dispatchIfCurrent(stillCurrent: () -> Boolean, callback: () -> Unit) {
|
||||||
@@ -4707,7 +5003,7 @@ data class GatewayAttachment(
|
|||||||
val sizeBytes: Long? = null,
|
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)
|
internal class GatewayPreflightException(message: String) : Exception(message)
|
||||||
|
|
||||||
/** Attachment bytes were not safely bound to a Gateway turn; never silently fall through to SSE. */
|
/** Attachment bytes were not safely bound to a Gateway turn; never silently fall through to SSE. */
|
||||||
|
|||||||
+112
-34
@@ -7,6 +7,7 @@ import kotlinx.serialization.json.JsonPrimitive
|
|||||||
import kotlinx.serialization.json.contentOrNull
|
import kotlinx.serialization.json.contentOrNull
|
||||||
import kotlinx.serialization.json.doubleOrNull
|
import kotlinx.serialization.json.doubleOrNull
|
||||||
import kotlinx.serialization.json.intOrNull
|
import kotlinx.serialization.json.intOrNull
|
||||||
|
import kotlinx.serialization.json.longOrNull
|
||||||
import kotlinx.serialization.json.booleanOrNull
|
import kotlinx.serialization.json.booleanOrNull
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -195,7 +196,8 @@ class GatewayEventMapper(
|
|||||||
|
|
||||||
"tool.start" -> {
|
"tool.start" -> {
|
||||||
clearActivityStatuses()
|
clearActivityStatuses()
|
||||||
val name = payload.string("name") ?: "unknown"
|
val identity = payload.effectiveToolIdentity()
|
||||||
|
val name = identity.name
|
||||||
// A pending generating placeholder for this name is adopted
|
// A pending generating placeholder for this name is adopted
|
||||||
// (consumed FIFO) whether or not the server sent a real id.
|
// (consumed FIFO) whether or not the server sent a real id.
|
||||||
val adopted = generatingIdsByName[name]?.removeFirstOrNull()
|
val adopted = generatingIdsByName[name]?.removeFirstOrNull()
|
||||||
@@ -207,7 +209,7 @@ class GatewayEventMapper(
|
|||||||
}
|
}
|
||||||
else -> syntheticToolId(name)
|
else -> syntheticToolId(name)
|
||||||
}
|
}
|
||||||
val argsPreview = payload?.get("args")
|
val argsPreview = identity.argsPreview ?: payload?.get("args")
|
||||||
?.takeUnless { it is JsonPrimitive && it.contentOrNull.isNullOrBlank() }
|
?.takeUnless { it is JsonPrimitive && it.contentOrNull.isNullOrBlank() }
|
||||||
?.toString()
|
?.toString()
|
||||||
?.takeIf { it.isNotBlank() && it != "null" }
|
?.takeIf { it.isNotBlank() && it != "null" }
|
||||||
@@ -219,7 +221,7 @@ class GatewayEventMapper(
|
|||||||
|
|
||||||
"tool.complete" -> {
|
"tool.complete" -> {
|
||||||
clearActivityStatuses()
|
clearActivityStatuses()
|
||||||
val name = payload.string("name") ?: "unknown"
|
val name = payload.effectiveToolIdentity().name
|
||||||
val toolId = payload.string("tool_id")
|
val toolId = payload.string("tool_id")
|
||||||
?: openSyntheticIdsByName[name]?.removeFirstOrNull()
|
?: openSyntheticIdsByName[name]?.removeFirstOrNull()
|
||||||
?: return
|
?: return
|
||||||
@@ -278,41 +280,19 @@ class GatewayEventMapper(
|
|||||||
|
|
||||||
"error" -> {
|
"error" -> {
|
||||||
turnEnded = true
|
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",
|
"subagent.spawn_requested", "subagent.start", "subagent.thinking", "subagent.tool",
|
||||||
"subagent.progress", "subagent.complete",
|
"subagent.progress", "subagent.complete",
|
||||||
-> {
|
-> {
|
||||||
clearActivityStatuses()
|
clearActivityStatuses()
|
||||||
val phase = when (type) {
|
parseSubagentEvent(type, payload)?.let(callbacks.onSubagentEvent)
|
||||||
"subagent.spawn_requested" -> GatewaySubagentEvent.Phase.SPAWN_REQUESTED
|
|
||||||
"subagent.start" -> GatewaySubagentEvent.Phase.START
|
|
||||||
"subagent.thinking" -> GatewaySubagentEvent.Phase.THINKING
|
|
||||||
"subagent.tool" -> GatewaySubagentEvent.Phase.TOOL
|
|
||||||
"subagent.progress" -> GatewaySubagentEvent.Phase.PROGRESS
|
|
||||||
else -> GatewaySubagentEvent.Phase.COMPLETE
|
|
||||||
}
|
|
||||||
callbacks.onSubagentEvent(
|
|
||||||
GatewaySubagentEvent(
|
|
||||||
phase = phase,
|
|
||||||
taskIndex = payload.int("task_index") ?: 0,
|
|
||||||
taskCount = payload.int("task_count") ?: 1,
|
|
||||||
goal = payload.string("goal") ?: "",
|
|
||||||
status = payload.string("status"),
|
|
||||||
summary = payload.string("summary"),
|
|
||||||
toolName = payload.string("tool_name"),
|
|
||||||
// subagent.tool sets tool_preview AND mirrors it into
|
|
||||||
// text; thinking/progress carry text only.
|
|
||||||
preview = payload.string("tool_preview") ?: payload.string("text"),
|
|
||||||
durationSeconds = payload.double("duration_seconds"),
|
|
||||||
subagentId = payload.string("subagent_id"),
|
|
||||||
childSessionId = payload.string("child_session_id"),
|
|
||||||
parentId = payload.string("parent_id"),
|
|
||||||
depth = payload.int("depth"),
|
|
||||||
model = payload.string("model"),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
"tool.output_risk" -> {
|
"tool.output_risk" -> {
|
||||||
@@ -397,8 +377,26 @@ class GatewayEventMapper(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Known-but-unrendered (notification.show, …) and unknown types
|
"notification.show" -> {
|
||||||
// alike: ignore.
|
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
|
else -> Unit
|
||||||
}
|
}
|
||||||
previousEventType = type
|
previousEventType = type
|
||||||
@@ -442,6 +440,42 @@ class GatewayEventMapper(
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
/** Shared by turn transcripts and the session-owned activity stream. */
|
||||||
|
fun parseSubagentEvent(type: String, payload: JsonObject?): GatewaySubagentEvent? {
|
||||||
|
if (type !in setOf(
|
||||||
|
"subagent.spawn_requested", "subagent.start", "subagent.thinking",
|
||||||
|
"subagent.tool", "subagent.progress", "subagent.complete",
|
||||||
|
)) return null
|
||||||
|
val phase = when (type) {
|
||||||
|
"subagent.spawn_requested" -> GatewaySubagentEvent.Phase.SPAWN_REQUESTED
|
||||||
|
"subagent.start" -> GatewaySubagentEvent.Phase.START
|
||||||
|
"subagent.thinking" -> GatewaySubagentEvent.Phase.THINKING
|
||||||
|
"subagent.tool" -> GatewaySubagentEvent.Phase.TOOL
|
||||||
|
"subagent.progress" -> GatewaySubagentEvent.Phase.PROGRESS
|
||||||
|
else -> GatewaySubagentEvent.Phase.COMPLETE
|
||||||
|
}
|
||||||
|
|
||||||
|
return GatewaySubagentEvent(
|
||||||
|
phase = phase,
|
||||||
|
taskIndex = payload.int("task_index") ?: 0,
|
||||||
|
taskCount = payload.int("task_count") ?: 1,
|
||||||
|
goal = payload.string("goal") ?: "",
|
||||||
|
status = payload.string("status"),
|
||||||
|
summary = payload.string("summary"),
|
||||||
|
toolName = payload.string("tool_name"),
|
||||||
|
// subagent.tool sets tool_preview AND mirrors it into
|
||||||
|
// text; thinking/progress carry text only.
|
||||||
|
preview = payload.string("tool_preview") ?: payload.string("text"),
|
||||||
|
durationSeconds = payload.double("duration_seconds"),
|
||||||
|
subagentId = payload.string("subagent_id"),
|
||||||
|
childSessionId = payload.string("child_session_id"),
|
||||||
|
parentId = payload.string("parent_id"),
|
||||||
|
depth = payload.int("depth"),
|
||||||
|
model = payload.string("model"),
|
||||||
|
delegationId = payload.string("delegation_id"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
const val PROVIDER_WAIT_STATUS_KIND = "provider_wait"
|
const val PROVIDER_WAIT_STATUS_KIND = "provider_wait"
|
||||||
const val COMPACTION_STATUS_KIND = "compacting"
|
const val COMPACTION_STATUS_KIND = "compacting"
|
||||||
const val ERROR_STATUS_KIND = "error"
|
const val ERROR_STATUS_KIND = "error"
|
||||||
@@ -450,6 +484,19 @@ class GatewayEventMapper(
|
|||||||
private const val MAX_MOA_REFERENCE_CHARS = 16_000
|
private const val MAX_MOA_REFERENCE_CHARS = 16_000
|
||||||
private val OUTPUT_RISK_LEVELS = setOf("low", "medium", "high", "critical")
|
private val OUTPUT_RISK_LEVELS = setOf("low", "medium", "high", "critical")
|
||||||
private val TERMINAL_EVENTS = setOf("message.complete", "error")
|
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 {
|
internal fun isFailedMoaReference(text: String): Boolean {
|
||||||
val normalized = text.trimStart().lowercase()
|
val normalized = text.trimStart().lowercase()
|
||||||
return normalized.startsWith("[failed:") || normalized.startsWith("[skipped:")
|
return normalized.startsWith("[failed:") || normalized.startsWith("[skipped:")
|
||||||
@@ -590,12 +637,43 @@ private const val MAX_CLARIFY_CHOICES = 4
|
|||||||
private const val SUDO_TIMEOUT_SECONDS = 120
|
private const val SUDO_TIMEOUT_SECONDS = 120
|
||||||
private const val SECRET_TIMEOUT_SECONDS = 300
|
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? =
|
private fun JsonObject?.string(key: String): String? =
|
||||||
(this?.get(key) as? JsonPrimitive)?.contentOrNull
|
(this?.get(key) as? JsonPrimitive)?.contentOrNull
|
||||||
|
|
||||||
private fun JsonObject?.int(key: String): Int? =
|
private fun JsonObject?.int(key: String): Int? =
|
||||||
(this?.get(key) as? JsonPrimitive)?.intOrNull
|
(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? =
|
private fun JsonObject?.double(key: String): Double? =
|
||||||
(this?.get(key) as? JsonPrimitive)?.doubleOrNull
|
(this?.get(key) as? JsonPrimitive)?.doubleOrNull
|
||||||
|
|
||||||
|
|||||||
@@ -91,26 +91,19 @@ enum class GatewayApprovalModeCapability {
|
|||||||
* is unit-testable without an AndroidViewModel. ConnectionViewModel
|
* is unit-testable without an AndroidViewModel. ConnectionViewModel
|
||||||
* delegates here with its live state.
|
* delegates here with its live state.
|
||||||
*
|
*
|
||||||
* Manual picks pass through untouched (ChatViewModel handles per-turn
|
* Manual picks pass through untouched. "auto" follows the saved connection's
|
||||||
* fallback when a "gateway" pick can't serve a send); "auto" prefers the
|
* stable owner: Dashboard/Gateway for a standard connection, or the
|
||||||
* gateway while the dashboard probe is unresolved or ready. A capability-
|
* capability-preferred SSE surface for a true API-only compatibility record.
|
||||||
* preferred SSE fallback is selected only after a definitive unavailable,
|
* Live reachability and sign-in state never change the owner of an open chat.
|
||||||
* unsupported, or sign-in-required verdict.
|
|
||||||
*/
|
*/
|
||||||
fun resolveStreamingEndpointPreference(
|
fun resolveStreamingEndpointPreference(
|
||||||
preference: String,
|
preference: String,
|
||||||
gateway: GatewayAvailability,
|
gateway: GatewayAvailability,
|
||||||
capabilities: ServerCapabilities,
|
capabilities: ServerCapabilities,
|
||||||
|
gatewayOwned: Boolean = true,
|
||||||
): String = when (preference) {
|
): String = when (preference) {
|
||||||
"sessions", "completions", "runs", "gateway" -> preference
|
"sessions", "completions", "runs", "gateway" -> preference
|
||||||
else -> if (
|
else -> if (gatewayOwned) "gateway" else capabilities.preferredChatEndpoint()
|
||||||
gateway == GatewayAvailability.Ready ||
|
|
||||||
gateway == GatewayAvailability.Unknown
|
|
||||||
) {
|
|
||||||
"gateway"
|
|
||||||
} else {
|
|
||||||
capabilities.preferredChatEndpoint()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -263,6 +256,16 @@ data class GatewayToolOutputRisk(
|
|||||||
val redacted: Boolean,
|
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
|
* One `subagent.*` lifecycle event, emitted on the PARENT session. Lifecycle
|
||||||
* per task: SPAWN_REQUESTED → START → (THINKING | TOOL | PROGRESS)* →
|
* per task: SPAWN_REQUESTED → START → (THINKING | TOOL | PROGRESS)* →
|
||||||
@@ -290,6 +293,8 @@ data class GatewaySubagentEvent(
|
|||||||
val depth: Int? = null,
|
val depth: Int? = null,
|
||||||
/** Effective child model, when the emitter exposes it. */
|
/** Effective child model, when the emitter exposes it. */
|
||||||
val model: String? = null,
|
val model: String? = null,
|
||||||
|
/** Exact delegation group id shared with persisted async completion metadata. */
|
||||||
|
val delegationId: String? = null,
|
||||||
) {
|
) {
|
||||||
enum class Phase { SPAWN_REQUESTED, START, THINKING, TOOL, PROGRESS, COMPLETE }
|
enum class Phase { SPAWN_REQUESTED, START, THINKING, TOOL, PROGRESS, COMPLETE }
|
||||||
}
|
}
|
||||||
@@ -734,6 +739,16 @@ class GatewayTurnCallbacks(
|
|||||||
val onStatusUpdate: (kind: String?, text: String) -> Unit = { _, _ -> },
|
val onStatusUpdate: (kind: String?, text: String) -> Unit = { _, _ -> },
|
||||||
/** Clear a transient status only when [kind] still owns the visible status slot. */
|
/** Clear a transient status only when [kind] still owns the visible status slot. */
|
||||||
val onStatusClear: (kind: String) -> Unit = { _ -> },
|
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(
|
suspend fun getMessages(
|
||||||
sessionId: String,
|
sessionId: String,
|
||||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
mode: SessionMessageLoadMode = SessionMessageLoadMode.LATEST,
|
||||||
): List<MessageItem> = withContext(Dispatchers.IO) {
|
): List<MessageItem> = withContext(Dispatchers.IO) {
|
||||||
loadSessionMessages(mode) { page ->
|
loadSessionMessages(mode) { page ->
|
||||||
runCatching {
|
try {
|
||||||
val url = "$baseUrl/api/sessions/$sessionId/messages".toHttpUrlOrNull()
|
val url = "$baseUrl/api/sessions/$sessionId/messages".toHttpUrlOrNull()
|
||||||
?.newBuilder()
|
?.newBuilder()
|
||||||
?.addQueryParameter("limit", page.limit.toString())
|
?.addQueryParameter("limit", page.limit.toString())
|
||||||
@@ -740,14 +740,20 @@ class HermesApiClient(
|
|||||||
val request = authRequest(url.toString()).get().build()
|
val request = authRequest(url.toString()).get().build()
|
||||||
client.newCall(request).execute().use { response ->
|
client.newCall(request).execute().use { response ->
|
||||||
if (!response.isSuccessful) error("HTTP ${response.code}")
|
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)
|
val parsed = json.decodeFromString<MessageListResponse>(body)
|
||||||
SessionMessagePage(
|
SessionMessagePage(
|
||||||
messages = parsed.data ?: parsed.items ?: parsed.messages ?: emptyList(),
|
messages = parsed.data ?: parsed.items ?: parsed.messages ?: emptyList(),
|
||||||
pagination = parsed.pagination,
|
pagination = parsed.pagination,
|
||||||
payloadChars = body.length,
|
payloadChars = body.length,
|
||||||
)
|
)
|
||||||
}
|
}.let { Result.success(it) }
|
||||||
|
} catch (error: CancellationException) {
|
||||||
|
throw error
|
||||||
|
} catch (error: Exception) {
|
||||||
|
Result.failure(error)
|
||||||
}
|
}
|
||||||
}.getOrElse { error ->
|
}.getOrElse { error ->
|
||||||
if (error is CancellationException) throw error
|
if (error is CancellationException) throw error
|
||||||
|
|||||||
+1
-1
@@ -72,7 +72,7 @@ internal suspend fun loadSessionMessages(
|
|||||||
Result.success(collected)
|
Result.success(collected)
|
||||||
} catch (error: CancellationException) {
|
} catch (error: CancellationException) {
|
||||||
throw error
|
throw error
|
||||||
} catch (error: Throwable) {
|
} catch (error: Exception) {
|
||||||
Result.failure(error)
|
Result.failure(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-3
@@ -195,7 +195,7 @@ class StandardHermesVoiceClient(
|
|||||||
.let { Result.success<VoiceSpeechStream?>(it) }
|
.let { Result.success<VoiceSpeechStream?>(it) }
|
||||||
} catch (cancelled: CancellationException) {
|
} catch (cancelled: CancellationException) {
|
||||||
throw cancelled
|
throw cancelled
|
||||||
} catch (error: Throwable) {
|
} catch (error: Exception) {
|
||||||
Result.failure(error)
|
Result.failure(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -222,7 +222,9 @@ class StandardHermesVoiceClient(
|
|||||||
if (!response.isSuccessful) {
|
if (!response.isSuccessful) {
|
||||||
return Result.failure(apiFailure(response, operation))
|
return Result.failure(apiFailure(response, operation))
|
||||||
}
|
}
|
||||||
val body = response.body.string()
|
val body = response.body.readUtf8Bounded(
|
||||||
|
DashboardApiClient.MAX_JSON_RESPONSE_BYTES,
|
||||||
|
)
|
||||||
if (body.isBlank()) {
|
if (body.isBlank()) {
|
||||||
return Result.failure(IOException("$operation returned an empty response"))
|
return Result.failure(IOException("$operation returned an empty response"))
|
||||||
}
|
}
|
||||||
@@ -245,7 +247,11 @@ class StandardHermesVoiceClient(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun apiFailure(response: Response, operation: String): IOException {
|
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 detail = body.takeIf { it.isNotBlank() } ?: response.message
|
||||||
val message = when (response.code) {
|
val message = when (response.code) {
|
||||||
400 -> "$operation rejected that input - ${detail.ifBlank { "bad request" }}"
|
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.relay.RelayHttpClient
|
||||||
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
import com.hermesandroid.relay.network.upstream.GatewayChatClient
|
||||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.JsonObject
|
||||||
import kotlinx.serialization.json.decodeFromJsonElement
|
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(
|
class ProviderUsageRepository(
|
||||||
private val gatewayClientProvider: () -> GatewayChatClient?,
|
private val gatewayClientProvider: () -> GatewayChatClient?,
|
||||||
private val dashboardClientProvider: () -> DashboardApiClient? = { null },
|
private val dashboardClientProvider: () -> DashboardApiClient? = { null },
|
||||||
@@ -14,33 +16,142 @@ class ProviderUsageRepository(
|
|||||||
private val profileProvider: () -> String? = { null },
|
private val profileProvider: () -> String? = { null },
|
||||||
private val sessionProvider: () -> String? = { null },
|
private val sessionProvider: () -> String? = { null },
|
||||||
) {
|
) {
|
||||||
private val json = Json {
|
|
||||||
ignoreUnknownKeys = true
|
|
||||||
coerceInputValues = true
|
|
||||||
explicitNulls = false
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun fetch(): Result<ProviderUsageResponse?> {
|
suspend fun fetch(): Result<ProviderUsageResponse?> {
|
||||||
val profile = profileProvider()
|
val profile = profileProvider()
|
||||||
val session = sessionProvider()
|
val session = sessionProvider()
|
||||||
|
val upstream: Result<ProviderUsageResponse?> = gatewayClientProvider()
|
||||||
|
?.usageBars()
|
||||||
|
?.mapCatching(::providerUsageFromUpstreamBars)
|
||||||
|
?: Result.success(null)
|
||||||
|
|
||||||
val dashboard = dashboardClientProvider()
|
val dashboard = dashboardClientProvider()
|
||||||
|
var enhancement: Result<ProviderUsageResponse?>? = null
|
||||||
if (dashboard != null) {
|
if (dashboard != null) {
|
||||||
val enhanced = dashboard.getProviderUsage(profile, session)
|
enhancement = dashboard.getProviderUsage(profile, session)
|
||||||
if (enhanced.isSuccess && enhanced.getOrNull() != null) return enhanced
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val relay = relayHttpClient.fetchProviderUsage(
|
if (enhancement?.getOrNull() == null) {
|
||||||
profile = profile,
|
enhancement = relayHttpClient.fetchProviderUsage(
|
||||||
sessionId = session,
|
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()
|
return when {
|
||||||
if (gateway != null) {
|
upstream.isFailure && enhancement?.isFailure == true ->
|
||||||
val upstream = gateway.providerUsage()
|
Result.failure(enhancement?.exceptionOrNull()!!)
|
||||||
.mapCatching { json.decodeFromJsonElement<ProviderUsageResponse>(it) }
|
enhancement?.isFailure == true -> Result.failure(enhancement?.exceptionOrNull()!!)
|
||||||
if (upstream.isSuccess) return upstream
|
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.VoiceAudioRoute
|
||||||
import com.hermesandroid.relay.data.VoiceEngineMode
|
import com.hermesandroid.relay.data.VoiceEngineMode
|
||||||
import com.hermesandroid.relay.data.VoicePreferencesRepository
|
import com.hermesandroid.relay.data.VoicePreferencesRepository
|
||||||
|
import com.hermesandroid.relay.data.VoiceProfileScope
|
||||||
import com.hermesandroid.relay.data.VoiceSettings
|
import com.hermesandroid.relay.data.VoiceSettings
|
||||||
import com.hermesandroid.relay.network.relay.RelayVoiceAudioClientAdapter
|
import com.hermesandroid.relay.network.relay.RelayVoiceAudioClientAdapter
|
||||||
import com.hermesandroid.relay.network.relay.RelayVoiceClient
|
import com.hermesandroid.relay.network.relay.RelayVoiceClient
|
||||||
@@ -170,6 +171,9 @@ internal class HermesRuntimeBinder(
|
|||||||
relayHttpClient = connection.relayHttpClient,
|
relayHttpClient = connection.relayHttpClient,
|
||||||
mediaSettingsRepo = connection.mediaSettingsRepo,
|
mediaSettingsRepo = connection.mediaSettingsRepo,
|
||||||
mediaCacheWriter = connection.mediaCacheWriter,
|
mediaCacheWriter = connection.mediaCacheWriter,
|
||||||
|
dashboardMediaClientProvider = {
|
||||||
|
connection.activeDashboardUrl()?.let(connection::dashboardClientForActive)
|
||||||
|
},
|
||||||
)
|
)
|
||||||
chat.setSelectedProfileProvider { connection.selectedProfile.value }
|
chat.setSelectedProfileProvider { connection.selectedProfile.value }
|
||||||
chat.setIsolatedProfileApiProvider { connection.selectedProfileUsesIsolatedApiRoute() }
|
chat.setIsolatedProfileApiProvider { connection.selectedProfileUsesIsolatedApiRoute() }
|
||||||
@@ -262,6 +266,11 @@ internal class HermesRuntimeBinder(
|
|||||||
jobs += runtime.coroutineScope.launch {
|
jobs += runtime.coroutineScope.launch {
|
||||||
chat.isStreaming.collect(connection::setChatStreaming)
|
chat.isStreaming.collect(connection::setChatStreaming)
|
||||||
}
|
}
|
||||||
|
jobs += runtime.coroutineScope.launch {
|
||||||
|
chat.conversationBinding.collect { binding ->
|
||||||
|
connection.setActiveConversationTransport(binding.transport)
|
||||||
|
}
|
||||||
|
}
|
||||||
jobs += runtime.coroutineScope.launch {
|
jobs += runtime.coroutineScope.launch {
|
||||||
combine(
|
combine(
|
||||||
connection.activeConnectionId,
|
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 {
|
jobs += runtime.coroutineScope.launch {
|
||||||
combine(
|
combine(
|
||||||
connection.streamingEndpoint,
|
connection.streamingEndpoint,
|
||||||
@@ -398,13 +437,22 @@ internal class HermesRuntimeBinder(
|
|||||||
connection.chatReady,
|
connection.chatReady,
|
||||||
connection.standardVoiceAvailability,
|
connection.standardVoiceAvailability,
|
||||||
connection.relayVoiceReady,
|
connection.relayVoiceReady,
|
||||||
connection.profileSelectionSettled,
|
connection.relayConfigured,
|
||||||
) { settings, chatReady, standard, relayReady, profileSettled ->
|
) { settings, chatReady, standard, relayReady, relayConfigured ->
|
||||||
|
VoiceReadinessInputs(
|
||||||
|
settings = settings,
|
||||||
|
chatReady = chatReady,
|
||||||
|
standardAvailability = standard,
|
||||||
|
relayReady = relayReady,
|
||||||
|
relayConfigured = relayConfigured,
|
||||||
|
)
|
||||||
|
}.combine(connection.profileSelectionSettled) { inputs, profileSettled ->
|
||||||
resolveVoiceActivationReadiness(
|
resolveVoiceActivationReadiness(
|
||||||
settings,
|
inputs.settings,
|
||||||
chatReady,
|
inputs.chatReady,
|
||||||
standard,
|
inputs.standardAvailability,
|
||||||
relayReady,
|
inputs.relayReady,
|
||||||
|
inputs.relayConfigured,
|
||||||
profileSettled,
|
profileSettled,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -558,6 +606,22 @@ internal class HermesRuntimeBinder(
|
|||||||
val hiddenSources: Set<String> = emptySet(),
|
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 {
|
private companion object {
|
||||||
const val PROFILE_SETTLE_BACKSTOP_MS = 2_500L
|
const val PROFILE_SETTLE_BACKSTOP_MS = 2_500L
|
||||||
const val PROFILE_CONTEXT_COALESCE_MS = 160L
|
const val PROFILE_CONTEXT_COALESCE_MS = 160L
|
||||||
@@ -596,12 +660,14 @@ internal fun resolveVoiceActivationReadiness(
|
|||||||
chatReady: Boolean,
|
chatReady: Boolean,
|
||||||
standardAvailability: StandardVoiceAvailability,
|
standardAvailability: StandardVoiceAvailability,
|
||||||
relayReady: Boolean,
|
relayReady: Boolean,
|
||||||
|
relayConfigured: Boolean,
|
||||||
profileSettled: Boolean,
|
profileSettled: Boolean,
|
||||||
): HermesVoiceActivationReadiness {
|
): HermesVoiceActivationReadiness {
|
||||||
if (!profileSettled) {
|
if (!profileSettled) {
|
||||||
return HermesVoiceActivationReadiness.Waiting("Loading the selected Hermes profile")
|
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 -> {
|
VoiceEngineMode.RealtimeAgent -> {
|
||||||
if (relayReady) {
|
if (relayReady) {
|
||||||
HermesVoiceActivationReadiness.Ready(HermesVoiceActivationRoute.Realtime)
|
HermesVoiceActivationReadiness.Ready(HermesVoiceActivationRoute.Realtime)
|
||||||
@@ -613,7 +679,7 @@ internal fun resolveVoiceActivationReadiness(
|
|||||||
if (!chatReady) {
|
if (!chatReady) {
|
||||||
return HermesVoiceActivationReadiness.Waiting("Waiting for Hermes chat")
|
return HermesVoiceActivationReadiness.Waiting("Waiting for Hermes chat")
|
||||||
}
|
}
|
||||||
when (VoiceAudioRoute.fromStorage(settings.audioRoute)) {
|
when (VoiceAudioRoute.fromStorage(effectiveSettings.audioRoute)) {
|
||||||
VoiceAudioRoute.Relay -> if (relayReady) {
|
VoiceAudioRoute.Relay -> if (relayReady) {
|
||||||
HermesVoiceActivationReadiness.Ready(
|
HermesVoiceActivationReadiness.Ready(
|
||||||
HermesVoiceActivationRoute.RelayAudio
|
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(
|
private fun standardVoiceReadiness(
|
||||||
availability: StandardVoiceAvailability,
|
availability: StandardVoiceAvailability,
|
||||||
): HermesVoiceActivationReadiness = when (availability) {
|
): 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
|
||||||
@@ -36,7 +36,7 @@ import androidx.compose.material.icons.filled.Settings
|
|||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.SnackbarDuration
|
import androidx.compose.material3.SnackbarDuration
|
||||||
import androidx.compose.material3.SnackbarHost
|
import com.hermesandroid.relay.ui.components.ThemedMessageHost
|
||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.SnackbarResult
|
import androidx.compose.material3.SnackbarResult
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
@@ -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.petPerchSurface
|
||||||
import com.hermesandroid.relay.ui.components.pet.platformModalOwnsPetLayer
|
import com.hermesandroid.relay.ui.components.pet.platformModalOwnsPetLayer
|
||||||
import com.hermesandroid.relay.ui.components.ConnectionSwitcherSheet
|
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.ChatTransportStatusBadge
|
||||||
import com.hermesandroid.relay.ui.components.ChatTransportTier
|
import com.hermesandroid.relay.ui.components.ChatTransportTier
|
||||||
import com.hermesandroid.relay.ui.components.ConnectionSecurityGlyph
|
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.BuildFlavor
|
||||||
import com.hermesandroid.relay.data.CandidateBuild
|
import com.hermesandroid.relay.data.CandidateBuild
|
||||||
import com.hermesandroid.relay.data.Connection
|
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.EndpointCandidate
|
||||||
import com.hermesandroid.relay.data.FeatureFlags
|
import com.hermesandroid.relay.data.FeatureFlags
|
||||||
import com.hermesandroid.relay.data.SupervisedModePolicy
|
import com.hermesandroid.relay.data.SupervisedModePolicy
|
||||||
@@ -227,11 +230,7 @@ val LocalSnackbarHost = staticCompositionLocalOf<SnackbarHostState> {
|
|||||||
// Short-lived snackbar by default; retryable errors get Long so users have
|
// Short-lived snackbar by default; retryable errors get Long so users have
|
||||||
// time to tap the action before it auto-dismisses.
|
// time to tap the action before it auto-dismisses.
|
||||||
suspend fun SnackbarHostState.showHumanError(err: HumanError): SnackbarResult {
|
suspend fun SnackbarHostState.showHumanError(err: HumanError): SnackbarResult {
|
||||||
return showSnackbar(
|
return showSnackbar(com.hermesandroid.relay.ui.components.HumanErrorVisuals(err))
|
||||||
message = err.body,
|
|
||||||
actionLabel = err.actionLabel,
|
|
||||||
duration = if (err.retryable) SnackbarDuration.Long else SnackbarDuration.Short,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Startup chrome should wait for either standard chat surface, not Relay. */
|
/** Startup chrome should wait for either standard chat surface, not Relay. */
|
||||||
@@ -283,6 +282,8 @@ internal fun resolveAppChatRuntimeStatus(
|
|||||||
connection: Connection?,
|
connection: Connection?,
|
||||||
gatewayAvailability: GatewayAvailability,
|
gatewayAvailability: GatewayAvailability,
|
||||||
apiHealth: ConnectionViewModel.HealthStatus,
|
apiHealth: ConnectionViewModel.HealthStatus,
|
||||||
|
streamingEndpoint: String = "auto",
|
||||||
|
conversationOwner: SessionTransport? = null,
|
||||||
): ChatRuntimeStatus {
|
): ChatRuntimeStatus {
|
||||||
val capabilities = connection?.capabilities
|
val capabilities = connection?.capabilities
|
||||||
val gateway = when {
|
val gateway = when {
|
||||||
@@ -298,7 +299,11 @@ internal fun resolveAppChatRuntimeStatus(
|
|||||||
apiHealth == ConnectionViewModel.HealthStatus.Probing -> ChatTransportReadiness.Connecting
|
apiHealth == ConnectionViewModel.HealthStatus.Probing -> ChatTransportReadiness.Connecting
|
||||||
else -> ChatTransportReadiness.Unavailable
|
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(
|
internal fun shouldSettleStartupUnreachable(
|
||||||
@@ -360,7 +365,7 @@ internal fun resolveFooterRouteCandidate(
|
|||||||
*
|
*
|
||||||
* Endpoint roles are operator and wire metadata, so an internal role such as
|
* Endpoint roles are operator and wire metadata, so an internal role such as
|
||||||
* `authenticated_dashboard` must never leak into this constrained surface.
|
* `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.
|
* the route's ordinary transport label.
|
||||||
*/
|
*/
|
||||||
internal fun resolveFooterRouteLabel(
|
internal fun resolveFooterRouteLabel(
|
||||||
@@ -1007,6 +1012,17 @@ fun RelayApp() {
|
|||||||
chatSessions.firstOrNull { it.sessionId == currentChatSessionId }
|
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
|
// Bind Git to the active coding session when upstream supplies its exact
|
||||||
// workspace metadata. CWD fallback only matches a path-segment descendant;
|
// workspace metadata. CWD fallback only matches a path-segment descendant;
|
||||||
// an ambiguous multi-repo catalog stays unselected until the user chooses.
|
// an ambiguous multi-repo catalog stays unselected until the user chooses.
|
||||||
@@ -1023,7 +1039,7 @@ fun RelayApp() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val gitWorkspaceAvailable = gitRepoScanningEnabled &&
|
val gitWorkspaceAvailable =
|
||||||
(gitReposState as? GitStateUiState.Ready)?.repos?.isNotEmpty() == true
|
(gitReposState as? GitStateUiState.Ready)?.repos?.isNotEmpty() == true
|
||||||
val gitWorkspaceSummary = remember(
|
val gitWorkspaceSummary = remember(
|
||||||
gitReposState,
|
gitReposState,
|
||||||
@@ -1593,6 +1609,7 @@ fun RelayApp() {
|
|||||||
// evidence alone left a window where the reveal showed the CTA for
|
// evidence alone left a window where the reveal showed the CTA for
|
||||||
// the few hundred ms until the client-based health verdict landed.
|
// the few hundred ms until the client-based health verdict landed.
|
||||||
val chatReady by connectionViewModel.chatReady.collectAsState()
|
val chatReady by connectionViewModel.chatReady.collectAsState()
|
||||||
|
val conversationOwner by connectionViewModel.activeConversationTransport.collectAsState()
|
||||||
var startupGateMinElapsed by remember { mutableStateOf(false) }
|
var startupGateMinElapsed by remember { mutableStateOf(false) }
|
||||||
var startupGateTimedOut by remember { mutableStateOf(false) }
|
var startupGateTimedOut by remember { mutableStateOf(false) }
|
||||||
var startupGateReleased by remember { mutableStateOf(false) }
|
var startupGateReleased by remember { mutableStateOf(false) }
|
||||||
@@ -1619,6 +1636,8 @@ fun RelayApp() {
|
|||||||
connection = activeConnection,
|
connection = activeConnection,
|
||||||
gatewayAvailability = gatewayAvailability,
|
gatewayAvailability = gatewayAvailability,
|
||||||
apiHealth = apiHealth,
|
apiHealth = apiHealth,
|
||||||
|
streamingEndpoint = streamingEndpoint,
|
||||||
|
conversationOwner = conversationOwner,
|
||||||
)
|
)
|
||||||
// A Dashboard/Gateway-only connection is a complete standard Hermes
|
// A Dashboard/Gateway-only connection is a complete standard Hermes
|
||||||
// connection. Startup readiness follows the same transport-neutral
|
// connection. Startup readiness follows the same transport-neutral
|
||||||
@@ -1929,6 +1948,8 @@ fun RelayApp() {
|
|||||||
// child TopAppBar doesn't double-pad when this banner owns the top edge.
|
// child TopAppBar doesn't double-pad when this banner owns the top edge.
|
||||||
val activeMessageCount by UiMessageBus.activeCount.collectAsState()
|
val activeMessageCount by UiMessageBus.activeCount.collectAsState()
|
||||||
val showMessageBanner = activeMessageCount > 0
|
val showMessageBanner = activeMessageCount > 0
|
||||||
|
val modalMessageHostActive by UiMessageBus.modalHostActive.collectAsState()
|
||||||
|
val showActionMessage = snackbarHostState.currentSnackbarData != null && !modalMessageHostActive
|
||||||
// Update availability (unified): googlePlay = Play In-App Update FLEXIBLE,
|
// Update availability (unified): googlePlay = Play In-App Update FLEXIBLE,
|
||||||
// sideload = GitHub releases. The handle filters dismissed versions +
|
// sideload = GitHub releases. The handle filters dismissed versions +
|
||||||
// throttles checks internally, exposing a surfaceable status for the
|
// throttles checks internally, exposing a surfaceable status for the
|
||||||
@@ -2054,6 +2075,14 @@ fun RelayApp() {
|
|||||||
includeStatusBarPadding =
|
includeStatusBarPadding =
|
||||||
!showUnattendedBanner && !showDemoBanner && !showHostResourcePressure,
|
!showUnattendedBanner && !showDemoBanner && !showHostResourcePressure,
|
||||||
)
|
)
|
||||||
|
// Action feedback owns layout space at the top, never the composer's
|
||||||
|
// touch area. Modal windows keep their own scoped host.
|
||||||
|
ThemedMessageHost(
|
||||||
|
snackbarHostState,
|
||||||
|
modifier = if (showActionMessage && !showMessageBanner &&
|
||||||
|
!showUnattendedBanner && !showDemoBanner && !showHostResourcePressure
|
||||||
|
) Modifier.windowInsetsPadding(WindowInsets.statusBars) else Modifier,
|
||||||
|
)
|
||||||
|
|
||||||
// The update banner AND the connection-status indicator now render as
|
// The update banner AND the connection-status indicator now render as
|
||||||
// floating overlay TOASTS in the Box below (see the top-overlay Column
|
// floating overlay TOASTS in the Box below (see the top-overlay Column
|
||||||
@@ -2094,7 +2123,7 @@ fun RelayApp() {
|
|||||||
// participates in the top-inset accounting.
|
// participates in the top-inset accounting.
|
||||||
if (showUnattendedBanner || showDemoBanner || showHostResourcePressure ||
|
if (showUnattendedBanner || showDemoBanner || showHostResourcePressure ||
|
||||||
connectionChipVisible ||
|
connectionChipVisible ||
|
||||||
showMessageBanner
|
showMessageBanner || showActionMessage
|
||||||
) {
|
) {
|
||||||
Modifier.consumeWindowInsets(WindowInsets.statusBars)
|
Modifier.consumeWindowInsets(WindowInsets.statusBars)
|
||||||
} else {
|
} else {
|
||||||
@@ -2102,7 +2131,6 @@ fun RelayApp() {
|
|||||||
}
|
}
|
||||||
),
|
),
|
||||||
contentWindowInsets = WindowInsets(0),
|
contentWindowInsets = WindowInsets(0),
|
||||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
|
||||||
bottomBar = {
|
bottomBar = {
|
||||||
if (
|
if (
|
||||||
!suppressGlobalChrome &&
|
!suppressGlobalChrome &&
|
||||||
@@ -2125,7 +2153,9 @@ fun RelayApp() {
|
|||||||
?: stringResource(R.string.status_no_route),
|
?: stringResource(R.string.status_no_route),
|
||||||
)
|
)
|
||||||
val transportStatus = resolveChatTransportStatus(
|
val transportStatus = resolveChatTransportStatus(
|
||||||
streamingEndpoint = streamingEndpoint,
|
streamingEndpoint = connectionViewModel.resolveActiveStreamingEndpoint(
|
||||||
|
streamingEndpoint,
|
||||||
|
),
|
||||||
gatewayAvailability = gatewayAvailability,
|
gatewayAvailability = gatewayAvailability,
|
||||||
serverCapabilities = serverCapabilities,
|
serverCapabilities = serverCapabilities,
|
||||||
)
|
)
|
||||||
@@ -2176,6 +2206,9 @@ fun RelayApp() {
|
|||||||
// Routine in-progress reconnect surfaces here (amber cue)
|
// Routine in-progress reconnect surfaces here (amber cue)
|
||||||
// instead of a take-space banner or a floating toast.
|
// instead of a take-space banner or a floating toast.
|
||||||
reconnecting = connectionReconnecting,
|
reconnecting = connectionReconnecting,
|
||||||
|
maxContentWidth = chatResponsiveLayout(
|
||||||
|
LocalConfiguration.current.screenWidthDp,
|
||||||
|
).chromeMaxWidth,
|
||||||
modifier = Modifier.petPerchSurface(
|
modifier = Modifier.petPerchSurface(
|
||||||
key = APP_STATUS_PET_WALK_REGION,
|
key = APP_STATUS_PET_WALK_REGION,
|
||||||
routes = APP_STATUS_PET_ROUTES,
|
routes = APP_STATUS_PET_ROUTES,
|
||||||
@@ -2184,7 +2217,10 @@ fun RelayApp() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
) { innerPadding ->
|
) { innerPadding ->
|
||||||
CompositionLocalProvider(LocalSnackbarHost provides snackbarHostState) {
|
CompositionLocalProvider(
|
||||||
|
LocalSnackbarHost provides snackbarHostState,
|
||||||
|
com.hermesandroid.relay.ui.components.LocalMessageActionHost provides snackbarHostState,
|
||||||
|
) {
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
@@ -2448,103 +2484,110 @@ fun RelayApp() {
|
|||||||
|
|
||||||
val screenChatLabel = stringResource(R.string.screen_chat_label)
|
val screenChatLabel = stringResource(R.string.screen_chat_label)
|
||||||
|
|
||||||
ChatScreen(
|
ChatMediaViewerHost(
|
||||||
chatViewModel = chatViewModel,
|
activeConnectionId,
|
||||||
connectionViewModel = connectionViewModel,
|
effectiveSessionProfileName,
|
||||||
voiceViewModel = voiceViewModel,
|
currentChatSessionId,
|
||||||
voiceClient = voiceClient,
|
chatSupervisedPolicy,
|
||||||
maxBubbleWidth = maxBubbleWidth,
|
) {
|
||||||
voicePresentationMode = voicePresentationMode,
|
ChatScreen(
|
||||||
onVoicePresentationModeChange = { mode ->
|
chatViewModel = chatViewModel,
|
||||||
connectionSwitchScope.launch {
|
connectionViewModel = connectionViewModel,
|
||||||
voicePreferences.setPresentationMode(mode)
|
voiceViewModel = voiceViewModel,
|
||||||
}
|
voiceClient = voiceClient,
|
||||||
},
|
maxBubbleWidth = maxBubbleWidth,
|
||||||
openAgentSheetOnEntry = openAgentSheetArg,
|
voicePresentationMode = voicePresentationMode,
|
||||||
onAgentSheetArgConsumed = {
|
onVoicePresentationModeChange = { mode ->
|
||||||
backStackEntry.arguments?.putBoolean(
|
connectionSwitchScope.launch {
|
||||||
Screen.Chat.ARG_OPEN_AGENT_SHEET, false,
|
voicePreferences.setPresentationMode(mode)
|
||||||
)
|
|
||||||
},
|
|
||||||
// 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
|
openAgentSheetOnEntry = openAgentSheetArg,
|
||||||
}
|
onAgentSheetArgConsumed = {
|
||||||
},
|
backStackEntry.arguments?.putBoolean(
|
||||||
onNavigateToTerminal = {
|
Screen.Chat.ARG_OPEN_AGENT_SHEET, false,
|
||||||
navController.navigate(Screen.Terminal.route) {
|
)
|
||||||
launchSingleTop = true
|
},
|
||||||
}
|
// AgentInfoSheet footer jumps straight into the full
|
||||||
},
|
// Connections CRUD screen — saves a detour through
|
||||||
onNavigateToSettings = {
|
// Settings → Gateways.
|
||||||
navController.navigate(Screen.Settings.route) {
|
onNavigateToConnections = {
|
||||||
launchSingleTop = true
|
navController.navigate(Screen.ConnectionsSettings.route)
|
||||||
}
|
},
|
||||||
},
|
onNavigateToConnect = {
|
||||||
onNavigateToAppearanceSettings = {
|
navController.navigate(Screen.Pair.route()) {
|
||||||
navController.navigate(Screen.AppearanceSettings.route) {
|
launchSingleTop = true
|
||||||
launchSingleTop = true
|
}
|
||||||
}
|
},
|
||||||
},
|
onRepairConnection = {
|
||||||
onNavigateToVoiceSettings = {
|
navController.navigate(
|
||||||
navController.navigate(Screen.VoiceSettings.route) {
|
Screen.Pair.route(
|
||||||
launchSingleTop = true
|
connectionId = activeConnectionId,
|
||||||
}
|
autoStart = "relay",
|
||||||
},
|
),
|
||||||
onNavigateToProfileInspector = { profileName ->
|
) {
|
||||||
navController.navigate(Screen.ProfileInspector.route(profileName)) {
|
launchSingleTop = true
|
||||||
launchSingleTop = true
|
}
|
||||||
}
|
},
|
||||||
},
|
// Empty-chat "needs connection" card also offers the offline
|
||||||
supervisedPolicy = chatSupervisedPolicy,
|
// demo, so a skipped / never-connected first run can explore
|
||||||
onNavigateToBotMode = {
|
// without leaving Chat. Safe here — this state only shows when
|
||||||
navController.navigate(Screen.BotMode.route) { launchSingleTop = true }
|
// nothing is configured, so there's no placeholder in flight.
|
||||||
},
|
onTryDemo = enterDemo,
|
||||||
gitWorkspaceAvailable = gitWorkspaceAvailable,
|
onNavigateToDashboardSignIn = {
|
||||||
gitWorkspaceSummary = gitWorkspaceSummary,
|
navController.navigate(Screen.DashboardSignIn.route()) {
|
||||||
onNavigateToGitWorkspace = {
|
launchSingleTop = true
|
||||||
navController.navigate(Screen.GitState.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) {
|
composable(Screen.BotMode.route) {
|
||||||
BotModeScreen(
|
BotModeScreen(
|
||||||
|
|||||||
@@ -8,26 +8,50 @@ import kotlinx.coroutines.flow.asSharedFlow
|
|||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import java.util.concurrent.atomic.AtomicLong
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
|
||||||
/** Visual tone of a transient banner message. Errors are NOT modelled here —
|
/** Visual tone of a transient banner message. */
|
||||||
* they stay on the snackbar (see [LocalSnackbarHost]); this bus is info-only. */
|
enum class UiMessageSeverity { Info, Success, Status, Warning, Error }
|
||||||
enum class UiMessageSeverity { Info, Success, Status }
|
|
||||||
|
|
||||||
data class UiMessage(
|
data class UiMessage(
|
||||||
val id: Long,
|
val id: Long,
|
||||||
val text: String,
|
val text: String,
|
||||||
val severity: UiMessageSeverity,
|
val severity: UiMessageSeverity,
|
||||||
val ttlMillis: Long,
|
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
|
||||||
|
data object ClearAll : UiMessageEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun reduceUiMessages(
|
||||||
|
current: List<UiMessage>,
|
||||||
|
event: UiMessageEvent,
|
||||||
|
maxRetained: Int,
|
||||||
|
): List<UiMessage> = when (event) {
|
||||||
|
UiMessageEvent.ClearAll -> emptyList()
|
||||||
|
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
|
* App-wide bus for transient status, confirmation, and error messages that
|
||||||
* surface in the top [com.hermesandroid.relay.ui.components.MessageBannerHost]
|
* surface in the top [com.hermesandroid.relay.ui.components.MessageBannerHost]
|
||||||
* — a thin banner that takes its own space (content slides down, no overlay),
|
* — a thin banner that takes its own space (content slides down, no overlay),
|
||||||
* shows the newest line collapsed, expands to a few recent lines, auto-dismisses
|
* shows the newest line collapsed, expands to a few recent lines, auto-dismisses
|
||||||
* and coalesces duplicates.
|
* and coalesces duplicates.
|
||||||
*
|
*
|
||||||
* Deliberately info-only: errors and persistent/actionable messages keep going
|
* Messages requiring Retry or Undo use ThemedMessageHost and retain their
|
||||||
* to the snackbar so they demand acknowledgement. Migrate frequent
|
* action-result contract. Upstream keyed AgentNotices own their sticky/clear lifecycle.
|
||||||
|
* Migrate frequent
|
||||||
* `snackbarHostState.showSnackbar("…")` confirmations/status to [info] /
|
* `snackbarHostState.showSnackbar("…")` confirmations/status to [info] /
|
||||||
* [success] / [status] here.
|
* [success] / [status] here.
|
||||||
*
|
*
|
||||||
@@ -39,8 +63,25 @@ object UiMessageBus {
|
|||||||
const val STATUS_TTL_MS = 6_000L
|
const val STATUS_TTL_MS = 6_000L
|
||||||
|
|
||||||
private val counter = AtomicLong(0L)
|
private val counter = AtomicLong(0L)
|
||||||
private val _events = MutableSharedFlow<UiMessage>(extraBufferCapacity = 24)
|
private val hosts = linkedMapOf<Long, Boolean>()
|
||||||
val events: SharedFlow<UiMessage> = _events.asSharedFlow()
|
private val _activeHost = MutableStateFlow<Long?>(null)
|
||||||
|
internal val activeHost = _activeHost.asStateFlow()
|
||||||
|
private val _modalHostActive = MutableStateFlow(false)
|
||||||
|
internal val modalHostActive = _modalHostActive.asStateFlow()
|
||||||
|
internal fun registerHost(primary: Boolean): Long = synchronized(hosts) {
|
||||||
|
counter.incrementAndGet().also {
|
||||||
|
hosts[it] = primary
|
||||||
|
_activeHost.value = hosts.keys.lastOrNull()
|
||||||
|
_modalHostActive.value = hosts.values.any { primaryHost -> !primaryHost }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
internal fun unregisterHost(id: Long) { synchronized(hosts) {
|
||||||
|
hosts.remove(id)
|
||||||
|
_activeHost.value = hosts.keys.lastOrNull()
|
||||||
|
_modalHostActive.value = hosts.values.any { !it }
|
||||||
|
} }
|
||||||
|
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
|
// Number of messages currently shown by the host. Lifted here so the app
|
||||||
// scaffold can fold banner visibility into its status-bar inset accounting
|
// scaffold can fold banner visibility into its status-bar inset accounting
|
||||||
@@ -52,12 +93,33 @@ object UiMessageBus {
|
|||||||
text: String,
|
text: String,
|
||||||
severity: UiMessageSeverity = UiMessageSeverity.Info,
|
severity: UiMessageSeverity = UiMessageSeverity.Info,
|
||||||
ttlMillis: Long = DEFAULT_TTL_MS,
|
ttlMillis: Long = DEFAULT_TTL_MS,
|
||||||
|
key: String? = null,
|
||||||
) {
|
) {
|
||||||
val trimmed = text.trim()
|
val trimmed = text.trim()
|
||||||
if (trimmed.isEmpty()) return
|
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)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearAll() { _events.tryEmit(UiMessageEvent.ClearAll) }
|
||||||
|
|
||||||
|
fun warning(text: String, ttlMillis: Long = STATUS_TTL_MS) = post(text, UiMessageSeverity.Warning, ttlMillis)
|
||||||
|
fun error(text: String, ttlMillis: Long = 10_000L) = post(text, UiMessageSeverity.Error, ttlMillis)
|
||||||
|
|
||||||
/** Neutral confirmation/info (e.g. "Pairing code copied"). */
|
/** Neutral confirmation/info (e.g. "Pairing code copied"). */
|
||||||
fun info(text: String, ttlMillis: Long = DEFAULT_TTL_MS) =
|
fun info(text: String, ttlMillis: Long = DEFAULT_TTL_MS) =
|
||||||
post(text, UiMessageSeverity.Info, ttlMillis)
|
post(text, UiMessageSeverity.Info, ttlMillis)
|
||||||
|
|||||||
+20
-24
@@ -1,6 +1,6 @@
|
|||||||
package com.hermesandroid.relay.ui.components
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.compose.foundation.BorderStroke
|
import androidx.compose.foundation.BorderStroke
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
@@ -209,7 +209,7 @@ fun ActiveCardRelayStatusSection(
|
|||||||
val relayUiState by connectionViewModel.relayUiState.collectAsState()
|
val relayUiState by connectionViewModel.relayUiState.collectAsState()
|
||||||
val relayRowState by connectionViewModel.relayRowState.collectAsState()
|
val relayRowState by connectionViewModel.relayRowState.collectAsState()
|
||||||
|
|
||||||
// Pre-resolve strings for Toast (non-composable context)
|
// Pre-resolve strings for action callbacks (non-composable context).
|
||||||
val reconnectingRelayToast = stringResource(R.string.active_section_reconnecting_relay)
|
val reconnectingRelayToast = stringResource(R.string.active_section_reconnecting_relay)
|
||||||
val relayStatusText = when (relayRowState.phase) {
|
val relayStatusText = when (relayRowState.phase) {
|
||||||
RelayUiState.NotConfigured -> stringResource(R.string.relay_state_optional)
|
RelayUiState.NotConfigured -> stringResource(R.string.relay_state_optional)
|
||||||
@@ -250,11 +250,7 @@ fun ActiveCardRelayStatusSection(
|
|||||||
onClick = {
|
onClick = {
|
||||||
if (relayUiState == RelayUiState.Stale) {
|
if (relayUiState == RelayUiState.Stale) {
|
||||||
connectionViewModel.reconnectIfStale()
|
connectionViewModel.reconnectIfStale()
|
||||||
Toast.makeText(
|
UiMessageBus.status(reconnectingRelayToast)
|
||||||
context,
|
|
||||||
reconnectingRelayToast,
|
|
||||||
Toast.LENGTH_SHORT,
|
|
||||||
).show()
|
|
||||||
} else {
|
} else {
|
||||||
onOpenRelayInfo()
|
onOpenRelayInfo()
|
||||||
}
|
}
|
||||||
@@ -613,7 +609,7 @@ private fun CapabilityRow(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Advanced compatibility and override content:
|
* Advanced compatibility and override content:
|
||||||
* - optional direct API fallback URL/key
|
* - optional Direct API URL/key
|
||||||
* - explicit direct Relay endpoint override/test
|
* - explicit direct Relay endpoint override/test
|
||||||
* - allow-insecure-connections development toggle
|
* - allow-insecure-connections development toggle
|
||||||
*
|
*
|
||||||
@@ -817,7 +813,7 @@ private fun ManualUrlSubsection(
|
|||||||
}
|
}
|
||||||
val autoRelayUrl = RelayUrlDeriver.deriveFromApiUrl(apiUrlInput)
|
val autoRelayUrl = RelayUrlDeriver.deriveFromApiUrl(apiUrlInput)
|
||||||
|
|
||||||
// Pre-resolve strings for Toast (non-composable context)
|
// Pre-resolve strings for action callbacks (non-composable context).
|
||||||
val apiHermesVoiceReachableToast = stringResource(R.string.active_section_api_hermes_voice_reachable)
|
val apiHermesVoiceReachableToast = stringResource(R.string.active_section_api_hermes_voice_reachable)
|
||||||
val apiRelayVoiceReachableToast = stringResource(R.string.active_section_api_relay_voice_reachable)
|
val apiRelayVoiceReachableToast = stringResource(R.string.active_section_api_relay_voice_reachable)
|
||||||
val apiReachableVoiceReviewToast = stringResource(R.string.active_section_api_reachable_voice_review)
|
val apiReachableVoiceReviewToast = stringResource(R.string.active_section_api_reachable_voice_review)
|
||||||
@@ -926,21 +922,21 @@ private fun ManualUrlSubsection(
|
|||||||
relayOverrideVisible = true
|
relayOverrideVisible = true
|
||||||
result.relayUrl?.let { relayUrlInput = it }
|
result.relayUrl?.let { relayUrlInput = it }
|
||||||
}
|
}
|
||||||
Toast.makeText(
|
val feedback = when {
|
||||||
context,
|
result.apiReachable && result.voiceConfigReachable ->
|
||||||
when {
|
if (result.voiceRoute == "standard") {
|
||||||
result.apiReachable && result.voiceConfigReachable ->
|
apiHermesVoiceReachableToast
|
||||||
if (result.voiceRoute == "standard") {
|
} else {
|
||||||
apiHermesVoiceReachableToast
|
apiRelayVoiceReachableToast
|
||||||
} else {
|
}
|
||||||
apiRelayVoiceReachableToast
|
result.apiReachable -> apiReachableVoiceReviewToast
|
||||||
}
|
else -> cannotReachApiToast
|
||||||
result.apiReachable ->
|
}
|
||||||
apiReachableVoiceReviewToast
|
when {
|
||||||
else -> cannotReachApiToast
|
result.apiReachable && result.voiceConfigReachable -> UiMessageBus.success(feedback)
|
||||||
},
|
result.apiReachable -> UiMessageBus.warning(feedback)
|
||||||
Toast.LENGTH_SHORT,
|
else -> UiMessageBus.error(feedback)
|
||||||
).show()
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enabled = apiUrlInput.isNotBlank() && !isTestingApi && inputApiKeyError == null,
|
enabled = apiUrlInput.isNotBlank() && !isTestingApi && inputApiKeyError == null,
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import androidx.compose.runtime.mutableStateMapOf
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -128,10 +129,11 @@ fun AttachmentGallery(
|
|||||||
val exportAllowed = LocalImageExportAllowed.current
|
val exportAllowed = LocalImageExportAllowed.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val blurMode = LocalMediaBlurMode.current
|
val blurMode = LocalMediaBlurMode.current
|
||||||
|
val viewerController = LocalChatMediaViewerController.current
|
||||||
val revealed = remember { mutableStateMapOf<String, Boolean>() }
|
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(
|
AttachmentGalleryViewer(
|
||||||
attachments = attachments,
|
attachments = attachments,
|
||||||
initialIndex = startIndex.coerceIn(attachments.indices),
|
initialIndex = startIndex.coerceIn(attachments.indices),
|
||||||
@@ -184,7 +186,21 @@ fun AttachmentGallery(
|
|||||||
.testTag("attachment-gallery-tile-$galleryIndex")
|
.testTag("attachment-gallery-tile-$galleryIndex")
|
||||||
.clip(RoundedCornerShape(GALLERY_CORNER))
|
.clip(RoundedCornerShape(GALLERY_CORNER))
|
||||||
.combinedClickable(
|
.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 },
|
onLongClick = { menuExpanded = true },
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -9,8 +9,7 @@ import android.media.audiofx.Visualizer
|
|||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.ParcelFileDescriptor
|
import android.os.ParcelFileDescriptor
|
||||||
import android.view.SurfaceView
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import android.widget.Toast
|
|
||||||
import androidx.annotation.OptIn
|
import androidx.annotation.OptIn
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
@@ -63,10 +62,12 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.runtime.DisposableEffect
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableLongStateOf
|
||||||
import androidx.compose.runtime.mutableStateMapOf
|
import androidx.compose.runtime.mutableStateMapOf
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.runtime.staticCompositionLocalOf
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
import androidx.compose.ui.Alignment
|
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.text.font.FontFamily
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.IntSize
|
import androidx.compose.ui.unit.IntSize
|
||||||
import androidx.compose.ui.viewinterop.AndroidView
|
|
||||||
import androidx.compose.ui.window.Dialog
|
import androidx.compose.ui.window.Dialog
|
||||||
import androidx.compose.ui.window.DialogProperties
|
import androidx.compose.ui.window.DialogProperties
|
||||||
import androidx.media3.common.MediaItem
|
import androidx.media3.common.MediaItem
|
||||||
import androidx.media3.common.Player
|
import androidx.media3.common.Player
|
||||||
import androidx.media3.common.util.UnstableApi
|
import androidx.media3.common.util.UnstableApi
|
||||||
import androidx.media3.exoplayer.ExoPlayer
|
import androidx.media3.exoplayer.ExoPlayer
|
||||||
|
import androidx.media3.ui.compose.ContentFrame
|
||||||
import coil3.compose.AsyncImage
|
import coil3.compose.AsyncImage
|
||||||
import com.hermesandroid.relay.data.Attachment
|
import com.hermesandroid.relay.data.Attachment
|
||||||
import com.hermesandroid.relay.data.AttachmentRenderMode
|
import com.hermesandroid.relay.data.AttachmentRenderMode
|
||||||
@@ -290,7 +291,7 @@ fun Modifier.zoomable(maxScale: Float = 6f): Modifier {
|
|||||||
* Dispatches on [Attachment.renderMode]:
|
* Dispatches on [Attachment.renderMode]:
|
||||||
* - IMAGE → zoomable image (Coil from the cached URI, or a decoded bitmap),
|
* - IMAGE → zoomable image (Coil from the cached URI, or a decoded bitmap),
|
||||||
* honoring the sensitive blur gate.
|
* 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.
|
* - AUDIO → ExoPlayer mini-player with scrubber + a Visualizer amplitude meter.
|
||||||
* - PDF → [PdfRenderer] paginated pages in a LazyColumn.
|
* - PDF → [PdfRenderer] paginated pages in a LazyColumn.
|
||||||
* - TEXT → in-app monospace text viewer.
|
* - TEXT → in-app monospace text viewer.
|
||||||
@@ -311,109 +312,112 @@ fun AttachmentViewer(
|
|||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
MessageOverlayScope {
|
||||||
val exportAllowed = LocalImageExportAllowed.current ||
|
val context = LocalContext.current
|
||||||
attachment.renderMode != AttachmentRenderMode.IMAGE
|
val exportAllowed = LocalImageExportAllowed.current ||
|
||||||
AllowDeviceRotation()
|
attachment.renderMode != AttachmentRenderMode.IMAGE
|
||||||
val scope = rememberCoroutineScope()
|
AllowDeviceRotation()
|
||||||
var busy by remember { mutableStateOf(false) }
|
val scope = rememberCoroutineScope()
|
||||||
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
val blurMode = LocalMediaBlurMode.current
|
val blurMode = LocalMediaBlurMode.current
|
||||||
var revealed by remember(attachment.cachedUri, attachment.relayToken) {
|
var revealed by remember(attachment.cachedUri, attachment.relayToken) {
|
||||||
mutableStateOf(initiallyRevealed)
|
mutableStateOf(initiallyRevealed)
|
||||||
}
|
|
||||||
val blurred = !revealed &&
|
|
||||||
attachment.renderMode == AttachmentRenderMode.IMAGE &&
|
|
||||||
shouldBlurImage(blurMode, attachment.sensitive)
|
|
||||||
|
|
||||||
val title = attachment.fileName
|
|
||||||
?: attachment.contentType.substringBefore(';').ifBlank { stringResource(R.string.attachment_title) }
|
|
||||||
|
|
||||||
// --- One shared Share / Save / Open-externally action set ----------
|
|
||||||
fun runWithBytes(action: suspend (ByteArray) -> Unit) {
|
|
||||||
scope.launch {
|
|
||||||
busy = true
|
|
||||||
val bytes = attachmentBytes(context, attachment)
|
|
||||||
if (bytes == null) {
|
|
||||||
busy = false
|
|
||||||
viewerToast(context, context.getString(R.string.inbound_attach_share_failed))
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
action(bytes)
|
|
||||||
busy = false
|
|
||||||
}
|
}
|
||||||
}
|
val blurred = !revealed &&
|
||||||
|
attachment.renderMode == AttachmentRenderMode.IMAGE &&
|
||||||
|
shouldBlurImage(blurMode, attachment.sensitive)
|
||||||
|
|
||||||
val onShare = {
|
val title = attachment.fileName
|
||||||
runWithBytes { bytes ->
|
?: attachment.contentType.substringBefore(';').ifBlank { stringResource(R.string.attachment_title) }
|
||||||
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
|
||||||
MediaSaver.share(context, uri, attachment.contentType)
|
// --- One shared Share / Save / Open-externally action set ----------
|
||||||
}
|
fun runWithBytes(action: suspend (ByteArray) -> Unit) {
|
||||||
}
|
scope.launch {
|
||||||
val onSave = {
|
busy = true
|
||||||
runWithBytes { bytes ->
|
val bytes = attachmentBytes(context, attachment)
|
||||||
val result = if (attachment.renderMode == AttachmentRenderMode.IMAGE) {
|
if (bytes == null) {
|
||||||
MediaSaver.saveImage(context, bytes, attachment.fileName, attachment.contentType)
|
busy = false
|
||||||
} else {
|
UiMessageBus.error(context.getString(R.string.inbound_attach_share_failed))
|
||||||
MediaSaver.saveFile(context, bytes, attachment.fileName, attachment.contentType)
|
return@launch
|
||||||
}
|
|
||||||
when (result) {
|
|
||||||
is MediaSaver.SaveResult.Saved ->
|
|
||||||
viewerToast(context, context.getString(R.string.inbound_attach_saved, result.location))
|
|
||||||
MediaSaver.SaveResult.UseShareInstead -> {
|
|
||||||
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
|
||||||
MediaSaver.share(context, uri, attachment.contentType)
|
|
||||||
}
|
}
|
||||||
is MediaSaver.SaveResult.Failed ->
|
action(bytes)
|
||||||
viewerToast(context, context.getString(R.string.inbound_attach_save_failed, result.message))
|
busy = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
val onOpenExternal = {
|
val onShare = {
|
||||||
val cached = attachment.cachedUri
|
|
||||||
if (!cached.isNullOrBlank()) {
|
|
||||||
MediaSaver.open(context, Uri.parse(cached), attachment.contentType)
|
|
||||||
} else {
|
|
||||||
runWithBytes { bytes ->
|
runWithBytes { bytes ->
|
||||||
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
||||||
MediaSaver.open(context, uri, attachment.contentType)
|
MediaSaver.share(context, uri, attachment.contentType)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
val onSave = {
|
||||||
|
runWithBytes { bytes ->
|
||||||
Box(
|
val result = if (attachment.renderMode == AttachmentRenderMode.IMAGE) {
|
||||||
modifier = modifier
|
MediaSaver.saveImage(context, bytes, attachment.fileName, attachment.contentType)
|
||||||
.fillMaxSize()
|
} else {
|
||||||
.background(Color.Black.copy(alpha = 0.96f)),
|
MediaSaver.saveFile(context, bytes, attachment.fileName, attachment.contentType)
|
||||||
) {
|
}
|
||||||
// Body fills; toolbar floats on top. PDF/TEXT add their own top
|
when (result) {
|
||||||
// inset so the first line clears the toolbar.
|
is MediaSaver.SaveResult.Saved ->
|
||||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
UiMessageBus.success(context.getString(R.string.inbound_attach_saved, result.location))
|
||||||
when (attachment.renderMode) {
|
MediaSaver.SaveResult.UseShareInstead -> {
|
||||||
AttachmentRenderMode.IMAGE -> ImageBody(
|
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
||||||
attachment = attachment,
|
MediaSaver.share(context, uri, attachment.contentType)
|
||||||
blurred = blurred,
|
}
|
||||||
onReveal = { revealed = true },
|
is MediaSaver.SaveResult.Failed ->
|
||||||
)
|
UiMessageBus.error(context.getString(R.string.inbound_attach_save_failed, result.message))
|
||||||
AttachmentRenderMode.VIDEO -> VideoBody(attachment)
|
}
|
||||||
AttachmentRenderMode.AUDIO -> AudioBody(attachment)
|
}
|
||||||
AttachmentRenderMode.PDF -> PdfBody(attachment)
|
}
|
||||||
AttachmentRenderMode.TEXT -> TextBody(attachment)
|
val onOpenExternal = {
|
||||||
AttachmentRenderMode.GENERIC -> GenericBody(attachment, onOpenExternal)
|
val cached = attachment.cachedUri
|
||||||
|
if (!cached.isNullOrBlank()) {
|
||||||
|
MediaSaver.open(context, Uri.parse(cached), attachment.contentType)
|
||||||
|
} else {
|
||||||
|
runWithBytes { bytes ->
|
||||||
|
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
||||||
|
MediaSaver.open(context, uri, attachment.contentType)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
MediaViewerToolbar(
|
Box(
|
||||||
title = title,
|
modifier = modifier
|
||||||
busy = busy,
|
.fillMaxSize()
|
||||||
actionsEnabled = !blurred,
|
.background(Color.Black.copy(alpha = 0.96f))
|
||||||
exportAllowed = exportAllowed,
|
.testTag("attachment-viewer"),
|
||||||
onShare = onShare,
|
) {
|
||||||
onSave = onSave,
|
// Body fills; toolbar floats on top. PDF/TEXT add their own top
|
||||||
onOpenExternal = onOpenExternal,
|
// inset so the first line clears the toolbar.
|
||||||
onClose = onDismiss,
|
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
modifier = Modifier.align(Alignment.TopCenter),
|
when (attachment.renderMode) {
|
||||||
)
|
AttachmentRenderMode.IMAGE -> ImageBody(
|
||||||
|
attachment = attachment,
|
||||||
|
blurred = blurred,
|
||||||
|
onReveal = { revealed = true },
|
||||||
|
)
|
||||||
|
AttachmentRenderMode.VIDEO -> VideoBody(attachment)
|
||||||
|
AttachmentRenderMode.AUDIO -> AudioBody(attachment)
|
||||||
|
AttachmentRenderMode.PDF -> PdfBody(attachment)
|
||||||
|
AttachmentRenderMode.TEXT -> TextBody(attachment)
|
||||||
|
AttachmentRenderMode.GENERIC -> GenericBody(attachment, onOpenExternal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MediaViewerToolbar(
|
||||||
|
title = title,
|
||||||
|
busy = busy,
|
||||||
|
actionsEnabled = !blurred,
|
||||||
|
exportAllowed = exportAllowed,
|
||||||
|
onShare = onShare,
|
||||||
|
onSave = onSave,
|
||||||
|
onOpenExternal = onOpenExternal,
|
||||||
|
onClose = onDismiss,
|
||||||
|
modifier = Modifier.align(Alignment.TopCenter),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -450,164 +454,165 @@ internal fun AttachmentGalleryViewer(
|
|||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
MessageOverlayScope {
|
||||||
val exportAllowed = LocalImageExportAllowed.current
|
val context = LocalContext.current
|
||||||
AllowDeviceRotation()
|
val exportAllowed = LocalImageExportAllowed.current
|
||||||
val scope = rememberCoroutineScope()
|
AllowDeviceRotation()
|
||||||
var busy by remember { mutableStateOf(false) }
|
val scope = rememberCoroutineScope()
|
||||||
val revealed = remember { mutableStateMapOf<String, Boolean>() }
|
var busy by remember { mutableStateOf(false) }
|
||||||
LaunchedEffect(initiallyRevealedKeys) {
|
val revealed = remember { mutableStateMapOf<String, Boolean>() }
|
||||||
initiallyRevealedKeys.forEach { revealed[it] = true }
|
LaunchedEffect(initiallyRevealedKeys) {
|
||||||
}
|
initiallyRevealedKeys.forEach { revealed[it] = true }
|
||||||
val pagerState = rememberPagerState(
|
|
||||||
initialPage = initialIndex.coerceIn(attachments.indices),
|
|
||||||
pageCount = { attachments.size },
|
|
||||||
)
|
|
||||||
|
|
||||||
val currentIndex = pagerState.currentPage.coerceIn(attachments.indices)
|
|
||||||
val attachment = attachments[currentIndex]
|
|
||||||
val currentKey = galleryAttachmentKey(attachment, currentIndex)
|
|
||||||
val blurMode = LocalMediaBlurMode.current
|
|
||||||
val currentBlurred = revealed[currentKey] != true &&
|
|
||||||
shouldBlurImage(blurMode, attachment.sensitive)
|
|
||||||
val title = attachment.fileName
|
|
||||||
?: attachment.contentType.substringBefore(';').ifBlank { "Image" }
|
|
||||||
val toolbarTitle = "$title · ${currentIndex + 1} of ${attachments.size}"
|
|
||||||
|
|
||||||
// Capture the currently visible attachment in each click lambda. A
|
|
||||||
// swipe while IO is running must not redirect Save/Share to a new page.
|
|
||||||
fun runWithBytes(action: suspend (Attachment, ByteArray) -> Unit) {
|
|
||||||
if (currentBlurred || busy) return
|
|
||||||
val target = attachment
|
|
||||||
scope.launch {
|
|
||||||
busy = true
|
|
||||||
try {
|
|
||||||
val bytes = attachmentBytes(context, target)
|
|
||||||
if (bytes == null) {
|
|
||||||
viewerToast(context, "Couldn't read this image")
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
action(target, bytes)
|
|
||||||
} catch (error: Exception) {
|
|
||||||
viewerToast(
|
|
||||||
context,
|
|
||||||
error.message?.takeIf { it.isNotBlank() }
|
|
||||||
?: "Couldn't complete that image action",
|
|
||||||
)
|
|
||||||
} finally {
|
|
||||||
busy = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
val pagerState = rememberPagerState(
|
||||||
|
initialPage = initialIndex.coerceIn(attachments.indices),
|
||||||
|
pageCount = { attachments.size },
|
||||||
|
)
|
||||||
|
|
||||||
val onShare = {
|
val currentIndex = pagerState.currentPage.coerceIn(attachments.indices)
|
||||||
runWithBytes { target, bytes ->
|
val attachment = attachments[currentIndex]
|
||||||
val uri = MediaSaver.stageForShare(
|
val currentKey = galleryAttachmentKey(attachment, currentIndex)
|
||||||
context,
|
val blurMode = LocalMediaBlurMode.current
|
||||||
bytes,
|
val currentBlurred = revealed[currentKey] != true &&
|
||||||
target.fileName,
|
shouldBlurImage(blurMode, attachment.sensitive)
|
||||||
target.contentType,
|
val title = attachment.fileName
|
||||||
)
|
?: attachment.contentType.substringBefore(';').ifBlank { "Image" }
|
||||||
MediaSaver.share(context, uri, target.contentType)
|
val toolbarTitle = "$title · ${currentIndex + 1} of ${attachments.size}"
|
||||||
}
|
|
||||||
}
|
// Capture the currently visible attachment in each click lambda. A
|
||||||
val onSave = {
|
// swipe while IO is running must not redirect Save/Share to a new page.
|
||||||
runWithBytes { target, bytes ->
|
fun runWithBytes(action: suspend (Attachment, ByteArray) -> Unit) {
|
||||||
when (val result = MediaSaver.saveImage(
|
if (currentBlurred || busy) return
|
||||||
context,
|
val target = attachment
|
||||||
bytes,
|
scope.launch {
|
||||||
target.fileName,
|
busy = true
|
||||||
target.contentType,
|
try {
|
||||||
)) {
|
val bytes = attachmentBytes(context, target)
|
||||||
is MediaSaver.SaveResult.Saved ->
|
if (bytes == null) {
|
||||||
viewerToast(context, "Saved to ${result.location}")
|
UiMessageBus.error("Couldn't read this image")
|
||||||
MediaSaver.SaveResult.UseShareInstead -> {
|
return@launch
|
||||||
val uri = MediaSaver.stageForShare(
|
}
|
||||||
context,
|
action(target, bytes)
|
||||||
bytes,
|
} catch (error: Exception) {
|
||||||
target.fileName,
|
UiMessageBus.error(
|
||||||
target.contentType,
|
error.message?.takeIf { it.isNotBlank() }
|
||||||
|
?: "Couldn't complete that image action",
|
||||||
)
|
)
|
||||||
MediaSaver.share(context, uri, target.contentType)
|
} finally {
|
||||||
|
busy = false
|
||||||
}
|
}
|
||||||
is MediaSaver.SaveResult.Failed ->
|
|
||||||
viewerToast(context, "Save failed: ${result.message}")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
val onOpenExternal: () -> Unit = openExternal@{
|
val onShare = {
|
||||||
if (currentBlurred || busy) return@openExternal
|
runWithBytes { target, bytes ->
|
||||||
val target = attachment
|
|
||||||
val cached = target.cachedUri
|
|
||||||
if (!cached.isNullOrBlank()) {
|
|
||||||
runCatching {
|
|
||||||
MediaSaver.open(context, Uri.parse(cached), target.contentType)
|
|
||||||
}.onFailure {
|
|
||||||
viewerToast(context, "Couldn't open this image")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
runWithBytes { item, bytes ->
|
|
||||||
val uri = MediaSaver.stageForShare(
|
val uri = MediaSaver.stageForShare(
|
||||||
context,
|
context,
|
||||||
bytes,
|
bytes,
|
||||||
item.fileName,
|
target.fileName,
|
||||||
item.contentType,
|
target.contentType,
|
||||||
)
|
)
|
||||||
MediaSaver.open(context, uri, item.contentType)
|
MediaSaver.share(context, uri, target.contentType)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
val onSave = {
|
||||||
|
runWithBytes { target, bytes ->
|
||||||
Box(
|
when (val result = MediaSaver.saveImage(
|
||||||
modifier = modifier
|
context,
|
||||||
.fillMaxSize()
|
bytes,
|
||||||
.background(Color.Black.copy(alpha = 0.96f)),
|
target.fileName,
|
||||||
) {
|
target.contentType,
|
||||||
HorizontalPager(
|
)) {
|
||||||
state = pagerState,
|
is MediaSaver.SaveResult.Saved ->
|
||||||
beyondViewportPageCount = 0,
|
UiMessageBus.success("Saved to ${result.location}")
|
||||||
pageSpacing = 12.dp,
|
MediaSaver.SaveResult.UseShareInstead -> {
|
||||||
modifier = Modifier
|
val uri = MediaSaver.stageForShare(
|
||||||
.fillMaxSize()
|
context,
|
||||||
.testTag("attachment-gallery-pager"),
|
bytes,
|
||||||
) { page ->
|
target.fileName,
|
||||||
val pageAttachment = attachments[page]
|
target.contentType,
|
||||||
val pageKey = galleryAttachmentKey(pageAttachment, page)
|
)
|
||||||
val blurred = revealed[pageKey] != true && shouldBlurImage(
|
MediaSaver.share(context, uri, target.contentType)
|
||||||
blurMode,
|
}
|
||||||
pageAttachment.sensitive,
|
is MediaSaver.SaveResult.Failed ->
|
||||||
)
|
UiMessageBus.error("Save failed: ${result.message}")
|
||||||
ImageBody(
|
}
|
||||||
attachment = pageAttachment,
|
}
|
||||||
blurred = blurred,
|
}
|
||||||
onReveal = { revealed[pageKey] = true },
|
val onOpenExternal: () -> Unit = openExternal@{
|
||||||
)
|
if (currentBlurred || busy) return@openExternal
|
||||||
|
val target = attachment
|
||||||
|
val cached = target.cachedUri
|
||||||
|
if (!cached.isNullOrBlank()) {
|
||||||
|
runCatching {
|
||||||
|
MediaSaver.open(context, Uri.parse(cached), target.contentType)
|
||||||
|
}.onFailure {
|
||||||
|
UiMessageBus.error("Couldn't open this image")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
runWithBytes { item, bytes ->
|
||||||
|
val uri = MediaSaver.stageForShare(
|
||||||
|
context,
|
||||||
|
bytes,
|
||||||
|
item.fileName,
|
||||||
|
item.contentType,
|
||||||
|
)
|
||||||
|
MediaSaver.open(context, uri, item.contentType)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
MediaViewerToolbar(
|
Box(
|
||||||
title = toolbarTitle,
|
modifier = modifier
|
||||||
busy = busy,
|
.fillMaxSize()
|
||||||
actionsEnabled = !currentBlurred,
|
.background(Color.Black.copy(alpha = 0.96f)),
|
||||||
exportAllowed = exportAllowed,
|
) {
|
||||||
onShare = onShare,
|
HorizontalPager(
|
||||||
onSave = onSave,
|
state = pagerState,
|
||||||
onOpenExternal = onOpenExternal,
|
beyondViewportPageCount = 0,
|
||||||
onClose = onDismiss,
|
pageSpacing = 12.dp,
|
||||||
modifier = Modifier.align(Alignment.TopCenter),
|
modifier = Modifier
|
||||||
)
|
.fillMaxSize()
|
||||||
|
.testTag("attachment-gallery-pager"),
|
||||||
|
) { page ->
|
||||||
|
val pageAttachment = attachments[page]
|
||||||
|
val pageKey = galleryAttachmentKey(pageAttachment, page)
|
||||||
|
val blurred = revealed[pageKey] != true && shouldBlurImage(
|
||||||
|
blurMode,
|
||||||
|
pageAttachment.sensitive,
|
||||||
|
)
|
||||||
|
ImageBody(
|
||||||
|
attachment = pageAttachment,
|
||||||
|
blurred = blurred,
|
||||||
|
onReveal = { revealed[pageKey] = true },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
Text(
|
MediaViewerToolbar(
|
||||||
text = "${currentIndex + 1} / ${attachments.size}",
|
title = toolbarTitle,
|
||||||
style = MaterialTheme.typography.labelMedium,
|
busy = busy,
|
||||||
color = Color.White,
|
actionsEnabled = !currentBlurred,
|
||||||
modifier = Modifier
|
exportAllowed = exportAllowed,
|
||||||
.align(Alignment.BottomCenter)
|
onShare = onShare,
|
||||||
.windowInsetsPadding(WindowInsets.safeDrawing)
|
onSave = onSave,
|
||||||
.padding(bottom = 12.dp)
|
onOpenExternal = onOpenExternal,
|
||||||
.clip(RoundedCornerShape(50))
|
onClose = onDismiss,
|
||||||
.background(Color.Black.copy(alpha = 0.55f))
|
modifier = Modifier.align(Alignment.TopCenter),
|
||||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
)
|
||||||
)
|
|
||||||
|
Text(
|
||||||
|
text = "${currentIndex + 1} / ${attachments.size}",
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = Color.White,
|
||||||
|
modifier = Modifier
|
||||||
|
.align(Alignment.BottomCenter)
|
||||||
|
.windowInsetsPadding(WindowInsets.safeDrawing)
|
||||||
|
.padding(bottom = 12.dp)
|
||||||
|
.clip(RoundedCornerShape(50))
|
||||||
|
.background(Color.Black.copy(alpha = 0.55f))
|
||||||
|
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -737,17 +742,27 @@ private fun VideoBody(attachment: Attachment) {
|
|||||||
return
|
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) {
|
val player = remember(uri) {
|
||||||
ExoPlayer.Builder(context).build().apply {
|
ExoPlayer.Builder(context).build().apply {
|
||||||
setMediaItem(MediaItem.fromUri(uri))
|
setMediaItem(MediaItem.fromUri(uri))
|
||||||
|
if (savedPosition > 0L) seekTo(savedPosition)
|
||||||
|
playWhenReady = wantsToPlay
|
||||||
|
volume = if (muted) 0f else 1f
|
||||||
prepare()
|
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 isPlaying by remember { mutableStateOf(player.isPlaying) }
|
||||||
var muted by remember { mutableStateOf(false) }
|
|
||||||
var position by remember { mutableStateOf(0L) }
|
var position by remember { mutableStateOf(0L) }
|
||||||
var duration by remember { mutableStateOf(0L) }
|
var duration by remember { mutableStateOf(0L) }
|
||||||
|
|
||||||
@@ -761,24 +776,30 @@ private fun VideoBody(attachment: Attachment) {
|
|||||||
LaunchedEffect(player) {
|
LaunchedEffect(player) {
|
||||||
while (true) {
|
while (true) {
|
||||||
position = player.currentPosition.coerceAtLeast(0L)
|
position = player.currentPosition.coerceAtLeast(0L)
|
||||||
|
savedPosition = position
|
||||||
duration = player.duration.takeIf { it > 0L } ?: 0L
|
duration = player.duration.takeIf { it > 0L } ?: 0L
|
||||||
delay(250)
|
delay(250)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center) {
|
Column(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center) {
|
||||||
AndroidView(
|
Box(
|
||||||
factory = { ctx ->
|
modifier = Modifier.fillMaxWidth().weight(1f),
|
||||||
SurfaceView(ctx).also { player.setVideoSurfaceView(it) }
|
contentAlignment = Alignment.Center,
|
||||||
},
|
) {
|
||||||
modifier = Modifier.fillMaxWidth().weight(1f, fill = false).aspectRatio(16f / 9f),
|
ContentFrame(
|
||||||
)
|
player = player,
|
||||||
|
modifier = Modifier.fillMaxSize().testTag("attachment-video-content"),
|
||||||
|
contentScale = ContentScale.Fit,
|
||||||
|
)
|
||||||
|
}
|
||||||
PlaybackControls(
|
PlaybackControls(
|
||||||
isPlaying = isPlaying,
|
isPlaying = isPlaying,
|
||||||
position = position,
|
position = position,
|
||||||
duration = duration,
|
duration = duration,
|
||||||
onPlayPause = {
|
onPlayPause = {
|
||||||
if (player.isPlaying) player.pause() else player.play()
|
wantsToPlay = !player.playWhenReady
|
||||||
|
player.playWhenReady = wantsToPlay
|
||||||
},
|
},
|
||||||
onSeek = { player.seekTo(it) },
|
onSeek = { player.seekTo(it) },
|
||||||
trailing = {
|
trailing = {
|
||||||
@@ -1173,10 +1194,6 @@ private fun rememberPlayableUri(attachment: Attachment): Uri? {
|
|||||||
return uri
|
return uri
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun viewerToast(context: Context, message: String) {
|
|
||||||
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
|
|
||||||
private const val MAX_TEXT_BYTES = 2 * 1024 * 1024
|
private const val MAX_TEXT_BYTES = 2 * 1024 * 1024
|
||||||
|
|
||||||
// --- Non-composable IO helpers ---------------------------------------------
|
// --- Non-composable IO helpers ---------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.AccountTree
|
||||||
|
import androidx.compose.material.icons.filled.ChevronRight
|
||||||
|
import androidx.compose.material.icons.filled.Terminal
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.semantics.stateDescription
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.hermesandroid.relay.R
|
||||||
|
import com.hermesandroid.relay.data.ChatActivityKind
|
||||||
|
import com.hermesandroid.relay.data.ChatActivityPhase
|
||||||
|
import com.hermesandroid.relay.data.ChatActivityRecord
|
||||||
|
|
||||||
|
/** Stable transcript entry into the same read-only preview used by active work. */
|
||||||
|
@Composable
|
||||||
|
internal fun ChatActivityReceipt(
|
||||||
|
record: ChatActivityRecord,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val subagents = record.kind == ChatActivityKind.SUBAGENTS
|
||||||
|
val title = stringResource(
|
||||||
|
if (subagents) R.string.chat_activity_receipt_subagents else R.string.chat_activity_receipt_process,
|
||||||
|
)
|
||||||
|
val action = stringResource(
|
||||||
|
if (subagents) R.string.chat_activity_receipt_view_activity else R.string.chat_activity_receipt_view_output,
|
||||||
|
)
|
||||||
|
val status = if (subagents && record.children.isNotEmpty()) {
|
||||||
|
val groups = record.children.groupingBy { it.phase }.eachCount().toMutableMap()
|
||||||
|
val missing = (record.taskCount - record.children.size).coerceAtLeast(0)
|
||||||
|
if (missing > 0) groups[ChatActivityPhase.UNKNOWN] = (groups[ChatActivityPhase.UNKNOWN] ?: 0) + missing
|
||||||
|
val labels = groups.map { (phase, count) ->
|
||||||
|
stringResource(R.string.chat_activity_receipt_count_phase, count, activityPhaseLabel(phase))
|
||||||
|
}
|
||||||
|
labels.joinToString(" · ")
|
||||||
|
} else if (subagents && record.taskCount > 0) {
|
||||||
|
stringResource(R.string.chat_activity_receipt_count_phase, record.taskCount, activityPhaseLabel(record.phase))
|
||||||
|
} else {
|
||||||
|
activityPhaseLabel(record.phase)
|
||||||
|
}
|
||||||
|
Surface(
|
||||||
|
modifier = modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.heightIn(min = 48.dp)
|
||||||
|
.semantics(mergeDescendants = true) { stateDescription = status }
|
||||||
|
.clickable(role = Role.Button, onClickLabel = action, onClick = onClick),
|
||||||
|
shape = MaterialTheme.shapes.medium,
|
||||||
|
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.58f),
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
imageVector = if (subagents) Icons.Filled.AccountTree else Icons.Filled.Terminal,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = if (record.phase == ChatActivityPhase.FAILED) {
|
||||||
|
MaterialTheme.colorScheme.error
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
},
|
||||||
|
modifier = Modifier.size(16.dp),
|
||||||
|
)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(
|
||||||
|
text = "$title · $status",
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = action,
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Icon(
|
||||||
|
imageVector = Icons.Filled.ChevronRight,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun activityPhaseLabel(phase: ChatActivityPhase): String = stringResource(
|
||||||
|
when (phase) {
|
||||||
|
ChatActivityPhase.RUNNING -> R.string.bg_processes_running
|
||||||
|
ChatActivityPhase.COMPLETE -> R.string.agent_activity_status_completed
|
||||||
|
ChatActivityPhase.FAILED -> R.string.agent_activity_status_failed
|
||||||
|
ChatActivityPhase.CANCELLED -> R.string.task_status_cancelled
|
||||||
|
ChatActivityPhase.UNKNOWN -> R.string.agent_activity_status_unavailable
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.BoxScope
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.combinedClickable
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.animation.slideInVertically
|
||||||
|
import androidx.compose.animation.slideOutVertically
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.compose.ui.draw.clipToBounds
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
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.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
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.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.paneTitle
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.hermesandroid.relay.R
|
||||||
|
import com.hermesandroid.relay.diagnostics.DiagnosticsLog
|
||||||
|
import com.hermesandroid.relay.network.upstream.GatewayConnectionState
|
||||||
|
import com.hermesandroid.relay.viewmodel.ConnectionStepState
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun Modifier.chatDebugHeaderGesture(enabled: Boolean, onClick: () -> Unit, onHold: () -> Unit): Modifier =
|
||||||
|
combinedClickable(enabled = enabled, onClick = onClick, onLongClick = onHold,
|
||||||
|
onLongClickLabel = stringResource(R.string.chat_debug_open))
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun BoxScope.ChatDebugOverlay(
|
||||||
|
visible: Boolean,
|
||||||
|
headerHeight: Dp,
|
||||||
|
onClose: () -> Unit,
|
||||||
|
content: @Composable () -> Unit,
|
||||||
|
) {
|
||||||
|
BackHandler(enabled = visible, onBack = onClose)
|
||||||
|
if (visible) {
|
||||||
|
Box(Modifier.fillMaxSize().padding(top = headerHeight)
|
||||||
|
.background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.28f))
|
||||||
|
.clickable(onClick = onClose))
|
||||||
|
}
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = visible,
|
||||||
|
enter = slideInVertically { -it } + fadeIn(),
|
||||||
|
exit = slideOutVertically { -it } + fadeOut(),
|
||||||
|
modifier = Modifier.align(Alignment.TopCenter).padding(top = headerHeight).fillMaxWidth().clipToBounds(),
|
||||||
|
) { content() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read-only snapshot of the visible conversation; opening it sends no RPCs. */
|
||||||
|
@Composable
|
||||||
|
internal fun ChatDebugDrawer(
|
||||||
|
profile: String,
|
||||||
|
model: String,
|
||||||
|
sessionId: String?,
|
||||||
|
gateway: Boolean,
|
||||||
|
signedIn: Boolean,
|
||||||
|
signInRequired: Boolean,
|
||||||
|
socketState: GatewayConnectionState,
|
||||||
|
preparing: Boolean,
|
||||||
|
streaming: Boolean,
|
||||||
|
loadingHistory: Boolean,
|
||||||
|
directoryUnavailable: Boolean,
|
||||||
|
failure: String?,
|
||||||
|
onClose: () -> Unit,
|
||||||
|
onConnections: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
) {
|
||||||
|
val title = stringResource(R.string.chat_debug_title)
|
||||||
|
val safeFailure = DiagnosticsLog.redactReportText(failure)?.take(600)
|
||||||
|
val ready = socketState == GatewayConnectionState.Ready
|
||||||
|
val steps = buildList {
|
||||||
|
if (gateway) {
|
||||||
|
add(ConnectionSetupTimelineStep(
|
||||||
|
stringResource(R.string.chat_debug_sign_in),
|
||||||
|
stringResource(when {
|
||||||
|
signInRequired -> R.string.chat_debug_sign_in_needed
|
||||||
|
signedIn -> R.string.chat_debug_authenticated
|
||||||
|
else -> R.string.chat_debug_auth_unknown
|
||||||
|
}),
|
||||||
|
when {
|
||||||
|
signInRequired -> ConnectionStepState.Failed
|
||||||
|
signedIn -> ConnectionStepState.Done
|
||||||
|
else -> ConnectionStepState.Pending
|
||||||
|
},
|
||||||
|
))
|
||||||
|
add(ConnectionSetupTimelineStep(
|
||||||
|
stringResource(R.string.chat_debug_gateway),
|
||||||
|
stringResource(when (socketState) {
|
||||||
|
GatewayConnectionState.Ready -> R.string.chat_debug_socket_ready
|
||||||
|
GatewayConnectionState.MintingTicket -> R.string.chat_debug_ticket
|
||||||
|
GatewayConnectionState.Connecting -> R.string.chat_debug_socket_connecting
|
||||||
|
GatewayConnectionState.AwaitingReady -> R.string.chat_debug_socket_waiting
|
||||||
|
GatewayConnectionState.Idle -> R.string.chat_debug_socket_idle
|
||||||
|
}),
|
||||||
|
when {
|
||||||
|
ready -> ConnectionStepState.Done
|
||||||
|
signInRequired -> ConnectionStepState.Failed
|
||||||
|
socketState != GatewayConnectionState.Idle -> ConnectionStepState.Active
|
||||||
|
else -> ConnectionStepState.Pending
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
add(ConnectionSetupTimelineStep(
|
||||||
|
stringResource(R.string.chat_debug_session),
|
||||||
|
stringResource(when {
|
||||||
|
preparing -> R.string.chat_debug_preparing_detail
|
||||||
|
loadingHistory -> R.string.chat_debug_history_loading
|
||||||
|
directoryUnavailable -> R.string.chat_debug_history_failed
|
||||||
|
sessionId != null -> R.string.chat_debug_session_selected
|
||||||
|
else -> R.string.chat_debug_session_new
|
||||||
|
}),
|
||||||
|
when {
|
||||||
|
preparing || loadingHistory -> ConnectionStepState.Active
|
||||||
|
directoryUnavailable -> ConnectionStepState.Failed
|
||||||
|
sessionId != null -> ConnectionStepState.Done
|
||||||
|
else -> ConnectionStepState.Pending
|
||||||
|
},
|
||||||
|
))
|
||||||
|
add(ConnectionSetupTimelineStep(
|
||||||
|
stringResource(R.string.chat_debug_response),
|
||||||
|
stringResource(when {
|
||||||
|
safeFailure != null -> R.string.chat_debug_response_failed
|
||||||
|
preparing -> R.string.chat_debug_response_waiting
|
||||||
|
streaming -> R.string.chat_debug_response_active
|
||||||
|
else -> R.string.chat_debug_response_idle
|
||||||
|
}),
|
||||||
|
when {
|
||||||
|
safeFailure != null -> ConnectionStepState.Failed
|
||||||
|
preparing -> ConnectionStepState.Pending
|
||||||
|
streaming -> ConnectionStepState.Active
|
||||||
|
else -> ConnectionStepState.Pending
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
Surface(
|
||||||
|
modifier = modifier.fillMaxWidth().semantics { paneTitle = title },
|
||||||
|
shape = RoundedCornerShape(bottomStart = 24.dp, bottomEnd = 24.dp),
|
||||||
|
color = MaterialTheme.colorScheme.surface,
|
||||||
|
shadowElevation = 8.dp,
|
||||||
|
) {
|
||||||
|
Column(Modifier.heightIn(max = 560.dp).verticalScroll(rememberScrollState()).padding(20.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(title, style = MaterialTheme.typography.titleLarge)
|
||||||
|
Text(listOf(if (gateway) "Gateway" else "Direct API", profile, model)
|
||||||
|
.filter(String::isNotBlank).joinToString(" · "), style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
IconButton(onClick = onClose) {
|
||||||
|
Icon(Icons.Filled.Close, stringResource(R.string.chat_debug_close))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ConnectionSetupTimeline(steps)
|
||||||
|
if (safeFailure != null) {
|
||||||
|
Surface(color = MaterialTheme.colorScheme.errorContainer, shape = RoundedCornerShape(12.dp)) {
|
||||||
|
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
Text(safeFailure, style = MaterialTheme.typography.bodySmall)
|
||||||
|
if (safeFailure.contains("agent init failed", ignoreCase = true)) {
|
||||||
|
Text(stringResource(R.string.chat_debug_init_recovery), style = MaterialTheme.typography.bodySmall)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
Text(stringResource(R.string.chat_debug_session_id, sessionId ?: "—"),
|
||||||
|
style = MaterialTheme.typography.labelSmall, fontFamily = FontFamily.Monospace,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
TextButton(onClick = onConnections) { Text(stringResource(R.string.chat_debug_connections)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,7 +53,13 @@ fun ChatFailurePanel(
|
|||||||
Spacer(Modifier.width(10.dp))
|
Spacer(Modifier.width(10.dp))
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(
|
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,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = FontWeight.SemiBold,
|
fontWeight = FontWeight.SemiBold,
|
||||||
)
|
)
|
||||||
@@ -148,3 +154,10 @@ internal fun failureIdentity(route: String, model: String?, provider: String?):
|
|||||||
provider?.trim()?.takeIf { it.isNotEmpty() },
|
provider?.trim()?.takeIf { it.isNotEmpty() },
|
||||||
model?.trim()?.takeIf { it.isNotEmpty() },
|
model?.trim()?.takeIf { it.isNotEmpty() },
|
||||||
).distinct().joinToString(" · ")
|
).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.content.Intent
|
||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
|
import android.net.Uri
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
@@ -29,6 +30,7 @@ import androidx.compose.runtime.collectAsState
|
|||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.runtime.staticCompositionLocalOf
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
import androidx.compose.ui.Alignment
|
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
|
* Resolves a server-local image path — an absolute path the agent put in a
|
||||||
* markdown image `` — to raw bytes, via the relay's
|
* markdown image `` — to an on-disk cache URI, via the relay's
|
||||||
* `/media/by-path` route when a relay session is paired. Returns null when no
|
* authenticated Dashboard route (or Relay compatibility route). Returns a
|
||||||
* relay is available or the fetch fails, so the renderer falls back to the
|
* 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
|
* "this image is on the server" notice. Provided by ChatScreen from
|
||||||
* [com.hermesandroid.relay.viewmodel.ChatViewModel.resolveServerImage]; the
|
* [com.hermesandroid.relay.viewmodel.ChatViewModel.resolveServerImage]; the
|
||||||
* default is null, which preserves the standard (no-plugin) behavior where a
|
* 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).
|
* `RelayServerImage` on app open with a server-local image in history).
|
||||||
*/
|
*/
|
||||||
sealed interface ServerImageResult {
|
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
|
class Failure(val reason: String) : ServerImageResult
|
||||||
}
|
}
|
||||||
|
|
||||||
fun interface RelayServerImageResolver {
|
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 /
|
* [ServerImageResult.Failure] whose reason explains why (unpaired /
|
||||||
* sandboxed / missing / decode) so the UI can surface it instead of a
|
* sandboxed / missing / decode) so the UI can surface it instead of a
|
||||||
* generic placeholder. */
|
* generic placeholder. */
|
||||||
@@ -293,8 +295,10 @@ private sealed interface DataUrlImagePhase {
|
|||||||
@Composable
|
@Composable
|
||||||
private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
||||||
var phase by remember(image.src) { mutableStateOf<DataUrlImagePhase>(DataUrlImagePhase.Loading) }
|
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 blurMode = LocalMediaBlurMode.current
|
||||||
|
val exportAllowed = LocalImageExportAllowed.current
|
||||||
|
val viewerController = LocalChatMediaViewerController.current
|
||||||
var revealed by remember(image.src) { mutableStateOf(false) }
|
var revealed by remember(image.src) { mutableStateOf(false) }
|
||||||
LaunchedEffect(image.src) {
|
LaunchedEffect(image.src) {
|
||||||
phase = withInlineImageDecodeLock {
|
phase = withInlineImageDecodeLock {
|
||||||
@@ -329,17 +333,17 @@ private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
|||||||
reason = "Unsupported or oversized inline image.",
|
reason = "Unsupported or oversized inline image.",
|
||||||
)
|
)
|
||||||
is DataUrlImagePhase.Loaded -> {
|
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(
|
ChatImageViewer(
|
||||||
source = ChatImageViewerSource.Bitmap(
|
source = viewerSource,
|
||||||
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 },
|
|
||||||
),
|
|
||||||
onDismiss = { viewerOpen = false },
|
onDismiss = { viewerOpen = false },
|
||||||
sensitive = image.sensitive,
|
sensitive = image.sensitive,
|
||||||
initiallyRevealed = revealed,
|
initiallyRevealed = revealed,
|
||||||
@@ -358,7 +362,19 @@ private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
|||||||
.widthIn(max = maxWidth)
|
.widthIn(max = maxWidth)
|
||||||
.heightIn(max = 360.dp)
|
.heightIn(max = 360.dp)
|
||||||
.clip(RoundedCornerShape(12.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
|
@Composable
|
||||||
private fun RemoteChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
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 blurMode = LocalMediaBlurMode.current
|
||||||
|
val exportAllowed = LocalImageExportAllowed.current
|
||||||
|
val viewerController = LocalChatMediaViewerController.current
|
||||||
var revealed by remember(image.src) { mutableStateOf(false) }
|
var revealed by remember(image.src) { mutableStateOf(false) }
|
||||||
val blurred = !revealed && shouldBlurImage(blurMode, image.sensitive)
|
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(
|
ChatImageViewer(
|
||||||
source = ChatImageViewerSource.Coil(
|
source = viewerSource,
|
||||||
model = image.src,
|
|
||||||
displayName = image.alt.ifBlank { "image" },
|
|
||||||
mime = "image/*",
|
|
||||||
bytesProvider = { MediaSaver.fetchRemoteBytes(image.src).first },
|
|
||||||
),
|
|
||||||
onDismiss = { viewerOpen = false },
|
onDismiss = { viewerOpen = false },
|
||||||
sensitive = image.sensitive,
|
sensitive = image.sensitive,
|
||||||
initiallyRevealed = revealed,
|
initiallyRevealed = revealed,
|
||||||
@@ -395,7 +414,19 @@ private fun RemoteChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
|||||||
.widthIn(max = maxWidth)
|
.widthIn(max = maxWidth)
|
||||||
.heightIn(max = 360.dp)
|
.heightIn(max = 360.dp)
|
||||||
.clip(RoundedCornerShape(12.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()
|
val state by painter.state.collectAsState()
|
||||||
when (state) {
|
when (state) {
|
||||||
@@ -461,6 +492,7 @@ private fun RelayServerImage(
|
|||||||
maxWidth: Dp,
|
maxWidth: Dp,
|
||||||
resolver: RelayServerImageResolver,
|
resolver: RelayServerImageResolver,
|
||||||
) {
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
var phase by remember(image.src) {
|
var phase by remember(image.src) {
|
||||||
mutableStateOf<RelayImagePhase>(
|
mutableStateOf<RelayImagePhase>(
|
||||||
cachedInlineImage(image.src)
|
cachedInlineImage(image.src)
|
||||||
@@ -473,20 +505,22 @@ private fun RelayServerImage(
|
|||||||
phase = withContext(Dispatchers.IO) {
|
phase = withContext(Dispatchers.IO) {
|
||||||
val result = try {
|
val result = try {
|
||||||
resolver.fetch(image.src)
|
resolver.fetch(image.src)
|
||||||
} catch (t: Throwable) {
|
} catch (error: Exception) {
|
||||||
ServerImageResult.Failure(t.message ?: "relay fetch failed")
|
ServerImageResult.Failure(error.message ?: "relay fetch failed")
|
||||||
}
|
}
|
||||||
when (result) {
|
when (result) {
|
||||||
is ServerImageResult.Success -> {
|
is ServerImageResult.Success -> {
|
||||||
val bytes = result.bytes
|
val cachedUri = Uri.parse(result.cachedUri)
|
||||||
val bmp = runCatching {
|
val bmp = try {
|
||||||
decodeOrientedBitmap(bytes)
|
decodeBoundedOrientedBitmap(context, cachedUri)
|
||||||
}.getOrNull()?.asImageBitmap()
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}?.asImageBitmap()
|
||||||
if (bmp != null) {
|
if (bmp != null) {
|
||||||
putInlineImage(image.src, bmp, result.sensitive)
|
putInlineImage(image.src, bmp, result.sensitive)
|
||||||
RelayImagePhase.Loaded(bmp, result.sensitive)
|
RelayImagePhase.Loaded(bmp, result.sensitive)
|
||||||
} else {
|
} 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)
|
is ServerImageResult.Failure -> RelayImagePhase.Failed(result.reason)
|
||||||
@@ -527,23 +561,32 @@ private fun RelayServerImageContent(
|
|||||||
maxWidth: Dp,
|
maxWidth: Dp,
|
||||||
resolver: RelayServerImageResolver,
|
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 blurMode = LocalMediaBlurMode.current
|
||||||
|
val exportAllowed = LocalImageExportAllowed.current
|
||||||
|
val viewerController = LocalChatMediaViewerController.current
|
||||||
var revealed by remember(image.src) { mutableStateOf(false) }
|
var revealed by remember(image.src) { mutableStateOf(false) }
|
||||||
val sensitive = image.sensitive || fetchedSensitive
|
val sensitive = image.sensitive || fetchedSensitive
|
||||||
val blurred = !revealed && shouldBlurImage(blurMode, sensitive)
|
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(
|
ChatImageViewer(
|
||||||
source = ChatImageViewerSource.Bitmap(
|
source = viewerSource,
|
||||||
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 },
|
|
||||||
),
|
|
||||||
onDismiss = { viewerOpen = false },
|
onDismiss = { viewerOpen = false },
|
||||||
sensitive = sensitive,
|
sensitive = sensitive,
|
||||||
initiallyRevealed = revealed,
|
initiallyRevealed = revealed,
|
||||||
@@ -559,7 +602,19 @@ private fun RelayServerImageContent(
|
|||||||
.widthIn(max = maxWidth)
|
.widthIn(max = maxWidth)
|
||||||
.heightIn(max = 360.dp)
|
.heightIn(max = 360.dp)
|
||||||
.clip(RoundedCornerShape(12.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
|
||||||
|
}
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
package com.hermesandroid.relay.ui.components
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
@@ -107,135 +107,141 @@ fun ChatImageViewer(
|
|||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
MessageOverlayScope {
|
||||||
val exportAllowed = LocalImageExportAllowed.current
|
val context = LocalContext.current
|
||||||
AllowDeviceRotation()
|
val exportAllowed = LocalImageExportAllowed.current
|
||||||
val scope = rememberCoroutineScope()
|
AllowDeviceRotation()
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
var busy by remember { mutableStateOf(false) }
|
var busy by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
val blurMode = LocalMediaBlurMode.current
|
val blurMode = LocalMediaBlurMode.current
|
||||||
var revealed by remember(source) { mutableStateOf(initiallyRevealed) }
|
var revealed by remember(source) { mutableStateOf(initiallyRevealed) }
|
||||||
val blurred = !revealed && shouldBlurImage(blurMode, sensitive)
|
val blurred = !revealed && shouldBlurImage(blurMode, sensitive)
|
||||||
|
|
||||||
val gestureModifier = Modifier.fillMaxSize().zoomable()
|
val gestureModifier = Modifier.fillMaxSize().zoomable()
|
||||||
|
|
||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxSize()
|
|
||||||
.background(Color.Black.copy(alpha = 0.94f)),
|
|
||||||
contentAlignment = Alignment.Center,
|
|
||||||
) {
|
|
||||||
BlurredMedia(
|
|
||||||
blurred = blurred,
|
|
||||||
onReveal = { revealed = true },
|
|
||||||
modifier = Modifier.fillMaxSize(),
|
|
||||||
) {
|
|
||||||
when (source) {
|
|
||||||
is ChatImageViewerSource.Coil -> AsyncImage(
|
|
||||||
model = source.model,
|
|
||||||
contentDescription = source.displayName,
|
|
||||||
contentScale = ContentScale.Fit,
|
|
||||||
modifier = gestureModifier,
|
|
||||||
)
|
|
||||||
|
|
||||||
is ChatImageViewerSource.Bitmap -> Image(
|
|
||||||
bitmap = source.bitmap,
|
|
||||||
contentDescription = source.displayName,
|
|
||||||
contentScale = ContentScale.Fit,
|
|
||||||
modifier = gestureModifier,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (busy) {
|
|
||||||
CircularProgressIndicator(color = Color.White)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Control bar — top-right, inset past the status bar / notch.
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.align(Alignment.TopEnd)
|
.fillMaxSize()
|
||||||
.windowInsetsPadding(WindowInsets.safeDrawing)
|
.background(Color.Black.copy(alpha = 0.94f)),
|
||||||
.padding(8.dp),
|
contentAlignment = Alignment.Center,
|
||||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
|
||||||
) {
|
) {
|
||||||
val tint = IconButtonDefaults.iconButtonColors(contentColor = Color.White)
|
BlurredMedia(
|
||||||
val cdClose = stringResource(R.string.cd_close_viewer)
|
blurred = blurred,
|
||||||
val errorMsg = context.getString(R.string.image_viewer_error)
|
onReveal = { revealed = true },
|
||||||
if (exportAllowed) {
|
modifier = Modifier.fillMaxSize(),
|
||||||
val cdShare = stringResource(R.string.cd_share)
|
) {
|
||||||
val cdSave = stringResource(R.string.cd_save)
|
when (source) {
|
||||||
IconButton(
|
is ChatImageViewerSource.Coil -> AsyncImage(
|
||||||
onClick = {
|
model = source.model,
|
||||||
scope.launch {
|
contentDescription = source.displayName,
|
||||||
busy = true
|
contentScale = ContentScale.Fit,
|
||||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
modifier = gestureModifier,
|
||||||
busy = false
|
)
|
||||||
if (bytes == null) {
|
|
||||||
toast(context, errorMsg)
|
is ChatImageViewerSource.Bitmap -> Image(
|
||||||
return@launch
|
bitmap = source.bitmap,
|
||||||
}
|
contentDescription = source.displayName,
|
||||||
val uri = MediaSaver.stageForShare(
|
contentScale = ContentScale.Fit,
|
||||||
context,
|
modifier = gestureModifier,
|
||||||
bytes,
|
)
|
||||||
source.displayName,
|
|
||||||
source.mime,
|
|
||||||
)
|
|
||||||
MediaSaver.share(context, uri, source.mime)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
colors = tint,
|
|
||||||
) {
|
|
||||||
Icon(Icons.Filled.Share, contentDescription = cdShare)
|
|
||||||
}
|
|
||||||
val savedFmt = context.getString(R.string.image_viewer_saved)
|
|
||||||
val failedFmt = context.getString(R.string.image_viewer_failed)
|
|
||||||
IconButton(
|
|
||||||
onClick = {
|
|
||||||
scope.launch {
|
|
||||||
busy = true
|
|
||||||
val bytes = runCatching { source.bytesProvider() }.getOrNull()
|
|
||||||
if (bytes == null) {
|
|
||||||
busy = false
|
|
||||||
toast(context, errorMsg)
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
when (val result = MediaSaver.saveImage(context, bytes, source.displayName, source.mime)) {
|
|
||||||
is MediaSaver.SaveResult.Saved -> {
|
|
||||||
busy = false
|
|
||||||
toast(context, savedFmt.format(result.location))
|
|
||||||
}
|
|
||||||
MediaSaver.SaveResult.UseShareInstead -> {
|
|
||||||
busy = false
|
|
||||||
val uri = MediaSaver.stageForShare(
|
|
||||||
context,
|
|
||||||
bytes,
|
|
||||||
source.displayName,
|
|
||||||
source.mime,
|
|
||||||
)
|
|
||||||
MediaSaver.share(context, uri, source.mime)
|
|
||||||
}
|
|
||||||
is MediaSaver.SaveResult.Failed -> {
|
|
||||||
busy = false
|
|
||||||
toast(context, failedFmt.format(result.message))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
colors = tint,
|
|
||||||
) {
|
|
||||||
Icon(Icons.Filled.Download, contentDescription = cdSave)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
IconButton(onClick = onDismiss, colors = tint) {
|
|
||||||
Icon(Icons.Filled.Close, contentDescription = cdClose)
|
if (busy) {
|
||||||
|
CircularProgressIndicator(color = Color.White)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Control bar — top-right, inset past the status bar / notch.
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.align(Alignment.TopEnd)
|
||||||
|
.windowInsetsPadding(WindowInsets.safeDrawing)
|
||||||
|
.padding(8.dp),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
val tint = IconButtonDefaults.iconButtonColors(contentColor = Color.White)
|
||||||
|
val cdClose = stringResource(R.string.cd_close_viewer)
|
||||||
|
val errorMsg = context.getString(R.string.image_viewer_error)
|
||||||
|
if (exportAllowed) {
|
||||||
|
val cdShare = stringResource(R.string.cd_share)
|
||||||
|
val cdSave = stringResource(R.string.cd_save)
|
||||||
|
IconButton(
|
||||||
|
onClick = {
|
||||||
|
scope.launch {
|
||||||
|
busy = true
|
||||||
|
val bytes = try {
|
||||||
|
source.bytesProvider()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
busy = false
|
||||||
|
if (bytes == null) {
|
||||||
|
UiMessageBus.error(errorMsg)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
val uri = MediaSaver.stageForShare(
|
||||||
|
context,
|
||||||
|
bytes,
|
||||||
|
source.displayName,
|
||||||
|
source.mime,
|
||||||
|
)
|
||||||
|
MediaSaver.share(context, uri, source.mime)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
colors = tint,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Share, contentDescription = cdShare)
|
||||||
|
}
|
||||||
|
val savedFmt = context.getString(R.string.image_viewer_saved)
|
||||||
|
val failedFmt = context.getString(R.string.image_viewer_failed)
|
||||||
|
IconButton(
|
||||||
|
onClick = {
|
||||||
|
scope.launch {
|
||||||
|
busy = true
|
||||||
|
val bytes = try {
|
||||||
|
source.bytesProvider()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
if (bytes == null) {
|
||||||
|
busy = false
|
||||||
|
UiMessageBus.error(errorMsg)
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
when (val result = MediaSaver.saveImage(context, bytes, source.displayName, source.mime)) {
|
||||||
|
is MediaSaver.SaveResult.Saved -> {
|
||||||
|
busy = false
|
||||||
|
UiMessageBus.success(savedFmt.format(result.location))
|
||||||
|
}
|
||||||
|
MediaSaver.SaveResult.UseShareInstead -> {
|
||||||
|
busy = false
|
||||||
|
val uri = MediaSaver.stageForShare(
|
||||||
|
context,
|
||||||
|
bytes,
|
||||||
|
source.displayName,
|
||||||
|
source.mime,
|
||||||
|
)
|
||||||
|
MediaSaver.share(context, uri, source.mime)
|
||||||
|
}
|
||||||
|
is MediaSaver.SaveResult.Failed -> {
|
||||||
|
busy = false
|
||||||
|
UiMessageBus.error(failedFmt.format(result.message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
colors = tint,
|
||||||
|
) {
|
||||||
|
Icon(Icons.Filled.Download, contentDescription = cdSave)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
IconButton(onClick = onDismiss, colors = tint) {
|
||||||
|
Icon(Icons.Filled.Close, contentDescription = cdClose)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun toast(context: android.content.Context, message: String) {
|
|
||||||
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.hermesandroid.relay.ui.components
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
|
import com.hermesandroid.relay.data.BusyMessageAction
|
||||||
import androidx.compose.animation.AnimatedContent
|
import androidx.compose.animation.AnimatedContent
|
||||||
import androidx.compose.animation.AnimatedVisibility
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
import androidx.compose.animation.core.tween
|
import androidx.compose.animation.core.tween
|
||||||
@@ -191,6 +192,9 @@ fun ChatInputBar(
|
|||||||
physicalEnterSends: Boolean = true,
|
physicalEnterSends: Boolean = true,
|
||||||
largePasteThreshold: Int? = null,
|
largePasteThreshold: Int? = null,
|
||||||
onLargePaste: (String) -> Unit = {},
|
onLargePaste: (String) -> Unit = {},
|
||||||
|
busyAction: BusyMessageAction? = null,
|
||||||
|
correctionAvailable: Boolean = true,
|
||||||
|
onBusyActionChange: (BusyMessageAction) -> Unit = {},
|
||||||
) {
|
) {
|
||||||
val canSubmit = enabled && submitEnabled && trailing in setOf(
|
val canSubmit = enabled && submitEnabled && trailing in setOf(
|
||||||
ChatInputTrailing.SEND,
|
ChatInputTrailing.SEND,
|
||||||
@@ -236,7 +240,7 @@ fun ChatInputBar(
|
|||||||
// Correction and queueing are materially different actions. Keep the
|
// Correction and queueing are materially different actions. Keep the
|
||||||
// explanation, but lead with a visible state pill so the distinction
|
// explanation, but lead with a visible state pill so the distinction
|
||||||
// does not depend on the trailing icon or accent color alone.
|
// 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 detail = caption ?: lastCaption.orEmpty()
|
||||||
val actionLabel = when (trailing) {
|
val actionLabel = when (trailing) {
|
||||||
ChatInputTrailing.STEER -> stringResource(R.string.chat_input_steer_response)
|
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(
|
Surface(
|
||||||
shape = appearanceComposerShape(),
|
shape = appearanceComposerShape(),
|
||||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||||
@@ -646,6 +656,7 @@ fun ChatInputBar(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal data class LargeTextInsertion(
|
internal data class LargeTextInsertion(
|
||||||
val insertedText: String,
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
-54
@@ -1,6 +1,6 @@
|
|||||||
package com.hermesandroid.relay.ui.components
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||||
import androidx.compose.foundation.combinedClickable
|
import androidx.compose.foundation.combinedClickable
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
@@ -12,7 +12,6 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.platform.LocalContext
|
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||||
@@ -21,9 +20,9 @@ import com.hermesandroid.relay.ui.theme.RelayRefresh
|
|||||||
|
|
||||||
enum class ChatTransportTier(val endpointId: String, val label: String) {
|
enum class ChatTransportTier(val endpointId: String, val label: String) {
|
||||||
Gateway("gateway", "⚡ Gateway"),
|
Gateway("gateway", "⚡ Gateway"),
|
||||||
Sessions("sessions", "📡 Sessions"),
|
Sessions("sessions", "Direct API"),
|
||||||
Completions("completions", "Completions"),
|
Completions("completions", "Direct API"),
|
||||||
Runs("runs", "Runs"),
|
Runs("runs", "Direct API"),
|
||||||
Offline("offline", "offline"),
|
Offline("offline", "offline"),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,18 +66,6 @@ fun resolveChatTransportStatus(
|
|||||||
detail = "No reachable Hermes chat transport is available.",
|
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 {
|
fun manualSse(tier: ChatTransportTier, supported: Boolean): ChatTransportStatus {
|
||||||
if (!serverCapabilities.healthy) return offline()
|
if (!serverCapabilities.healthy) return offline()
|
||||||
return if (supported) {
|
return if (supported) {
|
||||||
@@ -94,23 +81,17 @@ fun resolveChatTransportStatus(
|
|||||||
}
|
}
|
||||||
|
|
||||||
return when (preference) {
|
return when (preference) {
|
||||||
"auto" -> when {
|
"auto", "gateway" -> when {
|
||||||
gatewayReady -> ChatTransportStatus(
|
gatewayReady -> ChatTransportStatus(
|
||||||
tier = ChatTransportTier.Gateway,
|
tier = ChatTransportTier.Gateway,
|
||||||
tone = ChatTransportTone.Active,
|
tone = ChatTransportTone.Active,
|
||||||
reason = "auto → Gateway (best)",
|
reason = "Gateway connected",
|
||||||
detail = ChatTransportTier.Gateway.detailText(),
|
detail = ChatTransportTier.Gateway.detailText(),
|
||||||
)
|
)
|
||||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
else -> unavailable(
|
||||||
}
|
ChatTransportTier.Gateway,
|
||||||
"gateway" -> when {
|
gatewayFallbackReason(gatewayAvailability),
|
||||||
gatewayReady -> ChatTransportStatus(
|
|
||||||
tier = ChatTransportTier.Gateway,
|
|
||||||
tone = ChatTransportTone.Active,
|
|
||||||
reason = "Gateway selected",
|
|
||||||
detail = ChatTransportTier.Gateway.detailText(),
|
|
||||||
)
|
)
|
||||||
else -> sseFallback(gatewayFallbackReason(gatewayAvailability))
|
|
||||||
}
|
}
|
||||||
"sessions" -> manualSse(ChatTransportTier.Sessions, serverCapabilities.sessionsChatStream)
|
"sessions" -> manualSse(ChatTransportTier.Sessions, serverCapabilities.sessionsChatStream)
|
||||||
"completions" -> manualSse(ChatTransportTier.Completions, serverCapabilities.portable)
|
"completions" -> manualSse(ChatTransportTier.Completions, serverCapabilities.portable)
|
||||||
@@ -119,42 +100,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 =
|
private fun gatewayFallbackReason(availability: GatewayAvailability): String =
|
||||||
when (availability) {
|
when (availability) {
|
||||||
GatewayAvailability.SignInRequired -> "gateway sign-in required"
|
GatewayAvailability.SignInRequired -> "Gateway sign-in required"
|
||||||
GatewayAvailability.Unreachable -> "gateway unavailable"
|
GatewayAvailability.Unreachable -> "Gateway unavailable"
|
||||||
GatewayAvailability.Unsupported -> "gateway unsupported"
|
GatewayAvailability.Unsupported -> "Gateway unsupported"
|
||||||
GatewayAvailability.Unknown -> "checking gateway"
|
GatewayAvailability.Unknown -> "Checking Gateway"
|
||||||
GatewayAvailability.Ready -> "gateway ready"
|
GatewayAvailability.Ready -> "Gateway ready"
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun ChatTransportTier.plainName(): String =
|
private fun ChatTransportTier.plainName(): String =
|
||||||
when (this) {
|
when (this) {
|
||||||
ChatTransportTier.Gateway -> "Gateway"
|
ChatTransportTier.Gateway -> "Gateway"
|
||||||
ChatTransportTier.Sessions -> "Sessions"
|
ChatTransportTier.Sessions -> "Direct API"
|
||||||
ChatTransportTier.Completions -> "Completions"
|
ChatTransportTier.Completions -> "Direct API"
|
||||||
ChatTransportTier.Runs -> "Runs"
|
ChatTransportTier.Runs -> "Direct API"
|
||||||
ChatTransportTier.Offline -> "offline"
|
ChatTransportTier.Offline -> "offline"
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun ChatTransportTier.detailText(): String =
|
private fun ChatTransportTier.detailText(): String =
|
||||||
when (this) {
|
when (this) {
|
||||||
ChatTransportTier.Gateway ->
|
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 ->
|
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 ->
|
ChatTransportTier.Completions ->
|
||||||
"Completions uses OpenAI-compatible SSE at /v1/chat/completions."
|
"Direct API compatibility chat."
|
||||||
ChatTransportTier.Runs ->
|
ChatTransportTier.Runs ->
|
||||||
"Runs uses /v1/runs plus streamed run events."
|
"Direct API compatibility chat with streamed run events."
|
||||||
ChatTransportTier.Offline ->
|
ChatTransportTier.Offline ->
|
||||||
"No chat transport is reachable."
|
"No chat transport is reachable."
|
||||||
}
|
}
|
||||||
@@ -166,18 +139,13 @@ fun ChatTransportStatusBadge(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
onClick: (() -> Unit)? = null,
|
onClick: (() -> Unit)? = null,
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
|
||||||
val textColor = status.textColor()
|
val textColor = status.textColor()
|
||||||
val background = status.backgroundColor()
|
val background = status.backgroundColor()
|
||||||
Surface(
|
Surface(
|
||||||
modifier = modifier.combinedClickable(
|
modifier = modifier.combinedClickable(
|
||||||
onClick = { onClick?.invoke() },
|
onClick = { onClick?.invoke() },
|
||||||
onLongClick = {
|
onLongClick = {
|
||||||
Toast.makeText(
|
UiMessageBus.info("${status.reason}: ${status.detail}")
|
||||||
context,
|
|
||||||
"${status.reason}: ${status.detail}",
|
|
||||||
Toast.LENGTH_LONG,
|
|
||||||
).show()
|
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
shape = RoundedCornerShape(999.dp),
|
shape = RoundedCornerShape(999.dp),
|
||||||
|
|||||||
+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
|
* progress" moment (pairing, long upload, a bridge action sequence). When first
|
||||||
* reused, decouple it from [ConnectionStatusSnapshot] and rename to a generic
|
* reused, decouple it from [ConnectionStatusSnapshot] and rename to a generic
|
||||||
* `StatusToast`. It also anchors [UpdateAvailableBanner]'s visual language + the
|
* `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
|
* Rendered as a top-aligned overlay inside a `Box` — it slides down OVER the UI
|
||||||
* without shifting layout. Pair it with `AnimatedVisibility(enter =
|
* without shifting layout. Pair it with `AnimatedVisibility(enter =
|
||||||
|
|||||||
@@ -741,6 +741,7 @@ fun AgentInfoSheet(
|
|||||||
val relayConnectionState by connectionViewModel.relayConnectionState.collectAsState()
|
val relayConnectionState by connectionViewModel.relayConnectionState.collectAsState()
|
||||||
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||||
val voiceReady by connectionViewModel.voiceReady.collectAsState()
|
val voiceReady by connectionViewModel.voiceReady.collectAsState()
|
||||||
|
val standardVoiceReady by connectionViewModel.standardVoiceReady.collectAsState()
|
||||||
val proactiveEnabled by connectionViewModel.proactiveEnabled.collectAsState()
|
val proactiveEnabled by connectionViewModel.proactiveEnabled.collectAsState()
|
||||||
val activeEndpoint by connectionViewModel.activeEndpoint.collectAsState()
|
val activeEndpoint by connectionViewModel.activeEndpoint.collectAsState()
|
||||||
val allConnections by connectionViewModel.connectionStore.connections.collectAsState()
|
val allConnections by connectionViewModel.connectionStore.connections.collectAsState()
|
||||||
@@ -842,6 +843,7 @@ fun AgentInfoSheet(
|
|||||||
val sessionCaps = sessionCapabilities(
|
val sessionCaps = sessionCapabilities(
|
||||||
transport = sessionTransport,
|
transport = sessionTransport,
|
||||||
gatewayAvailability = gatewayAvailability,
|
gatewayAvailability = gatewayAvailability,
|
||||||
|
upstreamMediaAvailable = gatewayAvailability == GatewayAvailability.Ready || standardVoiceReady,
|
||||||
relayConnected = relayConnectionState == ConnectionState.Connected,
|
relayConnected = relayConnectionState == ConnectionState.Connected,
|
||||||
relayConfigured = relayUrl.isNotBlank(),
|
relayConfigured = relayUrl.isNotBlank(),
|
||||||
voiceReady = voiceReady,
|
voiceReady = voiceReady,
|
||||||
@@ -3423,6 +3425,8 @@ private fun LegacyAgentInfoSheet(
|
|||||||
val sessionCaps = sessionCapabilities(
|
val sessionCaps = sessionCapabilities(
|
||||||
transport = sessionTransport,
|
transport = sessionTransport,
|
||||||
gatewayAvailability = gatewayAvailability,
|
gatewayAvailability = gatewayAvailability,
|
||||||
|
upstreamMediaAvailable = gatewayAvailability == GatewayAvailability.Ready ||
|
||||||
|
connectionViewModel.standardVoiceReady.collectAsState().value,
|
||||||
relayConnected = relayConnected,
|
relayConnected = relayConnected,
|
||||||
relayConfigured = relayUrl.isNotBlank(),
|
relayConfigured = relayUrl.isNotBlank(),
|
||||||
voiceReady = voiceReady,
|
voiceReady = voiceReady,
|
||||||
|
|||||||
+16
-4
@@ -13,6 +13,8 @@ import androidx.compose.foundation.layout.size
|
|||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Check
|
import androidx.compose.material.icons.filled.Check
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
@@ -20,10 +22,12 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.hermesandroid.relay.viewmodel.ConnectionStepState
|
||||||
|
|
||||||
data class ConnectionSetupTimelineStep(
|
data class ConnectionSetupTimelineStep(
|
||||||
val title: String,
|
val title: String,
|
||||||
val detail: String,
|
val detail: String,
|
||||||
|
val state: ConnectionStepState = ConnectionStepState.Done,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Compact completed-state timeline shared by connection and auth flows. */
|
/** Compact completed-state timeline shared by connection and auth flows. */
|
||||||
@@ -43,13 +47,21 @@ fun ConnectionSetupTimeline(
|
|||||||
Box(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.size(28.dp)
|
.size(28.dp)
|
||||||
.background(MaterialTheme.colorScheme.primaryContainer, CircleShape),
|
.background(when (step.state) {
|
||||||
|
ConnectionStepState.Failed -> MaterialTheme.colorScheme.errorContainer
|
||||||
|
ConnectionStepState.Pending -> MaterialTheme.colorScheme.surfaceVariant
|
||||||
|
else -> MaterialTheme.colorScheme.primaryContainer
|
||||||
|
}, CircleShape),
|
||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
Icon(
|
if (step.state == ConnectionStepState.Active) {
|
||||||
imageVector = Icons.Filled.Check,
|
CircularProgressIndicator(Modifier.size(17.dp), strokeWidth = 2.dp)
|
||||||
|
} else if (step.state == ConnectionStepState.Pending) {
|
||||||
|
Text("·", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
} else Icon(
|
||||||
|
imageVector = if (step.state == ConnectionStepState.Failed) Icons.Filled.Close else Icons.Filled.Check,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
tint = if (step.state == ConnectionStepState.Failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onPrimaryContainer,
|
||||||
modifier = Modifier.size(17.dp),
|
modifier = Modifier.size(17.dp),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import android.Manifest
|
|||||||
import android.content.ClipData
|
import android.content.ClipData
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.annotation.StringRes
|
import androidx.annotation.StringRes
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
@@ -132,7 +132,7 @@ import java.net.URI
|
|||||||
* Settings → Gateways. Hermes setup starts with the one Dashboard address
|
* Settings → Gateways. Hermes setup starts with the one Dashboard address
|
||||||
* the phone can open, probes public `/api/status`, and lets advertised
|
* the phone can open, probes public `/api/status`, and lets advertised
|
||||||
* capabilities select authentication. A separate public sign-in URL is never
|
* 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.
|
* routes remain explicit advanced paths.
|
||||||
*
|
*
|
||||||
* Steps:
|
* Steps:
|
||||||
@@ -343,11 +343,7 @@ fun ConnectionWizard(
|
|||||||
// user at the manual pairing paths (URL entry / 6-char code)
|
// user at the manual pairing paths (URL entry / 6-char code)
|
||||||
// instead of leaving them on a vanishing toast with no scanner.
|
// instead of leaving them on a vanishing toast with no scanner.
|
||||||
step = WizardStep.Nearby
|
step = WizardStep.Nearby
|
||||||
Toast.makeText(
|
UiMessageBus.warning(context.getString(R.string.cw_camera_denied))
|
||||||
context,
|
|
||||||
context.getString(R.string.cw_camera_denied),
|
|
||||||
Toast.LENGTH_LONG
|
|
||||||
).show()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package com.hermesandroid.relay.ui.components
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
import android.content.Context
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import android.widget.Toast
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -104,120 +103,119 @@ private fun CrashReportDialog(report: ReliabilityReport, onDismiss: () -> Unit)
|
|||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||||
) {
|
) {
|
||||||
Surface(
|
MessageOverlayScope {
|
||||||
modifier = Modifier.fillMaxWidth(0.94f),
|
Surface(
|
||||||
shape = appearanceRoundedCornerShape(24.dp),
|
modifier = Modifier.fillMaxWidth(0.94f),
|
||||||
color = MaterialTheme.colorScheme.surface,
|
shape = appearanceRoundedCornerShape(24.dp),
|
||||||
tonalElevation = 6.dp,
|
color = MaterialTheme.colorScheme.surface,
|
||||||
) {
|
tonalElevation = 6.dp,
|
||||||
Column(modifier = Modifier.padding(20.dp)) {
|
) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Column(modifier = Modifier.padding(20.dp)) {
|
||||||
Icon(
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
imageVector = Icons.Filled.WarningAmber,
|
Icon(
|
||||||
contentDescription = null,
|
imageVector = Icons.Filled.WarningAmber,
|
||||||
tint = MaterialTheme.colorScheme.error,
|
contentDescription = null,
|
||||||
modifier = Modifier.size(24.dp),
|
tint = MaterialTheme.colorScheme.error,
|
||||||
)
|
modifier = Modifier.size(24.dp),
|
||||||
Spacer(Modifier.width(12.dp))
|
)
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.crash_title),
|
||||||
|
style = MaterialTheme.typography.titleMedium,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.crash_title),
|
text = stringResource(R.string.crash_body),
|
||||||
style = MaterialTheme.typography.titleMedium,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
fontWeight = FontWeight.SemiBold,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(Modifier.height(8.dp))
|
Text(
|
||||||
Text(
|
text = stringResource(R.string.crash_privacy),
|
||||||
text = stringResource(R.string.crash_body),
|
style = MaterialTheme.typography.bodySmall,
|
||||||
style = MaterialTheme.typography.bodyMedium,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
modifier = Modifier.padding(top = 6.dp),
|
||||||
)
|
)
|
||||||
|
|
||||||
Text(
|
if (showDetails) {
|
||||||
text = stringResource(R.string.crash_privacy),
|
Spacer(Modifier.height(14.dp))
|
||||||
style = MaterialTheme.typography.bodySmall,
|
Box(
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
modifier = Modifier
|
||||||
modifier = Modifier.padding(top = 6.dp),
|
.fillMaxWidth()
|
||||||
)
|
.heightIn(min = 120.dp, max = 300.dp)
|
||||||
|
.clip(appearanceRoundedCornerShape(12.dp))
|
||||||
if (showDetails) {
|
.background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f)),
|
||||||
Spacer(Modifier.height(14.dp))
|
) {
|
||||||
Box(
|
SelectionContainer {
|
||||||
modifier = Modifier
|
Text(
|
||||||
.fillMaxWidth()
|
text = reportText,
|
||||||
.heightIn(min = 120.dp, max = 300.dp)
|
fontFamily = FontFamily.Monospace,
|
||||||
.clip(appearanceRoundedCornerShape(12.dp))
|
fontSize = 11.sp,
|
||||||
.background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f)),
|
lineHeight = 15.sp,
|
||||||
) {
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
SelectionContainer {
|
modifier = Modifier
|
||||||
Text(
|
.verticalScroll(rememberScrollState())
|
||||||
text = reportText,
|
.padding(12.dp),
|
||||||
fontFamily = FontFamily.Monospace,
|
)
|
||||||
fontSize = 11.sp,
|
}
|
||||||
lineHeight = 15.sp,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
modifier = Modifier
|
|
||||||
.verticalScroll(rememberScrollState())
|
|
||||||
.padding(12.dp),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(Modifier.height(18.dp))
|
Spacer(Modifier.height(18.dp))
|
||||||
// FlowRow so the actions wrap instead of clipping on narrow /
|
// FlowRow so the actions wrap instead of clipping on narrow /
|
||||||
// foldable cover screens now that a fourth (Share) action exists.
|
// foldable cover screens now that a fourth (Share) action exists.
|
||||||
FlowRow(
|
FlowRow(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
||||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
) {
|
) {
|
||||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_dismiss)) }
|
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_dismiss)) }
|
||||||
if (!showDetails) {
|
if (!showDetails) {
|
||||||
Button(onClick = { showDetails = true }) {
|
Button(onClick = { showDetails = true }) {
|
||||||
Text(stringResource(R.string.crash_review))
|
Text(stringResource(R.string.crash_review))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
OutlinedButton(
|
OutlinedButton(
|
||||||
onClick = {
|
onClick = {
|
||||||
IssueReport.copyToClipboard(context, reportText)
|
|
||||||
toast(context, copiedMessage)
|
|
||||||
},
|
|
||||||
) { Text(stringResource(R.string.common_copy)) }
|
|
||||||
// Universal, GitHub-free path: hand the full report to the
|
|
||||||
// system share sheet (email, chat apps, notes, Drive…). The
|
|
||||||
// user picks the destination, so nothing leaves the device
|
|
||||||
// until they choose to send it — same privacy posture as Copy.
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = {
|
|
||||||
val shared = IssueReport.share(
|
|
||||||
context,
|
|
||||||
reportSubject,
|
|
||||||
reportText,
|
|
||||||
chooserTitle = shareTitle,
|
|
||||||
)
|
|
||||||
if (!shared) {
|
|
||||||
IssueReport.copyToClipboard(context, reportText)
|
IssueReport.copyToClipboard(context, reportText)
|
||||||
toast(context, noShareMessage)
|
UiMessageBus.success(copiedMessage)
|
||||||
}
|
},
|
||||||
onDismiss()
|
) { Text(stringResource(R.string.common_copy)) }
|
||||||
},
|
// Universal, GitHub-free path: hand the full report to the
|
||||||
) { Text(stringResource(R.string.common_share)) }
|
// system share sheet (email, chat apps, notes, Drive…). The
|
||||||
Button(
|
// user picks the destination, so nothing leaves the device
|
||||||
onClick = {
|
// until they choose to send it — same privacy posture as Copy.
|
||||||
IssueReport.copyToClipboard(context, reportText)
|
OutlinedButton(
|
||||||
val opened = IssueReport.openUrl(context, CrashReporter.buildGithubIssueUrl(report))
|
onClick = {
|
||||||
toast(context, if (opened) openedMessage else noBrowserMessage)
|
val shared = IssueReport.share(
|
||||||
onDismiss()
|
context,
|
||||||
},
|
reportSubject,
|
||||||
) { Text(stringResource(R.string.common_report)) }
|
reportText,
|
||||||
|
chooserTitle = shareTitle,
|
||||||
|
)
|
||||||
|
if (!shared) {
|
||||||
|
IssueReport.copyToClipboard(context, reportText)
|
||||||
|
UiMessageBus.warning(noShareMessage)
|
||||||
|
}
|
||||||
|
onDismiss()
|
||||||
|
},
|
||||||
|
) { Text(stringResource(R.string.common_share)) }
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
IssueReport.copyToClipboard(context, reportText)
|
||||||
|
val opened = IssueReport.openUrl(context, CrashReporter.buildGithubIssueUrl(report))
|
||||||
|
if (opened) UiMessageBus.success(openedMessage)
|
||||||
|
else UiMessageBus.warning(noBrowserMessage)
|
||||||
|
onDismiss()
|
||||||
|
},
|
||||||
|
) { Text(stringResource(R.string.common_report)) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun toast(context: Context, message: String) {
|
|
||||||
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
|
|
||||||
}
|
|
||||||
|
|||||||
+144
-149
@@ -1,7 +1,7 @@
|
|||||||
package com.hermesandroid.relay.ui.components
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
import android.text.format.DateFormat
|
import android.text.format.DateFormat
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -78,159 +78,158 @@ fun DiagnosticDetailDialog(entry: DiagnosticLogEntry, onDismiss: () -> Unit) {
|
|||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||||
) {
|
) {
|
||||||
Surface(
|
MessageOverlayScope {
|
||||||
modifier = Modifier.fillMaxWidth(0.94f),
|
Surface(
|
||||||
shape = appearanceRoundedCornerShape(24.dp),
|
modifier = Modifier.fillMaxWidth(0.94f),
|
||||||
color = MaterialTheme.colorScheme.surface,
|
shape = appearanceRoundedCornerShape(24.dp),
|
||||||
tonalElevation = 6.dp,
|
color = MaterialTheme.colorScheme.surface,
|
||||||
) {
|
tonalElevation = 6.dp,
|
||||||
Column(modifier = Modifier.padding(20.dp)) {
|
) {
|
||||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
Column(modifier = Modifier.padding(20.dp)) {
|
||||||
DiagnosticSeverityChip(entry.severity)
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
Spacer(Modifier.width(10.dp))
|
DiagnosticSeverityChip(entry.severity)
|
||||||
Text(
|
Spacer(Modifier.width(10.dp))
|
||||||
text = entry.category.label,
|
Text(
|
||||||
style = MaterialTheme.typography.labelMedium,
|
text = entry.category.label,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
)
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
}
|
)
|
||||||
|
}
|
||||||
|
|
||||||
Spacer(Modifier.height(10.dp))
|
|
||||||
Text(
|
|
||||||
text = entry.title,
|
|
||||||
style = MaterialTheme.typography.titleMedium,
|
|
||||||
fontWeight = FontWeight.SemiBold,
|
|
||||||
)
|
|
||||||
|
|
||||||
Spacer(Modifier.height(10.dp))
|
|
||||||
// Metadata rows — only render the ones that are present.
|
|
||||||
MetaRow("When", DateFormat.format("yyyy-MM-dd HH:mm:ss", entry.timestampMs).toString())
|
|
||||||
MetaRow("Severity", severityName)
|
|
||||||
MetaRow("Category", entry.category.label)
|
|
||||||
entry.operation?.let { MetaRow("Operation", it) }
|
|
||||||
entry.endpointRole?.let { MetaRow("Route", it) }
|
|
||||||
entry.configuredUrl?.let { MetaRow("Configured URL", it) }
|
|
||||||
entry.requestUrl?.let { MetaRow("Request", it) }
|
|
||||||
if (entry.configuredUrl == null && entry.requestUrl == null) {
|
|
||||||
entry.url?.let { MetaRow("URL", it) }
|
|
||||||
}
|
|
||||||
entry.elapsedMs?.let { MetaRow("Elapsed", "${it}ms") }
|
|
||||||
entry.suggestion?.let { suggestion ->
|
|
||||||
Spacer(Modifier.height(10.dp))
|
Spacer(Modifier.height(10.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "Suggested next step",
|
text = entry.title,
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.titleMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
fontWeight = FontWeight.SemiBold,
|
||||||
)
|
)
|
||||||
Text(
|
|
||||||
text = suggestion,
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurface,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(Modifier.height(14.dp))
|
Spacer(Modifier.height(10.dp))
|
||||||
val body = entry.stacktrace ?: entry.detail
|
// Metadata rows — only render the ones that are present.
|
||||||
if (body != null) {
|
MetaRow("When", DateFormat.format("yyyy-MM-dd HH:mm:ss", entry.timestampMs).toString())
|
||||||
Box(
|
MetaRow("Severity", severityName)
|
||||||
modifier = Modifier
|
MetaRow("Category", entry.category.label)
|
||||||
.fillMaxWidth()
|
entry.operation?.let { MetaRow("Operation", it) }
|
||||||
.heightIn(min = 120.dp, max = 320.dp)
|
entry.endpointRole?.let { MetaRow("Route", it) }
|
||||||
.background(
|
entry.configuredUrl?.let { MetaRow("Configured URL", it) }
|
||||||
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
|
entry.requestUrl?.let { MetaRow("Request", it) }
|
||||||
appearanceRoundedCornerShape(12.dp),
|
if (entry.configuredUrl == null && entry.requestUrl == null) {
|
||||||
),
|
entry.url?.let { MetaRow("URL", it) }
|
||||||
) {
|
}
|
||||||
SelectionContainer {
|
entry.elapsedMs?.let { MetaRow("Elapsed", "${it}ms") }
|
||||||
Text(
|
entry.suggestion?.let { suggestion ->
|
||||||
text = body,
|
Spacer(Modifier.height(10.dp))
|
||||||
fontFamily = FontFamily.Monospace,
|
Text(
|
||||||
fontSize = 11.sp,
|
text = "Suggested next step",
|
||||||
lineHeight = 15.sp,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
modifier = Modifier
|
)
|
||||||
.verticalScroll(rememberScrollState())
|
Text(
|
||||||
.padding(12.dp),
|
text = suggestion,
|
||||||
)
|
style = MaterialTheme.typography.bodySmall,
|
||||||
}
|
color = MaterialTheme.colorScheme.onSurface,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
Text(
|
|
||||||
text = stringResource(R.string.diagnostic_no_detail),
|
|
||||||
style = MaterialTheme.typography.bodySmall,
|
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (expectationVisible) {
|
|
||||||
Spacer(Modifier.height(14.dp))
|
Spacer(Modifier.height(14.dp))
|
||||||
OutlinedTextField(
|
val body = entry.stacktrace ?: entry.detail
|
||||||
value = expectation,
|
if (body != null) {
|
||||||
onValueChange = { expectation = it },
|
Box(
|
||||||
label = { Text("What were you expecting to happen?") },
|
modifier = Modifier
|
||||||
supportingText = {
|
.fillMaxWidth()
|
||||||
Text(stringResource(R.string.diagnostic_routine_hint))
|
.heightIn(min = 120.dp, max = 320.dp)
|
||||||
},
|
.background(
|
||||||
minLines = 2,
|
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
|
||||||
modifier = Modifier.fillMaxWidth(),
|
appearanceRoundedCornerShape(12.dp),
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(Modifier.height(18.dp))
|
|
||||||
FlowRow(
|
|
||||||
modifier = Modifier.fillMaxWidth(),
|
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
|
||||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
|
||||||
) {
|
|
||||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_close)) }
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = {
|
|
||||||
IssueReport.copyToClipboard(context, plainText)
|
|
||||||
toast(context, copiedToast)
|
|
||||||
},
|
|
||||||
) { Text(stringResource(R.string.common_copy)) }
|
|
||||||
OutlinedButton(
|
|
||||||
onClick = {
|
|
||||||
val shared = IssueReport.share(
|
|
||||||
context,
|
|
||||||
subject = "Hermes-Relay diagnostic — ${entry.title}",
|
|
||||||
text = plainText,
|
|
||||||
chooserTitle = exportChooserTitle,
|
|
||||||
)
|
|
||||||
if (!shared) {
|
|
||||||
IssueReport.copyToClipboard(context, plainText)
|
|
||||||
toast(context, "Copied — no app found to share to")
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) { Text(stringResource(R.string.common_export)) }
|
|
||||||
Button(
|
|
||||||
enabled = !expectationVisible || expectation.isNotBlank(),
|
|
||||||
onClick = {
|
|
||||||
if (needsExpectation && !expectationVisible) {
|
|
||||||
expectationVisible = true
|
|
||||||
return@Button
|
|
||||||
}
|
|
||||||
// Copy full text first; the GitHub URL only carries the
|
|
||||||
// head of long traces, so the user can paste the rest.
|
|
||||||
IssueReport.copyToClipboard(context, plainText)
|
|
||||||
val opened = IssueReport.openUrl(
|
|
||||||
context,
|
|
||||||
IssueReport.buildGithubIssueUrl(
|
|
||||||
title = DiagnosticIssuePrefill.issueTitle(entry),
|
|
||||||
bodyMarkdown = DiagnosticIssuePrefill.issueBody(
|
|
||||||
entry,
|
|
||||||
expectation = expectation.takeIf { expectationVisible },
|
|
||||||
),
|
|
||||||
labels = DiagnosticIssuePrefill.issueLabels(entry),
|
|
||||||
),
|
),
|
||||||
)
|
) {
|
||||||
toast(
|
SelectionContainer {
|
||||||
context,
|
Text(
|
||||||
if (opened) "Full diagnostic copied — paste it into the issue if truncated"
|
text = body,
|
||||||
else "Copied — no browser found to open GitHub",
|
fontFamily = FontFamily.Monospace,
|
||||||
)
|
fontSize = 11.sp,
|
||||||
},
|
lineHeight = 15.sp,
|
||||||
) { Text(stringResource(R.string.common_report)) }
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
modifier = Modifier
|
||||||
|
.verticalScroll(rememberScrollState())
|
||||||
|
.padding(12.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Text(
|
||||||
|
text = stringResource(R.string.diagnostic_no_detail),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (expectationVisible) {
|
||||||
|
Spacer(Modifier.height(14.dp))
|
||||||
|
OutlinedTextField(
|
||||||
|
value = expectation,
|
||||||
|
onValueChange = { expectation = it },
|
||||||
|
label = { Text("What were you expecting to happen?") },
|
||||||
|
supportingText = {
|
||||||
|
Text(stringResource(R.string.diagnostic_routine_hint))
|
||||||
|
},
|
||||||
|
minLines = 2,
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(18.dp))
|
||||||
|
FlowRow(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
|
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_close)) }
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = {
|
||||||
|
IssueReport.copyToClipboard(context, plainText)
|
||||||
|
UiMessageBus.success(copiedToast)
|
||||||
|
},
|
||||||
|
) { Text(stringResource(R.string.common_copy)) }
|
||||||
|
OutlinedButton(
|
||||||
|
onClick = {
|
||||||
|
val shared = IssueReport.share(
|
||||||
|
context,
|
||||||
|
subject = "Hermes-Relay diagnostic — ${entry.title}",
|
||||||
|
text = plainText,
|
||||||
|
chooserTitle = exportChooserTitle,
|
||||||
|
)
|
||||||
|
if (!shared) {
|
||||||
|
IssueReport.copyToClipboard(context, plainText)
|
||||||
|
UiMessageBus.warning("Copied — no app found to share to")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) { Text(stringResource(R.string.common_export)) }
|
||||||
|
Button(
|
||||||
|
enabled = !expectationVisible || expectation.isNotBlank(),
|
||||||
|
onClick = {
|
||||||
|
if (needsExpectation && !expectationVisible) {
|
||||||
|
expectationVisible = true
|
||||||
|
return@Button
|
||||||
|
}
|
||||||
|
// Copy full text first; the GitHub URL only carries the
|
||||||
|
// head of long traces, so the user can paste the rest.
|
||||||
|
IssueReport.copyToClipboard(context, plainText)
|
||||||
|
val opened = IssueReport.openUrl(
|
||||||
|
context,
|
||||||
|
IssueReport.buildGithubIssueUrl(
|
||||||
|
title = DiagnosticIssuePrefill.issueTitle(entry),
|
||||||
|
bodyMarkdown = DiagnosticIssuePrefill.issueBody(
|
||||||
|
entry,
|
||||||
|
expectation = expectation.takeIf { expectationVisible },
|
||||||
|
),
|
||||||
|
labels = DiagnosticIssuePrefill.issueLabels(entry),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if (opened) UiMessageBus.success("Full diagnostic copied — paste it into the issue if truncated")
|
||||||
|
else UiMessageBus.warning("Copied — no browser found to open GitHub")
|
||||||
|
},
|
||||||
|
) { Text(stringResource(R.string.common_report)) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -276,10 +275,6 @@ internal fun DiagnosticSeverityChip(severity: DiagnosticSeverity) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun toast(context: android.content.Context, message: String) {
|
|
||||||
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Full, copy/share-ready plain-text rendering of a single diagnostic entry. */
|
/** Full, copy/share-ready plain-text rendering of a single diagnostic entry. */
|
||||||
private fun DiagnosticLogEntry.toPlainText(): String = buildString {
|
private fun DiagnosticLogEntry.toPlainText(): String = buildString {
|
||||||
appendLine("Hermes-Relay diagnostic")
|
appendLine("Hermes-Relay diagnostic")
|
||||||
|
|||||||
@@ -847,7 +847,7 @@ internal fun routeSurfaceSecurityPresentation(
|
|||||||
val label = when (surface) {
|
val label = when (surface) {
|
||||||
EndpointSurface.Standard,
|
EndpointSurface.Standard,
|
||||||
EndpointSurface.Dashboard -> "Dashboard & Gateway"
|
EndpointSurface.Dashboard -> "Dashboard & Gateway"
|
||||||
EndpointSurface.Api -> "API fallback"
|
EndpointSurface.Api -> "Direct API"
|
||||||
EndpointSurface.Relay -> "Relay tools"
|
EndpointSurface.Relay -> "Relay tools"
|
||||||
}
|
}
|
||||||
val securityVerdict = classifySurfaceSecurity(
|
val securityVerdict = classifySurfaceSecurity(
|
||||||
|
|||||||
+50
-49
@@ -24,12 +24,12 @@ import androidx.compose.material.icons.filled.AccountTree
|
|||||||
import androidx.compose.material.icons.filled.CheckCircle
|
import androidx.compose.material.icons.filled.CheckCircle
|
||||||
import androidx.compose.material.icons.filled.Close
|
import androidx.compose.material.icons.filled.Close
|
||||||
import androidx.compose.material.icons.filled.ErrorOutline
|
import androidx.compose.material.icons.filled.ErrorOutline
|
||||||
|
import androidx.compose.material.icons.filled.HelpOutline
|
||||||
|
import androidx.compose.material.icons.filled.PauseCircleOutline
|
||||||
import androidx.compose.material.icons.filled.ExpandLess
|
import androidx.compose.material.icons.filled.ExpandLess
|
||||||
import androidx.compose.material.icons.filled.ExpandMore
|
import androidx.compose.material.icons.filled.ExpandMore
|
||||||
import androidx.compose.material.icons.filled.Refresh
|
import androidx.compose.material.icons.filled.Refresh
|
||||||
import androidx.compose.material.icons.filled.PauseCircleOutline
|
|
||||||
import androidx.compose.material.icons.filled.Stop
|
import androidx.compose.material.icons.filled.Stop
|
||||||
import androidx.compose.material.icons.filled.Terminal
|
|
||||||
import androidx.compose.material.icons.filled.Visibility
|
import androidx.compose.material.icons.filled.Visibility
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
@@ -66,7 +66,6 @@ import androidx.compose.ui.unit.dp
|
|||||||
import com.hermesandroid.relay.R
|
import com.hermesandroid.relay.R
|
||||||
import com.hermesandroid.relay.network.upstream.GatewayProcess
|
import com.hermesandroid.relay.network.upstream.GatewayProcess
|
||||||
import com.hermesandroid.relay.viewmodel.SubagentActivity
|
import com.hermesandroid.relay.viewmodel.SubagentActivity
|
||||||
import com.hermesandroid.relay.viewmodel.SubagentActivityPhase
|
|
||||||
import com.hermesandroid.relay.viewmodel.SubagentChildPreview
|
import com.hermesandroid.relay.viewmodel.SubagentChildPreview
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
@@ -84,27 +83,18 @@ internal fun GatewayBackgroundProcessStrip(
|
|||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
) {
|
) {
|
||||||
// Initial/switch refreshes are silent. The strip appears only after the
|
// Completed work remains reachable from its transcript receipt. Only active
|
||||||
// session actually owns a process, avoiding a transient "Checking" row on
|
// work owns composer space; refreshing history must not resurrect the strip.
|
||||||
// every ordinary chat open.
|
|
||||||
val visibleActivities = subagentActivities.takeIf { subagentPreviewVisibility.showLifecycle }.orEmpty()
|
val visibleActivities = subagentActivities.takeIf { subagentPreviewVisibility.showLifecycle }.orEmpty()
|
||||||
if (processes.isEmpty() && visibleActivities.isEmpty()) return
|
|
||||||
|
|
||||||
val running = processes.count { it.isRunning }
|
val running = processes.count { it.isRunning }
|
||||||
val runningAgents = visibleActivities.count { !it.isTerminal }
|
val runningAgents = visibleActivities.count { !it.isTerminal }
|
||||||
val failed = processes.count { !it.isRunning && (it.exitCode ?: 0) != 0 }
|
if (running == 0 && runningAgents == 0) return
|
||||||
val failedAgents = visibleActivities.count { it.phase == SubagentActivityPhase.FAILED }
|
|
||||||
val interruptedAgents = visibleActivities.count {
|
|
||||||
it.phase == SubagentActivityPhase.INTERRUPTED ||
|
|
||||||
it.phase == SubagentActivityPhase.ENDED_WITH_PARENT
|
|
||||||
}
|
|
||||||
val failureCount = failed + failedAgents
|
|
||||||
val status = when {
|
val status = when {
|
||||||
|
runningAgents > 0 && running > 0 -> stringResource(
|
||||||
|
R.string.current_chat_activity_summary, runningAgents, running,
|
||||||
|
)
|
||||||
runningAgents > 0 -> stringResource(R.string.subagent_lane_running_count, runningAgents)
|
runningAgents > 0 -> stringResource(R.string.subagent_lane_running_count, runningAgents)
|
||||||
running > 0 -> "$running ${stringResource(R.string.bg_processes_running)}"
|
else -> "$running ${stringResource(R.string.bg_processes_running)}"
|
||||||
failureCount > 0 -> "$failureCount ${stringResource(R.string.task_status_failed)}"
|
|
||||||
interruptedAgents > 0 -> stringResource(R.string.agent_activity_status_interrupted)
|
|
||||||
else -> stringResource(R.string.task_status_complete)
|
|
||||||
}
|
}
|
||||||
val openDescription = stringResource(R.string.current_chat_activity_open)
|
val openDescription = stringResource(R.string.current_chat_activity_open)
|
||||||
|
|
||||||
@@ -130,24 +120,7 @@ internal fun GatewayBackgroundProcessStrip(
|
|||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 9.dp),
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 9.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
if (running > 0 || runningAgents > 0 || loading) {
|
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||||
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
|
||||||
} else {
|
|
||||||
Icon(
|
|
||||||
imageVector = when {
|
|
||||||
failureCount > 0 -> Icons.Filled.ErrorOutline
|
|
||||||
interruptedAgents > 0 -> Icons.Filled.PauseCircleOutline
|
|
||||||
else -> Icons.Filled.CheckCircle
|
|
||||||
},
|
|
||||||
contentDescription = null,
|
|
||||||
modifier = Modifier.size(17.dp),
|
|
||||||
tint = when {
|
|
||||||
failureCount > 0 -> MaterialTheme.colorScheme.error
|
|
||||||
interruptedAgents > 0 -> MaterialTheme.colorScheme.tertiary
|
|
||||||
else -> MaterialTheme.colorScheme.primary
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Spacer(Modifier.width(9.dp))
|
Spacer(Modifier.width(9.dp))
|
||||||
Text(
|
Text(
|
||||||
text = stringResource(R.string.current_chat_activity_title),
|
text = stringResource(R.string.current_chat_activity_title),
|
||||||
@@ -157,11 +130,7 @@ internal fun GatewayBackgroundProcessStrip(
|
|||||||
Text(
|
Text(
|
||||||
text = status,
|
text = status,
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
color = if (failureCount > 0 && running == 0) {
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
MaterialTheme.colorScheme.error
|
|
||||||
} else {
|
|
||||||
MaterialTheme.colorScheme.onSurfaceVariant
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Filled.Visibility,
|
imageVector = Icons.Filled.Visibility,
|
||||||
@@ -190,6 +159,8 @@ internal fun GatewayBackgroundProcessSheet(
|
|||||||
onDismissProcess: (String) -> Unit,
|
onDismissProcess: (String) -> Unit,
|
||||||
onOpenSubagentChild: (String) -> Unit,
|
onOpenSubagentChild: (String) -> Unit,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
|
readOnlyHistory: Boolean = false,
|
||||||
|
historyNotice: String? = null,
|
||||||
) {
|
) {
|
||||||
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
|
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = false)
|
||||||
val listState = androidx.compose.foundation.lazy.rememberLazyListState()
|
val listState = androidx.compose.foundation.lazy.rememberLazyListState()
|
||||||
@@ -246,17 +217,19 @@ internal fun GatewayBackgroundProcessSheet(
|
|||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.weight(1f)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.current_chat_activity_title),
|
stringResource(
|
||||||
|
if (readOnlyHistory) R.string.chat_activity_history_title else R.string.current_chat_activity_title,
|
||||||
|
),
|
||||||
modifier = Modifier.semantics { heading() },
|
modifier = Modifier.semantics { heading() },
|
||||||
style = MaterialTheme.typography.titleLarge,
|
style = MaterialTheme.typography.titleLarge,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.current_chat_activity_subtitle),
|
historyNotice ?: stringResource(R.string.current_chat_activity_subtitle),
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (processes.isNotEmpty()) IconButton(onClick = onRefresh, enabled = !loading) {
|
if (processes.isNotEmpty() && !readOnlyHistory) IconButton(onClick = onRefresh, enabled = !loading) {
|
||||||
if (loading) {
|
if (loading) {
|
||||||
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||||
} else {
|
} else {
|
||||||
@@ -300,7 +273,9 @@ internal fun GatewayBackgroundProcessSheet(
|
|||||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.current_chat_activity_empty),
|
stringResource(
|
||||||
|
if (readOnlyHistory) R.string.chat_activity_history_empty else R.string.current_chat_activity_empty,
|
||||||
|
),
|
||||||
modifier = Modifier.padding(top = 12.dp),
|
modifier = Modifier.padding(top = 12.dp),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
@@ -341,7 +316,7 @@ internal fun GatewayBackgroundProcessSheet(
|
|||||||
GatewayProcessRow(
|
GatewayProcessRow(
|
||||||
process = process,
|
process = process,
|
||||||
stopping = process.id in stoppingProcessIds,
|
stopping = process.id in stoppingProcessIds,
|
||||||
onStop = { onStop(process.id) },
|
onStop = if (readOnlyHistory) null else ({ onStop(process.id) }),
|
||||||
onDismiss = null,
|
onDismiss = null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -356,7 +331,7 @@ internal fun GatewayBackgroundProcessSheet(
|
|||||||
process = process,
|
process = process,
|
||||||
stopping = false,
|
stopping = false,
|
||||||
onStop = null,
|
onStop = null,
|
||||||
onDismiss = { onDismissProcess(process.id) },
|
onDismiss = if (readOnlyHistory) null else ({ onDismissProcess(process.id) }),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -384,7 +359,7 @@ private fun GatewayProcessRow(
|
|||||||
onDismiss: (() -> Unit)?,
|
onDismiss: (() -> Unit)?,
|
||||||
) {
|
) {
|
||||||
var expanded by remember(process.id) { mutableStateOf(false) }
|
var expanded by remember(process.id) { mutableStateOf(false) }
|
||||||
val failed = !process.isRunning && (process.exitCode ?: 0) != 0
|
val failed = processDisplayPhase(process) == ProcessDisplayPhase.FAILED
|
||||||
val output = sanitizeTerminalText(
|
val output = sanitizeTerminalText(
|
||||||
process.outputTail.orEmpty().ifBlank { process.outputPreview.orEmpty() },
|
process.outputTail.orEmpty().ifBlank { process.outputPreview.orEmpty() },
|
||||||
).trimEnd()
|
).trimEnd()
|
||||||
@@ -478,9 +453,11 @@ private fun GatewayProcessRow(
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun ProcessStateIcon(process: GatewayProcess, failed: Boolean, stopping: Boolean) {
|
private fun ProcessStateIcon(process: GatewayProcess, failed: Boolean, stopping: Boolean) {
|
||||||
|
val phase = processDisplayPhase(process)
|
||||||
val tint: Color = when {
|
val tint: Color = when {
|
||||||
failed -> MaterialTheme.colorScheme.error
|
failed -> MaterialTheme.colorScheme.error
|
||||||
process.isRunning || stopping -> MaterialTheme.colorScheme.primary
|
process.isRunning || stopping -> MaterialTheme.colorScheme.primary
|
||||||
|
phase == ProcessDisplayPhase.UNKNOWN || phase == ProcessDisplayPhase.CANCELLED -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
else -> MaterialTheme.colorScheme.tertiary
|
else -> MaterialTheme.colorScheme.tertiary
|
||||||
}
|
}
|
||||||
Surface(
|
Surface(
|
||||||
@@ -501,6 +478,14 @@ private fun ProcessStateIcon(process: GatewayProcess, failed: Boolean, stopping:
|
|||||||
modifier = Modifier.size(18.dp),
|
modifier = Modifier.size(18.dp),
|
||||||
tint = tint,
|
tint = tint,
|
||||||
)
|
)
|
||||||
|
phase == ProcessDisplayPhase.UNKNOWN || phase == ProcessDisplayPhase.CANCELLED -> Icon(
|
||||||
|
imageVector = if (phase == ProcessDisplayPhase.UNKNOWN) Icons.Filled.HelpOutline else Icons.Filled.PauseCircleOutline,
|
||||||
|
contentDescription = stringResource(
|
||||||
|
if (phase == ProcessDisplayPhase.UNKNOWN) R.string.agent_activity_status_unavailable else R.string.task_status_cancelled,
|
||||||
|
),
|
||||||
|
modifier = Modifier.size(18.dp),
|
||||||
|
tint = tint,
|
||||||
|
)
|
||||||
else -> Icon(
|
else -> Icon(
|
||||||
Icons.Filled.CheckCircle,
|
Icons.Filled.CheckCircle,
|
||||||
contentDescription = stringResource(R.string.tool_completed_a11y),
|
contentDescription = stringResource(R.string.tool_completed_a11y),
|
||||||
@@ -514,8 +499,11 @@ private fun ProcessStateIcon(process: GatewayProcess, failed: Boolean, stopping:
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun processMetadata(process: GatewayProcess, failed: Boolean): String {
|
private fun processMetadata(process: GatewayProcess, failed: Boolean): String {
|
||||||
|
val phase = processDisplayPhase(process)
|
||||||
val state = when {
|
val state = when {
|
||||||
process.isRunning -> stringResource(R.string.bg_processes_running)
|
process.isRunning -> stringResource(R.string.bg_processes_running)
|
||||||
|
phase == ProcessDisplayPhase.UNKNOWN -> stringResource(R.string.agent_activity_status_unavailable)
|
||||||
|
phase == ProcessDisplayPhase.CANCELLED -> stringResource(R.string.task_status_cancelled)
|
||||||
failed -> stringResource(R.string.task_status_failed) +
|
failed -> stringResource(R.string.task_status_failed) +
|
||||||
process.exitCode?.let { " · exit $it" }.orEmpty()
|
process.exitCode?.let { " · exit $it" }.orEmpty()
|
||||||
else -> stringResource(R.string.task_status_complete) +
|
else -> stringResource(R.string.task_status_complete) +
|
||||||
@@ -525,6 +513,19 @@ private fun processMetadata(process: GatewayProcess, failed: Boolean): String {
|
|||||||
if (process.detached) " · recovered" else ""
|
if (process.detached) " · recovered" else ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal enum class ProcessDisplayPhase { RUNNING, COMPLETE, FAILED, CANCELLED, UNKNOWN }
|
||||||
|
|
||||||
|
/** A recovered or unfamiliar state is not evidence of successful completion. */
|
||||||
|
internal fun processDisplayPhase(process: GatewayProcess): ProcessDisplayPhase = when {
|
||||||
|
process.isRunning -> ProcessDisplayPhase.RUNNING
|
||||||
|
process.status.equals("unknown", ignoreCase = true) -> ProcessDisplayPhase.UNKNOWN
|
||||||
|
process.status.equals("cancelled", ignoreCase = true) ||
|
||||||
|
process.status.equals("canceled", ignoreCase = true) -> ProcessDisplayPhase.CANCELLED
|
||||||
|
process.status.equals("failed", ignoreCase = true) || (process.exitCode ?: 0) != 0 -> ProcessDisplayPhase.FAILED
|
||||||
|
process.exitCode == 0 || process.status.lowercase() in setOf("complete", "completed", "exited") -> ProcessDisplayPhase.COMPLETE
|
||||||
|
else -> ProcessDisplayPhase.UNKNOWN
|
||||||
|
}
|
||||||
|
|
||||||
private val ansiTerminalEscape = Regex(
|
private val ansiTerminalEscape = Regex(
|
||||||
"\u001B(?:\\].*?(?:\u0007|\u001B\\\\)|\\[[0-?]*[ -/]*[@-~]|[ -/]*[@-~])",
|
"\u001B(?:\\].*?(?:\u0007|\u001B\\\\)|\\[[0-?]*[ -/]*[@-~]|[ -/]*[@-~])",
|
||||||
RegexOption.DOT_MATCHES_ALL,
|
RegexOption.DOT_MATCHES_ALL,
|
||||||
|
|||||||
+92
-32
@@ -5,7 +5,7 @@ import android.graphics.Bitmap
|
|||||||
import android.graphics.pdf.PdfRenderer
|
import android.graphics.pdf.PdfRenderer
|
||||||
import android.media.MediaMetadataRetriever
|
import android.media.MediaMetadataRetriever
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import com.hermesandroid.relay.R
|
import com.hermesandroid.relay.R
|
||||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||||
@@ -14,6 +14,7 @@ import androidx.compose.foundation.Image
|
|||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.combinedClickable
|
import androidx.compose.foundation.combinedClickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.aspectRatio
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
@@ -44,6 +45,7 @@ import androidx.compose.runtime.getValue
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
@@ -206,29 +208,49 @@ private fun FailedCard(
|
|||||||
modifier: Modifier,
|
modifier: Modifier,
|
||||||
maxWidth: Dp
|
maxWidth: Dp
|
||||||
) {
|
) {
|
||||||
|
val hostOnly = attachment.errorMessage == ChatViewModel.MEDIA_HOST_ONLY
|
||||||
Surface(
|
Surface(
|
||||||
shape = appearanceRoundedCornerShape(10.dp),
|
shape = appearanceRoundedCornerShape(10.dp),
|
||||||
color = MaterialTheme.colorScheme.errorContainer,
|
color = if (hostOnly) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.errorContainer,
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.widthIn(max = maxWidth)
|
.widthIn(max = maxWidth)
|
||||||
.clickable { onRetry() }
|
.then(if (hostOnly) Modifier else Modifier.clickable { onRetry() })
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.padding(12.dp),
|
modifier = Modifier.padding(12.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
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)) {
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
Text(
|
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,
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
color = MaterialTheme.colorScheme.onErrorContainer
|
color = if (hostOnly) {
|
||||||
|
MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
} else {
|
||||||
|
MaterialTheme.colorScheme.onErrorContainer
|
||||||
|
},
|
||||||
)
|
)
|
||||||
Text(
|
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,
|
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) {
|
LaunchedEffect(attachment.cachedUri, attachment.content) {
|
||||||
val decoded = withContext(Dispatchers.IO) {
|
val decoded = withContext(Dispatchers.IO) {
|
||||||
runCatching {
|
try {
|
||||||
val bytes: ByteArray? = when {
|
when {
|
||||||
!attachment.cachedUri.isNullOrBlank() ->
|
!attachment.cachedUri.isNullOrBlank() ->
|
||||||
context.contentResolver.openInputStream(Uri.parse(attachment.cachedUri))
|
decodeBoundedOrientedBitmap(context, Uri.parse(attachment.cachedUri))
|
||||||
?.use { it.readBytes() }
|
?.asImageBitmap()
|
||||||
attachment.content.isNotBlank() ->
|
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
|
else -> null
|
||||||
}
|
}
|
||||||
bytes?.let { decodeOrientedBitmap(it)?.asImageBitmap() }
|
} catch (_: Exception) {
|
||||||
}.getOrNull()
|
null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (decoded != null) bitmap = decoded else decodeFailed = true
|
if (decoded != null) bitmap = decoded else decodeFailed = true
|
||||||
}
|
}
|
||||||
@@ -309,9 +335,14 @@ private fun ImageRender(
|
|||||||
}
|
}
|
||||||
|
|
||||||
val blurMode = LocalMediaBlurMode.current
|
val blurMode = LocalMediaBlurMode.current
|
||||||
|
val viewerController = LocalChatMediaViewerController.current
|
||||||
var revealed by remember(attachment.cachedUri, attachment.content) { mutableStateOf(false) }
|
var revealed by remember(attachment.cachedUri, attachment.content) { mutableStateOf(false) }
|
||||||
val blurred = !revealed && shouldBlurImage(blurMode, attachment.sensitive)
|
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) }
|
var menuExpanded by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
val bmp = bitmap
|
val bmp = bitmap
|
||||||
@@ -332,7 +363,7 @@ private fun ImageRender(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (viewerOpen) {
|
if (viewerController == null && viewerOpen) {
|
||||||
AttachmentViewer(
|
AttachmentViewer(
|
||||||
attachment = attachment,
|
attachment = attachment,
|
||||||
onDismiss = { viewerOpen = false },
|
onDismiss = { viewerOpen = false },
|
||||||
@@ -347,12 +378,25 @@ private fun ImageRender(
|
|||||||
contentDescription = attachment.fileName,
|
contentDescription = attachment.fileName,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.widthIn(max = maxWidth)
|
.widthIn(max = maxWidth)
|
||||||
|
.fillMaxWidth()
|
||||||
|
.aspectRatio(bmp.width.toFloat() / bmp.height.coerceAtLeast(1))
|
||||||
.clip(RoundedCornerShape(8.dp))
|
.clip(RoundedCornerShape(8.dp))
|
||||||
.combinedClickable(
|
.combinedClickable(
|
||||||
onClick = { viewerOpen = true },
|
onClick = {
|
||||||
|
if (viewerController != null) {
|
||||||
|
viewerController.openAttachment(
|
||||||
|
attachment = attachment,
|
||||||
|
initiallyRevealed = revealed,
|
||||||
|
blurMode = blurMode,
|
||||||
|
exportAllowed = exportAllowed,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
viewerOpen = true
|
||||||
|
}
|
||||||
|
},
|
||||||
onLongClick = { menuExpanded = true },
|
onLongClick = { menuExpanded = true },
|
||||||
),
|
),
|
||||||
contentScale = ContentScale.FillWidth,
|
contentScale = ContentScale.Fit,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
// One-tap save overlay — hidden while the blur cover is up so it
|
// One-tap save overlay — hidden while the blur cover is up so it
|
||||||
@@ -386,15 +430,20 @@ private fun FileCardRender(
|
|||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val (emoji, typeLabel) = emojiAndLabelFor(attachment.renderMode, attachment.contentType)
|
val (emoji, typeLabel) = emojiAndLabelFor(attachment.renderMode, attachment.contentType)
|
||||||
var menuExpanded by remember { mutableStateOf(false) }
|
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);
|
// Real thumbnail when one is cheap (video first frame, PDF first page);
|
||||||
// null falls back to the type emoji.
|
// null falls back to the type emoji.
|
||||||
val thumbnail = rememberAttachmentThumbnail(attachment)
|
val thumbnail = rememberAttachmentThumbnail(attachment)
|
||||||
val blurMode = LocalMediaBlurMode.current
|
val blurMode = LocalMediaBlurMode.current
|
||||||
|
val viewerController = LocalChatMediaViewerController.current
|
||||||
val blurThumb = thumbnail != null && shouldBlurThumb(blurMode, attachment)
|
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.
|
// Non-image types don't blur in the viewer; open straight through.
|
||||||
AttachmentViewer(
|
AttachmentViewer(
|
||||||
attachment = attachment,
|
attachment = attachment,
|
||||||
@@ -410,7 +459,18 @@ private fun FileCardRender(
|
|||||||
.widthIn(max = maxWidth)
|
.widthIn(max = maxWidth)
|
||||||
// Tap previews in-app; long-press surfaces Open-externally / Share / Save.
|
// Tap previews in-app; long-press surfaces Open-externally / Share / Save.
|
||||||
.combinedClickable(
|
.combinedClickable(
|
||||||
onClick = { viewerOpen = true },
|
onClick = {
|
||||||
|
if (viewerController != null) {
|
||||||
|
viewerController.openAttachment(
|
||||||
|
attachment = attachment,
|
||||||
|
initiallyRevealed = true,
|
||||||
|
blurMode = blurMode,
|
||||||
|
exportAllowed = exportAllowed,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
viewerOpen = true
|
||||||
|
}
|
||||||
|
},
|
||||||
onLongClick = { menuExpanded = true },
|
onLongClick = { menuExpanded = true },
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
@@ -556,7 +616,7 @@ fun SaveOverlayButton(onClick: () -> Unit, modifier: Modifier = Modifier) {
|
|||||||
private suspend fun shareAttachment(context: Context, attachment: Attachment) {
|
private suspend fun shareAttachment(context: Context, attachment: Attachment) {
|
||||||
val bytes = attachmentBytes(context, attachment)
|
val bytes = attachmentBytes(context, attachment)
|
||||||
if (bytes == null) {
|
if (bytes == null) {
|
||||||
attachmentToast(context, context.getString(R.string.inbound_attach_share_failed))
|
UiMessageBus.error(context.getString(R.string.inbound_attach_share_failed))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
||||||
@@ -566,7 +626,7 @@ private suspend fun shareAttachment(context: Context, attachment: Attachment) {
|
|||||||
suspend fun saveAttachment(context: Context, attachment: Attachment) {
|
suspend fun saveAttachment(context: Context, attachment: Attachment) {
|
||||||
val bytes = attachmentBytes(context, attachment)
|
val bytes = attachmentBytes(context, attachment)
|
||||||
if (bytes == null) {
|
if (bytes == null) {
|
||||||
attachmentToast(context, context.getString(R.string.inbound_attach_share_failed))
|
UiMessageBus.error(context.getString(R.string.inbound_attach_share_failed))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val result = if (attachment.renderMode == AttachmentRenderMode.IMAGE) {
|
val result = if (attachment.renderMode == AttachmentRenderMode.IMAGE) {
|
||||||
@@ -576,13 +636,13 @@ suspend fun saveAttachment(context: Context, attachment: Attachment) {
|
|||||||
}
|
}
|
||||||
when (result) {
|
when (result) {
|
||||||
is MediaSaver.SaveResult.Saved ->
|
is MediaSaver.SaveResult.Saved ->
|
||||||
attachmentToast(context, context.getString(R.string.inbound_attach_saved, result.location))
|
UiMessageBus.success(context.getString(R.string.inbound_attach_saved, result.location))
|
||||||
MediaSaver.SaveResult.UseShareInstead -> {
|
MediaSaver.SaveResult.UseShareInstead -> {
|
||||||
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
val uri = MediaSaver.stageForShare(context, bytes, attachment.fileName, attachment.contentType)
|
||||||
MediaSaver.share(context, uri, attachment.contentType)
|
MediaSaver.share(context, uri, attachment.contentType)
|
||||||
}
|
}
|
||||||
is MediaSaver.SaveResult.Failed ->
|
is MediaSaver.SaveResult.Failed ->
|
||||||
attachmentToast(context, context.getString(R.string.inbound_attach_save_failed, result.message))
|
UiMessageBus.error(context.getString(R.string.inbound_attach_save_failed, result.message))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -598,7 +658,7 @@ private suspend fun openAttachmentExternally(context: Context, attachment: Attac
|
|||||||
if (uri != null) {
|
if (uri != null) {
|
||||||
MediaSaver.open(context, uri, attachment.contentType)
|
MediaSaver.open(context, uri, attachment.contentType)
|
||||||
} else {
|
} else {
|
||||||
attachmentToast(context, context.getString(R.string.inbound_attach_open_failed))
|
UiMessageBus.error(context.getString(R.string.inbound_attach_open_failed))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -628,7 +688,11 @@ private fun rememberAttachmentThumbnail(attachment: Attachment): ImageBitmap? {
|
|||||||
}
|
}
|
||||||
LaunchedEffect(attachment.cachedUri, attachment.content, attachment.renderMode) {
|
LaunchedEffect(attachment.cachedUri, attachment.content, attachment.renderMode) {
|
||||||
thumb = withContext(Dispatchers.IO) {
|
thumb = withContext(Dispatchers.IO) {
|
||||||
runCatching { generateThumbnail(context, attachment) }.getOrNull()
|
try {
|
||||||
|
generateThumbnail(context, attachment)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return thumb
|
return thumb
|
||||||
@@ -710,10 +774,6 @@ internal suspend fun attachmentBytes(context: Context, attachment: Attachment):
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun attachmentToast(context: Context, message: String) {
|
|
||||||
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun emojiAndLabelFor(
|
private fun emojiAndLabelFor(
|
||||||
mode: AttachmentRenderMode,
|
mode: AttachmentRenderMode,
|
||||||
|
|||||||
@@ -46,7 +46,11 @@ internal fun decodeInlineImageDataUrl(
|
|||||||
// ceil(maxBytes / 3) * 4 plus at most two trailing padding characters.
|
// ceil(maxBytes / 3) * 4 plus at most two trailing padding characters.
|
||||||
val maxEncoded = ((maxBytes.toLong() + 2L) / 3L) * 4L
|
val maxEncoded = ((maxBytes.toLong() + 2L) / 3L) * 4L
|
||||||
if (encoded.length.toLong() > maxEncoded) return null
|
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
|
if (bytes.isEmpty() || bytes.size > maxBytes || !matchesImageMagic(mime, bytes)) return null
|
||||||
return DecodedInlineImageData(bytes, mime)
|
return DecodedInlineImageData(bytes, mime)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ fun MarkdownContent(
|
|||||||
modifier: Modifier = Modifier
|
modifier: Modifier = Modifier
|
||||||
) {
|
) {
|
||||||
ConfiguredMarkdownContent(
|
ConfiguredMarkdownContent(
|
||||||
content = content,
|
content = markdownRenderWindow(content),
|
||||||
textColor = textColor,
|
textColor = textColor,
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
)
|
)
|
||||||
@@ -318,7 +318,7 @@ fun StreamingMarkdownContent(
|
|||||||
var generation by remember { mutableIntStateOf(0) }
|
var generation by remember { mutableIntStateOf(0) }
|
||||||
key(generation) {
|
key(generation) {
|
||||||
NativeStreamingMarkdownGeneration(
|
NativeStreamingMarkdownGeneration(
|
||||||
content = content.withoutLeadingBlankLines(),
|
content = markdownRenderWindow(content.withoutLeadingBlankLines()),
|
||||||
textColor = textColor,
|
textColor = textColor,
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
onResetRequired = { generation += 1 },
|
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(
|
internal data class StreamingMarkdownAppendPlan(
|
||||||
val resetRequired: Boolean,
|
val resetRequired: Boolean,
|
||||||
val delta: String,
|
val delta: String,
|
||||||
|
|||||||
@@ -26,11 +26,13 @@ import androidx.compose.material.icons.filled.Info
|
|||||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||||
import androidx.compose.material.icons.filled.Sync
|
import androidx.compose.material.icons.filled.Sync
|
||||||
|
import androidx.compose.material.icons.filled.Warning
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
import androidx.compose.runtime.DisposableEffect
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -46,6 +48,7 @@ import androidx.compose.ui.semantics.LiveRegionMode
|
|||||||
import androidx.compose.ui.semantics.liveRegion
|
import androidx.compose.ui.semantics.liveRegion
|
||||||
import androidx.compose.ui.semantics.semantics
|
import androidx.compose.ui.semantics.semantics
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.compositeOver
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
@@ -53,7 +56,9 @@ import androidx.compose.ui.unit.dp
|
|||||||
import com.hermesandroid.relay.R
|
import com.hermesandroid.relay.R
|
||||||
import com.hermesandroid.relay.ui.UiMessage
|
import com.hermesandroid.relay.ui.UiMessage
|
||||||
import com.hermesandroid.relay.ui.UiMessageBus
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
|
import com.hermesandroid.relay.ui.UiMessageEvent
|
||||||
import com.hermesandroid.relay.ui.UiMessageSeverity
|
import com.hermesandroid.relay.ui.UiMessageSeverity
|
||||||
|
import com.hermesandroid.relay.ui.reduceUiMessages
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
private const val MAX_RETAINED = 6
|
private const val MAX_RETAINED = 6
|
||||||
@@ -61,20 +66,26 @@ private const val MAX_VISIBLE_EXPANDED = 3
|
|||||||
private const val ROW_MIN_HEIGHT_DP = 34
|
private const val ROW_MIN_HEIGHT_DP = 34
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Top, thin, info-only banner host. Collects [UiMessageBus] and renders the
|
* Top, thin, themed banner host. Collects [UiMessageBus] and renders the
|
||||||
* newest transient message on one line; tapping expands to the recent few
|
* newest transient message on one line; tapping expands to the recent few
|
||||||
* (scrolling past three). It takes its own vertical space — the Scaffold below
|
* (scrolling past three). It takes its own vertical space — the Scaffold below
|
||||||
* reflows, so content slides down smoothly instead of being covered by an
|
* reflows, so content slides down smoothly instead of being covered by an
|
||||||
* overlay. Auto-dismisses (paused while expanded) and coalesces duplicates so a
|
* overlay. Auto-dismisses (paused while expanded) and coalesces duplicates so a
|
||||||
* burst of the same status collapses to one refreshed row.
|
* burst of the same status collapses to one refreshed row.
|
||||||
*
|
*
|
||||||
* Errors stay on the snackbar — only post info/success/status here.
|
* Actionable messages use ThemedMessageHost. Modal hosts render above their
|
||||||
|
* dialog while the primary host retains messages for the return to the app.
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun MessageBannerHost(
|
fun MessageBannerHost(
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
includeStatusBarPadding: Boolean = true,
|
includeStatusBarPadding: Boolean = true,
|
||||||
|
primary: Boolean = true,
|
||||||
) {
|
) {
|
||||||
|
val hostId = remember { UiMessageBus.registerHost(primary) }
|
||||||
|
val activeHost by UiMessageBus.activeHost.collectAsState()
|
||||||
|
val active = activeHost == hostId
|
||||||
|
DisposableEffect(hostId) { onDispose { UiMessageBus.unregisterHost(hostId) } }
|
||||||
// Backing queue (oldest first; newest is last). expiresAt is kept in a
|
// Backing queue (oldest first; newest is last). expiresAt is kept in a
|
||||||
// parallel map so coalescing/auto-dismiss can address rows by id.
|
// parallel map so coalescing/auto-dismiss can address rows by id.
|
||||||
val shown = remember { mutableStateListOf<UiMessage>() }
|
val shown = remember { mutableStateListOf<UiMessage>() }
|
||||||
@@ -82,18 +93,19 @@ fun MessageBannerHost(
|
|||||||
var expanded by remember { mutableStateOf(false) }
|
var expanded by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
UiMessageBus.events.collect { msg ->
|
UiMessageBus.events.collect { event ->
|
||||||
// Coalesce identical text so e.g. repeated "Reconnecting…" collapses
|
val next = reduceUiMessages(shown, event, MAX_RETAINED)
|
||||||
// to a single, freshly-timed row rather than stacking.
|
val retainedIds = next.mapTo(mutableSetOf()) { it.id }
|
||||||
shown.filter { it.text == msg.text }.forEach { dup ->
|
expiresAt.keys.filterNot(retainedIds::contains).forEach { expiresAt.remove(it) }
|
||||||
shown.remove(dup)
|
shown.clear()
|
||||||
expiresAt.remove(dup.id)
|
shown.addAll(next)
|
||||||
}
|
if (event is UiMessageEvent.Show) {
|
||||||
shown.add(msg)
|
val msg = event.message
|
||||||
expiresAt[msg.id] = nowMs() + msg.ttlMillis
|
expiresAt[msg.id] = if (msg.ttlMillis == 0L) {
|
||||||
while (shown.size > MAX_RETAINED) {
|
Long.MAX_VALUE
|
||||||
val dropped = shown.removeAt(0)
|
} else {
|
||||||
expiresAt.remove(dropped.id)
|
nowMs() + msg.ttlMillis
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -104,6 +116,7 @@ fun MessageBannerHost(
|
|||||||
while (shown.isNotEmpty()) {
|
while (shown.isNotEmpty()) {
|
||||||
val now = nowMs()
|
val now = nowMs()
|
||||||
val soonest = shown.minOfOrNull { expiresAt[it.id] ?: Long.MAX_VALUE } ?: break
|
val soonest = shown.minOfOrNull { expiresAt[it.id] ?: Long.MAX_VALUE } ?: break
|
||||||
|
if (soonest == Long.MAX_VALUE) break
|
||||||
if (soonest <= now) {
|
if (soonest <= now) {
|
||||||
shown.filter { (expiresAt[it.id] ?: Long.MAX_VALUE) <= now }.forEach { expired ->
|
shown.filter { (expiresAt[it.id] ?: Long.MAX_VALUE) <= now }.forEach { expired ->
|
||||||
shown.remove(expired)
|
shown.remove(expired)
|
||||||
@@ -116,12 +129,12 @@ fun MessageBannerHost(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Collapse + report count to the scaffold (for inset accounting).
|
// Collapse + report count to the scaffold (for inset accounting).
|
||||||
LaunchedEffect(shown.size) {
|
LaunchedEffect(shown.size, active) {
|
||||||
if (shown.isEmpty()) expanded = false
|
if (shown.isEmpty()) expanded = false
|
||||||
UiMessageBus.reportActiveCount(shown.size)
|
if (primary) UiMessageBus.reportActiveCount(if (active) shown.size else 0)
|
||||||
}
|
}
|
||||||
DisposableEffect(Unit) {
|
DisposableEffect(Unit) {
|
||||||
onDispose { UiMessageBus.reportActiveCount(0) }
|
onDispose { if (primary) UiMessageBus.reportActiveCount(0) }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mirror the live queue into a retained copy so the exit animation still
|
// Mirror the live queue into a retained copy so the exit animation still
|
||||||
@@ -141,7 +154,7 @@ fun MessageBannerHost(
|
|||||||
// under the notch. The smooth "slide" lives in animateContentSize below
|
// under the notch. The smooth "slide" lives in animateContentSize below
|
||||||
// (collapsed↔expanded and message-count changes).
|
// (collapsed↔expanded and message-count changes).
|
||||||
AnimatedVisibility(
|
AnimatedVisibility(
|
||||||
visible = shown.isNotEmpty(),
|
visible = active && shown.isNotEmpty(),
|
||||||
enter = fadeIn(tween(180)),
|
enter = fadeIn(tween(180)),
|
||||||
exit = fadeOut(tween(160)),
|
exit = fadeOut(tween(160)),
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
@@ -149,7 +162,7 @@ fun MessageBannerHost(
|
|||||||
MessageBannerContent(
|
MessageBannerContent(
|
||||||
messages = rendered,
|
messages = rendered,
|
||||||
expanded = expanded,
|
expanded = expanded,
|
||||||
onToggle = { if (rendered.size > 1) expanded = !expanded },
|
onToggle = { expanded = !expanded },
|
||||||
includeStatusBarPadding = includeStatusBarPadding,
|
includeStatusBarPadding = includeStatusBarPadding,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -164,6 +177,7 @@ private fun MessageBannerContent(
|
|||||||
) {
|
) {
|
||||||
val newest = messages.lastOrNull() ?: return
|
val newest = messages.lastOrNull() ?: return
|
||||||
val multiple = messages.size > 1
|
val multiple = messages.size > 1
|
||||||
|
val expandable = multiple || newest.text.length > 80 || newest.severity in setOf(UiMessageSeverity.Warning, UiMessageSeverity.Error)
|
||||||
val insetModifier = if (includeStatusBarPadding) {
|
val insetModifier = if (includeStatusBarPadding) {
|
||||||
Modifier.windowInsetsPadding(WindowInsets.statusBars)
|
Modifier.windowInsetsPadding(WindowInsets.statusBars)
|
||||||
} else {
|
} else {
|
||||||
@@ -184,14 +198,14 @@ private fun MessageBannerContent(
|
|||||||
tonalElevation = 0.dp,
|
tonalElevation = 0.dp,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.then(if (multiple) Modifier.clickable(onClick = onToggle) else Modifier)
|
.then(if (expandable) Modifier.clickable(onClick = onToggle) else Modifier)
|
||||||
.animateContentSize(animationSpec = tween(durationMillis = 180)),
|
.animateContentSize(animationSpec = tween(durationMillis = 180)),
|
||||||
) {
|
) {
|
||||||
if (!expanded) {
|
if (!expanded) {
|
||||||
MessageRow(
|
MessageRow(
|
||||||
message = newest,
|
message = newest,
|
||||||
trailing = {
|
trailing = {
|
||||||
if (multiple) {
|
if (expandable) {
|
||||||
Row(
|
Row(
|
||||||
horizontalArrangement = Arrangement.spacedBy(2.dp),
|
horizontalArrangement = Arrangement.spacedBy(2.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
@@ -230,6 +244,7 @@ private fun MessageBannerContent(
|
|||||||
ordered.forEachIndexed { index, message ->
|
ordered.forEachIndexed { index, message ->
|
||||||
MessageRow(
|
MessageRow(
|
||||||
message = message,
|
message = message,
|
||||||
|
expanded = true,
|
||||||
trailing = {
|
trailing = {
|
||||||
if (index == 0) {
|
if (index == 0) {
|
||||||
Icon(
|
Icon(
|
||||||
@@ -250,6 +265,7 @@ private fun MessageBannerContent(
|
|||||||
@Composable
|
@Composable
|
||||||
private fun MessageRow(
|
private fun MessageRow(
|
||||||
message: UiMessage,
|
message: UiMessage,
|
||||||
|
expanded: Boolean = false,
|
||||||
trailing: @Composable (() -> Unit)? = null,
|
trailing: @Composable (() -> Unit)? = null,
|
||||||
) {
|
) {
|
||||||
Row(
|
Row(
|
||||||
@@ -269,7 +285,7 @@ private fun MessageRow(
|
|||||||
Text(
|
Text(
|
||||||
text = message.text,
|
text = message.text,
|
||||||
style = MaterialTheme.typography.labelMedium,
|
style = MaterialTheme.typography.labelMedium,
|
||||||
maxLines = 1,
|
maxLines = if (expanded) 12 else 1,
|
||||||
overflow = TextOverflow.Ellipsis,
|
overflow = TextOverflow.Ellipsis,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
)
|
)
|
||||||
@@ -278,22 +294,28 @@ private fun MessageRow(
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun severityContainer(severity: UiMessageSeverity): Color = when (severity) {
|
internal fun severityContainer(severity: UiMessageSeverity): Color = (when (severity) {
|
||||||
|
UiMessageSeverity.Error -> MaterialTheme.colorScheme.errorContainer
|
||||||
UiMessageSeverity.Success -> MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.58f)
|
UiMessageSeverity.Success -> MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.58f)
|
||||||
UiMessageSeverity.Status -> MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.74f)
|
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)
|
UiMessageSeverity.Info -> MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.90f)
|
||||||
}
|
}).compositeOver(MaterialTheme.colorScheme.surface)
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun severityOnContainer(severity: UiMessageSeverity): Color = when (severity) {
|
internal fun severityOnContainer(severity: UiMessageSeverity): Color = when (severity) {
|
||||||
|
UiMessageSeverity.Error -> MaterialTheme.colorScheme.onErrorContainer
|
||||||
UiMessageSeverity.Success -> MaterialTheme.colorScheme.onTertiaryContainer
|
UiMessageSeverity.Success -> MaterialTheme.colorScheme.onTertiaryContainer
|
||||||
UiMessageSeverity.Status -> MaterialTheme.colorScheme.onSecondaryContainer
|
UiMessageSeverity.Status -> MaterialTheme.colorScheme.onSecondaryContainer
|
||||||
|
UiMessageSeverity.Warning -> MaterialTheme.colorScheme.onErrorContainer
|
||||||
UiMessageSeverity.Info -> MaterialTheme.colorScheme.onSurfaceVariant
|
UiMessageSeverity.Info -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun severityIcon(severity: UiMessageSeverity): ImageVector = when (severity) {
|
internal fun severityIcon(severity: UiMessageSeverity): ImageVector = when (severity) {
|
||||||
|
UiMessageSeverity.Error -> Icons.Filled.Warning
|
||||||
UiMessageSeverity.Success -> Icons.Filled.CheckCircle
|
UiMessageSeverity.Success -> Icons.Filled.CheckCircle
|
||||||
UiMessageSeverity.Status -> Icons.Filled.Sync
|
UiMessageSeverity.Status -> Icons.Filled.Sync
|
||||||
|
UiMessageSeverity.Warning -> Icons.Filled.Warning
|
||||||
UiMessageSeverity.Info -> Icons.Filled.Info
|
UiMessageSeverity.Info -> Icons.Filled.Info
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -856,13 +856,13 @@ fun MessageBubble(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delivery status — only on agent-Thread reply bubbles (a user
|
// Delivery status for local user messages, including steering.
|
||||||
// message routed over the relay proactive channel). Null on every
|
// Use the bubble's foreground: accent-on-accent hides the label.
|
||||||
// ordinary chat message, which render nothing here.
|
|
||||||
message.deliveryStatus?.takeIf { isUser }?.let { status ->
|
message.deliveryStatus?.takeIf { isUser }?.let { status ->
|
||||||
Spacer(modifier = Modifier.height(2.dp))
|
Spacer(modifier = Modifier.height(2.dp))
|
||||||
MessageDeliveryIndicator(
|
MessageDeliveryIndicator(
|
||||||
status = status,
|
status = status,
|
||||||
|
contentColor = textColor,
|
||||||
text = MessageDeliveryIndicatorText(
|
text = MessageDeliveryIndicatorText(
|
||||||
sending = stringResource(R.string.msg_bubble_sending),
|
sending = stringResource(R.string.msg_bubble_sending),
|
||||||
queued = stringResource(R.string.msg_bubble_queued),
|
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.runtime.Composable
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
import androidx.compose.ui.semantics.LiveRegionMode
|
import androidx.compose.ui.semantics.LiveRegionMode
|
||||||
import androidx.compose.ui.semantics.Role
|
import androidx.compose.ui.semantics.Role
|
||||||
@@ -57,6 +58,7 @@ fun MessageDeliveryIndicator(
|
|||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
failureMessage: String? = null,
|
failureMessage: String? = null,
|
||||||
onRetry: (() -> Unit)? = null,
|
onRetry: (() -> Unit)? = null,
|
||||||
|
contentColor: Color? = null,
|
||||||
) {
|
) {
|
||||||
val retryAction = onRetry.takeIf { status == MessageDeliveryStatus.FAILED }
|
val retryAction = onRetry.takeIf { status == MessageDeliveryStatus.FAILED }
|
||||||
val retryable = retryAction != null
|
val retryable = retryAction != null
|
||||||
@@ -67,7 +69,7 @@ fun MessageDeliveryIndicator(
|
|||||||
retryable = retryable,
|
retryable = retryable,
|
||||||
)
|
)
|
||||||
val presentation = messageDeliveryPresentation(status)
|
val presentation = messageDeliveryPresentation(status)
|
||||||
val tint = when (presentation.colorRole) {
|
val tint = contentColor ?: when (presentation.colorRole) {
|
||||||
DeliveryColorRole.NEUTRAL -> MaterialTheme.colorScheme.onSurfaceVariant
|
DeliveryColorRole.NEUTRAL -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
DeliveryColorRole.ACCENT -> MaterialTheme.colorScheme.primary
|
DeliveryColorRole.ACCENT -> MaterialTheme.colorScheme.primary
|
||||||
DeliveryColorRole.QUEUED -> MaterialTheme.colorScheme.tertiary
|
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
|
* Temporarily allow the device to rotate (portrait or landscape, following the
|
||||||
* sensor) while this composable is in the composition, overriding the app-wide
|
* user's rotation preference) while this composable is in the composition,
|
||||||
* portrait lock declared in the manifest (`MainActivity` screenOrientation).
|
* overriding the app-wide portrait lock declared in the manifest
|
||||||
|
* (`MainActivity` screenOrientation).
|
||||||
* Restores the previous orientation (portrait) when it leaves the composition.
|
* Restores the previous orientation (portrait) when it leaves the composition.
|
||||||
*
|
*
|
||||||
* Used by the full-screen media viewers ([ChatImageViewer], [AttachmentViewer])
|
* 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
|
* 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
|
* stays portrait-locked. Uses `USER` so the viewer follows the device only when
|
||||||
* upside-down) so the viewer rotates with the device regardless of the system
|
* the user has enabled rotation instead of overriding their system preference.
|
||||||
* auto-rotate toggle; swap to `SCREEN_ORIENTATION_USER` to instead respect that
|
|
||||||
* toggle.
|
|
||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
fun AllowDeviceRotation() {
|
fun AllowDeviceRotation() {
|
||||||
@@ -28,7 +27,7 @@ fun AllowDeviceRotation() {
|
|||||||
DisposableEffect(Unit) {
|
DisposableEffect(Unit) {
|
||||||
val activity = context.findActivity()
|
val activity = context.findActivity()
|
||||||
val previous = activity?.requestedOrientation
|
val previous = activity?.requestedOrientation
|
||||||
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
|
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER
|
||||||
onDispose {
|
onDispose {
|
||||||
activity?.requestedOrientation =
|
activity?.requestedOrientation =
|
||||||
previous ?: ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
previous ?: ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package com.hermesandroid.relay.ui.components
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
import android.graphics.Matrix
|
import android.graphics.Matrix
|
||||||
|
import android.net.Uri
|
||||||
import androidx.exifinterface.media.ExifInterface
|
import androidx.exifinterface.media.ExifInterface
|
||||||
import java.io.ByteArrayInputStream
|
import java.io.ByteArrayInputStream
|
||||||
|
|
||||||
@@ -25,6 +27,11 @@ internal fun imageOrientationTransform(orientation: Int): ImageOrientationTransf
|
|||||||
else -> ImageOrientationTransform()
|
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
|
* Decode image bytes for display and apply their EXIF orientation. BitmapFactory
|
||||||
* returns the stored pixel layout and otherwise leaves portrait phone photos
|
* 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)
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||||
} ?: return null
|
} ?: return null
|
||||||
|
|
||||||
val orientation = runCatching {
|
val orientation = try {
|
||||||
ByteArrayInputStream(bytes).use { stream ->
|
ByteArrayInputStream(bytes).use { stream ->
|
||||||
ExifInterface(stream).getAttributeInt(
|
ExifInterface(stream).getAttributeInt(
|
||||||
ExifInterface.TAG_ORIENTATION,
|
ExifInterface.TAG_ORIENTATION,
|
||||||
ExifInterface.ORIENTATION_NORMAL,
|
ExifInterface.ORIENTATION_NORMAL,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
|
} catch (_: Exception) {
|
||||||
|
ExifInterface.ORIENTATION_NORMAL
|
||||||
|
}
|
||||||
val transform = imageOrientationTransform(orientation)
|
val transform = imageOrientationTransform(orientation)
|
||||||
if (transform.rotationDegrees == 0f && !transform.flipHorizontal) return decoded
|
if (transform.rotationDegrees == 0f && !transform.flipHorizontal) return decoded
|
||||||
|
|
||||||
@@ -56,9 +65,81 @@ internal fun decodeOrientedBitmap(
|
|||||||
if (transform.rotationDegrees != 0f) postRotate(transform.rotationDegrees)
|
if (transform.rotationDegrees != 0f) postRotate(transform.rotationDegrees)
|
||||||
if (transform.flipHorizontal) postScale(-1f, 1f)
|
if (transform.flipHorizontal) postScale(-1f, 1f)
|
||||||
}
|
}
|
||||||
return runCatching {
|
val oriented = try {
|
||||||
Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
|
Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
|
||||||
}.getOrNull()?.also { oriented ->
|
} catch (_: Exception) {
|
||||||
if (oriented !== decoded) decoded.recycle()
|
null
|
||||||
|
}
|
||||||
|
return oriented?.also { bitmap ->
|
||||||
|
if (bitmap !== decoded) decoded.recycle()
|
||||||
} ?: decoded
|
} ?: 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? =
|
private suspend fun decodePendingAttachmentImage(attachment: Attachment): ImageBitmap? =
|
||||||
withContext(Dispatchers.IO) {
|
withContext(Dispatchers.IO) {
|
||||||
runCatching {
|
try {
|
||||||
val bytes = Base64.decode(attachment.content, Base64.DEFAULT)
|
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 }
|
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
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
|
var sample = 1
|
||||||
while (
|
while (
|
||||||
@@ -314,7 +314,9 @@ private suspend fun decodePendingAttachmentImage(attachment: Attachment): ImageB
|
|||||||
bytes,
|
bytes,
|
||||||
BitmapFactory.Options().apply { inSampleSize = sample },
|
BitmapFactory.Options().apply { inSampleSize = sample },
|
||||||
)?.asImageBitmap()
|
)?.asImageBitmap()
|
||||||
}.getOrNull()
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed interface PendingPreviewState {
|
private sealed interface PendingPreviewState {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import androidx.compose.foundation.background
|
|||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.WindowInsets
|
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.safeDrawing
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
import androidx.compose.foundation.layout.windowInsetsPadding
|
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.material3.Text
|
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.alpha
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
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.RelayRefresh
|
||||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||||
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
|
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
|
||||||
@@ -41,74 +46,81 @@ fun RelayStatusStrip(
|
|||||||
/** Optional security marker rendered just before the route label. */
|
/** Optional security marker rendered just before the route label. */
|
||||||
securityGlyph: (@Composable () -> Unit)? = null,
|
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
|
* route label. This is where a **routine** in-progress relay reconnect
|
||||||
* surfaces — the top chrome stays empty so chat content never shifts.
|
* surfaces — the top chrome stays empty so chat content never shifts.
|
||||||
*/
|
*/
|
||||||
reconnecting: Boolean = false,
|
reconnecting: Boolean = false,
|
||||||
|
maxContentWidth: Dp? = null,
|
||||||
) {
|
) {
|
||||||
Column(
|
Box(
|
||||||
modifier = modifier
|
modifier = Modifier.fillMaxWidth(),
|
||||||
.fillMaxWidth()
|
contentAlignment = Alignment.Center,
|
||||||
.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(
|
Column(
|
||||||
modifier = Modifier
|
modifier = modifier
|
||||||
|
.then(maxContentWidth?.let { Modifier.widthIn(max = it) } ?: Modifier)
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.heightIn(min = 22.dp)
|
.windowInsetsPadding(
|
||||||
.padding(horizontal = 14.dp, vertical = 2.dp),
|
WindowInsets.safeDrawing.only(
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom,
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
),
|
||||||
|
)
|
||||||
|
.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(
|
Row(
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier
|
||||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
.fillMaxWidth()
|
||||||
|
.heightIn(min = 22.dp)
|
||||||
|
.padding(horizontal = 14.dp, vertical = 2.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
leadingBadge()
|
Row(
|
||||||
if (securityGlyph != null) {
|
modifier = Modifier.weight(1f),
|
||||||
securityGlyph()
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
}
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
// Route is in flux mid-reconnect, so the amber cue replaces the
|
) {
|
||||||
// route label rather than stacking beside it in the 22dp strip.
|
leadingBadge()
|
||||||
when {
|
if (securityGlyph != null) {
|
||||||
reconnecting -> ReconnectingCue(modifier = Modifier.weight(1f))
|
securityGlyph()
|
||||||
routeLabel.isNotBlank() -> Text(
|
}
|
||||||
text = "· $routeLabel",
|
// Route is in flux mid-reconnect, so the amber cue replaces the
|
||||||
style = relayMetadataStyle(),
|
// route label rather than stacking beside it in the 22dp strip.
|
||||||
color = RelayRefresh.Muted,
|
when {
|
||||||
maxLines = 1,
|
reconnecting -> ReconnectingCue(modifier = Modifier.weight(1f))
|
||||||
overflow = TextOverflow.Ellipsis,
|
routeLabel.isNotBlank() -> Text(
|
||||||
modifier = Modifier.weight(1f),
|
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
|
* 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.
|
* empty (chat/agent status rides the chat header subtitle) so nothing shifts.
|
||||||
* Pulse is frame-throttled via [rememberAmbientPhase] to avoid pinning the
|
* Pulse is frame-throttled via [rememberAmbientPhase] to avoid pinning the
|
||||||
@@ -132,7 +144,7 @@ private fun ReconnectingCue(modifier: Modifier = Modifier) {
|
|||||||
.background(RelayRefresh.Amber),
|
.background(RelayRefresh.Amber),
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
text = "Reconnecting…",
|
text = stringResource(R.string.settings_relay_reconnecting),
|
||||||
style = relayMetadataStyle(),
|
style = relayMetadataStyle(),
|
||||||
color = RelayRefresh.Amber,
|
color = RelayRefresh.Amber,
|
||||||
maxLines = 1,
|
maxLines = 1,
|
||||||
|
|||||||
@@ -141,8 +141,8 @@ internal data class SessionCapability(
|
|||||||
* live. SSE paths only get post-hoc reasoning, so this is gateway-only.
|
* 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
|
* While the gateway is still being probed (Unknown) we surface it as a
|
||||||
* "checking" reason rather than a confirmed chip.
|
* "checking" reason rather than a confirmed chip.
|
||||||
* - Media / Terminal → require the relay to be CONNECTED (the relay brokers
|
* - Media → current upstream Dashboard managed-file delivery OR connected
|
||||||
* those channels). A configured-but-disconnected relay is not enough.
|
* Relay compatibility transport. Terminal remains Relay-owned.
|
||||||
* - Voice → `voiceReady` (standard dashboard voice OR relay voice — whichever
|
* - Voice → `voiceReady` (standard dashboard voice OR relay voice — whichever
|
||||||
* the connection actually has).
|
* the connection actually has).
|
||||||
*/
|
*/
|
||||||
@@ -150,6 +150,7 @@ internal data class SessionCapability(
|
|||||||
internal fun sessionCapabilities(
|
internal fun sessionCapabilities(
|
||||||
transport: SessionPathTransport,
|
transport: SessionPathTransport,
|
||||||
gatewayAvailability: GatewayAvailability,
|
gatewayAvailability: GatewayAvailability,
|
||||||
|
upstreamMediaAvailable: Boolean,
|
||||||
relayConnected: Boolean,
|
relayConnected: Boolean,
|
||||||
relayConfigured: Boolean,
|
relayConfigured: Boolean,
|
||||||
voiceReady: Boolean,
|
voiceReady: Boolean,
|
||||||
@@ -170,11 +171,11 @@ internal fun sessionCapabilities(
|
|||||||
),
|
),
|
||||||
SessionCapability(
|
SessionCapability(
|
||||||
type = "media",
|
type = "media",
|
||||||
available = relayConnected,
|
available = upstreamMediaAvailable || relayConnected,
|
||||||
reason = when {
|
reason = when {
|
||||||
relayConnected -> null
|
upstreamMediaAvailable || relayConnected -> null
|
||||||
relayConfigured -> stringResource(R.string.session_path_relay_not_connected)
|
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(
|
SessionCapability(
|
||||||
@@ -401,7 +402,7 @@ internal fun SessionPathDetails(
|
|||||||
* Vertical "transport path" ladder, basic → best:
|
* Vertical "transport path" ladder, basic → best:
|
||||||
* Completions → Runs → Sessions → Gateway. The active tier is filled +
|
* Completions → Runs → Sessions → Gateway. The active tier is filled +
|
||||||
* highlighted; tiers the server doesn't expose render muted; the resolver's
|
* 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
|
* beneath. Uses the same [resolveChatTransportStatus] the status badge does, so
|
||||||
* the drawer and the badge can never disagree.
|
* the drawer and the badge can never disagree.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package com.hermesandroid.relay.ui.components
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
@@ -92,68 +92,70 @@ fun SupportBundleDialog(state: SupportReviewState, onDismiss: () -> Unit) {
|
|||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||||
) {
|
) {
|
||||||
Surface(
|
MessageOverlayScope {
|
||||||
modifier = Modifier.fillMaxWidth(0.94f),
|
Surface(
|
||||||
shape = appearanceRoundedCornerShape(24.dp),
|
modifier = Modifier.fillMaxWidth(0.94f),
|
||||||
tonalElevation = 6.dp,
|
shape = appearanceRoundedCornerShape(24.dp),
|
||||||
) {
|
tonalElevation = 6.dp,
|
||||||
Column(modifier = Modifier.padding(20.dp)) {
|
) {
|
||||||
Text(stringResource(R.string.support_bundle_title), style = MaterialTheme.typography.titleMedium)
|
Column(modifier = Modifier.padding(20.dp)) {
|
||||||
Spacer(Modifier.height(6.dp))
|
Text(stringResource(R.string.support_bundle_title), style = MaterialTheme.typography.titleMedium)
|
||||||
Text(
|
Spacer(Modifier.height(6.dp))
|
||||||
stringResource(R.string.support_bundle_privacy, state.recordCount),
|
Text(
|
||||||
style = MaterialTheme.typography.bodySmall,
|
stringResource(R.string.support_bundle_privacy, state.recordCount),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
)
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
Spacer(Modifier.height(14.dp))
|
)
|
||||||
Box(
|
Spacer(Modifier.height(14.dp))
|
||||||
modifier = Modifier
|
Box(
|
||||||
.fillMaxWidth()
|
modifier = Modifier
|
||||||
.heightIn(min = 160.dp, max = 420.dp)
|
.fillMaxWidth()
|
||||||
.background(
|
.heightIn(min = 160.dp, max = 420.dp)
|
||||||
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
|
.background(
|
||||||
appearanceRoundedCornerShape(12.dp),
|
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
|
||||||
),
|
appearanceRoundedCornerShape(12.dp),
|
||||||
) {
|
),
|
||||||
SelectionContainer {
|
) {
|
||||||
Text(
|
SelectionContainer {
|
||||||
text = state.text,
|
Text(
|
||||||
fontFamily = FontFamily.Monospace,
|
text = state.text,
|
||||||
fontSize = 11.sp,
|
fontFamily = FontFamily.Monospace,
|
||||||
lineHeight = 15.sp,
|
fontSize = 11.sp,
|
||||||
modifier = Modifier.verticalScroll(rememberScrollState()).padding(12.dp),
|
lineHeight = 15.sp,
|
||||||
)
|
modifier = Modifier.verticalScroll(rememberScrollState()).padding(12.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
Spacer(Modifier.height(18.dp))
|
||||||
Spacer(Modifier.height(18.dp))
|
FlowRow(
|
||||||
FlowRow(
|
modifier = Modifier.fillMaxWidth(),
|
||||||
modifier = Modifier.fillMaxWidth(),
|
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
|
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
) {
|
||||||
) {
|
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_close)) }
|
||||||
TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_close)) }
|
OutlinedButton(
|
||||||
OutlinedButton(
|
enabled = state.shareEnabled,
|
||||||
enabled = state.shareEnabled,
|
onClick = {
|
||||||
onClick = {
|
|
||||||
IssueReport.copyToClipboard(context, state.text)
|
|
||||||
Toast.makeText(context, copied, Toast.LENGTH_LONG).show()
|
|
||||||
},
|
|
||||||
) { Text(stringResource(R.string.common_copy)) }
|
|
||||||
Button(
|
|
||||||
enabled = state.shareEnabled,
|
|
||||||
onClick = {
|
|
||||||
if (!IssueReport.share(
|
|
||||||
context,
|
|
||||||
subject = chooser,
|
|
||||||
text = state.text,
|
|
||||||
chooserTitle = chooser,
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
IssueReport.copyToClipboard(context, state.text)
|
IssueReport.copyToClipboard(context, state.text)
|
||||||
Toast.makeText(context, noShare, Toast.LENGTH_LONG).show()
|
UiMessageBus.success(copied)
|
||||||
}
|
},
|
||||||
},
|
) { Text(stringResource(R.string.common_copy)) }
|
||||||
) { Text(stringResource(R.string.common_share)) }
|
Button(
|
||||||
|
enabled = state.shareEnabled,
|
||||||
|
onClick = {
|
||||||
|
if (!IssueReport.share(
|
||||||
|
context,
|
||||||
|
subject = chooser,
|
||||||
|
text = state.text,
|
||||||
|
chooserTitle = chooser,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
IssueReport.copyToClipboard(context, state.text)
|
||||||
|
UiMessageBus.warning(noShare)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) { Text(stringResource(R.string.common_share)) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
package com.hermesandroid.relay.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.IconButton
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.SnackbarDuration
|
||||||
|
import androidx.compose.material3.SnackbarHost
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
|
import androidx.compose.material3.SnackbarVisuals
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.staticCompositionLocalOf
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.hermesandroid.relay.R
|
||||||
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
|
import com.hermesandroid.relay.ui.UiMessageSeverity
|
||||||
|
import com.hermesandroid.relay.util.HumanError
|
||||||
|
|
||||||
|
val LocalMessageActionHost = staticCompositionLocalOf<SnackbarHostState?> { null }
|
||||||
|
|
||||||
|
data class HumanErrorVisuals(val error: HumanError) : SnackbarVisuals {
|
||||||
|
override val message get() = error.body
|
||||||
|
override val actionLabel get() = error.actionLabel
|
||||||
|
override val withDismissAction = true
|
||||||
|
override val duration get() = if (error.retryable) SnackbarDuration.Long else SnackbarDuration.Short
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Uses the app banner's appearance while preserving existing suspend/action contracts. */
|
||||||
|
@Composable
|
||||||
|
fun ThemedMessageHost(hostState: SnackbarHostState, modifier: Modifier = Modifier, scoped: Boolean = false) {
|
||||||
|
val modalActive by UiMessageBus.modalHostActive.collectAsState()
|
||||||
|
if (!scoped && modalActive) return
|
||||||
|
SnackbarHost(hostState = hostState, modifier = modifier) { data ->
|
||||||
|
val error = (data.visuals as? HumanErrorVisuals)?.error
|
||||||
|
val severity = if (error != null) UiMessageSeverity.Error else UiMessageSeverity.Info
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.padding(12.dp).fillMaxWidth(),
|
||||||
|
shape = RoundedCornerShape(10.dp),
|
||||||
|
color = severityContainer(severity), contentColor = severityOnContainer(severity),
|
||||||
|
) {
|
||||||
|
Column(Modifier.padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp)) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Icon(severityIcon(severity), null, Modifier.size(18.dp))
|
||||||
|
Column(Modifier.weight(1f).padding(10.dp).heightIn(max = 200.dp).verticalScroll(rememberScrollState())) {
|
||||||
|
error?.title?.let { Text(it, style = MaterialTheme.typography.titleSmall) }
|
||||||
|
Text(data.visuals.message, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
IconButton(onClick = data::dismiss) {
|
||||||
|
Icon(Icons.Filled.Close, stringResource(R.string.common_dismiss))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.visuals.actionLabel?.let { label ->
|
||||||
|
TextButton(onClick = data::performAction, modifier = Modifier.align(Alignment.End)) { Text(label) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Modal-window host; the root retains the same bus events until their normal expiry. */
|
||||||
|
@Composable
|
||||||
|
fun MessageOverlayScope(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
|
||||||
|
val actions = LocalMessageActionHost.current
|
||||||
|
Box(modifier) {
|
||||||
|
content()
|
||||||
|
MessageBannerHost(Modifier.align(Alignment.TopCenter), includeStatusBarPadding = false, primary = false)
|
||||||
|
if (actions != null) ThemedMessageHost(actions, Modifier.align(Alignment.BottomCenter), scoped = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -57,6 +57,18 @@ import androidx.compose.ui.text.style.TextOverflow
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.hermesandroid.relay.R
|
import com.hermesandroid.relay.R
|
||||||
import com.hermesandroid.relay.data.ToolCall
|
import com.hermesandroid.relay.data.ToolCall
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.JsonObject
|
||||||
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
|
|
||||||
|
/** A completed dispatch call is not evidence that its detached child finished. */
|
||||||
|
internal fun isDetachedDelegationDispatch(toolCall: ToolCall): Boolean {
|
||||||
|
if (toolCall.name != "delegate_task" || !toolCall.isComplete || toolCall.success != true) return false
|
||||||
|
val result = toolCall.result ?: return false
|
||||||
|
val payload = runCatching { Json.parseToJsonElement(result) as? JsonObject }.getOrNull() ?: return false
|
||||||
|
return (payload["status"] as? JsonPrimitive)?.content == "dispatched" ||
|
||||||
|
(payload["mode"] as? JsonPrimitive)?.content == "background"
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ToolProgressCard(
|
fun ToolProgressCard(
|
||||||
@@ -116,7 +128,9 @@ fun ToolProgressCard(
|
|||||||
}
|
}
|
||||||
|
|
||||||
val toolIcon = toolIcon(toolCall.name)
|
val toolIcon = toolIcon(toolCall.name)
|
||||||
|
val detachedDispatch = isDetachedDelegationDispatch(toolCall)
|
||||||
val statusText = when {
|
val statusText = when {
|
||||||
|
detachedDispatch -> stringResource(R.string.tool_progress_status_dispatched)
|
||||||
toolCall.isComplete && toolCall.success == true -> stringResource(R.string.tool_progress_status_completed)
|
toolCall.isComplete && toolCall.success == true -> stringResource(R.string.tool_progress_status_completed)
|
||||||
toolCall.isComplete && toolCall.success == false -> stringResource(R.string.tool_progress_status_failed)
|
toolCall.isComplete && toolCall.success == false -> stringResource(R.string.tool_progress_status_failed)
|
||||||
isPreparing -> stringResource(R.string.tool_preparing_a11y)
|
isPreparing -> stringResource(R.string.tool_preparing_a11y)
|
||||||
@@ -187,7 +201,7 @@ fun ToolProgressCard(
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Duration + completion time ("3.1s · 5:32 PM")
|
// Duration + completion time ("3.1s · 5:32 PM")
|
||||||
val metaLabel = listOfNotNull(duration, timeLabel).joinToString(" · ")
|
val metaLabel = if (detachedDispatch) statusText else listOfNotNull(duration, timeLabel).joinToString(" · ")
|
||||||
if (metaLabel.isNotEmpty()) {
|
if (metaLabel.isNotEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
text = metaLabel,
|
text = metaLabel,
|
||||||
|
|||||||
@@ -23,18 +23,26 @@ import androidx.compose.foundation.layout.Box
|
|||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
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.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.statusBarsPadding
|
import androidx.compose.foundation.layout.statusBarsPadding
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
|
import androidx.compose.foundation.layout.widthIn
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.LazyListState
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
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.Icons
|
||||||
import androidx.compose.material.icons.filled.CenterFocusStrong
|
import androidx.compose.material.icons.filled.CenterFocusStrong
|
||||||
import androidx.compose.material.icons.filled.Close
|
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.GraphicEq
|
||||||
import androidx.compose.material.icons.filled.Image
|
import androidx.compose.material.icons.filled.Image
|
||||||
import androidx.compose.material.icons.filled.Mic
|
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.Settings
|
||||||
import androidx.compose.material.icons.filled.Stop
|
import androidx.compose.material.icons.filled.Stop
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.HorizontalDivider
|
import androidx.compose.material3.HorizontalDivider
|
||||||
import androidx.compose.material3.LinearProgressIndicator
|
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.key.onPreviewKeyEvent
|
||||||
import androidx.compose.ui.input.pointer.pointerInput
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
import androidx.compose.ui.layout.ContentScale
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.platform.LocalConfiguration
|
||||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||||
|
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||||
import androidx.compose.ui.platform.testTag
|
import androidx.compose.ui.platform.testTag
|
||||||
import androidx.compose.ui.semantics.Role
|
import androidx.compose.ui.semantics.Role
|
||||||
import androidx.compose.ui.semantics.contentDescription
|
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.font.FontWeight
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
import androidx.compose.ui.text.style.TextOverflow
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.Dp
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.zIndex
|
import androidx.compose.ui.zIndex
|
||||||
import com.hermesandroid.relay.data.ChatMessage
|
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.LocalAgentAvatar
|
||||||
import com.hermesandroid.relay.ui.components.avatar.LocalBackgroundVisualizationEnabled
|
import com.hermesandroid.relay.ui.components.avatar.LocalBackgroundVisualizationEnabled
|
||||||
import com.hermesandroid.relay.ui.LocalSnackbarHost
|
import com.hermesandroid.relay.ui.LocalSnackbarHost
|
||||||
|
import com.hermesandroid.relay.ui.chatResponsiveLayout
|
||||||
import com.hermesandroid.relay.ui.showHumanError
|
import com.hermesandroid.relay.ui.showHumanError
|
||||||
|
import com.hermesandroid.relay.ui.useSplitVoiceLayout
|
||||||
import com.hermesandroid.relay.util.HumanError
|
import com.hermesandroid.relay.util.HumanError
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import com.hermesandroid.relay.viewmodel.BackgroundRunPhase
|
import com.hermesandroid.relay.viewmodel.BackgroundRunPhase
|
||||||
@@ -112,6 +126,8 @@ import com.hermesandroid.relay.R
|
|||||||
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
import com.hermesandroid.relay.ui.theme.appearanceRoundedCornerShape
|
||||||
|
|
||||||
internal const val VOICE_MODE_MIC_TEST_TAG = "voiceModeMic"
|
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
|
* Full-screen voice-mode overlay. Renders the MorphingSphere in its voiceMode
|
||||||
@@ -135,8 +151,7 @@ fun VoiceModeOverlay(
|
|||||||
onModeChange: (InteractionMode) -> Unit,
|
onModeChange: (InteractionMode) -> Unit,
|
||||||
onClearError: () -> Unit,
|
onClearError: () -> Unit,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
// Nullable so existing call sites compile; when wired, voice errors
|
// Retained for callers; uiState.error owns the modal while voice is visible.
|
||||||
// surface as global snackbars in addition to the inline banner below.
|
|
||||||
errorEvents: SharedFlow<HumanError>? = null,
|
errorEvents: SharedFlow<HumanError>? = null,
|
||||||
// === PHASE3-voice-mode-transcript ===
|
// === PHASE3-voice-mode-transcript ===
|
||||||
// Compact rolling transcript of the last N chat messages — the
|
// Compact rolling transcript of the last N chat messages — the
|
||||||
@@ -186,6 +201,56 @@ fun VoiceModeOverlay(
|
|||||||
val backgroundVisualizationEnabled = LocalBackgroundVisualizationEnabled.current
|
val backgroundVisualizationEnabled = LocalBackgroundVisualizationEnabled.current
|
||||||
val surface = MaterialTheme.colorScheme.surface
|
val surface = MaterialTheme.colorScheme.surface
|
||||||
val haptic = LocalHapticFeedback.current
|
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) }
|
var controlsExpanded by remember { mutableStateOf(false) }
|
||||||
val focusMode = presentationMode == VoicePresentationMode.Focus
|
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
|
// (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
|
// 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 /
|
// and left a retry-only, un-dismissable toast at the bottom during long /
|
||||||
@@ -253,6 +318,11 @@ fun VoiceModeOverlay(
|
|||||||
onOpenSettings = onOpenSettings,
|
onOpenSettings = onOpenSettings,
|
||||||
onExit = onDismiss,
|
onExit = onDismiss,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
|
.then(
|
||||||
|
responsiveLayout.focusVoiceMaxWidth?.let {
|
||||||
|
Modifier.widthIn(max = it)
|
||||||
|
} ?: Modifier,
|
||||||
|
)
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.statusBarsPadding()
|
.statusBarsPadding()
|
||||||
.padding(horizontal = 12.dp, vertical = 8.dp)
|
.padding(horizontal = 12.dp, vertical = 8.dp)
|
||||||
@@ -328,162 +398,93 @@ fun VoiceModeOverlay(
|
|||||||
exit = fadeOut(tween(120)),
|
exit = fadeOut(tween(120)),
|
||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
) {
|
) {
|
||||||
Column(
|
Box(
|
||||||
modifier = Modifier
|
modifier = Modifier.fillMaxSize(),
|
||||||
.fillMaxSize()
|
contentAlignment = Alignment.Center,
|
||||||
.padding(top = 92.dp, bottom = 160.dp, start = 20.dp, end = 20.dp),
|
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
|
||||||
) {
|
) {
|
||||||
Box(
|
if (splitFocusLayout) {
|
||||||
modifier = Modifier
|
Row(
|
||||||
.fillMaxWidth()
|
modifier = Modifier
|
||||||
.weight(1.0f),
|
.widthIn(max = responsiveLayout.focusVoiceMaxWidth ?: 1120.dp)
|
||||||
contentAlignment = Alignment.Center,
|
.fillMaxSize()
|
||||||
) {
|
.navigationBarsPadding()
|
||||||
if (backgroundVisualizationEnabled) {
|
.padding(top = 92.dp, bottom = 28.dp, start = 32.dp, end = 32.dp)
|
||||||
LocalAgentAvatar.current.Render(
|
.testTag(VOICE_FOCUS_SPLIT_LAYOUT_TEST_TAG),
|
||||||
state = AvatarRenderState(
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
state = voiceStateToSphereState(uiState.state),
|
) {
|
||||||
voiceAmplitude = uiState.amplitude,
|
VoiceFocusIdentityPane(
|
||||||
voiceMode = true,
|
uiState = uiState,
|
||||||
),
|
backgroundVisualizationEnabled = backgroundVisualizationEnabled,
|
||||||
modifier = Modifier.fillMaxSize(),
|
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(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
|
Column(
|
||||||
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,
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.then(
|
||||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
responsiveLayout.focusVoiceMaxWidth?.let {
|
||||||
)
|
Modifier.widthIn(max = it)
|
||||||
}
|
} ?: Modifier,
|
||||||
|
)
|
||||||
BackgroundRunChip(
|
.fillMaxSize()
|
||||||
run = uiState.backgroundRun,
|
.padding(top = 92.dp, bottom = 160.dp, start = 20.dp, end = 20.dp)
|
||||||
onCancel = onBackgroundRunCancel,
|
.testTag(VOICE_FOCUS_STACKED_LAYOUT_TEST_TAG),
|
||||||
onTap = onBackgroundRunTap,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
modifier = Modifier
|
) {
|
||||||
.fillMaxWidth()
|
VoiceFocusIdentityPane(
|
||||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
uiState = uiState,
|
||||||
)
|
backgroundVisualizationEnabled = backgroundVisualizationEnabled,
|
||||||
|
onMicTap = focusMicTap,
|
||||||
Spacer(Modifier.height(8.dp))
|
onMicHoldPress = focusMicHoldPress,
|
||||||
|
onMicHoldRelease = focusMicHoldRelease,
|
||||||
DestructiveCountdownRow(
|
showMic = false,
|
||||||
countdown = uiState.destructiveCountdown,
|
modifier = Modifier
|
||||||
modifier = Modifier
|
.fillMaxWidth()
|
||||||
.fillMaxWidth()
|
.weight(1f),
|
||||||
.padding(horizontal = 24.dp),
|
)
|
||||||
)
|
VoiceFocusStatusAndTranscriptPane(
|
||||||
|
uiState = uiState,
|
||||||
PermissionDeniedChip(
|
transcriptMessages = visibleTranscriptMessages,
|
||||||
callout = uiState.permissionDeniedCallout,
|
pendingTranscriptText = pendingTranscriptText,
|
||||||
onTap = onPermissionDeniedChipTap,
|
transcriptListState = transcriptListState,
|
||||||
modifier = Modifier
|
showThinking = showThinking,
|
||||||
.fillMaxWidth()
|
onBackgroundRunCancel = onBackgroundRunCancel,
|
||||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
onBackgroundRunTap = onBackgroundRunTap,
|
||||||
)
|
onPermissionDeniedChipTap = onPermissionDeniedChipTap,
|
||||||
|
onHermesConfirmationAnswer = onHermesConfirmationAnswer,
|
||||||
HermesConfirmationCard(
|
onPresentationModeChange = onPresentationModeChange,
|
||||||
confirmation = uiState.hermesConfirmation,
|
onCardAction = onCardAction,
|
||||||
onAnswer = onHermesConfirmationAnswer,
|
onCardInput = onCardInput,
|
||||||
modifier = Modifier
|
horizontalContentPadding = 24.dp,
|
||||||
.fillMaxWidth()
|
modifier = Modifier
|
||||||
.padding(horizontal = 24.dp, vertical = 4.dp),
|
.fillMaxWidth()
|
||||||
)
|
.weight(1.25f),
|
||||||
|
)
|
||||||
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(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -498,6 +499,12 @@ fun VoiceModeOverlay(
|
|||||||
exit = fadeOut(tween(180)),
|
exit = fadeOut(tween(180)),
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.align(Alignment.BottomCenter)
|
.align(Alignment.BottomCenter)
|
||||||
|
.then(
|
||||||
|
responsiveLayout.chromeMaxWidth?.let {
|
||||||
|
Modifier.widthIn(max = it)
|
||||||
|
} ?: Modifier,
|
||||||
|
)
|
||||||
|
.fillMaxWidth()
|
||||||
.padding(bottom = 176.dp, start = 24.dp, end = 24.dp),
|
.padding(bottom = 176.dp, start = 24.dp, end = 24.dp),
|
||||||
) {
|
) {
|
||||||
BackgroundRunChip(
|
BackgroundRunChip(
|
||||||
@@ -508,53 +515,15 @@ fun VoiceModeOverlay(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Error banner
|
uiState.error?.let { error ->
|
||||||
AnimatedVisibility(
|
VoiceErrorDialog(
|
||||||
visible = uiState.error != null,
|
error = error,
|
||||||
enter = fadeIn(),
|
onDismiss = onClearError,
|
||||||
exit = fadeOut(),
|
onRetry = {
|
||||||
modifier = Modifier
|
onClearError()
|
||||||
.align(Alignment.TopCenter)
|
onMicTap()
|
||||||
.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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mic button — dispatch by current voice state.
|
// Mic button — dispatch by current voice state.
|
||||||
@@ -570,57 +539,259 @@ fun VoiceModeOverlay(
|
|||||||
// that visually said "Stop" but was actually wired to "Start."
|
// that visually said "Stop" but was actually wired to "Start."
|
||||||
VoiceMicButton(
|
VoiceMicButton(
|
||||||
uiState = uiState,
|
uiState = uiState,
|
||||||
onTap = {
|
onTap = focusMicTap,
|
||||||
dispatchVoiceMicTap(
|
onHoldPress = focusMicHoldPress,
|
||||||
uiState = uiState,
|
onHoldRelease = focusMicHoldRelease,
|
||||||
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()
|
|
||||||
},
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.align(Alignment.BottomCenter)
|
.align(Alignment.BottomCenter)
|
||||||
.padding(bottom = 48.dp),
|
.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
|
@Composable
|
||||||
private fun VoiceMicButton(
|
private fun VoiceMicButton(
|
||||||
uiState: VoiceUiState,
|
uiState: VoiceUiState,
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ package com.hermesandroid.relay.ui.screens
|
|||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
@@ -94,7 +94,7 @@ fun AboutScreen(
|
|||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val isDarkTheme = LocalBrand.current.isDark
|
val isDarkTheme = LocalBrand.current.isDark
|
||||||
|
|
||||||
// Pre-resolved Toast messages (Toast is not a composable scope)
|
// Pre-resolved messages for non-composable action callbacks.
|
||||||
val devUnlockedMsg = stringResource(R.string.about_dev_options_unlocked)
|
val devUnlockedMsg = stringResource(R.string.about_dev_options_unlocked)
|
||||||
val updateCopiedMsg = stringResource(R.string.about_update_copied)
|
val updateCopiedMsg = stringResource(R.string.about_update_copied)
|
||||||
val emDash = stringResource(R.string.about_em_dash)
|
val emDash = stringResource(R.string.about_em_dash)
|
||||||
@@ -235,17 +235,13 @@ fun AboutScreen(
|
|||||||
versionTapCount = 0
|
versionTapCount = 0
|
||||||
scope.launch {
|
scope.launch {
|
||||||
FeatureFlags.unlockDevOptions(context)
|
FeatureFlags.unlockDevOptions(context)
|
||||||
Toast.makeText(
|
UiMessageBus.success(devUnlockedMsg)
|
||||||
context,
|
|
||||||
devUnlockedMsg,
|
|
||||||
Toast.LENGTH_SHORT,
|
|
||||||
).show()
|
|
||||||
onUnlockDeveloperOptions()
|
onUnlockDeveloperOptions()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
remaining <= 3 -> {
|
remaining <= 3 -> {
|
||||||
val tapsMsg = context.getString(R.string.about_taps_to_unlock, remaining)
|
val tapsMsg = context.getString(R.string.about_taps_to_unlock, remaining)
|
||||||
Toast.makeText(context, tapsMsg, Toast.LENGTH_SHORT).show()
|
UiMessageBus.info(tapsMsg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -326,11 +322,7 @@ fun AboutScreen(
|
|||||||
if (ru.updateAvailable && !ru.updateCommand.isNullOrBlank()) {
|
if (ru.updateAvailable && !ru.updateCommand.isNullOrBlank()) {
|
||||||
TextButton(onClick = {
|
TextButton(onClick = {
|
||||||
clipboard.setText(AnnotatedString(ru.updateCommand))
|
clipboard.setText(AnnotatedString(ru.updateCommand))
|
||||||
Toast.makeText(
|
UiMessageBus.success(updateCopiedMsg)
|
||||||
context,
|
|
||||||
updateCopiedMsg,
|
|
||||||
Toast.LENGTH_SHORT,
|
|
||||||
).show()
|
|
||||||
}) {
|
}) {
|
||||||
Text(stringResource(R.string.about_copy_fix))
|
Text(stringResource(R.string.about_copy_fix))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ import androidx.compose.material3.MaterialTheme
|
|||||||
import androidx.compose.material3.OutlinedButton
|
import androidx.compose.material3.OutlinedButton
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.Slider
|
import androidx.compose.material3.Slider
|
||||||
import androidx.compose.material3.SnackbarHost
|
import com.hermesandroid.relay.ui.components.ThemedMessageHost
|
||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
@@ -268,7 +268,7 @@ fun AppearanceSettingsScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
snackbarHost = { ThemedMessageHost(snackbarHostState) },
|
||||||
) { innerPadding ->
|
) { innerPadding ->
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
package com.hermesandroid.relay.ui.screens
|
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.BorderStroke
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
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.GatewayChatClient
|
||||||
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
||||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
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.components.MessageBubble
|
||||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||||
import com.hermesandroid.relay.viewmodel.ChatViewModel
|
import com.hermesandroid.relay.viewmodel.ChatViewModel
|
||||||
@@ -84,24 +89,28 @@ fun BotChatScreen(
|
|||||||
connectionViewModel: ConnectionViewModel,
|
connectionViewModel: ConnectionViewModel,
|
||||||
onBack: () -> Unit,
|
onBack: () -> Unit,
|
||||||
) {
|
) {
|
||||||
BotChatScreen(
|
val busyMessageAction by connectionViewModel.busyMessageAction.collectAsState()
|
||||||
route = route,
|
ChatMediaViewerHost(route.key, sessionId) {
|
||||||
bot = bot,
|
BotChatScreen(
|
||||||
sessionId = sessionId,
|
route = route,
|
||||||
gatewayClient = gatewayClient,
|
bot = bot,
|
||||||
dashboardClient = dashboardClient,
|
sessionId = sessionId,
|
||||||
chatViewModel = chatViewModel,
|
gatewayClient = gatewayClient,
|
||||||
onBack = onBack,
|
dashboardClient = dashboardClient,
|
||||||
handlerFactory = ::ChatHandler,
|
chatViewModel = chatViewModel,
|
||||||
historyLoader = { profileName, storedSessionId, mode ->
|
onBack = onBack,
|
||||||
dashboardClient.getSessionMessages(
|
handlerFactory = ::ChatHandler,
|
||||||
sessionId = storedSessionId,
|
historyLoader = { profileName, storedSessionId, mode ->
|
||||||
profile = profileName,
|
dashboardClient.getSessionMessages(
|
||||||
mode = mode,
|
sessionId = storedSessionId,
|
||||||
)
|
profile = profileName,
|
||||||
},
|
mode = mode,
|
||||||
profileIconFlow = connectionViewModel::profileIconFlow,
|
)
|
||||||
)
|
},
|
||||||
|
profileIconFlow = connectionViewModel::profileIconFlow,
|
||||||
|
busyMessageAction = busyMessageAction,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@@ -117,6 +126,7 @@ internal fun BotChatScreen(
|
|||||||
handlerFactory: () -> ChatHandler,
|
handlerFactory: () -> ChatHandler,
|
||||||
historyLoader: BotChatHistoryLoader,
|
historyLoader: BotChatHistoryLoader,
|
||||||
profileIconFlow: BotChatProfileIconFlow,
|
profileIconFlow: BotChatProfileIconFlow,
|
||||||
|
busyMessageAction: BusyMessageAction = BusyMessageAction.CorrectNow,
|
||||||
) {
|
) {
|
||||||
val handler = remember(route.key) { handlerFactory() }
|
val handler = remember(route.key) { handlerFactory() }
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
@@ -133,6 +143,21 @@ internal fun BotChatScreen(
|
|||||||
.collectAsState(initial = null)
|
.collectAsState(initial = null)
|
||||||
val listState = rememberLazyListState()
|
val listState = rememberLazyListState()
|
||||||
var composer by remember(route.key, sessionId) { mutableStateOf("") }
|
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) {
|
DisposableEffect(chatViewModel, gatewayClient, dashboardClient, route.key) {
|
||||||
chatViewModel.initialize(apiClient = null, chatHandler = handler)
|
chatViewModel.initialize(apiClient = null, chatHandler = handler)
|
||||||
@@ -234,49 +259,82 @@ internal fun BotChatScreen(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
bottomBar = {
|
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(
|
Surface(
|
||||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant),
|
||||||
shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp),
|
shape = RoundedCornerShape(topStart = 18.dp, topEnd = 18.dp),
|
||||||
modifier = Modifier.imePadding(),
|
|
||||||
) {
|
) {
|
||||||
Row(
|
Column {
|
||||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
ChatMessageQueue(
|
||||||
verticalAlignment = Alignment.Bottom,
|
messages = queue,
|
||||||
) {
|
paused = queuePaused,
|
||||||
OutlinedTextField(
|
onResume = chatViewModel::resumeQueue,
|
||||||
value = composer,
|
onClear = chatViewModel::clearQueue,
|
||||||
onValueChange = { composer = it },
|
onRemove = chatViewModel::removeQueuedAt,
|
||||||
placeholder = { Text(stringResource(R.string.chat_placeholder_message)) },
|
canEdit = composer.isBlank() && attachments.isEmpty(),
|
||||||
modifier = Modifier.weight(1f),
|
onEdit = { index ->
|
||||||
minLines = 1,
|
chatViewModel.takeQueuedForEdit(index)?.let {
|
||||||
maxLines = 6,
|
composer = it
|
||||||
)
|
editingQueuedMessage = true
|
||||||
Spacer(Modifier.width(6.dp))
|
|
||||||
IconButton(
|
|
||||||
onClick = {
|
|
||||||
if (isStreaming) {
|
|
||||||
chatViewModel.cancelStream()
|
|
||||||
} else {
|
|
||||||
val text = composer.trim()
|
|
||||||
if (text.isNotEmpty()) {
|
|
||||||
composer = ""
|
|
||||||
chatViewModel.sendMessage(text)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
enabled = isStreaming || composer.isNotBlank(),
|
modifier = Modifier.padding(horizontal = 12.dp),
|
||||||
|
)
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.Bottom,
|
||||||
) {
|
) {
|
||||||
Icon(
|
OutlinedTextField(
|
||||||
if (isStreaming) Icons.Filled.Stop else Icons.AutoMirrored.Filled.Send,
|
value = composer,
|
||||||
contentDescription = stringResource(
|
onValueChange = { composer = it },
|
||||||
if (isStreaming) R.string.chat_input_stop_streaming
|
placeholder = { Text(stringResource(R.string.chat_placeholder_message)) },
|
||||||
else R.string.chat_input_send_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 ->
|
) { padding ->
|
||||||
Box(
|
Box(
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ import androidx.compose.material3.IconButton
|
|||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.SnackbarHost
|
import com.hermesandroid.relay.ui.components.ThemedMessageHost
|
||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
@@ -73,6 +73,7 @@ import com.hermesandroid.relay.R
|
|||||||
import com.hermesandroid.relay.data.BotGroupMessage
|
import com.hermesandroid.relay.data.BotGroupMessage
|
||||||
import com.hermesandroid.relay.data.BotGroupRoom
|
import com.hermesandroid.relay.data.BotGroupRoom
|
||||||
import com.hermesandroid.relay.data.BotGatewayRoute
|
import com.hermesandroid.relay.data.BotGatewayRoute
|
||||||
|
import com.hermesandroid.relay.data.BotGatewayRouteKey
|
||||||
import com.hermesandroid.relay.data.BotModeState
|
import com.hermesandroid.relay.data.BotModeState
|
||||||
import com.hermesandroid.relay.data.BotRosterEntry
|
import com.hermesandroid.relay.data.BotRosterEntry
|
||||||
import com.hermesandroid.relay.data.Connection
|
import com.hermesandroid.relay.data.Connection
|
||||||
@@ -84,6 +85,13 @@ import kotlinx.coroutines.launch
|
|||||||
|
|
||||||
internal enum class BotModeFilter { All, Bots, Groups }
|
internal enum class BotModeFilter { All, Bots, Groups }
|
||||||
|
|
||||||
|
/** Bundle-compatible key; length-prefix the connection so delimiters cannot alias owners. */
|
||||||
|
internal val BotRosterEntry.lazyItemKey: String
|
||||||
|
get() {
|
||||||
|
val owner = route?.key ?: return "bot:unbound:${profile.name}"
|
||||||
|
return "bot:route:${owner.connectionId.length}:${owner.connectionId}:${owner.profileName}"
|
||||||
|
}
|
||||||
|
|
||||||
private sealed interface BotModeRow {
|
private sealed interface BotModeRow {
|
||||||
val activityAtMs: Long
|
val activityAtMs: Long
|
||||||
|
|
||||||
@@ -109,7 +117,7 @@ fun BotModeScreen(
|
|||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val resources = LocalResources.current
|
val resources = LocalResources.current
|
||||||
val snackbar = remember { SnackbarHostState() }
|
val snackbar = remember { SnackbarHostState() }
|
||||||
var openingProfile by remember { mutableStateOf<String?>(null) }
|
var openingRoute by remember { mutableStateOf<BotGatewayRouteKey?>(null) }
|
||||||
var showCreateBot by remember { mutableStateOf(false) }
|
var showCreateBot by remember { mutableStateOf(false) }
|
||||||
var creatingBot by remember { mutableStateOf(false) }
|
var creatingBot by remember { mutableStateOf(false) }
|
||||||
var selectedGatewayId by rememberSaveable { mutableStateOf<String?>(null) }
|
var selectedGatewayId by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
@@ -136,10 +144,11 @@ fun BotModeScreen(
|
|||||||
onBack = onBack,
|
onBack = onBack,
|
||||||
onRefresh = connectionViewModel::refreshBotMode,
|
onRefresh = connectionViewModel::refreshBotMode,
|
||||||
onSelectGateway = { selectedGatewayId = it },
|
onSelectGateway = { selectedGatewayId = it },
|
||||||
openingProfile = openingProfile,
|
openingRoute = openingRoute,
|
||||||
onOpenBot = { bot ->
|
onOpenBot = { bot ->
|
||||||
val route = bot.route ?: return@BotModeContent
|
val route = bot.route ?: return@BotModeContent
|
||||||
openingProfile = bot.profile.name
|
if (openingRoute != null) return@BotModeContent
|
||||||
|
openingRoute = route.key
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val result = connectionViewModel.ensureCanonicalBotChat(route)
|
val result = connectionViewModel.ensureCanonicalBotChat(route)
|
||||||
.map { it.resolvedSessionId }
|
.map { it.resolvedSessionId }
|
||||||
@@ -147,12 +156,12 @@ fun BotModeScreen(
|
|||||||
onSuccess = { onOpenBotChat(route, it) },
|
onSuccess = { onOpenBotChat(route, it) },
|
||||||
onFailure = { snackbar.showSnackbar(it.message ?: chatOpenFailed) },
|
onFailure = { snackbar.showSnackbar(it.message ?: chatOpenFailed) },
|
||||||
)
|
)
|
||||||
openingProfile = null
|
openingRoute = null
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onOpenGroup = { onOpenGroup(it.key) },
|
onOpenGroup = { onOpenGroup(it.key) },
|
||||||
onNewBot = { showCreateBot = true },
|
onNewBot = { showCreateBot = true },
|
||||||
snackbarHost = { SnackbarHost(snackbar) },
|
snackbarHost = { ThemedMessageHost(snackbar) },
|
||||||
botAvatar = { bot, size ->
|
botAvatar = { bot, size ->
|
||||||
BotProfileAvatar(
|
BotProfileAvatar(
|
||||||
connectionViewModel = connectionViewModel,
|
connectionViewModel = connectionViewModel,
|
||||||
@@ -206,7 +215,7 @@ internal fun BotModeContent(
|
|||||||
onBack: () -> Unit,
|
onBack: () -> Unit,
|
||||||
onRefresh: () -> Unit,
|
onRefresh: () -> Unit,
|
||||||
onSelectGateway: (String?) -> Unit,
|
onSelectGateway: (String?) -> Unit,
|
||||||
openingProfile: String? = null,
|
openingRoute: BotGatewayRouteKey? = null,
|
||||||
onOpenBot: (BotRosterEntry) -> Unit,
|
onOpenBot: (BotRosterEntry) -> Unit,
|
||||||
onOpenGroup: (BotGroupRoom) -> Unit,
|
onOpenGroup: (BotGroupRoom) -> Unit,
|
||||||
onNewBot: () -> Unit,
|
onNewBot: () -> Unit,
|
||||||
@@ -404,12 +413,12 @@ internal fun BotModeContent(
|
|||||||
contentPadding = PaddingValues(horizontal = 16.dp),
|
contentPadding = PaddingValues(horizontal = 16.dp),
|
||||||
horizontalArrangement = Arrangement.spacedBy(18.dp),
|
horizontalArrangement = Arrangement.spacedBy(18.dp),
|
||||||
) {
|
) {
|
||||||
items(activeBots, key = { it.profile.name }) { bot ->
|
items(activeBots, key = { it.lazyItemKey }) { bot ->
|
||||||
Column(
|
Column(
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.width(78.dp)
|
.width(78.dp)
|
||||||
.clickable(enabled = openingProfile == null) { onOpenBot(bot) },
|
.clickable(enabled = openingRoute == null) { onOpenBot(bot) },
|
||||||
) {
|
) {
|
||||||
Box {
|
Box {
|
||||||
botAvatar(bot, 56.dp)
|
botAvatar(bot, 56.dp)
|
||||||
@@ -455,7 +464,7 @@ internal fun BotModeContent(
|
|||||||
itemsIndexed(
|
itemsIndexed(
|
||||||
items = rows,
|
items = rows,
|
||||||
key = { _, row -> when (row) {
|
key = { _, row -> when (row) {
|
||||||
is BotModeRow.Bot -> "bot:${row.value.profile.name}"
|
is BotModeRow.Bot -> row.value.lazyItemKey
|
||||||
is BotModeRow.Group -> "group:${row.value.key}"
|
is BotModeRow.Group -> "group:${row.value.key}"
|
||||||
} },
|
} },
|
||||||
) { index, row ->
|
) { index, row ->
|
||||||
@@ -463,7 +472,7 @@ internal fun BotModeContent(
|
|||||||
is BotModeRow.Bot -> BotConversationRow(
|
is BotModeRow.Bot -> BotConversationRow(
|
||||||
bot = row.value,
|
bot = row.value,
|
||||||
connectionLabel = row.value.route?.connectionLabel,
|
connectionLabel = row.value.route?.connectionLabel,
|
||||||
opening = openingProfile == row.value.profile.name,
|
opening = openingRoute != null && openingRoute == row.value.route?.key,
|
||||||
onClick = { onOpenBot(row.value) },
|
onClick = { onOpenBot(row.value) },
|
||||||
avatar = { botAvatar(row.value, 56.dp) },
|
avatar = { botAvatar(row.value, 56.dp) },
|
||||||
nowMs = nowMs,
|
nowMs = nowMs,
|
||||||
|
|||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
package com.hermesandroid.relay.ui.screens
|
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.AnimatedVisibility
|
||||||
import androidx.compose.animation.animateContentSize
|
import androidx.compose.animation.animateContentSize
|
||||||
import androidx.compose.foundation.Canvas
|
import androidx.compose.foundation.Canvas
|
||||||
@@ -9,6 +12,14 @@ import androidx.compose.foundation.MutatePriority
|
|||||||
import com.hermesandroid.relay.ui.theme.LocalBrand
|
import com.hermesandroid.relay.ui.theme.LocalBrand
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.ui.layout.onSizeChanged
|
||||||
|
import androidx.compose.ui.platform.testTag
|
||||||
|
import com.hermesandroid.relay.ui.components.ChatDebugDrawer
|
||||||
|
import com.hermesandroid.relay.ui.components.ChatActivityReceipt
|
||||||
|
import com.hermesandroid.relay.data.projectChatActivityReceipts
|
||||||
|
import com.hermesandroid.relay.viewmodel.previewActivities
|
||||||
|
import com.hermesandroid.relay.ui.components.ChatDebugOverlay
|
||||||
|
import com.hermesandroid.relay.ui.components.chatDebugHeaderGesture
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
@@ -98,6 +109,7 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.compose.foundation.layout.aspectRatio
|
import androidx.compose.foundation.layout.aspectRatio
|
||||||
import androidx.compose.ui.draw.alpha
|
import androidx.compose.ui.draw.alpha
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.draw.clipToBounds
|
||||||
import androidx.compose.ui.geometry.CornerRadius
|
import androidx.compose.ui.geometry.CornerRadius
|
||||||
import androidx.compose.ui.geometry.Offset
|
import androidx.compose.ui.geometry.Offset
|
||||||
import androidx.compose.ui.geometry.Size
|
import androidx.compose.ui.geometry.Size
|
||||||
@@ -119,6 +131,7 @@ import androidx.compose.ui.unit.Dp
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.zIndex
|
import androidx.compose.ui.zIndex
|
||||||
import com.hermesandroid.relay.R
|
import com.hermesandroid.relay.R
|
||||||
|
import com.hermesandroid.relay.ui.chatResponsiveLayout
|
||||||
import com.hermesandroid.relay.ui.theme.radialNavyBackground
|
import com.hermesandroid.relay.ui.theme.radialNavyBackground
|
||||||
import com.hermesandroid.relay.network.upstream.ApiModelOption
|
import com.hermesandroid.relay.network.upstream.ApiModelOption
|
||||||
import com.hermesandroid.relay.network.upstream.ChatMode
|
import com.hermesandroid.relay.network.upstream.ChatMode
|
||||||
@@ -145,7 +158,7 @@ import androidx.compose.animation.fadeIn
|
|||||||
import androidx.compose.animation.fadeOut
|
import androidx.compose.animation.fadeOut
|
||||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
import androidx.compose.material3.SmallFloatingActionButton
|
import androidx.compose.material3.SmallFloatingActionButton
|
||||||
import androidx.compose.material3.SnackbarHost
|
import com.hermesandroid.relay.ui.components.ThemedMessageHost
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
import androidx.compose.material3.SnackbarHostState
|
import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.SnackbarDuration
|
import androidx.compose.material3.SnackbarDuration
|
||||||
@@ -154,7 +167,7 @@ import android.content.ClipData
|
|||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.provider.Settings
|
import android.provider.Settings
|
||||||
import android.widget.Toast
|
import com.hermesandroid.relay.ui.UiMessageBus
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.PickVisualMediaRequest
|
import androidx.activity.result.PickVisualMediaRequest
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
@@ -749,6 +762,7 @@ fun ChatScreen(
|
|||||||
gitWorkspaceAvailable: Boolean = gitWorkspaceSummary != null,
|
gitWorkspaceAvailable: Boolean = gitWorkspaceSummary != null,
|
||||||
onNavigateToGitWorkspace: () -> Unit = {},
|
onNavigateToGitWorkspace: () -> Unit = {},
|
||||||
) {
|
) {
|
||||||
|
val responsiveLayout = chatResponsiveLayout(LocalConfiguration.current.screenWidthDp)
|
||||||
val supervised = supervisedPolicy.enabled
|
val supervised = supervisedPolicy.enabled
|
||||||
val supervisedVisibility = supervisedPolicy.visibility.resolved()
|
val supervisedVisibility = supervisedPolicy.visibility.resolved()
|
||||||
LaunchedEffect(supervisedPolicy) {
|
LaunchedEffect(supervisedPolicy) {
|
||||||
@@ -864,9 +878,17 @@ fun ChatScreen(
|
|||||||
|
|
||||||
|
|
||||||
val rawMessages by chatViewModel.messages.collectAsState()
|
val rawMessages by chatViewModel.messages.collectAsState()
|
||||||
val messages = remember(rawMessages, supervised, supervisedPolicy.capabilities.generatedImages) {
|
val activityRecords by chatViewModel.activityRecords.collectAsState()
|
||||||
if (!supervised) rawMessages
|
val activityOwner by chatViewModel.conversationBinding.collectAsState()
|
||||||
else rawMessages.map { message ->
|
val activitySessionId by chatViewModel.currentSessionId.collectAsState()
|
||||||
|
val receiptMessages = remember(rawMessages, activityRecords, activityOwner, activitySessionId, supervised, supervisedVisibility) {
|
||||||
|
if (activityOwner.transport == com.hermesandroid.relay.data.SessionTransport.SSE ||
|
||||||
|
(supervised && !supervisedVisibility.showWorkingStatus)
|
||||||
|
) rawMessages else projectChatActivityReceipts(rawMessages, activityRecords, activityOwner.contextKey, activitySessionId)
|
||||||
|
}
|
||||||
|
val messages = remember(receiptMessages, supervised, supervisedPolicy.capabilities.generatedImages) {
|
||||||
|
if (!supervised) receiptMessages
|
||||||
|
else receiptMessages.map { message ->
|
||||||
if (message.role == MessageRole.ASSISTANT) {
|
if (message.role == MessageRole.ASSISTANT) {
|
||||||
message.copy(
|
message.copy(
|
||||||
attachments = if (supervisedPolicy.capabilities.generatedImages) {
|
attachments = if (supervisedPolicy.capabilities.generatedImages) {
|
||||||
@@ -929,6 +951,10 @@ fun ChatScreen(
|
|||||||
val sessionArchivingSupported by chatViewModel.sessionArchivingSupported.collectAsState()
|
val sessionArchivingSupported by chatViewModel.sessionArchivingSupported.collectAsState()
|
||||||
val currentSessionId by chatViewModel.currentSessionId.collectAsState()
|
val currentSessionId by chatViewModel.currentSessionId.collectAsState()
|
||||||
val structuredChatFailure by chatViewModel.chatFailure.collectAsState()
|
val structuredChatFailure by chatViewModel.chatFailure.collectAsState()
|
||||||
|
val preparingGatewaySessionId by chatViewModel.gatewayPreparingSessionId.collectAsState()
|
||||||
|
val gatewaySocketState by chatViewModel.gatewaySocketState.collectAsState()
|
||||||
|
val preparingGatewaySession = isStreaming && currentSessionId != null &&
|
||||||
|
preparingGatewaySessionId == currentSessionId
|
||||||
val visibleChatFailure = scopedChatFailure(
|
val visibleChatFailure = scopedChatFailure(
|
||||||
structuredChatFailure,
|
structuredChatFailure,
|
||||||
currentSessionId,
|
currentSessionId,
|
||||||
@@ -955,6 +981,7 @@ fun ChatScreen(
|
|||||||
val backgroundProcessesLoading by chatViewModel.backgroundProcessesLoading.collectAsState()
|
val backgroundProcessesLoading by chatViewModel.backgroundProcessesLoading.collectAsState()
|
||||||
val stoppingProcessIds by chatViewModel.stoppingProcessIds.collectAsState()
|
val stoppingProcessIds by chatViewModel.stoppingProcessIds.collectAsState()
|
||||||
val subagentActivities by chatViewModel.subagentActivities.collectAsState()
|
val subagentActivities by chatViewModel.subagentActivities.collectAsState()
|
||||||
|
val retainedActivityPreview by chatViewModel.retainedActivityPreview.collectAsState()
|
||||||
val subagentChildPreview by chatViewModel.subagentChildPreview.collectAsState()
|
val subagentChildPreview by chatViewModel.subagentChildPreview.collectAsState()
|
||||||
val isLoadingHistory by chatViewModel.isLoadingHistory.collectAsState()
|
val isLoadingHistory by chatViewModel.isLoadingHistory.collectAsState()
|
||||||
val isLoadingSessions by chatViewModel.isLoadingSessions.collectAsState()
|
val isLoadingSessions by chatViewModel.isLoadingSessions.collectAsState()
|
||||||
@@ -1135,6 +1162,12 @@ fun ChatScreen(
|
|||||||
|
|
||||||
val availableSkills by chatViewModel.availableSkills.collectAsState()
|
val availableSkills by chatViewModel.availableSkills.collectAsState()
|
||||||
val queuedMessages by chatViewModel.queuedMessages.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 recentPrompts by chatViewModel.recentPrompts.collectAsState()
|
||||||
val recentPromptsEnabled by connectionViewModel.chatRecentPromptsEnabled.collectAsState()
|
val recentPromptsEnabled by connectionViewModel.chatRecentPromptsEnabled.collectAsState()
|
||||||
// Effective approval-bypass (server-computed: ORs global approvals.mode=off,
|
// Effective approval-bypass (server-computed: ORs global approvals.mode=off,
|
||||||
@@ -1187,7 +1220,10 @@ fun ChatScreen(
|
|||||||
// RPC burst while the session directory was also trying to hydrate.
|
// RPC burst while the session directory was also trying to hydrate.
|
||||||
}
|
}
|
||||||
DisposableEffect(chatViewModel) {
|
DisposableEffect(chatViewModel) {
|
||||||
onDispose { chatViewModel.setChatVisible(false) }
|
onDispose {
|
||||||
|
chatViewModel.setChatVisible(false)
|
||||||
|
chatViewModel.closeActivityPreview()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cold-open recovery: the dashboard probe that flips gatewayAvailability to
|
// Cold-open recovery: the dashboard probe that flips gatewayAvailability to
|
||||||
@@ -1358,14 +1394,10 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (request.payload.omittedUriCount > 0) {
|
if (request.payload.omittedUriCount > 0) {
|
||||||
Toast.makeText(
|
UiMessageBus.warning(context.getString(
|
||||||
context,
|
|
||||||
context.getString(
|
|
||||||
R.string.chat_shared_files_limited,
|
R.string.chat_shared_files_limited,
|
||||||
com.hermesandroid.relay.util.MAX_SHARED_CONTENT_ATTACHMENTS,
|
com.hermesandroid.relay.util.MAX_SHARED_CONTENT_ATTACHMENTS,
|
||||||
),
|
))
|
||||||
Toast.LENGTH_LONG,
|
|
||||||
).show()
|
|
||||||
}
|
}
|
||||||
com.hermesandroid.relay.util.SharedContentRequest.consume(request.id)
|
com.hermesandroid.relay.util.SharedContentRequest.consume(request.id)
|
||||||
}
|
}
|
||||||
@@ -1395,11 +1427,18 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
var showCommandPalette by remember { mutableStateOf(false) }
|
var showCommandPalette by remember { mutableStateOf(false) }
|
||||||
var showTranscriptSearch by rememberSaveable { 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 showModelSheet by remember { mutableStateOf(false) }
|
||||||
var showEffortSheet by remember { mutableStateOf(false) }
|
var showEffortSheet by remember { mutableStateOf(false) }
|
||||||
var showAgentInfo by remember { mutableStateOf(false) }
|
var showAgentInfo by remember { mutableStateOf(false) }
|
||||||
var showProfileShelf by remember { mutableStateOf(false) }
|
var showProfileShelf by remember { mutableStateOf(false) }
|
||||||
|
var showChatDebug by remember { mutableStateOf(false) }
|
||||||
|
var chatHeaderHeightPx by remember { mutableStateOf(0) }
|
||||||
|
LaunchedEffect(currentSessionId, activeConnection?.id, supervised) { showChatDebug = false }
|
||||||
var showProfileSwitcher by remember { mutableStateOf(false) }
|
var showProfileSwitcher by remember { mutableStateOf(false) }
|
||||||
var showProfileManager by remember { mutableStateOf(false) }
|
var showProfileManager by remember { mutableStateOf(false) }
|
||||||
var showBackgroundProcesses by remember { mutableStateOf(false) }
|
var showBackgroundProcesses by remember { mutableStateOf(false) }
|
||||||
@@ -1416,7 +1455,7 @@ fun ChatScreen(
|
|||||||
// A process inventory is scoped to one gateway session. Never leave a
|
// A process inventory is scoped to one gateway session. Never leave a
|
||||||
// sheet opened onto a different chat after a drawer/profile switch.
|
// sheet opened onto a different chat after a drawer/profile switch.
|
||||||
LaunchedEffect(currentSessionId, selectedProfile?.name, activeConnection?.id) {
|
LaunchedEffect(currentSessionId, selectedProfile?.name, activeConnection?.id) {
|
||||||
chatViewModel.closeSubagentChildPreview()
|
chatViewModel.closeActivityPreview()
|
||||||
showBackgroundProcesses = false
|
showBackgroundProcesses = false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1783,7 +1822,7 @@ fun ChatScreen(
|
|||||||
cameraLauncher.launch(uri)
|
cameraLauncher.launch(uri)
|
||||||
}.onFailure {
|
}.onFailure {
|
||||||
pendingCameraUri = null
|
pendingCameraUri = null
|
||||||
Toast.makeText(context, context.getString(R.string.chat_camera_open_failed), Toast.LENGTH_SHORT).show()
|
UiMessageBus.error(context.getString(R.string.chat_camera_open_failed))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var pendingCameraAfterPermission by remember { mutableStateOf(false) }
|
var pendingCameraAfterPermission by remember { mutableStateOf(false) }
|
||||||
@@ -1795,11 +1834,7 @@ fun ChatScreen(
|
|||||||
if (granted && wanted) {
|
if (granted && wanted) {
|
||||||
launchCamera()
|
launchCamera()
|
||||||
} else if (!granted) {
|
} else if (!granted) {
|
||||||
Toast.makeText(
|
UiMessageBus.warning(context.getString(R.string.chat_camera_perm_needed))
|
||||||
context,
|
|
||||||
context.getString(R.string.chat_camera_perm_needed),
|
|
||||||
Toast.LENGTH_SHORT,
|
|
||||||
).show()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val requestCameraCapture: () -> Unit = {
|
val requestCameraCapture: () -> Unit = {
|
||||||
@@ -2597,11 +2632,7 @@ fun ChatScreen(
|
|||||||
clipboard.setClipEntry(
|
clipboard.setClipEntry(
|
||||||
ClipEntry(ClipData.newPlainText(copySessionIdLabel, sessionId))
|
ClipEntry(ClipData.newPlainText(copySessionIdLabel, sessionId))
|
||||||
)
|
)
|
||||||
Toast.makeText(
|
UiMessageBus.success(copiedToClipboardMsg)
|
||||||
context,
|
|
||||||
copiedToClipboardMsg,
|
|
||||||
Toast.LENGTH_SHORT,
|
|
||||||
).show()
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
threadsCapabilityActive = threadsCapabilityActive,
|
threadsCapabilityActive = threadsCapabilityActive,
|
||||||
@@ -2747,6 +2778,7 @@ fun ChatScreen(
|
|||||||
) {
|
) {
|
||||||
// Top bar — messaging app style with avatar, name, model subtitle
|
// Top bar — messaging app style with avatar, name, model subtitle
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
|
modifier = Modifier.onSizeChanged { chatHeaderHeightPx = it.height },
|
||||||
navigationIcon = {
|
navigationIcon = {
|
||||||
if (!supervised || supervisedPolicy.capabilities.conversationHistory) {
|
if (!supervised || supervisedPolicy.capabilities.conversationHistory) {
|
||||||
IconButton(onClick = { scope.launch { drawerState.open() } }) {
|
IconButton(onClick = { scope.launch { drawerState.open() } }) {
|
||||||
@@ -2790,6 +2822,7 @@ fun ChatScreen(
|
|||||||
val showStreamingState = isStreaming &&
|
val showStreamingState = isStreaming &&
|
||||||
(!supervised || supervisedVisibility.showWorkingStatus)
|
(!supervised || supervisedVisibility.showWorkingStatus)
|
||||||
val statusText = when {
|
val statusText = when {
|
||||||
|
preparingGatewaySession -> stringResource(R.string.chat_debug_preparing)
|
||||||
headerChatReady -> if (showStreamingState) {
|
headerChatReady -> if (showStreamingState) {
|
||||||
stringResource(R.string.chat_streaming)
|
stringResource(R.string.chat_streaming)
|
||||||
} else {
|
} else {
|
||||||
@@ -2866,13 +2899,21 @@ fun ChatScreen(
|
|||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.clickable(enabled = !supervised) {
|
.chatDebugHeaderGesture(enabled = !supervised,
|
||||||
|
onHold = {
|
||||||
|
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||||
|
showProfileShelf = false
|
||||||
|
showChatDebug = !showChatDebug
|
||||||
|
},
|
||||||
|
onClick = {
|
||||||
|
showChatDebug = false
|
||||||
if (profileShelfAvailable) {
|
if (profileShelfAvailable) {
|
||||||
showProfileShelf = !showProfileShelf
|
showProfileShelf = !showProfileShelf
|
||||||
} else {
|
} else {
|
||||||
showAgentInfo = true
|
showAgentInfo = true
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
.testTag("chat-agent-header")
|
||||||
.semantics {
|
.semantics {
|
||||||
contentDescription = if (profileShelfAvailable) {
|
contentDescription = if (profileShelfAvailable) {
|
||||||
context.getString(
|
context.getString(
|
||||||
@@ -3311,7 +3352,13 @@ fun ChatScreen(
|
|||||||
) {
|
) {
|
||||||
Column(
|
Column(
|
||||||
horizontalAlignment = Alignment.CenterHorizontally,
|
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))
|
Spacer(modifier = Modifier.weight(0.15f))
|
||||||
|
|
||||||
@@ -3320,12 +3367,15 @@ fun ChatScreen(
|
|||||||
LocalBackgroundVisualizationEnabled.current &&
|
LocalBackgroundVisualizationEnabled.current &&
|
||||||
(!supervised || supervisedVisibility.showAgentIdentity)
|
(!supervised || supervisedVisibility.showAgentIdentity)
|
||||||
) {
|
) {
|
||||||
Box(
|
val avatarModifier = responsiveLayout.avatarSize?.let { size ->
|
||||||
modifier = Modifier
|
Modifier
|
||||||
.fillMaxWidth()
|
.size(size)
|
||||||
.aspectRatio(1f)
|
.clipToBounds()
|
||||||
.weight(0.7f, fill = false)
|
} ?: Modifier
|
||||||
) {
|
.fillMaxWidth()
|
||||||
|
.aspectRatio(1f)
|
||||||
|
.weight(0.7f, fill = false)
|
||||||
|
Box(modifier = avatarModifier) {
|
||||||
LocalAgentAvatar.current.Render(
|
LocalAgentAvatar.current.Render(
|
||||||
state = AvatarRenderState(
|
state = AvatarRenderState(
|
||||||
state = if (error != null) SphereState.Error else SphereState.Idle,
|
state = if (error != null) SphereState.Error else SphereState.Idle,
|
||||||
@@ -3568,7 +3618,14 @@ fun ChatScreen(
|
|||||||
LazyColumn(
|
LazyColumn(
|
||||||
state = listState,
|
state = listState,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxSize()
|
.align(Alignment.Center)
|
||||||
|
.fillMaxHeight()
|
||||||
|
.then(
|
||||||
|
responsiveLayout.transcriptMaxWidth?.let {
|
||||||
|
Modifier.widthIn(max = it)
|
||||||
|
} ?: Modifier,
|
||||||
|
)
|
||||||
|
.fillMaxWidth()
|
||||||
.padding(horizontal = 12.dp)
|
.padding(horizontal = 12.dp)
|
||||||
.padding(top = if (showTranscriptSearch) 112.dp else 0.dp),
|
.padding(top = if (showTranscriptSearch) 112.dp else 0.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(2.dp)
|
verticalArrangement = Arrangement.spacedBy(2.dp)
|
||||||
@@ -3637,7 +3694,15 @@ fun ChatScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (processNotification != null) {
|
if (message.activityRecord != null && (!supervised || supervisedVisibility.showWorkingStatus)) {
|
||||||
|
ChatActivityReceipt(
|
||||||
|
record = message.activityRecord,
|
||||||
|
onClick = {
|
||||||
|
showBackgroundProcesses = chatViewModel.openRetainedActivity(message.activityRecord, processNotification?.detail)
|
||||||
|
},
|
||||||
|
modifier = Modifier.padding(vertical = 4.dp),
|
||||||
|
)
|
||||||
|
} else if (processNotification != null) {
|
||||||
val notificationModifier = Modifier.padding(
|
val notificationModifier = Modifier.padding(
|
||||||
top = if (isFirstInGroup) 6.dp else 2.dp,
|
top = if (isFirstInGroup) 6.dp else 2.dp,
|
||||||
)
|
)
|
||||||
@@ -3879,6 +3944,9 @@ fun ChatScreen(
|
|||||||
// optional diagnostic scaffolding. Keep lanes
|
// optional diagnostic scaffolding. Keep lanes
|
||||||
// visible in Off, Compact, and Detailed modes.
|
// visible in Off, Compact, and Detailed modes.
|
||||||
laneGroups.keys.filterNotNull().sorted().forEach { taskIndex ->
|
laneGroups.keys.filterNotNull().sorted().forEach { taskIndex ->
|
||||||
|
val laneCalls = laneGroups.getValue(taskIndex)
|
||||||
|
val retainedIds = activityRecords.flatMap { it.children }.mapTo(HashSet()) { it.id }
|
||||||
|
if (laneCalls.all { it.subagentId != null && it.subagentId in retainedIds }) return@forEach
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
SubagentLane(
|
SubagentLane(
|
||||||
taskIndex = taskIndex,
|
taskIndex = taskIndex,
|
||||||
@@ -4014,7 +4082,7 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Copy feedback snackbar
|
// Copy feedback snackbar
|
||||||
SnackbarHost(
|
ThemedMessageHost(
|
||||||
hostState = snackbarHostState,
|
hostState = snackbarHostState,
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.align(Alignment.BottomCenter)
|
.align(Alignment.BottomCenter)
|
||||||
@@ -4029,7 +4097,7 @@ fun ChatScreen(
|
|||||||
subagentActivities = subagentActivities,
|
subagentActivities = subagentActivities,
|
||||||
subagentPreviewVisibility = subagentPreviewVisibility,
|
subagentPreviewVisibility = subagentPreviewVisibility,
|
||||||
loading = backgroundProcessesLoading,
|
loading = backgroundProcessesLoading,
|
||||||
onClick = { showBackgroundProcesses = true },
|
onClick = { chatViewModel.openCurrentActivityPreview(); showBackgroundProcesses = true },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4091,69 +4159,21 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
AnimatedVisibility(visible = queuedMessages.isNotEmpty()) {
|
ChatMessageQueue(
|
||||||
Column(
|
messages = queuedMessages,
|
||||||
modifier = Modifier
|
paused = queuePaused,
|
||||||
.fillMaxWidth()
|
onResume = chatViewModel::resumeQueue,
|
||||||
.padding(horizontal = 20.dp),
|
onClear = chatViewModel::clearQueue,
|
||||||
) {
|
onRemove = chatViewModel::removeQueuedAt,
|
||||||
Row(
|
canEdit = inputText.isBlank() && pendingAttachments.isEmpty(),
|
||||||
modifier = Modifier.fillMaxWidth(),
|
onEdit = { index ->
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
chatViewModel.takeQueuedForEdit(index)?.let {
|
||||||
horizontalArrangement = Arrangement.SpaceBetween
|
inputText = it
|
||||||
) {
|
editingQueuedMessage = true
|
||||||
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
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// Per-item: tap the text to pull it back into the composer
|
},
|
||||||
// for editing; ✕ to drop just that one. (Reorder omitted —
|
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp),
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val quoteYouLabel = stringResource(R.string.chat_quote_you)
|
val quoteYouLabel = stringResource(R.string.chat_quote_you)
|
||||||
val quoteHermesLabel = stringResource(R.string.chat_quote_hermes)
|
val quoteHermesLabel = stringResource(R.string.chat_quote_hermes)
|
||||||
@@ -4199,15 +4219,17 @@ fun ChatScreen(
|
|||||||
|
|
||||||
PendingAttachmentComposer(
|
PendingAttachmentComposer(
|
||||||
attachments = pendingAttachments,
|
attachments = pendingAttachments,
|
||||||
onPreview = { attachment, _ -> pendingAttachmentPreview = attachment },
|
onPreview = { _, index -> pendingAttachmentPreviewIndex = index },
|
||||||
onRemove = chatViewModel::removeAttachment,
|
onRemove = chatViewModel::removeAttachment,
|
||||||
onMove = chatViewModel::moveAttachment,
|
onMove = chatViewModel::moveAttachment,
|
||||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||||
)
|
)
|
||||||
pendingAttachmentPreview?.let { attachment ->
|
pendingAttachmentPreviewIndex
|
||||||
|
?.let(pendingAttachments::getOrNull)
|
||||||
|
?.let { attachment ->
|
||||||
AttachmentViewer(
|
AttachmentViewer(
|
||||||
attachment = attachment,
|
attachment = attachment,
|
||||||
onDismiss = { pendingAttachmentPreview = null },
|
onDismiss = { pendingAttachmentPreviewIndex = null },
|
||||||
initiallyRevealed = true,
|
initiallyRevealed = true,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -4260,25 +4282,32 @@ fun ChatScreen(
|
|||||||
// Gateway redirect is text-only. Attachment-bearing follow-ups must
|
// Gateway redirect is text-only. Attachment-bearing follow-ups must
|
||||||
// retain their files in the session-owned queue instead of showing
|
// retain their files in the session-owned queue instead of showing
|
||||||
// a correction action that cannot carry them.
|
// 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)
|
(!supervised || supervisedPolicy.capabilities.steerResponse)
|
||||||
|
val effectiveBusyAction = if (canSteerCurrentMessage && !editingQueuedMessage) busyActionOverride ?: busyMessageAction
|
||||||
|
else BusyMessageAction.QueueNext
|
||||||
|
val correctCurrentMessage = canSteerCurrentMessage &&
|
||||||
|
effectiveBusyAction == BusyMessageAction.CorrectNow
|
||||||
val trailing = when {
|
val trailing = when {
|
||||||
!isStreaming && hasContent -> ChatInputTrailing.SEND
|
!isStreaming && hasContent -> ChatInputTrailing.SEND
|
||||||
!isStreaming -> ChatInputTrailing.VOICE
|
!isStreaming -> ChatInputTrailing.VOICE
|
||||||
isStreaming && !hasContent -> ChatInputTrailing.STOP
|
isStreaming && !hasContent -> ChatInputTrailing.STOP
|
||||||
canSteerCurrentMessage -> ChatInputTrailing.STEER
|
correctCurrentMessage -> ChatInputTrailing.STEER
|
||||||
else -> ChatInputTrailing.QUEUE
|
else -> ChatInputTrailing.QUEUE
|
||||||
}
|
}
|
||||||
val inputCaption = when {
|
val inputCaption = when {
|
||||||
isStreaming && hasContent && canSteerCurrentMessage ->
|
isStreaming && hasContent && correctCurrentMessage ->
|
||||||
stringResource(R.string.chat_sends_now)
|
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 && hasContent -> stringResource(R.string.chat_delivered_after_turn)
|
||||||
isStreaming && steerNotice != null -> steerNotice
|
isStreaming && steerNotice != null -> steerNotice
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
val inputPlaceholder = when {
|
val inputPlaceholder = when {
|
||||||
editingMessage != null -> stringResource(R.string.chat_placeholder_edit)
|
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)
|
isStreaming -> stringResource(R.string.chat_placeholder_queue)
|
||||||
else -> stringResource(R.string.chat_placeholder_message)
|
else -> stringResource(R.string.chat_placeholder_message)
|
||||||
}
|
}
|
||||||
@@ -4530,6 +4559,12 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
ChatInputBar(
|
ChatInputBar(
|
||||||
|
busyAction = effectiveBusyAction.takeIf { isStreaming },
|
||||||
|
correctionAvailable = canSteerCurrentMessage,
|
||||||
|
onBusyActionChange = {
|
||||||
|
editingQueuedMessage = false
|
||||||
|
busyActionOverride = it
|
||||||
|
},
|
||||||
value = inputText,
|
value = inputText,
|
||||||
onValueChange = { inputText = it },
|
onValueChange = { inputText = it },
|
||||||
placeholder = inputPlaceholder,
|
placeholder = inputPlaceholder,
|
||||||
@@ -4558,7 +4593,9 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
chatViewModel.sendMessage(outboundText)
|
chatViewModel.sendMessage(outboundText, effectiveBusyAction)
|
||||||
|
editingQueuedMessage = false
|
||||||
|
busyActionOverride = null
|
||||||
inputText = ""
|
inputText = ""
|
||||||
finishSuccessfulSend()
|
finishSuccessfulSend()
|
||||||
}
|
}
|
||||||
@@ -4568,17 +4605,11 @@ fun ChatScreen(
|
|||||||
isDemoMode = isDemoMode,
|
isDemoMode = isDemoMode,
|
||||||
voiceReady = voiceReady,
|
voiceReady = voiceReady,
|
||||||
onDemoNotice = {
|
onDemoNotice = {
|
||||||
Toast.makeText(
|
UiMessageBus.warning("Voice is unavailable in the offline demo — connect to Hermes to use it")
|
||||||
context,
|
|
||||||
"Voice is unavailable in the offline demo — connect to Hermes to use it",
|
|
||||||
Toast.LENGTH_LONG,
|
|
||||||
).show()
|
|
||||||
},
|
},
|
||||||
onStartVoice = requestVoiceMode,
|
onStartVoice = requestVoiceMode,
|
||||||
onSetupNotice = {
|
onSetupNotice = {
|
||||||
Toast.makeText(
|
UiMessageBus.warning(when (standardVoiceAvailability) {
|
||||||
context,
|
|
||||||
when (standardVoiceAvailability) {
|
|
||||||
com.hermesandroid.relay.viewmodel.StandardVoiceAvailability.SignInRequired ->
|
com.hermesandroid.relay.viewmodel.StandardVoiceAvailability.SignInRequired ->
|
||||||
standardVoiceSignInRouteHint?.let { route ->
|
standardVoiceSignInRouteHint?.let { route ->
|
||||||
"Voice needs a one-time sign-in on the $route route — open Manage"
|
"Voice needs a one-time sign-in on the $route route — open Manage"
|
||||||
@@ -4587,9 +4618,7 @@ fun ChatScreen(
|
|||||||
"This Hermes build has no voice routes — update hermes-agent or pair Relay"
|
"This Hermes build has no voice routes — update hermes-agent or pair Relay"
|
||||||
else ->
|
else ->
|
||||||
context.getString(R.string.chat_voice_needs_route)
|
context.getString(R.string.chat_voice_needs_route)
|
||||||
},
|
})
|
||||||
Toast.LENGTH_SHORT,
|
|
||||||
).show()
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -4650,6 +4679,13 @@ fun ChatScreen(
|
|||||||
supervisedPolicy.capabilities.attachmentCategories
|
supervisedPolicy.capabilities.attachmentCategories
|
||||||
)) pasteImageFromClipboard else ({ }),
|
)) pasteImageFromClipboard else ({ }),
|
||||||
onLongPressAttach = { if (!supervised) showCommandPalette = true },
|
onLongPressAttach = { if (!supervised) showCommandPalette = true },
|
||||||
|
modifier = Modifier
|
||||||
|
.align(Alignment.CenterHorizontally)
|
||||||
|
.then(
|
||||||
|
responsiveLayout.chromeMaxWidth?.let {
|
||||||
|
Modifier.widthIn(max = it)
|
||||||
|
} ?: Modifier,
|
||||||
|
),
|
||||||
charLimit = charLimit,
|
charLimit = charLimit,
|
||||||
caption = turnStatus ?: inputCaption,
|
caption = turnStatus ?: inputCaption,
|
||||||
voiceReady = voiceReady,
|
voiceReady = voiceReady,
|
||||||
@@ -4806,6 +4842,30 @@ fun ChatScreen(
|
|||||||
}
|
}
|
||||||
} // end Column
|
} // end Column
|
||||||
|
|
||||||
|
ChatDebugOverlay(
|
||||||
|
visible = showChatDebug && !supervised,
|
||||||
|
headerHeight = with(density) { chatHeaderHeightPx.toDp() },
|
||||||
|
onClose = { showChatDebug = false },
|
||||||
|
) {
|
||||||
|
ChatDebugDrawer(
|
||||||
|
profile = AgentDisplay.profileDisplayName(conversationProfile)
|
||||||
|
?: stringResource(R.string.chat_server_default),
|
||||||
|
model = AgentDisplay.displayModelName(sessionModelState.model).orEmpty(),
|
||||||
|
sessionId = currentSessionId,
|
||||||
|
gateway = isGatewayTransport,
|
||||||
|
signedIn = chatGatewayAvailability == GatewayAvailability.Ready,
|
||||||
|
signInRequired = chatGatewayAvailability == GatewayAvailability.SignInRequired,
|
||||||
|
socketState = gatewaySocketState,
|
||||||
|
preparing = preparingGatewaySession,
|
||||||
|
streaming = isStreaming,
|
||||||
|
loadingHistory = isLoadingHistory,
|
||||||
|
directoryUnavailable = sessionListUnavailable,
|
||||||
|
failure = visibleChatFailure?.rawError,
|
||||||
|
onClose = { showChatDebug = false },
|
||||||
|
onConnections = { showChatDebug = false; onNavigateToConnections() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// Mic permission denied banner — title + body + Open Settings action.
|
// Mic permission denied banner — title + body + Open Settings action.
|
||||||
// System "Don't ask again" gives no callback, so a toast would leave
|
// System "Don't ask again" gives no callback, so a toast would leave
|
||||||
// the user stranded. Banner + direct-to-app-details deep link is the
|
// the user stranded. Banner + direct-to-app-details deep link is the
|
||||||
@@ -4945,8 +5005,8 @@ fun ChatScreen(
|
|||||||
|
|
||||||
if (showBackgroundProcesses) {
|
if (showBackgroundProcesses) {
|
||||||
GatewayBackgroundProcessSheet(
|
GatewayBackgroundProcessSheet(
|
||||||
processes = backgroundProcesses,
|
processes = retainedActivityPreview?.processes ?: backgroundProcesses,
|
||||||
subagentActivities = subagentActivities,
|
subagentActivities = retainedActivityPreview?.record?.previewActivities() ?: subagentActivities,
|
||||||
subagentChildPreview = subagentChildPreview,
|
subagentChildPreview = subagentChildPreview,
|
||||||
subagentPreviewVisibility = subagentPreviewVisibility,
|
subagentPreviewVisibility = subagentPreviewVisibility,
|
||||||
loading = backgroundProcessesLoading,
|
loading = backgroundProcessesLoading,
|
||||||
@@ -4955,8 +5015,10 @@ fun ChatScreen(
|
|||||||
onStop = chatViewModel::stopBackgroundProcess,
|
onStop = chatViewModel::stopBackgroundProcess,
|
||||||
onDismissProcess = chatViewModel::dismissBackgroundProcess,
|
onDismissProcess = chatViewModel::dismissBackgroundProcess,
|
||||||
onOpenSubagentChild = chatViewModel::openSubagentChildPreview,
|
onOpenSubagentChild = chatViewModel::openSubagentChildPreview,
|
||||||
|
readOnlyHistory = retainedActivityPreview != null,
|
||||||
|
historyNotice = if (retainedActivityPreview != null) stringResource(R.string.chat_activity_history_notice) else null,
|
||||||
onDismiss = {
|
onDismiss = {
|
||||||
chatViewModel.closeSubagentChildPreview()
|
chatViewModel.closeActivityPreview()
|
||||||
showBackgroundProcesses = false
|
showBackgroundProcesses = false
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -5497,13 +5559,9 @@ private suspend fun ingestAttachmentFromUri(
|
|||||||
} catch (cancelled: CancellationException) {
|
} catch (cancelled: CancellationException) {
|
||||||
throw cancelled
|
throw cancelled
|
||||||
} catch (_: AttachmentTooLargeException) {
|
} catch (_: AttachmentTooLargeException) {
|
||||||
Toast.makeText(
|
UiMessageBus.warning(context.getString(R.string.chat_file_too_large, maxAttachmentMb))
|
||||||
context,
|
|
||||||
context.getString(R.string.chat_file_too_large, maxAttachmentMb),
|
|
||||||
Toast.LENGTH_SHORT,
|
|
||||||
).show()
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Toast.makeText(context, context.getString(R.string.chat_failed_read_file), Toast.LENGTH_SHORT).show()
|
UiMessageBus.error(context.getString(R.string.chat_failed_read_file))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.hermesandroid.relay.ui.screens
|
package com.hermesandroid.relay.ui.screens
|
||||||
|
|
||||||
|
import com.hermesandroid.relay.ui.components.ChatBusyActionSelector
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
@@ -499,6 +500,22 @@ fun ChatSettingsScreen(
|
|||||||
|
|
||||||
HorizontalDivider()
|
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
|
val physicalKeyboardEnterBehavior by
|
||||||
connectionViewModel.physicalKeyboardEnterBehavior.collectAsState()
|
connectionViewModel.physicalKeyboardEnterBehavior.collectAsState()
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
@@ -706,8 +723,9 @@ fun ChatSettingsScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Live preview of the exact text that will be sent.
|
// Representative preview of each enabled block.
|
||||||
// Rebuilds on every toggle change via remember(key1..key5).
|
// The chat context audit remains the exact selected-
|
||||||
|
// session preview. Rebuilds on every toggle change.
|
||||||
val previewText = remember(
|
val previewText = remember(
|
||||||
appContextEnabled,
|
appContextEnabled,
|
||||||
appContextBridgeState,
|
appContextBridgeState,
|
||||||
@@ -735,6 +753,14 @@ fun ChatSettingsScreen(
|
|||||||
destructiveVerbCount = 5,
|
destructiveVerbCount = 5,
|
||||||
autoDisableMinutes = 15,
|
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(
|
Card(
|
||||||
@@ -778,7 +804,7 @@ fun ChatSettingsScreen(
|
|||||||
serverCaps,
|
serverCaps,
|
||||||
) {
|
) {
|
||||||
resolveChatTransportStatus(
|
resolveChatTransportStatus(
|
||||||
streamingEndpoint = streamingEndpoint,
|
streamingEndpoint = resolvedStreamingEndpoint,
|
||||||
gatewayAvailability = gatewayAvailability,
|
gatewayAvailability = gatewayAvailability,
|
||||||
serverCapabilities = serverCaps,
|
serverCapabilities = serverCaps,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ import androidx.compose.ui.unit.dp
|
|||||||
import com.hermesandroid.relay.R
|
import com.hermesandroid.relay.R
|
||||||
import com.hermesandroid.relay.data.Connection
|
import com.hermesandroid.relay.data.Connection
|
||||||
import com.hermesandroid.relay.data.EndpointCandidate
|
import com.hermesandroid.relay.data.EndpointCandidate
|
||||||
|
import com.hermesandroid.relay.data.SessionTransport
|
||||||
import com.hermesandroid.relay.data.capabilities
|
import com.hermesandroid.relay.data.capabilities
|
||||||
import com.hermesandroid.relay.data.displayLabel
|
import com.hermesandroid.relay.data.displayLabel
|
||||||
import com.hermesandroid.relay.data.gatewayRouteUrl
|
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.ConnectionViewModel
|
||||||
import com.hermesandroid.relay.viewmodel.RelayUiState
|
import com.hermesandroid.relay.viewmodel.RelayUiState
|
||||||
import com.hermesandroid.relay.viewmodel.StandardVoiceAvailability
|
import com.hermesandroid.relay.viewmodel.StandardVoiceAvailability
|
||||||
|
import com.hermesandroid.relay.viewmodel.resolveActiveChatTransport
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -476,12 +478,16 @@ private fun ActiveOverview(
|
|||||||
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
val effectiveDashboardUrl by connectionViewModel.effectiveDashboardUrl.collectAsState()
|
||||||
val relayConfigured by connectionViewModel.relayConfigured.collectAsState()
|
val relayConfigured by connectionViewModel.relayConfigured.collectAsState()
|
||||||
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
val standardVoiceAvailability by connectionViewModel.standardVoiceAvailability.collectAsState()
|
||||||
val usingApiFallback = apiReachable && gatewayAvailability in setOf(
|
val streamingEndpoint by connectionViewModel.streamingEndpoint.collectAsState()
|
||||||
GatewayAvailability.SignInRequired,
|
// Observe the binding as well as the saved preference so a restored
|
||||||
GatewayAvailability.Unreachable,
|
// conversation immediately presents its actual owner.
|
||||||
GatewayAvailability.Unsupported,
|
val activeConversationTransport by connectionViewModel.activeConversationTransport.collectAsState()
|
||||||
)
|
val usingDirectApi = resolveActiveChatTransport(
|
||||||
val currentRouteUrl = if (usingApiFallback) {
|
boundOwner = activeConversationTransport,
|
||||||
|
connection = connection,
|
||||||
|
preference = streamingEndpoint,
|
||||||
|
) == SessionTransport.SSE
|
||||||
|
val currentRouteUrl = if (usingDirectApi) {
|
||||||
activeEndpoint?.api?.url ?: connection.apiServerUrl
|
activeEndpoint?.api?.url ?: connection.apiServerUrl
|
||||||
} else {
|
} else {
|
||||||
effectiveDashboardUrl
|
effectiveDashboardUrl
|
||||||
@@ -492,23 +498,29 @@ private fun ActiveOverview(
|
|||||||
effectiveDashboardUrl = currentRouteUrl,
|
effectiveDashboardUrl = currentRouteUrl,
|
||||||
)
|
)
|
||||||
val routeStatus = when {
|
val routeStatus = when {
|
||||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
usingDirectApi && apiReachable ->
|
||||||
OverviewStatus(stringResource(R.string.active_section_reachable), OverviewTone.Good)
|
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)
|
OverviewStatus(stringResource(R.string.active_section_sign_in), OverviewTone.Info)
|
||||||
gatewayAvailability == GatewayAvailability.Unknown ||
|
(!usingDirectApi && gatewayAvailability == GatewayAvailability.Unknown) ||
|
||||||
apiHealth == ConnectionViewModel.HealthStatus.Probing ->
|
(usingDirectApi && apiHealth == ConnectionViewModel.HealthStatus.Probing) ->
|
||||||
OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
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)
|
OverviewStatus(stringResource(R.string.active_section_unsupported), OverviewTone.Warning)
|
||||||
else -> OverviewStatus(stringResource(R.string.active_section_unreachable), OverviewTone.Warning)
|
else -> OverviewStatus(stringResource(R.string.active_section_unreachable), OverviewTone.Warning)
|
||||||
}
|
}
|
||||||
val chatStatus = when {
|
val chatStatus = when {
|
||||||
gatewayAvailability == GatewayAvailability.Ready || usingApiFallback ->
|
usingDirectApi && apiReachable ->
|
||||||
OverviewStatus(stringResource(R.string.active_section_ready), OverviewTone.Good)
|
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)
|
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)
|
OverviewStatus(stringResource(R.string.active_section_offline), OverviewTone.Warning)
|
||||||
else -> OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
else -> OverviewStatus(stringResource(R.string.active_section_checking), OverviewTone.Neutral)
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user