diff --git a/.claude/skills/branching-strategy/SKILL.md b/.claude/skills/branching-strategy/SKILL.md index 38c74190b..b65703358 100644 --- a/.claude/skills/branching-strategy/SKILL.md +++ b/.claude/skills/branching-strategy/SKILL.md @@ -5,49 +5,10 @@ description: Use when creating a new branch or git worktree for a feature, bugfi # Branching Strategy -## Overview +Follow **Creating Work Branches** and **Branch Roles** in the root `AGENTS.md`. They are the only source for bases, branch names and merge targets. -New work branches start from a user-selected `upstream/XX-dev` integration branch. The current checkout and `main` are not implicit bases. Resolve available lines from fetched refs; the user chooses the base. +The usual case after `git fetch origin --prune`: -`main` is the release line. `upstream/XX-dev` branches are the versioned dev/integration lines where feature and bugfix work lands. - -## Workflow - -1. **Refresh and discover bases.** Remote-tracking refs go stale here; fetch first: - ```bash - git fetch origin --prune - git branch -a --list '*upstream/*' # upstream/XX-dev lines - git branch -a --list '*feat/*' --list '*fix/*' # active working branches - ``` - If remote state is in doubt, cross-check with `gh api repos///branches --jq '.[].name'`. - -2. **Ask the user which base to start from** (AskUserQuestion). Always ask, even when only one `upstream/XX-dev` exists. Offer as choices: - - Each `upstream/XX-dev` branch — recommend the newest version. - - "An existing working branch" — for work that depends on another in-flight branch. - -3. **Create the branch** (name it `feat/` or `fix/`, matching existing repo conventions): - ```bash - git checkout -b fix/ - # or isolated: - git worktree add ../- -b feat/ - ``` - -4. **Dependent base? Flag the merge-back immediately.** If the base is a working branch rather than `upstream/XX-dev`, tell the user in your response, and repeat it when the work is ready to merge: - > ⚠️ This branch is based on ``, not `upstream/XX-dev`. It must merge back only after (or together with) its parent, and merging into `upstream/XX-dev` may conflict with the parent's changes. Rebase onto the parent if it moves. - -5. Don't push or set an upstream tracking branch until the user asks. - -## Quick Reference - -| Situation | Base | Extra step | -|---|---|---| -| Feature / bugfix | `upstream/XX-dev` chosen by user | — | -| Work depending on an in-flight branch | that working branch, if user confirms | Merge-back conflict warning (step 4) | -| Base unclear / user unavailable | stop and ask | Never guess | - -## Common Mistakes - -- **Branching from current HEAD or `main` without asking** — the checked-out branch is not evidence of the right base. List the `upstream/*-dev` lines and ask. -- **"Only one dev branch exists, so no need to ask"** — still ask; the user may want a dependent working branch as base, or a new dev line may be pending. -- **Silent dependent branch** — creating a branch off another feature branch without stating the merge-back risk leaves the user to discover conflicts at PR time. -- **Trusting stale remote refs** — always `git fetch origin --prune` before listing candidate bases. +```bash +git worktree add ../- -b feat/ origin/develop +``` diff --git a/.claude/skills/e2e-audit/SKILL.md b/.claude/skills/e2e-audit/SKILL.md index 263a2ce91..f865e3e76 100644 --- a/.claude/skills/e2e-audit/SKILL.md +++ b/.claude/skills/e2e-audit/SKILL.md @@ -1,18 +1,19 @@ --- name: e2e-audit -description: On-demand only — invoke with /e2e-audit. Journey-audit register reference for PR review, release gating, and stability/regression assessment in this repo. +description: On-demand only — invoke with /e2e-audit. Reads the historical Home journey-audit workbook as test input for PR review and regression assessment in this repo. disable-model-invocation: true --- -# Journey Audit Register +# Journey Audit Workbook ## Overview [docs/audits/ElastOS-Home-Journey-Audit.xlsx](../../../docs/audits/ElastOS-Home-Journey-Audit.xlsx) -is the canonical register of user journeys, static controls, and findings. It is -the reference for stability and correctness for every PR and release. Treat it -as a contract: product-behavior changes are measured against it, and the -register is updated in the same PR that changes what it describes. +is a historical snapshot of user journeys, static controls, and findings. It is +test input, not a current record. Current acceptance lives in GitHub: each +owning issue keeps its Acceptance record (see +[AGENTS.md](../../../AGENTS.md#acceptance-record)), and #93 owns the release +gates. The workbook is not updated. ## Reading the workbook @@ -36,29 +37,22 @@ python3 .claude/skills/e2e-audit/read-workbook.py "Journey Matrix" # TSV dump python3 .claude/skills/e2e-audit/read-workbook.py Findings --grep AUTH-01 ``` -## The invariant +## Using it 1. Before changing behavior in an area, read that area's Journey Matrix rows and every Finding whose Journey IDs reference them. -2. A journey recorded as Pass stays Pass. A change that intentionally alters a - journey's expected behavior updates the journey row in the same PR and names - the change in the PR description. -3. A finding closes only with its "Proof to close" evidence. Dispositions are - updated in place, never deleted. -4. New product surface ships with new journey rows (ID, Area, Expected - behavior, Steps, Prerequisites) in the same PR. -5. Verdicts are evidence-bound. Live status and Live evidence come only from - installed, live checks; source reading updates Source state only. The - snapshot pins installed evidence to an exact source commit — later source - changes need their own installed checks before any live claim. -6. Release gate: no open P1 finding against a touched area, and a refreshed - audit snapshot for the exact release revision. The register drives - pre-release testing. +2. Transfer the relevant journeys and open findings to the owning GitHub issue + as acceptance checks. Record results there, not in the workbook. +3. Keep journeys that passed working. A change that intentionally alters one + names the change in the PR description and the owning issue. +4. Live status in the workbook is pinned to its snapshot source commit. Any + current live claim needs installed evidence from the exact candidate. ## Common mistakes +- Treating the workbook as current status — its verdicts date from the + snapshot; the owning issue holds current status. - Claiming a journey passes because code compiles or unit tests pass — the - register separates Source state from Live evidence for exactly this reason. -- Changing an area without searching the workbook for its journey IDs. + workbook separates Source state from Live evidence for exactly this reason. - Reading the evidence labels as repo paths — evidence files stay outside the repository (see [docs/audits/README.md](../../../docs/audits/README.md)). diff --git a/.cursor/rules/branching-strategy.mdc b/.cursor/rules/branching-strategy.mdc index 75ab59a05..b702828a0 100644 --- a/.cursor/rules/branching-strategy.mdc +++ b/.cursor/rules/branching-strategy.mdc @@ -6,12 +6,4 @@ alwaysApply: false # Branching Strategy -New work branches start from an `upstream/XX-dev` integration branch (e.g. `upstream/0.6-dev`) — never silently from `main` or from whatever branch is checked out. The user chooses the base; never pick it yourself. - -1. `git fetch origin --prune`, then list `upstream/*-dev` lines and active `feat/*`/`fix/*` branches. -2. Ask the user which base to start from, offering each `upstream/XX-dev` (newest recommended) plus "an existing working branch" for work that depends on another in-flight branch. Ask even when only one dev line exists. -3. Create the branch as `feat/` or `fix/` from the chosen base. -4. If the base is a working branch rather than `upstream/XX-dev`, warn immediately: it must merge back only after (or together with) its parent, merging into `upstream/XX-dev` may conflict with the parent's changes, and it needs a rebase if the parent moves. Repeat the warning at merge time. -5. Do not push or set upstream tracking until asked. - -Canonical workflow: @.claude/skills/branching-strategy/SKILL.md +Follow **Creating Work Branches** and **Branch Roles** in @AGENTS.md. They are the only source for bases, branch names and merge targets. diff --git a/.gitattributes b/.gitattributes index 89d0ee34e..cec3adbcb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,6 @@ capsules/gba-emulator/browser/mgba.js -diff linguist-generated=true capsules/gba-emulator/browser/mgba.wasm -diff linguist-generated=true +# Preserve identified upstream bytes and unified-diff context lines. +third-party/selkies/upstream/** -whitespace +third-party/selkies/licenses/** -whitespace +third-party/selkies/patches/*.patch -whitespace diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 000000000..2e0502050 --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +# Git has already resolved the pushed object. A merge here would check a +# different object from the one Git is about to publish. +exec "$(dirname "$0")/../scripts/ci-local-prepush.sh" "$@" diff --git a/.github/actions/rust-compile-cache/action.yml b/.github/actions/rust-compile-cache/action.yml new file mode 100644 index 000000000..c58946e5c --- /dev/null +++ b/.github/actions/rust-compile-cache/action.yml @@ -0,0 +1,49 @@ +name: Rust compile cache +description: Content-addressed Rust compile cache for test jobs +runs: + using: composite + steps: + - name: install checksummed sccache + continue-on-error: true + shell: bash + run: | + set -euo pipefail + checksum=(sha256sum) + case "$RUNNER_OS/$RUNNER_ARCH" in + Linux/X64) + archive=sccache-v0.18.0-x86_64-unknown-linux-musl + digest=45f1447fbe231e3037bde351ef70677dd212216c8d62ae7ca409fecc4d6acc89 + ;; + Linux/ARM64) + archive=sccache-v0.18.0-aarch64-unknown-linux-musl + digest=2b3284d5da3b46a47dc4229e75bb7b88ac4aa99c8d754fb7d2f84997e5a4354a + ;; + macOS/ARM64) + archive=sccache-v0.18.0-aarch64-apple-darwin + digest=308184519b646f5125289e8515b36f6ca65a13a041923994aebe702348674e8e + checksum=(shasum -a 256) + ;; + *) exit 1 ;; + esac + directory="$RUNNER_TEMP/rust-compile-cache" + mkdir -p "$directory" + curl -fsSL --connect-timeout 30 --max-time 120 --retry 3 \ + "https://github.com/mozilla/sccache/releases/download/v0.18.0/$archive.tar.gz" \ + -o "$directory/$archive.tar.gz" + echo "$digest $directory/$archive.tar.gz" | "${checksum[@]}" -c - + tar -xzf "$directory/$archive.tar.gz" -C "$directory" "$archive/sccache" + # The job's Swatinem/rust-cache step restores and saves this directory. + # The daemon runs rustc and its proc macros, so it holds no Actions + # credential and uses no remote backend. + cache="$directory/objects" + # Keep the daemon that compiles every later step alive for its check. + if SCCACHE_DIR="$cache" SCCACHE_CACHE_SIZE=2G SCCACHE_IDLE_TIMEOUT=0 \ + "$directory/$archive/sccache" --start-server; then + echo "$directory/$archive" >> "$GITHUB_PATH" + { + echo "SCCACHE_DIR=$cache" + echo "SCCACHE_CACHE_SIZE=2G" + echo "RUSTC_WRAPPER=sccache" + echo "CARGO_INCREMENTAL=0" + } >> "$GITHUB_ENV" + fi diff --git a/.github/scripts/release-mac-capacity-test.py b/.github/scripts/release-mac-capacity-test.py old mode 100644 new mode 100755 index 0baca8b97..d0d4ff1f8 --- a/.github/scripts/release-mac-capacity-test.py +++ b/.github/scripts/release-mac-capacity-test.py @@ -22,7 +22,7 @@ class CapacityTests(unittest.TestCase): def setUp(self): self.record, self.growth, self.clock, self.commands = {}, 100, 0, [] - self.disk = SimpleNamespace(total=1000, free=100) + self.disk = SimpleNamespace(total=1000, free=50) self.bindings = Mock(return_value={'sdk': 'native', 'clang_sha256': 'a'}) self.images = [{'image': {'state': 'Ready'}}, {'image': {'state': 'Deleting'}}, {}] @@ -38,8 +38,8 @@ def query(self, argv, timeout=30): return '' def refusal(self, *, status='unavailable', growth=100, kind=ValueError): - error = kind(f'hosted Mac capacity unavailable: free=100 total=1000 planned_growth={growth}') - error.capacity = {'status': status, 'planned_growth_bytes': growth, 'free_bytes_after': 100, 'total_bytes': 1000} + error = kind(f'hosted Mac capacity unavailable: free=50 total=1000 planned_growth={growth}') + error.capacity = {'status': status, 'planned_growth_bytes': growth, 'free_bytes_after': 50, 'total_bytes': 1000} return error def run_capacity(self, prepare, **overrides): @@ -87,7 +87,7 @@ def test_shortfall_claim_cannot_override_measured_space_or_changed_tools(self): self.disk.free = 250 with self.assertRaises(ValueError): self.run_capacity(Mock(side_effect=self.refusal())) - self.disk.free = 100 + self.disk.free = 50 self.bindings.side_effect = [{'sdk': 'native'}, {'sdk': 'changed'}] with self.assertRaisesRegex(ValueError, 'Native build inputs changed'): self.run_capacity(Mock(side_effect=self.refusal())) @@ -133,9 +133,11 @@ def test_second_shortfall_stays_failed(self): self.assertIs(caught.exception, second) self.assertNotEqual(self.record.get('status'), 'ready') - def test_reserve_boundary_is_exact(self): - self.assertTrue(controller.enough(SimpleNamespace(total=1000, free=250), 100)) - self.assertFalse(controller.enough(SimpleNamespace(total=1000, free=249), 100)) + def test_growth_boundary_is_exact(self): + self.assertTrue(controller.enough(SimpleNamespace(total=1000, free=100), 100)) + self.assertFalse(controller.enough(SimpleNamespace(total=1000, free=99), 100)) + # Volume size alone never refuses growth that fits. + self.assertTrue(controller.enough(SimpleNamespace(total=10**15, free=100), 100)) def test_entrypoint_refuses_local_and_self_hosted_runs(self): with patch.object(sys, 'argv', ['capacity']), patch.object(controller, 'query') as query: diff --git a/.github/scripts/release-mac-capacity.py b/.github/scripts/release-mac-capacity.py old mode 100644 new mode 100755 index b753458d2..959c11023 --- a/.github/scripts/release-mac-capacity.py +++ b/.github/scripts/release-mac-capacity.py @@ -50,7 +50,7 @@ def native_bindings(): def enough(disk, growth): - return (disk.free - growth) * 100 >= disk.total * 15 + return disk.free >= growth def run_capacity(record, growth, prepare, measure, bindings=native_bindings, @@ -67,7 +67,7 @@ def run_capacity(record, growth, prepare, measure, bindings=native_bindings, for key in ('free_bytes_after', 'total_bytes')) and str(error) == f"hosted Mac capacity unavailable: free={receipt['free_bytes_after']} " f"total={receipt['total_bytes']} planned_growth={growth}" - and (receipt['free_bytes_after'] - growth) * 100 < receipt['total_bytes'] * 15 + and receipt['free_bytes_after'] < growth and not enough(measure(), growth)): raise help_text = query(['/usr/bin/xcrun', 'simctl', 'help', 'runtime']) @@ -87,7 +87,7 @@ def inventory(): record['recheck'] = prepare() record['native_after'] = bindings() need(record['native_after'] == record['native_before'], 'Native build inputs changed') - need(enough(measure(), growth), 'Capacity below planned growth and 15% reserve') + need(enough(measure(), growth), 'Capacity below planned growth') record['status'] = 'ready' @@ -118,7 +118,7 @@ def prepare(): finally: capacity.cli_reclaim_xcode = original record = {'status': 'unavailable', 'source_commit': os.environ['SOURCE_COMMIT'], - 'source_tree': os.environ['SOURCE_TREE'], 'planned_growth_bytes': growth, 'reserve_percent': 15} + 'source_tree': os.environ['SOURCE_TREE'], 'planned_growth_bytes': growth} try: run_capacity(record, growth, prepare, lambda: shutil.disk_usage(root)) finally: diff --git a/.github/workflows/canary-holder-linux.yml b/.github/workflows/canary-holder-linux.yml new file mode 100644 index 000000000..e28dd55d6 --- /dev/null +++ b/.github/workflows/canary-holder-linux.yml @@ -0,0 +1,496 @@ +# Issue #89: qualify the IPFS holder's idle recovery and the gateway's Kubo +# lifetime with the Runtime and providers built from the source under test. +name: Canary Linux holder + +on: + pull_request: + # scripts/ci-release-policy-test.py requires every repository input the + # holder job's scripts call to match these paths. + paths: + - .github/workflows/canary-holder-linux.yml + - rust-toolchain.toml + - .cargo/config.toml + - components.json + - capsules/ipfs-provider/** + - elastos/capsules/localhost-provider/** + - elastos/crates/elastos-common/** + - elastos/crates/elastos-guest/** + - elastos/Cargo.toml + - elastos/Cargo.lock + - elastos/crates/elastos-runtime/src/provider/registry.rs + - elastos/crates/elastos-server/src/ipfs.rs + - elastos/crates/elastos-server/src/server_infra.rs + - elastos/crates/elastos-server/src/gateway_entry.rs + - elastos/crates/elastos-server/src/gateway_cmd.rs + - scripts/holder-idle-ci.py + - scripts/update-hop-compare.py + - scripts/seed-kubo-cache.sh + - scripts/release-upstream-input.py + - scripts/release-upstream-recipes.json + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: canary-holder-linux-${{ github.ref }} + cancel-in-progress: false + +env: + CARGO_BUILD_JOBS: '4' + CARGO_TARGET_DIR: ${{ github.workspace }}/holder-target + PYTHONDONTWRITEBYTECODE: '1' + +jobs: + holder: + runs-on: ubuntu-24.04 + timeout-minutes: 90 + defaults: + run: + shell: bash + working-directory: source + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + path: source + persist-credentials: false + - uses: dtolnay/rust-toolchain@7e38f4b43b4db5c8dd498af069a4f6196df1d067 + with: + toolchain: 1.91.0 + - name: build Runtime, IPFS provider and localhost provider from this source + timeout-minutes: 40 + run: | + set -euo pipefail + # `--bin elastos` filters every selected package, so build localhost-provider on its own. + cargo build --locked --release --manifest-path elastos/Cargo.toml -p elastos-server --bin elastos + cargo build --locked --release --manifest-path elastos/Cargo.toml -p localhost-provider + cargo build --locked --release --manifest-path capsules/ipfs-provider/Cargo.toml + build="$RUNNER_TEMP/holder-build" + install -d -m 700 "$build" "$RUNNER_TEMP/holder-output" + install -m 700 "$CARGO_TARGET_DIR"/release/{elastos,ipfs-provider,localhost-provider} "$build/" + if ldd "$build"/* | grep 'not found'; then exit 1; fi + echo "HOLDER_BUILD=$build" >> "$GITHUB_ENV" + echo "HOLDER_OUTPUT=$RUNNER_TEMP/holder-output" >> "$GITHUB_ENV" + - name: test the IPFS provider and the gateway role + timeout-minutes: 30 + run: | + set -euo pipefail + cargo test --locked --manifest-path capsules/ipfs-provider/Cargo.toml + for filter in runtime_host_role_init browser_home_public_mode_refuses_before_provider_setup public_gateway_ipfs_refresh; do + cargo test --locked --manifest-path elastos/Cargo.toml -p elastos-server --lib "$filter" + done + cargo test --locked --manifest-path elastos/Cargo.toml -p elastos-runtime private_ipfs_generic_and_remote_dispatch_rejected_before_transmission + - name: seed the checksum-pinned isolated Kubo prerequisite + run: | + set -euo pipefail + # Issue #217 owns replacing this accepted build-time prerequisite. + scripts/seed-kubo-cache.sh "$RUNNER_TEMP/holder-kubo-cache" "$HOLDER_BUILD/kubo-input" linux-amd64 + - name: prove repeated watcher stops and uncached gateway and Carrier recovery + timeout-minutes: 20 + run: | + set -euo pipefail + umask 077 + python3 - <<'PY' + import base64, hashlib, importlib.util, json, os, re, select, shutil, socket, subprocess, time, urllib.error, urllib.parse, urllib.request + from pathlib import Path + spec = importlib.util.spec_from_file_location('observer', 'scripts/update-hop-compare.py') + observer = importlib.util.module_from_spec(spec) + spec.loader.exec_module(observer) + output, accepted = Path(os.environ['HOLDER_OUTPUT']), Path(os.environ['HOLDER_BUILD']) + processes = observer.CliProcesses(output) + root = Path.home() / '.local/share/elastos-issue89-holder' + assert not root.exists() and not root.is_symlink() + root.mkdir(mode=0o700, parents=True) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + result = {'schema': 'elastos.issue89.holder-idle/v1', 'source_commit': os.environ['GITHUB_SHA'], 'passed': False, + 'clock': 'production watcher, fixture last_used aged to now-601; no elapsed-time claim', + 'source_modified': False, 'service_restarts': 0, 'provider_restarts': 0, 'reads': [], 'idle_stops': []} + def sha(path): + with path.open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + def env(home): + return {**observer.cli_environment(home), 'XDG_DATA_HOME': str(home / '.local/share'), + 'ELASTOS_DATA_DIR': str(home / '.local/share/elastos')} + def port(kind=socket.SOCK_STREAM): + with socket.socket(socket.AF_INET, kind) as probe: + probe.bind(('127.0.0.1', 0)) + return probe.getsockname()[1] + def command(home, argv, label): + response = processes.command(argv, env(home), home, label, timeout=90) + assert response['exit'] == 0, label + ' failed; see fixture logs' + return processes.text(label).strip() + def get(url, bound=128 * 1024**2, timeout=90): + with opener.open(url, timeout=timeout) as response: + assert response.status == 200 + payload = response.read(bound + 1) + assert len(payload) <= bound + return payload + def ready(home, host, http_port, full_api=False): + deadline = time.monotonic() + 60 + while time.monotonic() < deadline and host.poll() is None: + try: + get(f'http://127.0.0.1:{http_port}' + ('/api/health' if full_api else '/healthz'), 65536, 2) + return + except (OSError, urllib.error.URLError): + time.sleep(.2) + raise AssertionError('Runtime readiness failed; see fixture logs') + def child_identity(pid): + path = Path('/proc') / str(pid) + return {'pid': pid, 'start_time': (path / 'stat').read_text().rsplit(')', 1)[1].split()[19], + 'exe': os.readlink(path / 'exe')} + def provider_identity(host, provider): + matches = [row for row in observer.cli_census() if row['group'] == host.pid + and row['command'].split(' ', 1)[0] == str(provider)] + assert len(matches) == 1, 'exact single native provider generation required' + return child_identity(matches[0]['pid']) + def read(home, http_port, cid, expected, label): + cache = home / 'gateway-cache' / (cid + '.raw') + assert not cache.exists(), 'qualification read must be uncached' + record = {'label': label, 'cid': cid, 'ingress': 'public gateway /content/:cid', + 'expected_sha256': sha(expected), 'expected_size': expected.stat().st_size, 'cache_absent': True} + try: + payload = get(f'http://127.0.0.1:{http_port}/content/{cid}') + record.update(size=len(payload), sha256=hashlib.sha256(payload).hexdigest()) + record['passed'] = record['size'] == expected.stat().st_size and record['sha256'] == record['expected_sha256'] + except (OSError, urllib.error.URLError, AssertionError) as error: + record.update(passed=False, error_type=type(error).__name__) + result['reads'].append(record) + return record['passed'] + def post(url, request, bound, token=None): + headers = {'Content-Type': 'application/json'} + if token is not None: + headers['Authorization'] = 'Bearer ' + token + wire = urllib.request.Request(url, data=json.dumps(request).encode(), headers=headers, method='POST') + return json.loads(get(wire, bound)) + def attach(data, owner, api_port): + # Match Runtime's attach_to_runtime contract. Secrets and session + # tokens remain in this process, outside logs and proof receipts. + path = data / 'runtime-coords.json' + assert not path.is_symlink() and path.stat().st_mode & 0o077 == 0 + coords = json.loads(path.read_bytes()) + assert coords['pid'] == owner.pid and coords['runtime_kind'] == 'operator' + parsed = urllib.parse.urlsplit(coords['api_url']) + assert parsed.scheme == 'http' and parsed.hostname == '127.0.0.1' + assert parsed.port == api_port and parsed.path in ('', '/') + assert parsed.username is None and parsed.password is None and not parsed.query and not parsed.fragment + api = coords['api_url'].rstrip('/') + response = post(api + '/api/auth/attach', {'secret': coords['attach_secret'], 'scope': 'shell'}, 65536) + assert response['session_type'] == 'shell' and isinstance(response['token'], str) and response['token'] + return api, response['token'] + def content_read(auth, cid, expected, label, carrier=False, destination=None): + record = {'label': label, 'cid': cid, 'ingress': 'private Runtime /api/provider/content/fetch', + 'transfer': 'complete unbounded bytes', 'expected_sha256': sha(expected), + 'expected_size': expected.stat().st_size, 'carrier_claim': carrier, + 'legacy_carrier_content_fetch_journey': False} + try: + # No range, max_bytes, bounded_read or prepare operation is + # sent. The first post-stop operation is this content read. + bound = 4 * ((record['expected_size'] + 2) // 3) + 65536 + response = post(auth[0] + '/api/provider/content/fetch', {'cid': cid}, bound, auth[1]) + assert response['status'] == 'ok' and response['data']['cid'] == cid + payload = base64.b64decode(response['data']['data'], validate=True) + record.update(size=len(payload), sha256=hashlib.sha256(payload).hexdigest()) + record['passed'] = record['size'] == record['expected_size'] and record['sha256'] == record['expected_sha256'] + if carrier: + availability = response['data']['availability'] + assert availability['provider'] == 'carrier-availability' + assert availability['policy'] == 'carrier_provider_invoke' + assert availability['transport'] == 'carrier-provider-plane' + assert availability['status'] == 'network_available' + record['transport'] = 'typed availability / Carrier provider_invoke / holder Content / native IPFS cat' + else: + record['transport'] = 'local Content / native IPFS cat' + if destination is not None: + assert record['passed'] and not destination.exists() + destination.write_bytes(payload) + destination.chmod(0o700) + assert sha(destination) == record['expected_sha256'] + except (OSError, urllib.error.URLError, AssertionError, ValueError, KeyError) as error: + record.update(passed=False, error_type=type(error).__name__) + result['reads'].append(record) + return record['passed'] + def idle_stop(data, owner, identity, label, log_label): + coord_path = data / 'ipfs-coords.json' + coord = json.loads(coord_path.read_bytes()) + before = child_identity(coord['kubo_pid']) + assert before['exe'] == str(data / 'bin/kubo') + initial_stops = len(re.findall(r'Kubo idle for [0-9]+s \(threshold 600s\), stopping', processes.text(log_label, 'stderr'))) + aged = {**coord, 'last_used': int(time.time()) - 601} + # The fixture changes only its clock input. The production watcher + # owns SIGTERM, coordination cleanup and the next cycle. + temporary = coord_path.with_suffix('.fixture-clock') + temporary.write_text(json.dumps(aged)) + temporary.chmod(0o600) + temporary.replace(coord_path) + started, deadline = time.monotonic(), time.monotonic() + 75 + while time.monotonic() < deadline: + assert owner.poll() is None and child_identity(identity['pid']) == identity + if not coord_path.exists(): + break + current = json.loads(coord_path.read_bytes()) + assert current['kubo_pid'] == coord['kubo_pid'] and current['last_used'] == aged['last_used'] + time.sleep(.2) + else: + raise AssertionError('production idle watcher did not stop Kubo within 75s') + stop_count = len(re.findall(r'Kubo idle for [0-9]+s \(threshold 600s\), stopping', processes.text(log_label, 'stderr'))) + assert stop_count == initial_stops + 1 + # Start the next read as soon as the watcher removes coordinates. + # Provider recovery owns waiting for shutdown and reaping the child. + result['idle_stops'].append({'label': label, 'elapsed_seconds': time.monotonic() - started, + 'original_last_used': coord['last_used'], 'fixture_last_used': aged['last_used'], + 'coord_removed': True, 'recovery_waited_for_old_process': False, + 'provider': identity, 'kubo': before, 'watcher_log_observed': True}) + return coord + def restarted(data, before, label): + after = json.loads((data / 'ipfs-coords.json').read_bytes()) + assert after['kubo_pid'] != before['kubo_pid'] + assert child_identity(after['kubo_pid'])['exe'] == str(data / 'bin/kubo') + result.setdefault('restarts', []).append({'label': label, 'before_pid': before['kubo_pid'], + 'after_pid': after['kubo_pid'], 'api_port': after['api_port']}) + # ensure_kubo reaps the stopped owned child before a successful read. + assert not (Path('/proc') / str(before['kubo_pid'])).exists(), 'stopped owned Kubo child was not reaped' + result['idle_stops'][-1]['old_process_reaped_after_recovery'] = True + try: + frozen = json.loads(Path('components.json').read_bytes()) + installed = {} + for role in ('holder', 'consumer', 'gateway', 'bounded'): + home = root / role + home.mkdir(mode=0o700) + data = home / '.local/share/elastos' + (data / 'bin').mkdir(mode=0o700, parents=True) + (home / '.local/bin').mkdir(mode=0o700, parents=True) + runtime = home / '.local/bin/elastos' + shutil.copyfile(accepted / 'elastos', runtime) + runtime.chmod(0o700) + manifest = {'external': {}, 'profiles': {}, 'capsules': {}} + # The consumer exercises Carrier immediately. An empty local + # Kubo backend would first search its absent DAG for 300s. + names = ('localhost-provider',) if role == 'consumer' else ('ipfs-provider', 'kubo') + if role == 'holder': + names += ('localhost-provider',) + for name in names: + source = accepted / name if name != 'kubo' else accepted / 'kubo-input/bin/kubo' + target = data / 'bin' / name + shutil.copyfile(source, target) + target.chmod(0o700) + assert sha(target) == sha(source) + entry = json.loads(json.dumps(frozen['external'][name])) + entry['platforms'] = {'linux-amd64': {**entry['platforms']['linux-amd64'], + 'checksum': 'sha256:' + sha(target), 'size': target.stat().st_size}} + manifest['external'][name] = entry + processes.roots[str(target)] = {sha(target)} + (data / 'components.json').write_text(json.dumps(manifest)) + (data / 'components.json').chmod(0o600) + processes.roots[str(runtime)] = {sha(runtime)} + http_port, carrier_port = port(), port(socket.SOCK_DGRAM) + (data / 'config.toml').write_text('carrier_bind_addr = "127.0.0.1:' + str(carrier_port) + '"\n' + 'gateway_public_publisher_bootstrap = true\ngateway_allowed_hosts = ["127.0.0.1"]\n') + (data / 'config.toml').chmod(0o600) + command(home, [str(runtime), 'node', 'info', '--json'], role + '-identity') + if role != 'consumer': + kubo_env = {**env(home), 'IPFS_PATH': str(data / 'ipfs-repo')} + reply = processes.command([str(data / 'bin/kubo'), 'init', '--profile=test'], kubo_env, home, role + '-kubo-init') + assert reply['exit'] == 0 + config_path = data / 'ipfs-repo/config' + config = json.loads(config_path.read_bytes()) + config['Bootstrap'] = [] + config['Addresses']['Swarm'] = [] + config['Routing']['Type'] = 'none' + config['Discovery']['MDNS']['Enabled'] = False + config['AutoConf']['Enabled'] = False + config_path.write_text(json.dumps(config)) + installed[role] = (home, data, runtime, http_port) + home, data, runtime, holder_port = installed['holder'] + warmup = root / 'warmup.bin' + warmup.write_bytes(b'issue89 real holder content fixture\n' * 4096) + cids = [] + generic = root / 'generic.bin' + generic.write_bytes(hashlib.sha256(b'issue89 generic file').digest() * 65536 + b'complete') + for label, content in [('warmup', warmup), ('release-binary', runtime), ('generic', generic)]: + kubo_env = {**env(home), 'IPFS_PATH': str(data / 'ipfs-repo')} + reply = processes.command([str(data / 'bin/kubo'), 'add', '--quiet', '--cid-version=1', '--pin=true', str(content)], + kubo_env, home, label + '-add') + assert reply['exit'] == 0 + cid = processes.text(label + '-add').strip() + assert re.fullmatch(r'b[a-z2-7]+', cid) + cids.append(cid) + holder = processes.spawn([str(runtime), 'serve', '--addr', '127.0.0.1:' + str(holder_port), + '--storage-path', str(data / 'storage')], env(home), home, 'holder') + ready(home, holder, holder_port, full_api=True) + holder_auth = attach(data, holder, holder_port) + # The full API exposes the existing peer provider contract. Obtain + # the real listening Carrier ticket before any idle-stop cycle. + ticket_response = post(holder_auth[0] + '/api/provider/peer/get_ticket', {}, 65536, holder_auth[1]) + assert ticket_response['status'] == 'ok' + ticket = ticket_response['data']['ticket'] + did = json.loads(processes.text('holder-identity'))['did'] + assert isinstance(ticket, str) and 0 < len(ticket) <= 65536 and re.fullmatch(r'[a-zA-Z2-7]+', ticket) + ticket_data = json.loads(base64.b32decode(ticket.upper() + '=' * (-len(ticket) % 8))) + assert len(ticket_data['endpoints']) == 1 + assert ticket_data['endpoints'][0]['id'] == ticket_response['data']['node_id'] + consumer_home, consumer_data, consumer_runtime, consumer_port = installed['consumer'] + command(consumer_home, [str(consumer_runtime), 'node', 'peer', 'add', '--did', did, + '--ticket', ticket, '--json'], 'consumer-local-holder-peer') + consumer = processes.spawn([str(consumer_runtime), 'serve', '--addr', '127.0.0.1:' + str(consumer_port), + '--storage-path', str(consumer_data / 'storage')], env(consumer_home), consumer_home, 'consumer') + ready(consumer_home, consumer, consumer_port, full_api=True) + assert not (consumer_data / 'bin/ipfs-provider').exists() + assert not (consumer_data / 'bin/kubo').exists() and not (consumer_data / 'ipfs-repo').exists() + consumer_auth = attach(consumer_data, consumer, consumer_port) + result['consumer'] = {'backend': 'Carrier-only content; no local IPFS provider or repository', + 'runtime_sha256': sha(consumer_runtime), 'carrier_ticket_identity_verified': True, + 'holder_peer_registered': True, 'host_command': 'serve'} + accepted_version = command(home, [str(runtime), '--version'], 'accepted-runtime-version') + assert accepted_version.startswith('elastos ') + assert content_read(holder_auth, cids[0], warmup, 'local-content-before-idle') + assert content_read(consumer_auth, cids[0], warmup, 'carrier-content-before-idle', carrier=True) + provider_before = provider_identity(holder, data / 'bin/ipfs-provider') + # Private Content fetch returns the entire accepted release binary. + # Carrier's typed provider route reaches the holder's IPFS backend; + # public gateway rendering has its own file size limit. This proof + # does not claim a separate legacy Carrier content_fetch journey. + fetched_runtime = consumer_home / '.local/bin/carrier-fetched-elastos' + before = idle_stop(data, holder, provider_before, 'carrier-release-binary', 'holder') + assert content_read(consumer_auth, cids[1], runtime, 'carrier-release-binary-after-idle', + carrier=True, destination=fetched_runtime) + restarted(data, before, 'carrier-release-binary') + processes.roots[str(fetched_runtime)] = {sha(fetched_runtime)} + fetched_version = command(consumer_home, [str(fetched_runtime), '--version'], 'carrier-fetched-runtime-version') + assert fetched_version == accepted_version + result['release_content'] = {'cid': cids[1], 'size': fetched_runtime.stat().st_size, + 'sha256': sha(fetched_runtime), 'version': fetched_version, + 'matches_accepted_runtime': True, 'carrier_route': 'typed Content availability/provider_invoke', + 'legacy_carrier_content_fetch_journey': False} + before = idle_stop(data, holder, provider_before, 'local-content-release-binary', 'holder') + assert content_read(holder_auth, cids[1], runtime, 'local-content-release-binary-after-idle') + restarted(data, before, 'local-content-release-binary') + before = idle_stop(data, holder, provider_before, 'carrier-content-generic-file', 'holder') + assert content_read(consumer_auth, cids[2], generic, 'carrier-content-generic-file-after-idle', carrier=True) + restarted(data, before, 'carrier-content-generic-file') + assert holder.poll() is None and consumer.poll() is None + assert provider_identity(holder, data / 'bin/ipfs-provider') == provider_before + result['same_provider_generation'] = True + result['same_holder_generation'] = child_identity(holder.pid) + # Full serve owns Content API access; gateway owns public + # /content rendering. Give that public journey its own Home/backend. + gateway_home, gateway_data, gateway_runtime, gateway_port = installed['gateway'] + for label, content, cid in [('warmup', warmup, cids[0]), ('generic', generic, cids[2])]: + kubo_env = {**env(gateway_home), 'IPFS_PATH': str(gateway_data / 'ipfs-repo')} + reply = processes.command([str(gateway_data / 'bin/kubo'), 'add', '--quiet', '--cid-version=1', + '--pin=true', str(content)], kubo_env, gateway_home, 'gateway-' + label + '-add') + assert reply['exit'] == 0 and processes.text('gateway-' + label + '-add').strip() == cid + gateway = processes.spawn([str(gateway_runtime), 'gateway', '--addr', '127.0.0.1:' + str(gateway_port), + '--cache-dir', str(gateway_home / 'gateway-cache')], env(gateway_home), gateway_home, 'gateway') + ready(gateway_home, gateway, gateway_port) + assert read(gateway_home, gateway_port, cids[0], warmup, 'gateway-before-idle') + gateway_provider = provider_identity(gateway, gateway_data / 'bin/ipfs-provider') + # The gateway role keeps Kubo up (idle stop disabled); the next step + # proves that over real idle time. Here the uncached read must reuse it. + assert 'Runtime host role Gateway; idle stop disabled' in processes.text('gateway', 'stderr') + gateway_kubo = json.loads((gateway_data / 'ipfs-coords.json').read_bytes())['kubo_pid'] + assert read(gateway_home, gateway_port, cids[2], generic, 'gateway-generic-file-uncached') + assert json.loads((gateway_data / 'ipfs-coords.json').read_bytes())['kubo_pid'] == gateway_kubo + assert gateway.poll() is None and provider_identity(gateway, gateway_data / 'bin/ipfs-provider') == gateway_provider + result['same_gateway_generation'] = child_identity(gateway.pid) + result['same_gateway_provider_generation'] = gateway_provider + # This separate fixture proves the native bounded backend contract. + # Carrier bounded routing remains covered by Runtime's existing + # tests; the full Content and public gateway reads above are unbounded. + bounded_home, bounded_data, _, _ = installed['bounded'] + kubo_env = {**env(bounded_home), 'IPFS_PATH': str(bounded_data / 'ipfs-repo')} + reply = processes.command([str(bounded_data / 'bin/kubo'), 'add', '--quiet', '--cid-version=1', + '--pin=true', str(generic)], kubo_env, bounded_home, 'bounded-content-add') + assert reply['exit'] == 0 + bounded_cid = processes.text('bounded-content-add').strip() + assert bounded_cid == cids[2] + diagnostic = (output / 'bounded.stderr').open('wb') + native = subprocess.Popen([str(bounded_data / 'bin/ipfs-provider')], env=env(bounded_home), + cwd=bounded_home, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=diagnostic, + start_new_session=True) + processes.processes.append(native) + processes.streams.extend([diagnostic, native.stdin, native.stdout]) + native_identity = child_identity(native.pid) + def native_request(request, timeout=70): + assert native.poll() is None and child_identity(native.pid) == native_identity + native.stdin.write(json.dumps(request).encode() + b'\n') + native.stdin.flush() + assert select.select([native.stdout], [], [], timeout)[0], 'native request deadline' + line = native.stdout.readline(128 * 1024) + assert line.endswith(b'\n') + return json.loads(line) + assert native_request({'op': 'init', 'config': {'base_path': str(bounded_data)}})['status'] == 'ok' + assert native_request({'op': 'runtime_prepare_backend'})['status'] == 'ok' + bounded_request = {'op': 'cat', 'bounded_read': True, 'cid': bounded_cid, + '_runtime_invocation': {'schema': 'elastos.provider.invocation/v1', 'source': 'content-provider', + 'target': 'ipfs', 'op': 'cat', 'transport': 'runtime-local-provider-plane', + 'transfer': 'bytes', 'range': {'start': 8, 'end': 65543}, + 'progress': {'request_id': 'issue89-bounded', 'expected_bytes': 65536}}} + def bounded_hit(label): + started = time.monotonic() + response = native_request(bounded_request, 6) + assert response['status'] == 'ok' + body = base64.b64decode(response['data']['data'], validate=True) + assert body == generic.read_bytes()[8:65544] + assert response['data']['_runtime_applied_range'] == { + 'schema': 'elastos.provider.applied-range/v1', 'cid': bounded_cid, + 'path': '', 'start': 8, 'end': 65543} + elapsed = time.monotonic() - started + assert elapsed <= 5.5 + result['reads'].append({'label': label, 'ingress': 'native-provider-stdio', + 'carrier_claim': False, 'size': len(body), 'sha256': hashlib.sha256(body).hexdigest(), + 'elapsed_seconds': elapsed, 'passed': True}) + bounded_hit('bounded-before-idle') + for cycle in (1, 2): + label = 'bounded-cycle-' + str(cycle) + before = idle_stop(bounded_data, native, native_identity, label, 'bounded') + started = time.monotonic() + miss = native_request(bounded_request, 6) + elapsed = time.monotonic() - started + assert miss == {'status': 'error', 'code': 'bounded_read_failed', 'message': 'Bounded content read failed'} + assert elapsed <= 5.5 and not (bounded_data / 'ipfs-coords.json').exists() + result['reads'].append({'label': label + '-cold-refusal', 'ingress': 'native-provider-stdio', + 'elapsed_seconds': elapsed, 'code': miss['code'], 'passed': True}) + # The first post-stop operation was the bounded read. The + # fixture now performs Runtime's private prepare and one retry. + assert native_request({'op': 'runtime_prepare_backend'})['status'] == 'ok' + bounded_hit(label + '-prepare-retry') + restarted(bounded_data, before, label) + result['bounded_backend_contract'] = 'real native process; cold refusal then Runtime-owned prepare/retry sequence' + result['installed_binaries'] = {name: {'sha256': sha(data / 'bin' / name), 'size': (data / 'bin' / name).stat().st_size} + for name in ('ipfs-provider', 'kubo')} + result['installed_runtime_sha256'] = sha(runtime) + result['installed_manifest_sha256'] = sha(data / 'components.json') + assert not subprocess.check_output(['git', 'status', '--porcelain=v1', '--untracked-files=all'], + text=True).strip(), 'source changed during qualification' + result['passed'] = True + except Exception as error: + result['failure'] = {'type': type(error).__name__, 'message': str(error)} + raise + finally: + result['cleanup'] = processes.cleanup() + # Identity, repository and Home state stay outside the public artifact. + if not result['cleanup']['errors'] and result['cleanup']['remaining_pids'] == []: + shutil.rmtree(root) + result['fixture_removed'] = True + else: + result['passed'] = False + (output / 'holder-idle.json').write_text(json.dumps(result, indent=2) + '\n') + assert not result['cleanup']['errors'] and result['cleanup']['remaining_pids'] == [], 'fixture cleanup incomplete' + PY + - name: prove gateway Kubo remains alive through real idle time and immediate Carrier read + timeout-minutes: 15 + run: | + set -euo pipefail + umask 077 + python3 -I -S scripts/holder-idle-ci.py + - name: upload qualification observations + if: always() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: holder-idle-observations-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/holder-output/*.json + ${{ runner.temp }}/holder-output/*.stdout + ${{ runner.temp }}/holder-output/*.stderr + if-no-files-found: warn + retention-days: 7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1a8dff1f4..9ac6b55bd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,20 +8,32 @@ on: required: false default: "" push: - branches: [main] + # develop pushes keep the shared build caches warm for every PR into develop. + branches: [main, develop] tags: ["v*"] pull_request: + merge_group: + types: [checks_requested] permissions: contents: read + actions: read concurrency: - group: ci-${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true + group: ci-${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: CARGO_TERM_COLOR: always RUSTFLAGS: "-D warnings" + # Reviewed ARM64 archive pin, shared by the producer and every CI consumer. + CI_LLAMA_AMD64_SHA256: 0dee60d855f864aa9e8a7200014baf9419e3a4c9ccb3f3609532aad0ed34f2c0 + CI_LLAMA_ARM64_SHA256: a92e404708feae91cbede43322e445971450de8a204f4ff51502a7f42f5df8b8 + # An explicit dispatch ref may select a tag independently of the workflow ref. + CI_USE_CACHE: ${{ github.ref_type != 'tag' && !(github.event_name == 'workflow_dispatch' && inputs.ref != '') }} + # Only develop pushes write shared caches (Rust, apt, Kubo, engine). PR, + # merge-queue and main runs only read them. + CI_SAVE_CACHE: ${{ github.event_name == 'push' && github.ref == 'refs/heads/develop' }} jobs: # Fast, compile-free gate: formatting and script-based source proofs. @@ -32,41 +44,236 @@ jobs: runs-on: ubuntu-24.04 timeout-minutes: 15 steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} - - uses: dtolnay/rust-toolchain@1.91.0 + - uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 with: components: rustfmt - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '26' - name: cargo fmt working-directory: elastos run: cargo fmt --all -- --check - - name: architecture entropy checks - run: | - bash scripts/check-wci-alignment.sh - node scripts/home-entropy-check.mjs - node scripts/browser-entropy-check.mjs + # scripts/test-source-gate.sh owns the list; the local pre-push gate runs it too. + - name: product data contracts + run: ./scripts/test-source-gate.sh product-data + - name: local pre-push gate behavior + run: ./scripts/test-source-gate.sh prepush - name: product UI source proofs - run: | - node --version - node scripts/home-shell-regression-smoke.mjs - node scripts/home-agent-shell-smoke.mjs - node --test scripts/home-agent-cancellation.test.mjs - node scripts/people-discovery-smoke.mjs + run: ./scripts/test-source-gate.sh product-ui - name: release artifact source proofs + run: ./scripts/test-source-gate.sh release + + test-behaviour: + name: test-behaviour + runs-on: ubuntu-24.04 + timeout-minutes: 25 + needs: source-gate + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '26' + - name: install explicit Browser test inputs + timeout-minutes: 15 + env: + DEBUG: pw:install + run: ./scripts/test-behaviour.sh inputs + - name: JavaScript behavior tests + run: | + python3 scripts/browser-vm-linux-network.test.py + ./scripts/test-behaviour.sh + - name: Browser startup status screenshots + if: always() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: browser-startup-status + path: ${{ runner.temp }}/browser-status-screenshots/ + if-no-files-found: ignore + + # Every tracked Cargo.lock against the current RustSec database. Reviewed + # exceptions live only in elastos/.cargo/audit.toml, which cargo-audit + # reads from its working directory. No cache: the binary is a checksummed + # release and the database must be fresh. + cargo-audit: + name: cargo-audit + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} + persist-credentials: false + - name: install checksummed cargo-audit + run: | + set -euo pipefail + archive=cargo-audit-x86_64-unknown-linux-musl-v0.22.2 + directory="$RUNNER_TEMP/cargo-audit" + mkdir -p "$directory" + curl -fsSL --connect-timeout 30 --max-time 120 --retry 3 \ + "https://github.com/rustsec/rustsec/releases/download/cargo-audit%2Fv0.22.2/$archive.tgz" \ + -o "$directory/$archive.tgz" + echo "7fb9497f8594b389e5fce5ef9b92db08432996895b2e0c5a0167a69ed445c428 $directory/$archive.tgz" | sha256sum -c - + tar -xzf "$directory/$archive.tgz" -C "$directory" "$archive/cargo-audit" + echo "$directory/$archive" >> "$GITHUB_PATH" + - name: audit every Cargo.lock + working-directory: elastos + run: | + set -euo pipefail + # A failed listing must fail the job, not audit a partial list. + listing=$(git -C .. ls-files '*Cargo.lock') + locks=() + while IFS= read -r lock; do [[ -n "$lock" ]] && locks+=("$lock"); done <<< "$listing" + (( ${#locks[@]} > 0 )) + db="$RUNNER_TEMP/advisory-db" + failed=0 + for lock in "${locks[@]}"; do + echo "::group::$lock" + cargo-audit audit --db "$db" --file "../$lock" || failed=1 + echo "::endgroup::" + done + exit "$failed" + + # One reviewed input per Linux architecture. PRs restore their develop base's cache; + # only a develop push can save a verified recipe result in this namespace. + engine-llama-amd64: + name: engine-llama-amd64 + runs-on: ubuntu-24.04 + timeout-minutes: 45 + needs: source-gate + container: + image: ubuntu@sha256:5ec03bb3441e8b0bf3b4f9cd4629a1ae763010dc3035bb8da3ae6cf026486401 + defaults: + run: + shell: bash + env: + DEBIAN_FRONTEND: noninteractive + BUILD_CONTAINER_IMAGE: ubuntu@sha256:5ec03bb3441e8b0bf3b4f9cd4629a1ae763010dc3035bb8da3ae6cf026486401 + ENGINE_BUILD_TOOLS: build-essential cmake git ca-certificates curl binutils file python3 + steps: + - name: install engine build tools + run: | + apt-get update -qq + read -r -a tools <<< "$ENGINE_BUILD_TOOLS" + apt-get install -y -qq --no-install-recommends "${tools[@]}" + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} + persist-credentials: false + - name: bind engine cache to build recipe + id: engine-recipe run: | - python3 scripts/components-release-integrity-check.py --self-test - python3 scripts/publish-platform-artifacts-test.py - python3 scripts/release-platform-input-test.py - python3 scripts/prepare-release-platform-test.py - python3 scripts/media-tools-build-test.py - python3 scripts/update-hop-compare-test.py - - name: Browser close handshake - run: node --test scripts/browser-window-close-handshake.test.mjs + recipe_hash=$( { + cat scripts/build/build-llama-server-bundle.sh + cat scripts/verify-linux-engine.py + printf '\n%s\n%s\n' "$BUILD_CONTAINER_IMAGE" "$ENGINE_BUILD_TOOLS" + } | sha256sum | cut -d ' ' -f 1) + echo "cache-key=develop-llama-amd64-${recipe_hash}" >> "$GITHUB_OUTPUT" + - name: restore pinned AMD64 engine + id: engine-cache + if: env.CI_USE_CACHE == 'true' + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/llama-amd64-bundle + key: ${{ steps.engine-recipe.outputs.cache-key }} + - name: build and validate pinned AMD64 engine + id: engine-build + if: steps.engine-cache.outputs.cache-hit != 'true' + run: | + RECIPE_COMMIT="$(git -c safe.directory="$GITHUB_WORKSPACE" rev-parse HEAD)" + export RECIPE_COMMIT + bash scripts/build/build-llama-server-bundle.sh --platform linux-amd64 "$RUNNER_TEMP/llama-amd64-bundle" + - name: verify accepted AMD64 engine archive + run: bash scripts/build/build-llama-server-bundle.sh --platform linux-amd64 --verify-archive "$RUNNER_TEMP/llama-amd64-bundle" + - name: save pinned AMD64 engine + if: env.CI_USE_CACHE == 'true' && github.event_name == 'push' && github.ref == 'refs/heads/develop' && steps.engine-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/llama-amd64-bundle + key: ${{ steps.engine-cache.outputs.cache-primary-key }} + - name: upload pinned AMD64 engine input + # Retain build receipts on a pin mismatch for review; dependent jobs + # require this job to succeed before they can consume the archive. + if: "!cancelled() && (steps.engine-cache.outputs.cache-hit == 'true' || steps.engine-build.outcome == 'success')" + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: llama-amd64-bundle + path: ${{ runner.temp }}/llama-amd64-bundle/ + if-no-files-found: error + retention-days: 1 + compression-level: 0 + + engine-llama-arm64: + name: engine-llama-arm64 + runs-on: ubuntu-24.04-arm + timeout-minutes: 45 + needs: source-gate + container: + image: ubuntu@sha256:1cc7bb38a74c0e126716646e47c0b3c5c139547d386d5ff7a64cf3ea316ca523 + defaults: + run: + shell: bash + env: + DEBIAN_FRONTEND: noninteractive + BUILD_CONTAINER_IMAGE: ubuntu@sha256:1cc7bb38a74c0e126716646e47c0b3c5c139547d386d5ff7a64cf3ea316ca523 + ENGINE_BUILD_TOOLS: build-essential cmake git ca-certificates curl binutils file python3 + steps: + - name: install engine build tools + run: | + apt-get update -qq + read -r -a tools <<< "$ENGINE_BUILD_TOOLS" + apt-get install -y -qq --no-install-recommends "${tools[@]}" + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} + persist-credentials: false + - name: bind engine cache to build recipe + id: engine-recipe + run: | + recipe_hash=$( { + cat scripts/build/build-llama-server-bundle.sh + cat scripts/verify-linux-engine.py + printf '\n%s\n%s\n' "$BUILD_CONTAINER_IMAGE" "$ENGINE_BUILD_TOOLS" + } | sha256sum | cut -d ' ' -f 1) + echo "cache-key=develop-llama-arm64-${recipe_hash}" >> "$GITHUB_OUTPUT" + - name: restore pinned ARM64 engine + id: engine-cache + if: env.CI_USE_CACHE == 'true' + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/llama-arm64-bundle + key: ${{ steps.engine-recipe.outputs.cache-key }} + - name: build and validate pinned ARM64 engine + id: engine-build + if: steps.engine-cache.outputs.cache-hit != 'true' + run: | + RECIPE_COMMIT="$(git -c safe.directory="$GITHUB_WORKSPACE" rev-parse HEAD)" + export RECIPE_COMMIT + bash scripts/build/build-llama-server-bundle.sh "$RUNNER_TEMP/llama-arm64-bundle" + - name: verify accepted ARM64 engine archive + run: bash scripts/build/build-llama-server-bundle.sh --verify-archive "$RUNNER_TEMP/llama-arm64-bundle" + - name: save pinned ARM64 engine + if: env.CI_USE_CACHE == 'true' && github.event_name == 'push' && github.ref == 'refs/heads/develop' && steps.engine-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/llama-arm64-bundle + key: ${{ steps.engine-cache.outputs.cache-primary-key }} + - name: upload pinned ARM64 engine input + # Retain build receipts on a pin mismatch for review; dependent jobs + # require this job to succeed before they can consume the archive. + if: "!cancelled() && (steps.engine-cache.outputs.cache-hit == 'true' || steps.engine-build.outcome == 'success')" + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: llama-arm64-bundle + path: ${{ runner.temp }}/llama-arm64-bundle/ + if-no-files-found: error + retention-days: 1 + compression-level: 0 lint: name: lint @@ -74,53 +281,78 @@ jobs: timeout-minutes: 45 needs: source-gate steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} - - uses: dtolnay/rust-toolchain@1.91.0 + - uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 with: components: clippy - - uses: Swatinem/rust-cache@v2 + - name: configure Rust compile cache + if: env.CI_USE_CACHE == 'true' + uses: ./.github/actions/rust-compile-cache + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + if: env.CI_USE_CACHE == 'true' with: workspaces: elastos - prefix-key: ${{ runner.os }}-elastos-bd - # Shared intermediate build dir (root .cargo/config.toml build-dir) - cache-directories: target-build + prefix-key: ${{ runner.os }}-elastos-bd-${{ hashFiles('**/Cargo.lock', 'rust-toolchain.toml') }} + cache-targets: false + cache-bin: false + cache-directories: ${{ env.SCCACHE_DIR }} + save-if: ${{ env.CI_SAVE_CACHE == 'true' }} # clippy runs the full type-check pass, so a separate `cargo check` # would be redundant. - name: cargo clippy working-directory: elastos run: cargo clippy --workspace --all-targets -- -D warnings + - name: Rust compile cache statistics + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: sccache --show-stats + - name: Rust compile cache holds no Actions credential + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + test -z "${ACTIONS_RUNTIME_TOKEN:-}" + # The daemon that the cache action started compiled every step above. + seen=0 + for pid in $(pgrep -x sccache || true); do + if [ "$RUNNER_OS" = Linux ]; then + environ=$(tr '\0' '\n' 2>/dev/null < "/proc/$pid/environ" || true) + else + environ=$(ps -wwE -o command= -p "$pid" || true) + fi + if grep -qF ACTIONS_RUNTIME_TOKEN= <<< "$environ"; then + echo "::error::sccache daemon $pid holds ACTIONS_RUNTIME_TOKEN" + exit 1 + fi + if grep -qF SCCACHE_DIR= <<< "$environ"; then seen=$((seen + 1)); fi + done + # Both runners show a same-user daemon's environment; reading none proves nothing. + if [ "$seen" = 0 ]; then + echo "::error::no readable sccache daemon environment" + exit 1 + fi test-elastos: name: test-elastos runs-on: ubuntu-24.04 - timeout-minutes: 45 + timeout-minutes: 60 needs: source-gate steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} - - uses: dtolnay/rust-toolchain@1.91.0 - - uses: Swatinem/rust-cache@v2 + - uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 + - name: configure Rust compile cache + if: env.CI_USE_CACHE == 'true' + uses: ./.github/actions/rust-compile-cache + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + if: env.CI_USE_CACHE == 'true' with: workspaces: elastos - prefix-key: ${{ runner.os }}-elastos-test-bd - # Shared intermediate build dir (root .cargo/config.toml build-dir) - cache-directories: target-build - # The three provider workspaces are release-built from cold on every - # run otherwise; with the cache restored, cargo only re-fingerprints - # the workspace members and reuses every dependency artifact. - - name: cache provider build artifacts - uses: actions/cache@v4 - with: - path: | - capsules/protected-content-protect-provider/target - capsules/protected-content-decrypt-provider/target - capsules/custody-provider/target - key: providers-bd-target-${{ runner.os }}-${{ hashFiles('capsules/protected-content-protect-provider/Cargo.lock', 'capsules/protected-content-decrypt-provider/Cargo.lock', 'capsules/custody-provider/Cargo.lock', 'rust-toolchain.toml') }} - restore-keys: | - providers-bd-target-${{ runner.os }}- + prefix-key: ${{ runner.os }}-elastos-test-bd-${{ hashFiles('**/Cargo.lock', 'rust-toolchain.toml') }} + cache-targets: false + cache-bin: false + cache-directories: ${{ env.SCCACHE_DIR }} + save-if: ${{ env.CI_SAVE_CACHE == 'true' }} - name: build provider process binaries for tests run: | cargo build --release --manifest-path capsules/protected-content-protect-provider/Cargo.toml --target-dir capsules/protected-content-protect-provider/target @@ -135,6 +367,55 @@ jobs: run: cargo test --workspace --no-fail-fast # Network-sensitive tests are #[ignore] and won't run. # Run them explicitly with: cargo test --workspace -- --ignored + - name: list workspace tests + working-directory: elastos + run: | + set -euo pipefail + cargo test --workspace -- --list | tee "${RUNNER_TEMP}/elastos-test-list.txt" + total=$(awk '/: test$/ {n++} END {print n+0}' "${RUNNER_TEMP}/elastos-test-list.txt") + echo "Workspace listed tests: ${total}" | tee -a "${GITHUB_STEP_SUMMARY}" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '26' + - name: install content boundary browser fixture + timeout-minutes: 20 + env: + DEBUG: pw:install + run: | + # 1.60 fixes ZIP extraction hanging on Node 26 (Playwright #40747). + npm install --prefix "${RUNNER_TEMP}/content-sandbox-browser" --no-save --package-lock=false playwright@1.60.0 + "${RUNNER_TEMP}/content-sandbox-browser/node_modules/.bin/playwright" install chromium --with-deps --only-shell + - name: gateway content sandbox browser regression + working-directory: elastos + env: + ELASTOS_PLAYWRIGHT_MODULE: ${{ runner.temp }}/content-sandbox-browser/node_modules/playwright/index.mjs + run: cargo test -p elastos-server content_sandbox_browser -- --ignored --nocapture + - name: Rust compile cache statistics + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: sccache --show-stats + - name: Rust compile cache holds no Actions credential + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + test -z "${ACTIONS_RUNTIME_TOKEN:-}" + # The daemon that the cache action started compiled every step above. + seen=0 + for pid in $(pgrep -x sccache || true); do + if [ "$RUNNER_OS" = Linux ]; then + environ=$(tr '\0' '\n' 2>/dev/null < "/proc/$pid/environ" || true) + else + environ=$(ps -wwE -o command= -p "$pid" || true) + fi + if grep -qF ACTIONS_RUNTIME_TOKEN= <<< "$environ"; then + echo "::error::sccache daemon $pid holds ACTIONS_RUNTIME_TOKEN" + exit 1 + fi + if grep -qF SCCACHE_DIR= <<< "$environ"; then seen=$((seen + 1)); fi + done + # Both runners show a same-user daemon's environment; reading none proves nothing. + if [ "$seen" = 0 ]; then + echo "::error::no readable sccache daemon environment" + exit 1 + fi test-capsules: name: test-capsules @@ -142,62 +423,113 @@ jobs: timeout-minutes: 45 needs: source-gate steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} - - uses: dtolnay/rust-toolchain@1.91.0 + - uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 with: targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + - name: configure Rust compile cache + if: env.CI_USE_CACHE == 'true' + uses: ./.github/actions/rust-compile-cache + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + if: env.CI_USE_CACHE == 'true' with: - # Registry/index cache only: this job never builds the elastos - # workspace, and the capsule build artifacts live in the shared - # intermediate build dir cached below. + # Registry/index and sccache objects; sccache owns compilation reuse. workspaces: elastos - prefix-key: ${{ runner.os }}-capsules-bd + prefix-key: ${{ runner.os }}-capsules-bd-${{ hashFiles('**/Cargo.lock', 'rust-toolchain.toml') }} cache-targets: false - # The capsule workspaces overlap almost entirely in dependencies, so - # `just test-capsules` builds them into one shared target dir; caching - # it turns every warm run's dependency builds into fingerprint checks. - # The key rotates with any capsule lockfile or toolchain change, which - # bounds stale-artifact growth under the restore-keys fallback. - - name: cache capsule build artifacts - uses: actions/cache@v4 - with: - # The shared intermediates (root .cargo/config.toml build-dir); - # final artifacts stay in each capsule's own small target dir. - path: target-build - key: capsules-bd-target-${{ runner.os }}-${{ hashFiles('capsules/*/Cargo.lock', 'rust-toolchain.toml') }} - restore-keys: | - capsules-bd-target-${{ runner.os }}- + cache-bin: false + cache-directories: ${{ env.SCCACHE_DIR }} + save-if: ${{ env.CI_SAVE_CACHE == 'true' }} # The elastos workspace suite never builds or tests own-workspace # capsules; this mirrors `just test-capsules`. - - name: test own-workspace capsules + - name: lint and test own-workspace capsules run: | set -uo pipefail failed=0 for lock in capsules/*/Cargo.lock; do capsule="$(dirname "$lock")" + echo "== linting $capsule ==" + (cd "$capsule" && cargo clippy --all-targets -- -D warnings) || failed=1 echo "== testing $capsule ==" (cd "$capsule" && cargo test --no-fail-fast) || failed=1 done exit "$failed" + # Playwright 1.59.1's installer hangs extracting Chromium under Node 26; + # the smokes themselves run on Node 26 below. + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '24' + - name: install browser layout smoke tools + timeout-minutes: 20 + run: | + sudo apt-get update + sudo apt-get install -y just + npm ci --prefix elastos/tools/browser-playwright-engine + npx --prefix elastos/tools/browser-playwright-engine playwright install --with-deps chromium + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '26' + # The smokes default to a macOS Brave install unless BRAVE_BIN is set. + - name: browser layout smokes + run: | + BRAVE_BIN="$(cd elastos/tools/browser-playwright-engine && node -p "require('playwright').chromium.executablePath()")" + export BRAVE_BIN + just product-ui-browser + + - name: list own-workspace capsule tests + run: | + set -euo pipefail + : > "${RUNNER_TEMP}/capsules-test-list.txt" + for lock in capsules/*/Cargo.lock; do + capsule="$(dirname "$lock")" + echo "== listing $capsule ==" + (cd "$capsule" && cargo test -- --list) | tee -a "${RUNNER_TEMP}/capsules-test-list.txt" + done + total=$(awk '/: test$/ {n++} END {print n+0}' "${RUNNER_TEMP}/capsules-test-list.txt") + echo "Capsules listed tests: ${total}" | tee -a "${GITHUB_STEP_SUMMARY}" + - name: Rust compile cache statistics + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: sccache --show-stats + - name: Rust compile cache holds no Actions credential + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + test -z "${ACTIONS_RUNTIME_TOKEN:-}" + # The daemon that the cache action started compiled every step above. + seen=0 + for pid in $(pgrep -x sccache || true); do + if [ "$RUNNER_OS" = Linux ]; then + environ=$(tr '\0' '\n' 2>/dev/null < "/proc/$pid/environ" || true) + else + environ=$(ps -wwE -o command= -p "$pid" || true) + fi + if grep -qF ACTIONS_RUNTIME_TOKEN= <<< "$environ"; then + echo "::error::sccache daemon $pid holds ACTIONS_RUNTIME_TOKEN" + exit 1 + fi + if grep -qF SCCACHE_DIR= <<< "$environ"; then seen=$((seen + 1)); fi + done + # Both runners show a same-user daemon's environment; reading none proves nothing. + if [ "$seen" = 0 ]; then + echo "::error::no readable sccache daemon environment" + exit 1 + fi # Rehearses the ELACITY-2298 dKMS ceremony (offline custody composition + # Carrier dial-proof preflight) against a fresh instance of the # deploy/custody-host 3-node compose harness -- scripts/custody-harness-ci-smoke.sh # owns all the logic (throwaway client identity, throwaway compose # project, receipt assertions, full teardown); this job is thin glue over - # it. Gated to workflow_dispatch and PRs that actually touch the harness - # image, the proof driver, or the protected-content/carrier crates it - # exercises -- NOT every push, since the image build + 3-node bring-up - # add real wall time. + # it. Trusted develop/main pushes warm the shared image cache. Runs also for + # every merge group, workflow_dispatch, and PRs that change an input the + # smoke builds or calls. custody-harness-smoke: name: custody-harness-smoke runs-on: ubuntu-24.04 timeout-minutes: 60 needs: source-gate - if: github.event_name == 'workflow_dispatch' || github.event_name == 'pull_request' + if: github.event_name == 'workflow_dispatch' || github.event_name == 'pull_request' || github.event_name == 'merge_group' || (github.event_name == 'push' && (github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main')) # The top-level `permissions: contents: read` above zeroes every other # scope for every job; dorny/paths-filter resolves a pull_request's # changed files via the GitHub API (this job's checkout is fetch-depth 1, @@ -208,24 +540,42 @@ jobs: contents: read pull-requests: read steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} - name: detect custody/carrier-relevant changes id: filter if: github.event_name == 'pull_request' - uses: dorny/paths-filter@v3 + uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3 with: + # scripts/ci-release-policy-test.py requires every repository input + # the smoke's scripts call to match this filter. filters: | custody: + - '.github/workflows/ci.yml' + - 'rust-toolchain.toml' + - '.cargo/config.toml' + - 'elastos/.cargo/config.toml' + - 'components.json' - 'deploy/custody-host/**' - 'scripts/protected-content-installed-e2e-proof.sh' - 'scripts/protected-content-installed-static-audit.py' - 'scripts/custody-harness-ci-smoke.sh' + - 'scripts/setup-source-home.sh' + - 'scripts/mac-source-home-restart.sh' - 'capsules/custody-provider/**' - 'capsules/availability-provider/**' - 'capsules/ipfs-provider/**' + - 'capsules/chain-provider/**' + - 'elastos/Cargo.toml' + - 'elastos/Cargo.lock' + - 'elastos/crates/elastos-runtime/**' - 'elastos/crates/elastos-protected-content-*/**' + # Path dependencies of the capsules above. + - 'elastos/crates/elastos-auth/**' + - 'elastos/crates/elastos-common/**' + - 'elastos/crates/elastos-guest/**' + - 'elastos/crates/elastos-identity/**' # Targeted, not the whole elastos-server crate (which would # fire this 60-minute job on most PRs): exactly the modules # this smoke actually exercises -- Carrier transport/dial, @@ -240,37 +590,36 @@ jobs: - 'elastos/crates/elastos-server/src/protected_content_config.rs' - id: should-run run: | - if [ "${{ github.event_name }}" = "workflow_dispatch" ] || [ "${{ steps.filter.outputs.custody }}" = "true" ]; then + if [ "${{ github.event_name }}" = "workflow_dispatch" ] || [ "${{ github.event_name }}" = "merge_group" ] || [ "${{ github.event_name }}" = "push" ] || [ "${{ steps.filter.outputs.custody }}" = "true" ]; then echo "run=true" >> "$GITHUB_OUTPUT" else echo "run=false" >> "$GITHUB_OUTPUT" echo "no custody/carrier-relevant paths changed on this PR; skipping the smoke run" >> "$GITHUB_STEP_SUMMARY" fi - if: steps.should-run.outputs.run == 'true' - uses: dtolnay/rust-toolchain@1.91.0 + uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 # Builds the host `elastos` binary the smoke script itself invokes # (identity show, node peer add, node status) -- same cache shape as # the test-elastos/lint jobs above. - - if: steps.should-run.outputs.run == 'true' - uses: Swatinem/rust-cache@v2 + - if: steps.should-run.outputs.run == 'true' && env.CI_USE_CACHE == 'true' + uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 with: workspaces: elastos - prefix-key: ${{ runner.os }}-custody-smoke-bd + prefix-key: ${{ runner.os }}-custody-smoke-bd-${{ hashFiles('**/Cargo.lock', 'rust-toolchain.toml') }} cache-directories: target-build + save-if: ${{ env.CI_SAVE_CACHE == 'true' }} - if: steps.should-run.outputs.run == 'true' - uses: docker/setup-buildx-action@v3 - # Pre-warms the custody-host image's BuildKit layer cache via the GHA - # cache backend, tagged/loaded exactly as deploy/custody-host/up.sh's - # own `docker compose up -d --build` expects it -- that later build - # then hits this same local layer cache instead of rebuilding cold. - - name: pre-build custody-host image (GHA layer cache) + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + # Builds the custody-host image, tagged/loaded exactly as + # deploy/custody-host/up.sh's own `docker compose up -d --build` expects + # it, so that later build hits this local layer cache. Restored layers + # would skip the Dockerfile's pinned-hash checks, so none are restored. + - name: pre-build custody-host image if: steps.should-run.outputs.run == 'true' run: | docker buildx build \ -f deploy/custody-host/Dockerfile \ -t elastos-custody-host:latest \ - --cache-from type=gha \ - --cache-to type=gha,mode=max \ --load \ . - name: custody harness smoke @@ -278,62 +627,251 @@ jobs: run: scripts/custody-harness-ci-smoke.sh - name: upload evidence receipt on failure if: failure() && steps.should-run.outputs.run == 'true' - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 with: name: custody-harness-smoke-evidence path: /tmp/custody-harness-ci-smoke-evidence/ retention-days: 7 if-no-files-found: ignore + # The release's Browser helper source builds (scripts/release-upstream-assets.py) + # otherwise run only in release-package.yml. Pull requests that change one of + # their inputs run them here; merge groups and workflow_dispatch always do. + release-upstream-paths: + name: release-upstream-paths + runs-on: ubuntu-24.04 + timeout-minutes: 5 + # dorny/paths-filter reads a pull request's changed files from the API. + permissions: + contents: read + pull-requests: read + outputs: + run: ${{ github.event_name == 'workflow_dispatch' || github.event_name == 'merge_group' || steps.filter.outputs.upstream == 'true' }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} + persist-credentials: false + - name: detect release upstream input changes + id: filter + if: github.event_name == 'pull_request' + uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3 + with: + # scripts/ci-release-policy-test.py requires every repository input + # the build calls, loads or packages to match this filter. + filters: | + upstream: + - '.github/workflows/ci.yml' + - 'scripts/release-host-prerequisites.sh' + - 'scripts/release-upstream-assets.py' + - 'scripts/release-upstream-input.py' + - 'scripts/release-upstream-recipes.json' + - 'scripts/browser-upstream-build.py' + - 'scripts/build/licenses/libcap-LICENSE.txt' + + # The release command for each platform with Browser helper source builds, + # with release-package.yml's toolchain, targets and host packages. Linux ARM64 + # packages the pinned engine this run's engine-llama-arm64 job provides. + release-upstream-assets: + name: release-upstream-assets (${{ matrix.platform }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + needs: [release-upstream-paths, engine-llama-arm64] + if: needs.release-upstream-paths.outputs.run == 'true' + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-24.04-arm + platform: linux-arm64 + host: linux + target: aarch64-unknown-linux-musl + - os: macos-15 + platform: darwin-arm64 + host: darwin + target: aarch64-apple-darwin + env: + UPSTREAM_PLATFORM: ${{ matrix.platform }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} + persist-credentials: false + - uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 + with: + targets: wasm32-unknown-unknown,${{ matrix.target }} + - name: install release host prerequisites + timeout-minutes: 20 + run: bash scripts/release-host-prerequisites.sh "${{ matrix.host }}" + - name: download pinned ARM64 engine input + if: matrix.platform == 'linux-arm64' + uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5 + with: + name: llama-arm64-bundle + path: ${{ runner.temp }}/llama-arm64-bundle + - name: build the release upstream assets + timeout-minutes: 75 + run: | + set -euo pipefail + # The release build step's umask, isolated HOME, Cargo and rustup. + umask 077 + export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" + install -d -m 700 "$RUNNER_TEMP/upstream-home" + # Darwin: Cargo and its C dependencies target macOS 11.0, not the runner SDK. + [[ "${{ matrix.host }}" != darwin ]] || export MACOSX_DEPLOYMENT_TARGET=11.0 + bundle=() + [[ "$UPSTREAM_PLATFORM" != linux-arm64 ]] \ + || bundle=(--llama-arm64-bundle "$RUNNER_TEMP/llama-arm64-bundle/llama-b10516-bin-ubuntu22.04-arm64-cpu.tar.gz") + HOME="$RUNNER_TEMP/upstream-home" python3 scripts/release-upstream-assets.py --platform "$UPSTREAM_PLATFORM" \ + --cache "$RUNNER_TEMP/upstream-cache" --output "$RUNNER_TEMP/upstream-assets" ${bundle[@]+"${bundle[@]}"} \ + > "$RUNNER_TEMP/upstream-assets.json" + # prepare-release-platform.sh merges this stdout with jq; it must be one JSON document. + jq -e '.external | length > 0' "$RUNNER_TEMP/upstream-assets.json" > /dev/null + # The source-home jobs run after the cheap source gate, in parallel - # with tests across the three architectures. They are the de-facto release builders: - # setup-source-home compiles the runtime, shell, home-cli and every provider - # in --release into the repo target dirs, so each job finishes by topping - # that up to a full workspace release build (incremental at that point) and - # packaging the binaries for its architecture — no separate cold - # build-release job is needed. + # with tests across the three architectures. setup-source-home compiles the + # runtime, shell, home-cli and every provider in --release; ARM also + # packages every candidate for the Jetson compatibility gate. Signed + # releases come from release-package.yml and reach users over Carrier. source-home-linux: name: source-home-linux (${{ matrix.os }}) runs-on: ${{ matrix.os }} - timeout-minutes: 90 - needs: source-gate + timeout-minutes: 120 + needs: [source-gate, engine-llama-amd64] + env: + CI_APT_PACKAGES: coturn e2fsprogs ffmpeg musl-tools nasm pkg-config strategy: fail-fast: false matrix: - os: [ubuntu-24.04, ubuntu-24.04-arm] - steps: - - uses: actions/checkout@v5 + os: [ubuntu-24.04] + steps: &source_home_linux_steps + - name: set job build directories + run: | + echo "CARGO_TARGET_DIR=$RUNNER_TEMP/source-home-linux-target" >> "$GITHUB_ENV" + echo "CARGO_BUILD_BUILD_DIR=$RUNNER_TEMP/source-home-linux-build" >> "$GITHUB_ENV" + # Published tarballs keep the shipped Cargo release profile. + - name: use CI journey release profile + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/develop') + run: | + echo "CARGO_PROFILE_RELEASE_LTO=false" >> "$GITHUB_ENV" + echo "CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16" >> "$GITHUB_ENV" + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '26' - - uses: dtolnay/rust-toolchain@1.91.0 + - uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 with: targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + - name: configure Rust compile cache + if: env.CI_USE_CACHE == 'true' + uses: ./.github/actions/rust-compile-cache + - name: verify compiler cache reuse and invalidation + if: env.RUSTC_WRAPPER == 'sccache' + run: python3 scripts/ci-rust-cache-smoke.py --output-json "$RUNNER_TEMP/source-home-cache-probe.json" + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + if: env.CI_USE_CACHE == 'true' with: workspaces: elastos - prefix-key: ${{ runner.os }}-${{ runner.arch }}-elastos-bd - # Shared intermediate build dir (root .cargo/config.toml build-dir) - cache-directories: target-build + prefix-key: ${{ matrix.os }}-${{ runner.arch }}-source-home-registry-${{ hashFiles('**/Cargo.lock', 'rust-toolchain.toml') }} + # Cache Cargo inputs; journey artifacts start fresh. + cache-targets: false + cache-directories: ${{ env.SCCACHE_DIR }} + save-if: ${{ env.CI_SAVE_CACHE == 'true' }} - name: require 16 GiB free disk run: | set -euo pipefail df -Pk . df -Pk . | awk 'NR == 2 { if ($4 < 16 * 1024 * 1024) exit 1 }' + - name: require fresh Linux build artifacts + run: | + set -euo pipefail + # Reuse this job's fresh source only, including across capsule workspaces. + for directory in "$CARGO_TARGET_DIR" "$CARGO_BUILD_BUILD_DIR"; do + test ! -e "$directory" + test ! -L "$directory" + mkdir -m 700 "$directory" + done + - name: prepare apt archive cache permissions + run: | + sudo install -d -o "$(id -u)" -g "$(id -g)" -m 755 /var/cache/apt/archives + sudo chown -R "$(id -u):$(id -g)" /var/cache/apt/archives + - name: restore Ubuntu prerequisite archives + if: env.CI_USE_CACHE == 'true' + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: /var/cache/apt/archives/*.deb + key: apt-${{ matrix.os }}-${{ runner.arch }}-${{ hashFiles('scripts/ci-apt-prerequisites.sh') }}-${{ env.CI_APT_PACKAGES }}-${{ github.run_id }} + restore-keys: apt-${{ matrix.os }}-${{ runner.arch }}-${{ hashFiles('scripts/ci-apt-prerequisites.sh') }}-${{ env.CI_APT_PACKAGES }}- - name: install host prerequisites + id: apt-prerequisites + timeout-minutes: 13 + run: bash scripts/ci-apt-prerequisites.sh + - name: save Ubuntu prerequisite archives + if: env.CI_USE_CACHE == 'true' && env.CI_SAVE_CACHE == 'true' && steps.apt-prerequisites.outputs.changed == 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: /var/cache/apt/archives/*.deb + key: apt-${{ matrix.os }}-${{ runner.arch }}-${{ hashFiles('scripts/ci-apt-prerequisites.sh') }}-${{ env.CI_APT_PACKAGES }}-${{ github.run_id }} + - name: bind Kubo cache to its pin + id: kubo-pin run: | - sudo apt-get update - sudo apt-get install -y coturn e2fsprogs ffmpeg musl-tools nasm pkg-config + platform=linux-amd64 + if [[ "${{ runner.arch }}" == ARM64 ]]; then platform=linux-arm64; fi + echo "KUBO_PLATFORM=$platform" >> "$GITHUB_ENV" + echo "KUBO_CACHE_DIR=$RUNNER_TEMP/kubo-cache" >> "$GITHUB_ENV" + python3 scripts/ci-kubo-cache.py key "$platform" "$RUNNER_TEMP/kubo-cache" + - name: restore verified Kubo inputs + id: kubo-cache + if: env.CI_USE_CACHE == 'true' + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ steps.kubo-pin.outputs.paths }} + key: ${{ steps.kubo-pin.outputs.key }} + - name: verify or download Kubo inputs + timeout-minutes: 10 + run: python3 scripts/ci-kubo-cache.py fetch "$KUBO_PLATFORM" "$KUBO_CACHE_DIR" + - name: save verified Kubo inputs + if: env.CI_USE_CACHE == 'true' && env.CI_SAVE_CACHE == 'true' && steps.kubo-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ steps.kubo-pin.outputs.paths }} + key: ${{ steps.kubo-pin.outputs.key }} + - name: download pinned AMD64 engine input + if: matrix.os == 'ubuntu-24.04' + uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5 + with: + name: llama-amd64-bundle + path: ${{ runner.temp }}/llama-amd64-bundle + - name: verify pinned AMD64 engine input + if: matrix.os == 'ubuntu-24.04' + run: bash scripts/build/build-llama-server-bundle.sh --platform linux-amd64 --verify-archive "$RUNNER_TEMP/llama-amd64-bundle" + - name: download pinned ARM64 engine input + if: matrix.os == 'ubuntu-22.04-arm' + uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5 + with: + name: llama-arm64-bundle + path: ${{ runner.temp }}/llama-arm64-bundle + - name: verify pinned ARM64 engine input + if: matrix.os == 'ubuntu-22.04-arm' + run: bash scripts/build/build-llama-server-bundle.sh --verify-archive "$RUNNER_TEMP/llama-arm64-bundle" - name: source-home into isolated HOME env: ELASTOS_COLLABORATION_STARTUP_MODE: isolated + SETUP_SOURCE_HOME_INSTALL_LLAMA_SERVER: '1' + SETUP_SOURCE_HOME_INSTALL_KUBO: '1' + ELASTOS_LLAMA_AMD64_BUNDLE: ${{ runner.temp }}/llama-amd64-bundle/llama-b10516-bin-ubuntu22.04-amd64-cpu.tar.gz + ELASTOS_LLAMA_ARM64_BUNDLE: ${{ runner.temp }}/llama-arm64-bundle/llama-b10516-bin-ubuntu22.04-arm64-cpu.tar.gz run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/source-home-logs" USER_HOME="${HOME}" SOURCE_HOME="${RUNNER_TEMP}/elastos-source-home" + export ELASTOS_NODE_BIN="$(command -v node)" + export ELASTOS_BROWSER_VM_TURNSERVER_BIN="$(command -v turnserver)" + [[ "${ELASTOS_NODE_BIN}" == /* && -x "${ELASTOS_NODE_BIN}" ]] || { echo 'CI requires its installed Node executable.' >&2; exit 1; } + [[ "${ELASTOS_BROWSER_VM_TURNSERVER_BIN}" == /* && -x "${ELASTOS_BROWSER_VM_TURNSERVER_BIN}" ]] || { echo 'CI requires its installed TURN executable.' >&2; exit 1; } mkdir -p "${SOURCE_HOME}" export CARGO_HOME="${CARGO_HOME:-${USER_HOME}/.cargo}" export RUSTUP_HOME="${RUSTUP_HOME:-${USER_HOME}/.rustup}" @@ -350,63 +888,220 @@ jobs: ELASTOS_DATA_DIR="${XDG_DATA_HOME}/elastos" \ scripts/installed-provider-verify.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/installed-provider-verify.log" - name: local-carrier setup smoke + env: + ELASTOS_LLAMA_AMD64_BUNDLE: ${{ runner.temp }}/llama-amd64-bundle/llama-b10516-bin-ubuntu22.04-amd64-cpu.tar.gz + ELASTOS_LLAMA_ARM64_BUNDLE: ${{ runner.temp }}/llama-arm64-bundle/llama-b10516-bin-ubuntu22.04-arm64-cpu.tar.gz run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/source-home-logs" scripts/local-carrier-setup-smoke.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/local-carrier-setup-smoke.log" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '24' + - name: prepare installed Home browser + timeout-minutes: 20 + run: | + npm ci --ignore-scripts --prefix elastos/tools/browser-playwright-engine + export PLAYWRIGHT_BROWSERS_PATH="$RUNNER_TEMP/installed-home-browser" + npx --prefix elastos/tools/browser-playwright-engine playwright install chromium --with-deps --only-shell + echo "PLAYWRIGHT_BROWSERS_PATH=$PLAYWRIGHT_BROWSERS_PATH" >> "$GITHUB_ENV" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '26' + - name: prepare signed SmolLM2 fixture + timeout-minutes: 20 + env: + CI_SOURCE_HOME: ${{ runner.temp }}/elastos-source-home + CI_MODEL_REPAIR_JOURNEY: ${{ matrix.os == 'ubuntu-24.04' }} + run: scripts/ci-installed-journeys.sh prepare + # Only the x86-64 job proves one reply Get from a separate holder Home over Carrier. + - name: installed Marketplace Get and Assistant reply + timeout-minutes: 30 + env: + CI_SOURCE_HOME: ${{ runner.temp }}/elastos-source-home + CI_CARRIER_GET: ${{ matrix.os == 'ubuntu-24.04' }} + CI_FINITE_MEMORY: ${{ matrix.os == 'ubuntu-24.04' }} + run: scripts/ci-installed-journeys.sh home + - name: installed model Stop, switch and interrupted Get recovery + if: matrix.os == 'ubuntu-24.04' + timeout-minutes: 30 + env: + CI_SOURCE_HOME: ${{ runner.temp }}/elastos-source-home + CI_MODEL_REPAIR_JOURNEY: 'true' + run: scripts/ci-installed-journeys.sh model-repair + - name: summarize installed model journey + if: always() + env: + CI_SOURCE_HOME: ${{ runner.temp }}/elastos-source-home + CI_CARRIER_GET: ${{ matrix.os == 'ubuntu-24.04' }} + CI_FINITE_MEMORY: ${{ matrix.os == 'ubuntu-24.04' }} + CI_MODEL_REPAIR_JOURNEY: ${{ matrix.os == 'ubuntu-24.04' }} + run: scripts/ci-installed-journeys.sh summary + - name: upload installed model journey + if: always() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: source-home-journeys-${{ matrix.os }} + path: | + ${{ runner.temp }}/source-home-journeys/**/*.json + ${{ runner.temp }}/source-home-journeys/**/*.png + retention-days: 7 + if-no-files-found: error + # ARM packages every candidate for the Jetson compatibility gate. - name: build and package release binaries + if: matrix.os == 'ubuntu-22.04-arm' run: | set -euo pipefail # Incremental on top of setup-source-home's release builds. - cargo build --manifest-path elastos/Cargo.toml --workspace --release + cargo build --locked --manifest-path elastos/Cargo.toml --workspace --release scripts/package-release-binaries.sh - - name: upload release binaries - if: github.ref_type == 'tag' || github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch' - uses: actions/upload-artifact@v5 - with: - name: elastos-runtime-${{ matrix.os }} - path: | - elastos-runtime-*.tar.gz - elastos-runtime-*.tar.gz.sha256 + - name: verify Jetson release compatibility + if: matrix.os == 'ubuntu-22.04-arm' + run: | + python3 scripts/verify-linux-arm64-package.py elastos-runtime-linux-arm64.tar.gz \ + --source-commit "$(git rev-parse HEAD)" \ + --source-tree "$(git rev-parse HEAD^{tree})" \ + --receipt elastos-runtime-linux-arm64.receipt.json + - name: Rust compile cache statistics + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + sccache --show-stats + sccache --show-stats --stats-format=json > "$RUNNER_TEMP/source-home-sccache.json" + { + echo '### Rust compiler cache' + echo '```text' + sccache --show-stats + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + - name: Rust compile cache holds no Actions credential + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + test -z "${ACTIONS_RUNTIME_TOKEN:-}" + # The daemon that the cache action started compiled every step above. + seen=0 + for pid in $(pgrep -x sccache || true); do + if [ "$RUNNER_OS" = Linux ]; then + environ=$(tr '\0' '\n' 2>/dev/null < "/proc/$pid/environ" || true) + else + environ=$(ps -wwE -o command= -p "$pid" || true) + fi + if grep -qF ACTIONS_RUNTIME_TOKEN= <<< "$environ"; then + echo "::error::sccache daemon $pid holds ACTIONS_RUNTIME_TOKEN" + exit 1 + fi + if grep -qF SCCACHE_DIR= <<< "$environ"; then seen=$((seen + 1)); fi + done + # Both runners show a same-user daemon's environment; reading none proves nothing. + if [ "$seen" = 0 ]; then + echo "::error::no readable sccache daemon environment" + exit 1 + fi - name: upload source-home logs if: failure() - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 with: name: source-home-linux-${{ matrix.os }}-logs path: ${{ runner.temp }}/source-home-logs/ retention-days: 7 if-no-files-found: ignore + source-home-linux-arm64: + name: source-home-linux (${{ matrix.check_name || matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + needs: [source-gate, engine-llama-arm64] + env: + CI_APT_PACKAGES: coturn e2fsprogs ffmpeg musl-tools nasm pkg-config + strategy: + fail-fast: false + matrix: + # Jetson's Ubuntu 22.04 host provides glibc 2.35. + os: [ubuntu-22.04-arm] + include: + # Keep the established check name; os controls the build and artifact. + - os: ubuntu-22.04-arm + check_name: ubuntu-24.04-arm + steps: *source_home_linux_steps + source-home-macos: name: source-home-macos - runs-on: macos-14 - timeout-minutes: 90 + runs-on: macos-15 + # The two hop builds may take 30 minutes and the update journey step 75. + timeout-minutes: 150 needs: source-gate + env: + # Cargo and its C dependencies target macOS 11.0, not the runner SDK. + MACOSX_DEPLOYMENT_TARGET: "11.0" steps: - - uses: actions/checkout@v5 + - name: set job build directories + run: | + echo "CARGO_TARGET_DIR=$RUNNER_TEMP/source-home-macos-target" >> "$GITHUB_ENV" + echo "CARGO_BUILD_BUILD_DIR=$RUNNER_TEMP/source-home-macos-build" >> "$GITHUB_ENV" + # Published tarballs keep the shipped Cargo release profile. + - name: use CI journey release profile + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/develop') + run: | + echo "CARGO_PROFILE_RELEASE_LTO=false" >> "$GITHUB_ENV" + echo "CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16" >> "$GITHUB_ENV" + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '26' - - uses: dtolnay/rust-toolchain@1.91.0 + - uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 with: targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@v2 + - name: configure Rust compile cache + if: env.CI_USE_CACHE == 'true' + uses: ./.github/actions/rust-compile-cache + - name: verify compiler cache reuse and invalidation + if: env.RUSTC_WRAPPER == 'sccache' + run: python3 scripts/ci-rust-cache-smoke.py --output-json "$RUNNER_TEMP/source-home-cache-probe.json" + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + if: env.CI_USE_CACHE == 'true' with: workspaces: elastos - prefix-key: ${{ runner.os }}-elastos-bd - # Shared intermediate build dir (root .cargo/config.toml build-dir) - cache-directories: target-build - # dist.ipfs.tech is intermittently slow or unreachable from GitHub's - # macOS runners, and setup's downloader makes a single 600s attempt. - # Cache the verified release tarball and pre-seed bin/kubo so setup - # skips the download entirely (ELACITY-2308). - - name: cache kubo release - uses: actions/cache@v4 - with: - path: ${{ runner.temp }}/kubo-cache - key: kubo-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('components.json') }} + prefix-key: ${{ runner.os }}-source-home-registry-${{ hashFiles('**/Cargo.lock', 'rust-toolchain.toml') }} + # Cache Cargo inputs; journey artifacts start fresh. + cache-targets: false + cache-directories: ${{ env.SCCACHE_DIR }} + save-if: ${{ env.CI_SAVE_CACHE == 'true' }} + - name: reserve hosted Mac build and fixture capacity + timeout-minutes: 10 + run: python3 scripts/update-hop-compare.py prepare-ci-disk + - name: require fresh Mac build intermediates + run: | + set -euo pipefail + # Keep outputs and Cargo 1.91 fingerprints outside restored caches. + # Reuse this job's fresh source across capsules and version builds. + for directory in "$CARGO_TARGET_DIR" "$CARGO_BUILD_BUILD_DIR"; do + test ! -e "$directory" + test ! -L "$directory" + mkdir -m 700 "$directory" + done + echo "CI_MAC_BUILD_DIR_FRESH=true" >> "$GITHUB_ENV" + - name: bind Kubo cache to its pin + id: kubo-pin + run: | + echo "KUBO_CACHE_DIR=$RUNNER_TEMP/kubo-cache" >> "$GITHUB_ENV" + python3 scripts/ci-kubo-cache.py key darwin-arm64 "$RUNNER_TEMP/kubo-cache" + - name: restore verified Kubo inputs + id: kubo-cache + if: env.CI_USE_CACHE == 'true' + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ steps.kubo-pin.outputs.paths }} + key: ${{ steps.kubo-pin.outputs.key }} + - name: verify or download Kubo inputs + timeout-minutes: 10 + run: python3 scripts/ci-kubo-cache.py fetch darwin-arm64 "$KUBO_CACHE_DIR" + - name: save verified Kubo inputs + if: env.CI_USE_CACHE == 'true' && env.CI_SAVE_CACHE == 'true' && steps.kubo-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ steps.kubo-pin.outputs.paths }} + key: ${{ steps.kubo-pin.outputs.key }} - name: seed kubo into the test HOME run: | set -euo pipefail @@ -420,15 +1115,22 @@ jobs: df -Pk . df -Pk . | awk 'NR == 2 { if ($4 < 16 * 1024 * 1024) exit 1 }' - name: install host prerequisites + timeout-minutes: 15 run: brew install e2fsprogs coturn ffmpeg - name: source-home into isolated MAC_TEST_HOME env: ELASTOS_COLLABORATION_STARTUP_MODE: isolated + SETUP_SOURCE_HOME_INSTALL_LLAMA_SERVER: '1' + SETUP_SOURCE_HOME_INSTALL_KUBO: '1' run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/source-home-logs" USER_HOME="${HOME}" MAC_TEST_HOME="${RUNNER_TEMP}/elastos-mac-test-home" + export ELASTOS_NODE_BIN="$(command -v node)" + export ELASTOS_BROWSER_VM_TURNSERVER_BIN="$(command -v turnserver)" + [[ "${ELASTOS_NODE_BIN}" == /* && -x "${ELASTOS_NODE_BIN}" ]] || { echo 'CI requires its installed Node executable.' >&2; exit 1; } + [[ "${ELASTOS_BROWSER_VM_TURNSERVER_BIN}" == /* && -x "${ELASTOS_BROWSER_VM_TURNSERVER_BIN}" ]] || { echo 'CI requires its installed TURN executable.' >&2; exit 1; } mkdir -p "${MAC_TEST_HOME}" export CARGO_HOME="${CARGO_HOME:-${USER_HOME}/.cargo}" export RUSTUP_HOME="${RUSTUP_HOME:-${USER_HOME}/.rustup}" @@ -440,58 +1142,458 @@ jobs: install -m 700 "$(command -v "${tool}")" "${MEDIA_TOOLS_DIR}/${tool}" done export SETUP_SOURCE_HOME_MEDIA_TOOLS_DIR="${MEDIA_TOOLS_DIR}" + # The update hop signs this build as the installed release, and a signed release + # version is X.Y.Z or X.Y.Z-{alpha|beta|rc}.N, never the default "-dev". + export ELASTOS_RELEASE_VERSION="$(cargo metadata --no-deps --format-version 1 --manifest-path elastos/Cargo.toml \ + | python3 -I -c 'import json, sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"] == "elastos-server"))')" + echo "ELASTOS_RELEASE_VERSION=$ELASTOS_RELEASE_VERSION" >> "$GITHUB_ENV" scripts/setup-source-home.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/setup-source-home.log" ELASTOS_DATA_DIR="${HOME}/Library/Application Support/elastos" \ scripts/installed-provider-verify.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/installed-provider-verify.log" - - name: build and package release binaries + # The installed Home journey signs up through the real page. Playwright + # 1.59.1's installer hangs extracting Chromium under Node 26; the journey runs on 26. + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '24' + - name: prepare installed Home browser + timeout-minutes: 5 + run: | + npm ci --ignore-scripts --prefix elastos/tools/browser-playwright-engine + export PLAYWRIGHT_BROWSERS_PATH="$RUNNER_TEMP/installed-home-browser" + npx --prefix elastos/tools/browser-playwright-engine playwright install chromium --only-shell + echo "PLAYWRIGHT_BROWSERS_PATH=$PLAYWRIGHT_BROWSERS_PATH" >> "$GITHUB_ENV" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '26' + - name: prepare signed SmolLM2 fixture + timeout-minutes: 20 + env: + CI_SOURCE_HOME: ${{ runner.temp }}/elastos-mac-test-home + run: scripts/ci-installed-journeys.sh prepare + - name: installed Marketplace Get and Assistant reply + timeout-minutes: 15 + env: + CI_SOURCE_HOME: ${{ runner.temp }}/elastos-mac-test-home + run: scripts/ci-installed-journeys.sh home-repeat + - name: summarize installed model journey + if: always() + env: + CI_SOURCE_HOME: ${{ runner.temp }}/elastos-mac-test-home + run: scripts/ci-installed-journeys.sh summary + - name: upload installed model journey + if: always() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: source-home-journeys-macos-15 + path: | + ${{ runner.temp }}/source-home-journeys/**/*.json + ${{ runner.temp }}/source-home-journeys/**/*.png + retention-days: 7 + if-no-files-found: error + # The hop starts from the published release the pin names. Its signed bytes are + # cached by the pin; only a miss reads them from the public seed. + - name: restore the pinned published release + id: previous-release-cache + if: env.CI_USE_CACHE == 'true' + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/previous-release-cache + key: previous-release-${{ hashFiles('scripts/update-hop-previous-release.json') }} + - name: fetch the pinned published release + timeout-minutes: 15 run: | set -euo pipefail - # Incremental on top of setup-source-home's release builds. - cargo build --manifest-path elastos/Cargo.toml --workspace --release - scripts/package-release-binaries.sh - - name: upload release binaries - if: github.ref_type == 'tag' || github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch' - uses: actions/upload-artifact@v5 + python3 scripts/update-hop-compare.py fetch-previous-release \ + "$RUNNER_TEMP/previous-release-cache" "$RUNNER_TEMP/previous-release" + - name: save the pinned published release + if: env.CI_USE_CACHE == 'true' && env.CI_SAVE_CACHE == 'true' && steps.previous-release-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 with: - name: elastos-runtime-macos-14 + path: ${{ runner.temp }}/previous-release-cache + key: previous-release-${{ hashFiles('scripts/update-hop-previous-release.json') }} + - name: build two actual Runtime versions + # This source compiled twice (new and next) over the restored intermediates. + timeout-minutes: 30 + run: | + set -euo pipefail + CI_HOP_ROOT="$HOME/.local/share/elastos-ci-update-hop" + test ! -e "$CI_HOP_ROOT" + mkdir -p "$CI_HOP_ROOT" + echo "CI_HOP_ROOT=$CI_HOP_ROOT" >> "$GITHUB_ENV" + python3 scripts/update-hop-compare.py build-ci-hop "$CI_HOP_ROOT/build-inputs" \ + --runtime "$CARGO_TARGET_DIR/release/elastos" --previous "$RUNNER_TEMP/previous-release" + python3 -I - "$CI_HOP_ROOT/build-inputs/build.json" <<'PY' + import json, os, pathlib, sys + path = pathlib.Path(sys.argv[1]) + build = json.loads(path.read_text()) + directory = pathlib.Path(os.environ['CARGO_BUILD_BUILD_DIR']) + assert directory == pathlib.Path(os.environ['RUNNER_TEMP']) / 'source-home-macos-build' + assert directory.is_dir() and not directory.is_symlink() + target = pathlib.Path(os.environ['CARGO_TARGET_DIR']) + assert target == pathlib.Path(os.environ['RUNNER_TEMP']) / 'source-home-macos-target' + assert target.is_dir() and not target.is_symlink() + assert os.environ['CI_MAC_BUILD_DIR_FRESH'] == 'true' + build['intermediates'] = {'directory': str(directory), 'initially_absent': True, + 'target_directory': str(target), + 'source': build['source']} + path.write_text(json.dumps(build, indent=2) + '\n') + PY + - name: generate disposable signed install and update fixture + timeout-minutes: 5 + run: | + set -euo pipefail + python3 scripts/update-hop-compare.py generate-ci-hop "$CI_HOP_ROOT/package" \ + --runtime "$CI_HOP_ROOT/build-inputs/elastos-old" \ + --next-runtime "$CI_HOP_ROOT/build-inputs/elastos-new" \ + --system-runtime "$CI_HOP_ROOT/build-inputs/elastos-system" \ + --build-receipt "$CI_HOP_ROOT/build-inputs/build.json" \ + --support-home "$RUNNER_TEMP/elastos-mac-test-home/Library/Application Support/elastos" \ + --previous "$RUNNER_TEMP/previous-release" \ + > "$CI_HOP_ROOT/generation.json" + - name: prove installed Home account and System update with Carrier hop and refusals + # Expected about 20 minutes. The Home journey's waits are capped at: sign-up 240 s, + # the published release's System update 480 s, 2 Home starts x 150 s, 2 reconnects + # x 420 s (next release, Undo), tampered refusal 330 s, Undo commands 2 x 300 s: + # 47 minutes in the worst case, plus the CLI installs and refusals. + timeout-minutes: 75 + env: + ELASTOS_CI_FIXTURE_SCOPE: ci-rehearsal + ELASTOS_CI_REQUIRE_REAL_RUNTIME: "1" + run: | + set -euo pipefail + export ELASTOS_CI_FIXTURE_MANIFEST_SHA256="$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))["manifest_sha256"])' "$CI_HOP_ROOT/generation.json")" + python3 scripts/update-hop-compare.py inspect "$CI_HOP_ROOT/package/fixture.json" + python3 scripts/update-hop-compare.py run "$CI_HOP_ROOT/package/fixture.json" "$CI_HOP_ROOT/package/results" + - name: require the update from the published release, no new provider warnings and Undo + run: python3 scripts/update-hop-compare.py check-result "$CI_HOP_ROOT/package/results/result.json" + - name: retain the safe CI hop receipt + if: always() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: macos-cli-update-hop-receipt path: | - elastos-runtime-*.tar.gz - elastos-runtime-*.tar.gz.sha256 + ${{ env.CI_HOP_ROOT }}/package/results/result.json + ${{ env.CI_HOP_ROOT }}/package/results/home-system/*.png + ${{ env.CI_HOP_ROOT }}/package/results/diagnostics/ + include-hidden-files: true + if-no-files-found: ignore + retention-days: 7 + - name: remove stopped CI hop fixture files + if: always() && env.CI_HOP_ROOT != '' + run: | + python3 -I - "$CI_HOP_ROOT" <<'PY' + import json, pathlib, shutil, sys + root = pathlib.Path(sys.argv[1]) + result = root / 'package/results/result.json' + if result.exists() and not json.loads(result.read_text()).get('cleanup', {}).get('passed'): + raise SystemExit('refusal cleanup was incomplete; disposable runner retains files until teardown') + if not result.exists() and (root / 'package/results').exists(): + raise SystemExit('refusal cleanup receipt is missing; disposable runner retains files until teardown') + build = root / 'build-inputs/build.json' + if (root / 'build-inputs').exists() and (not build.exists() or not json.loads(build.read_text()).get('cleanup', {}).get('passed')): + raise SystemExit('hop builder cleanup is incomplete; disposable runner retains files until teardown') + shutil.rmtree(root) + PY + - name: Rust compile cache statistics + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + sccache --show-stats + sccache --show-stats --stats-format=json > "$RUNNER_TEMP/source-home-sccache.json" + { + echo '### Rust compiler cache' + echo '```text' + sccache --show-stats + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + - name: Rust compile cache holds no Actions credential + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + test -z "${ACTIONS_RUNTIME_TOKEN:-}" + # The daemon that the cache action started compiled every step above. + seen=0 + for pid in $(pgrep -x sccache || true); do + if [ "$RUNNER_OS" = Linux ]; then + environ=$(tr '\0' '\n' 2>/dev/null < "/proc/$pid/environ" || true) + else + environ=$(ps -wwE -o command= -p "$pid" || true) + fi + if grep -qF ACTIONS_RUNTIME_TOKEN= <<< "$environ"; then + echo "::error::sccache daemon $pid holds ACTIONS_RUNTIME_TOKEN" + exit 1 + fi + if grep -qF SCCACHE_DIR= <<< "$environ"; then seen=$((seen + 1)); fi + done + # Both runners show a same-user daemon's environment; reading none proves nothing. + if [ "$seen" = 0 ]; then + echo "::error::no readable sccache daemon environment" + exit 1 + fi - name: upload source-home logs if: failure() - uses: actions/upload-artifact@v5 + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 with: name: source-home-macos-logs path: ${{ runner.temp }}/source-home-logs/ retention-days: 7 if-no-files-found: ignore - # Publish a GitHub Release for v* tags, attaching the per-architecture - # binary packages built by the source-home jobs. Only runs when every - # lint/test/source-home job is green. - release: - name: publish-github-release + # The macOS hop on Linux x86-64: the pinned published release installs with its + # own install.sh, updates to this source (new) and the release after it (next), + # refuses wrong signers, platform and version and a tampered offer, and is undone. + update-hop-linux: + name: update-hop-linux runs-on: ubuntu-24.04 - timeout-minutes: 15 - if: startsWith(github.ref, 'refs/tags/v') - needs: - - lint - - test-elastos - - test-capsules - - source-home-linux - - source-home-macos + # Source-home with the hop builds may take 45 minutes and the update journey 75. + timeout-minutes: 150 + needs: source-gate + env: + CI_APT_PACKAGES: coturn e2fsprogs ffmpeg musl-tools nasm pkg-config + steps: + - name: set job build directories + run: | + echo "CARGO_TARGET_DIR=$RUNNER_TEMP/update-hop-linux-target" >> "$GITHUB_ENV" + echo "CARGO_BUILD_BUILD_DIR=$RUNNER_TEMP/update-hop-linux-build" >> "$GITHUB_ENV" + # Published tarballs keep the shipped Cargo release profile. + - name: use CI journey release profile + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' || (github.event_name == 'push' && github.ref == 'refs/heads/develop') + run: | + echo "CARGO_PROFILE_RELEASE_LTO=false" >> "$GITHUB_ENV" + echo "CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16" >> "$GITHUB_ENV" + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }} + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '26' + - uses: dtolnay/rust-toolchain@72504271e02fb719eb4eb3eaece3a8e3d06f57c0 # 1.91.0 + with: + targets: wasm32-unknown-unknown + - name: configure Rust compile cache + if: env.CI_USE_CACHE == 'true' + uses: ./.github/actions/rust-compile-cache + - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + if: env.CI_USE_CACHE == 'true' + with: + workspaces: elastos + prefix-key: ubuntu-24.04-${{ runner.arch }}-update-hop-source-home-registry-${{ hashFiles('**/Cargo.lock', 'rust-toolchain.toml') }} + # Cache Cargo inputs; journey artifacts start fresh. + cache-targets: false + cache-directories: ${{ env.SCCACHE_DIR }} + save-if: ${{ env.CI_SAVE_CACHE == 'true' }} + # Two Runtime builds, both releases' support and eight installed Homes need + # more than the runner image leaves free; these preinstalled SDKs are unused. + - name: free hosted runner disk + run: | + sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup /opt/hostedtoolcache/CodeQL + df -Pk . + - name: require fresh Linux build artifacts + run: | + set -euo pipefail + for directory in "$CARGO_TARGET_DIR" "$CARGO_BUILD_BUILD_DIR"; do + test ! -e "$directory" + test ! -L "$directory" + mkdir -m 700 "$directory" + done + - name: prepare apt archive cache permissions + run: | + sudo install -d -o "$(id -u)" -g "$(id -g)" -m 755 /var/cache/apt/archives + sudo chown -R "$(id -u):$(id -g)" /var/cache/apt/archives + - name: restore Ubuntu prerequisite archives + if: env.CI_USE_CACHE == 'true' + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: /var/cache/apt/archives/*.deb + key: apt-ubuntu-24.04-${{ runner.arch }}-${{ hashFiles('scripts/ci-apt-prerequisites.sh') }}-${{ env.CI_APT_PACKAGES }}-${{ github.run_id }} + restore-keys: apt-ubuntu-24.04-${{ runner.arch }}-${{ hashFiles('scripts/ci-apt-prerequisites.sh') }}-${{ env.CI_APT_PACKAGES }}- + - name: install host prerequisites + timeout-minutes: 13 + run: bash scripts/ci-apt-prerequisites.sh + - name: bind Kubo cache to its pin + id: kubo-pin + run: | + echo "KUBO_CACHE_DIR=$RUNNER_TEMP/kubo-cache" >> "$GITHUB_ENV" + python3 scripts/ci-kubo-cache.py key linux-amd64 "$RUNNER_TEMP/kubo-cache" + - name: restore verified Kubo inputs + if: env.CI_USE_CACHE == 'true' + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ steps.kubo-pin.outputs.paths }} + key: ${{ steps.kubo-pin.outputs.key }} + - name: verify or download Kubo inputs + timeout-minutes: 10 + run: python3 scripts/ci-kubo-cache.py fetch linux-amd64 "$KUBO_CACHE_DIR" + - name: source-home into isolated HOME + env: + ELASTOS_COLLABORATION_STARTUP_MODE: isolated + SETUP_SOURCE_HOME_INSTALL_KUBO: '1' + run: | + set -euo pipefail + mkdir -p "${RUNNER_TEMP}/source-home-logs" + USER_HOME="${HOME}" + SOURCE_HOME="${RUNNER_TEMP}/elastos-source-home" + export ELASTOS_NODE_BIN="$(command -v node)" + export ELASTOS_BROWSER_VM_TURNSERVER_BIN="$(command -v turnserver)" + [[ "${ELASTOS_NODE_BIN}" == /* && -x "${ELASTOS_NODE_BIN}" ]] || { echo 'CI requires its installed Node executable.' >&2; exit 1; } + [[ "${ELASTOS_BROWSER_VM_TURNSERVER_BIN}" == /* && -x "${ELASTOS_BROWSER_VM_TURNSERVER_BIN}" ]] || { echo 'CI requires its installed TURN executable.' >&2; exit 1; } + mkdir -p "${SOURCE_HOME}" + export CARGO_HOME="${CARGO_HOME:-${USER_HOME}/.cargo}" + export RUSTUP_HOME="${RUSTUP_HOME:-${USER_HOME}/.rustup}" + export HOME="${SOURCE_HOME}" + export XDG_DATA_HOME="${SOURCE_HOME}/.local/share" + export PATH="${CARGO_HOME}/bin:${PATH}" + MEDIA_TOOLS_DIR="${RUNNER_TEMP}/source-home-media-tools" + install -d -m 700 "${MEDIA_TOOLS_DIR}" + for tool in ffmpeg ffprobe; do + install -m 700 "$(command -v "${tool}")" "${MEDIA_TOOLS_DIR}/${tool}" + done + export SETUP_SOURCE_HOME_MEDIA_TOOLS_DIR="${MEDIA_TOOLS_DIR}" + # The hop signs this build as the installed release: X.Y.Z or X.Y.Z-{alpha|beta|rc}.N. + export ELASTOS_RELEASE_VERSION="$(cargo metadata --no-deps --format-version 1 --manifest-path elastos/Cargo.toml \ + | python3 -I -c 'import json, sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"] == "elastos-server"))')" + scripts/setup-source-home.sh 2>&1 | tee "${RUNNER_TEMP}/source-home-logs/setup-source-home.log" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '24' + - name: prepare installed Home browser + timeout-minutes: 20 + run: | + npm ci --ignore-scripts --prefix elastos/tools/browser-playwright-engine + export PLAYWRIGHT_BROWSERS_PATH="$RUNNER_TEMP/installed-home-browser" + npx --prefix elastos/tools/browser-playwright-engine playwright install chromium --with-deps --only-shell + echo "PLAYWRIGHT_BROWSERS_PATH=$PLAYWRIGHT_BROWSERS_PATH" >> "$GITHUB_ENV" + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: '26' + # The seed's HTTP route does not serve every Linux artifact: after the published + # install.sh's HTTPS download, a disposable Home rolls back to the pinned head over Carrier. + - name: install the pinned published release + timeout-minutes: 30 + run: | + set -euo pipefail + python3 scripts/update-hop-compare.py install-previous-release \ + "$RUNNER_TEMP/previous-release-home" "$RUNNER_TEMP/previous-release" + - name: build two actual Runtime versions + timeout-minutes: 30 + run: | + set -euo pipefail + CI_HOP_ROOT="$HOME/.local/share/elastos-ci-update-hop" + test ! -e "$CI_HOP_ROOT" + mkdir -p "$CI_HOP_ROOT" + echo "CI_HOP_ROOT=$CI_HOP_ROOT" >> "$GITHUB_ENV" + df -Pk "$CI_HOP_ROOT" + python3 scripts/update-hop-compare.py build-ci-hop "$CI_HOP_ROOT/build-inputs" \ + --runtime "$CARGO_TARGET_DIR/release/elastos" --previous "$RUNNER_TEMP/previous-release" + - name: generate disposable signed install and update fixture + timeout-minutes: 5 + run: | + set -euo pipefail + python3 scripts/update-hop-compare.py generate-ci-hop "$CI_HOP_ROOT/package" \ + --runtime "$CI_HOP_ROOT/build-inputs/elastos-old" \ + --next-runtime "$CI_HOP_ROOT/build-inputs/elastos-new" \ + --system-runtime "$CI_HOP_ROOT/build-inputs/elastos-system" \ + --build-receipt "$CI_HOP_ROOT/build-inputs/build.json" \ + --support-home "$RUNNER_TEMP/elastos-source-home/.local/share/elastos" \ + --previous "$RUNNER_TEMP/previous-release" \ + > "$CI_HOP_ROOT/generation.json" + - name: prove installed Home account and System update with Carrier hop and refusals + # The same bounded waits as the macOS hop: 47 minutes in the worst case. + timeout-minutes: 75 + env: + ELASTOS_CI_FIXTURE_SCOPE: ci-rehearsal + ELASTOS_CI_REQUIRE_REAL_RUNTIME: "1" + run: | + set -euo pipefail + export ELASTOS_CI_FIXTURE_MANIFEST_SHA256="$(python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))["manifest_sha256"])' "$CI_HOP_ROOT/generation.json")" + python3 scripts/update-hop-compare.py inspect "$CI_HOP_ROOT/package/fixture.json" + python3 scripts/update-hop-compare.py run "$CI_HOP_ROOT/package/fixture.json" "$CI_HOP_ROOT/package/results" + - name: require the update from the published release, no new provider warnings and Undo + run: | + set -euo pipefail + python3 scripts/update-hop-compare.py check-result "$CI_HOP_ROOT/package/results/result.json" | tee -a "$GITHUB_STEP_SUMMARY" + - name: retain the safe CI hop receipt + if: always() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: linux-cli-update-hop-receipt + path: | + ${{ env.CI_HOP_ROOT }}/package/results/result.json + ${{ env.CI_HOP_ROOT }}/package/results/home-system/*.png + ${{ env.CI_HOP_ROOT }}/package/results/diagnostics/ + include-hidden-files: true + if-no-files-found: ignore + retention-days: 7 + - name: Rust compile cache statistics + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + sccache --show-stats + sccache --show-stats --stats-format=json > "$RUNNER_TEMP/source-home-sccache.json" + { + echo '### Rust compiler cache' + echo '```text' + sccache --show-stats + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + - name: Rust compile cache holds no Actions credential + if: always() && env.RUSTC_WRAPPER == 'sccache' + run: | + test -z "${ACTIONS_RUNTIME_TOKEN:-}" + # The daemon that the cache action started compiled every step above. + seen=0 + for pid in $(pgrep -x sccache || true); do + if [ "$RUNNER_OS" = Linux ]; then + environ=$(tr '\0' '\n' 2>/dev/null < "/proc/$pid/environ" || true) + else + environ=$(ps -wwE -o command= -p "$pid" || true) + fi + if grep -qF ACTIONS_RUNTIME_TOKEN= <<< "$environ"; then + echo "::error::sccache daemon $pid holds ACTIONS_RUNTIME_TOKEN" + exit 1 + fi + if grep -qF SCCACHE_DIR= <<< "$environ"; then seen=$((seen + 1)); fi + done + # Both runners show a same-user daemon's environment; reading none proves nothing. + if [ "$seen" = 0 ]; then + echo "::error::no readable sccache daemon environment" + exit 1 + fi + - name: upload source-home logs + if: failure() + uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5 + with: + name: update-hop-linux-logs + path: ${{ runner.temp }}/source-home-logs/ + retention-days: 7 + if-no-files-found: ignore + + # A pull request run stops at its first failed job, so the macOS and Linux + # journeys do not run on for 30+ minutes after a decisive failure. Pushes, + # merge queues and dispatches keep running every job to the end. This job + # runs no repository code and is the only one that may cancel the run. + cancel-on-failure: + name: cancel-on-failure + runs-on: ubuntu-24.04 + timeout-minutes: 160 + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository permissions: - contents: write + actions: write steps: - - uses: actions/download-artifact@v5 - with: - pattern: elastos-runtime-* - merge-multiple: true - - name: publish release - uses: softprops/action-gh-release@v2 - with: - name: ElastOS Runtime ${{ github.ref_name }} - generate_release_notes: true - files: | - elastos-runtime-*.tar.gz - elastos-runtime-*.tar.gz.sha256 + - name: cancel this run after the first failed job + env: + GH_TOKEN: ${{ github.token }} + run: | + set -uo pipefail + run="repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + done_polls=0 + # Jobs that wait on needs appear late; two quiet polls confirm the end. + while (( done_polls < 2 )); do + sleep 20 + counts="$(gh api "$run/attempts/$GITHUB_RUN_ATTEMPT/jobs?per_page=100" --jq \ + '[.jobs[] | select(.name != "cancel-on-failure")] | "\(map(select(.conclusion == "failure" or .conclusion == "timed_out")) | length) \(map(select(.status != "completed")) | length)"')" || continue + read -r failed pending <<< "$counts" + if (( failed > 0 )); then + echo "A job failed; cancelling the rest of this pull request run." + gh api -X POST "$run/cancel" + exit + fi + if (( pending == 0 )); then done_polls=$((done_polls + 1)); else done_polls=0; fi + done diff --git a/.github/workflows/release-package.yml b/.github/workflows/release-package.yml index 0a2eabe64..0d66eb751 100644 --- a/.github/workflows/release-package.yml +++ b/.github/workflows/release-package.yml @@ -8,7 +8,7 @@ on: workflow_dispatch: inputs: source_commit: - description: Commit on develop, or the head of an open PR into develop + description: Full SHA of a commit on develop required: true type: string install_version: @@ -19,6 +19,18 @@ on: description: Update version N+1, built with N's support required: true type: string + browser_image_cid: + description: Qualified common ARM64 guest archive CID (served as its immutable filename) + required: true + type: string + browser_image_sha256: + description: Independent SHA-256 of that guest archive + required: true + type: string + browser_image_size: + description: Exact archive bytes + required: true + type: string seed_package: description: Also build the Linux seed package (only to upgrade the seed Runtime) type: boolean @@ -35,8 +47,16 @@ env: SOURCE_COMMIT: ${{ inputs.source_commit }} INSTALL_VERSION: ${{ inputs.install_version }} UPDATE_VERSION: ${{ inputs.update_version }} + BROWSER_IMAGE_CID: ${{ inputs.browser_image_cid }} + BROWSER_IMAGE_SHA256: ${{ inputs.browser_image_sha256 }} + BROWSER_IMAGE_SIZE: ${{ inputs.browser_image_size }} + BROWSER_IMAGE_PUBLISHER_DID: ${{ vars.BROWSER_IMAGE_PUBLISHER_DID }} + BROWSER_IMAGE_PUBLISHER_NODE_ID: ${{ vars.BROWSER_IMAGE_PUBLISHER_NODE_ID }} + BROWSER_IMAGE_CONNECT_TICKET: ${{ secrets.BROWSER_IMAGE_CONNECT_TICKET }} CARGO_BUILD_JOBS: '4' PYTHONDONTWRITEBYTECODE: '1' + # Shipped release builds stay hermetic: no compiler wrapper or cache. + RUSTC_WRAPPER: '' jobs: admit: @@ -51,35 +71,49 @@ jobs: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail + [[ "$GITHUB_REPOSITORY" == Elacity/elastos-runtime ]] \ + || { echo 'The canonical builder repository is required' >&2; exit 1; } + [[ "$GITHUB_REF" == refs/heads/develop ]] \ + || { echo 'The develop builder ref is required' >&2; exit 1; } version='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$' [[ "$SOURCE_COMMIT" =~ ^[0-9a-f]{40}$ ]] || { echo 'source_commit must be a full SHA' >&2; exit 1; } [[ "$INSTALL_VERSION" =~ $version && "$UPDATE_VERSION" =~ $version && "$INSTALL_VERSION" != "$UPDATE_VERSION" ]] \ || { echo 'Two different SemVer versions are required' >&2; exit 1; } repo="repos/$GITHUB_REPOSITORY" tree=$(gh api "$repo/git/commits/$SOURCE_COMMIT" --jq .tree.sha) + [[ "$tree" =~ ^[0-9a-f]{40}$ ]] || { echo 'Source tree must be a full SHA' >&2; exit 1; } on_develop=$(gh api "$repo/compare/$SOURCE_COMMIT...develop" --jq '.status == "ahead" or .status == "identical"') - if [[ "$on_develop" != true ]]; then - # A key-free build of an open PR head may start before merge; the - # signer still refuses a commit that is not on develop. - open=$(gh api "$repo/commits/$SOURCE_COMMIT/pulls" --jq "[.[] | select(.state == \"open\" and .base.ref == \"develop\" - and .head.sha == \"$SOURCE_COMMIT\" and .head.repo.full_name == \"$GITHUB_REPOSITORY\")] | length") - behind=$(gh api "$repo/compare/develop...$SOURCE_COMMIT" --jq .behind_by) - [[ "$open" -ge 1 && "$behind" == 0 ]] \ - || { echo 'Source must be on develop or the head of an open PR containing develop' >&2; exit 1; } - fi + [[ "$on_develop" == true ]] || { echo 'Source must be a commit on develop' >&2; exit 1; } + # Preparation may run beside CI. Publication still requires green CI + # for this exact source and the release acceptance gate. echo "source_tree=$tree" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ inputs.source_commit }} + persist-credentials: false + - name: admit the common immutable image selector + run: | + set -euo pipefail + python3 -I -S scripts/browser-image-cid-input.py "$BROWSER_IMAGE_CID" "$BROWSER_IMAGE_SHA256" "$BROWSER_IMAGE_SIZE" + [[ "$BROWSER_IMAGE_PUBLISHER_DID" == did:key:* && "$BROWSER_IMAGE_PUBLISHER_NODE_ID" =~ ^[0-9a-f]{64}$ ]] \ + || { echo 'Configure the explicit Browser image publisher DID and Carrier node ID' >&2; exit 1; } mac: name: Apple silicon N and N+1 needs: admit - runs-on: macos-14 + runs-on: macos-15 timeout-minutes: 300 + permissions: + contents: read defaults: run: shell: bash working-directory: source env: SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} + RELEASE_PLATFORM: aarch64-darwin + # Cargo and its C dependencies target macOS 11.0, not the runner SDK. + MACOSX_DEPLOYMENT_TARGET: "11.0" steps: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: @@ -109,7 +143,7 @@ jobs: timeout-minutes: 20 run: | set -euo pipefail - brew install e2fsprogs coturn pkg-config openssl@3 + bash scripts/release-host-prerequisites.sh darwin python3 -I -S ../workflow/.github/scripts/release-mac-capacity.py - name: keep the capacity record if: always() && env.RELEASE_ROOT != '' @@ -126,14 +160,17 @@ jobs: umask 077 export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" inputs="$RELEASE_ROOT/inputs" + # Fresh Cargo directories for each version; removed after each build. for build in "N $INSTALL_VERSION" "N1 $UPDATE_VERSION"; do read -r name version <<< "$build" - export CARGO_TARGET_DIR="$RELEASE_ROOT/cargo-$name" CARGO_BUILD_BUILD_DIR="$RELEASE_ROOT/cargo-build-$name" - [[ ! -e "$CARGO_TARGET_DIR" && ! -e "$CARGO_BUILD_BUILD_DIR" ]] + export CARGO_TARGET_DIR="$RUNNER_TEMP/release-cargo-target" CARGO_BUILD_BUILD_DIR="$RUNNER_TEMP/release-cargo-build" + [[ ! -e "$CARGO_TARGET_DIR" && ! -L "$CARGO_TARGET_DIR" && ! -e "$CARGO_BUILD_BUILD_DIR" && ! -L "$CARGO_BUILD_BUILD_DIR" ]] reuse=() [[ "$name" == N ]] || reuse=(--reuse-support "$inputs/N") + image=() + [[ "$name" != N ]] || image=(--browser-vm-image-cid "$BROWSER_IMAGE_CID" --browser-vm-image-sha256 "$BROWSER_IMAGE_SHA256" --browser-vm-image-size "$BROWSER_IMAGE_SIZE") HOME="$RELEASE_ROOT/home" scripts/prepare-release-platform.sh \ - --version "$version" --output "$inputs/$name" ${reuse[@]+"${reuse[@]}"} + --version "$version" --output "$inputs/$name" ${reuse[@]+"${reuse[@]}"} ${image[@]+"${image[@]}"} python3 -I -S scripts/release-platform-input.py verify "$inputs/$name" > /dev/null rm -rf "$CARGO_TARGET_DIR" "$CARGO_BUILD_BUILD_DIR" done @@ -147,6 +184,7 @@ jobs: [[ "$(jq -r '[.source.commit, .source.tree, .platform, .version] | join(" ")' "$inputs/$name/platform-input.json")" \ == "$SOURCE_COMMIT $SOURCE_TREE aarch64-darwin $version" ]] [[ "$(HOME="$RELEASE_ROOT/home" "$inputs/$name/artifacts/elastos-aarch64-darwin" --version 2>&1)" == "elastos $version" ]] + python3 -I -S scripts/release-platform-input.py macos-floor --floor 11.0 "$inputs/$name/artifacts/elastos-aarch64-darwin" done [[ "$(git rev-parse HEAD)/$(git rev-parse 'HEAD^{tree}')" == "$SOURCE_COMMIT/$SOURCE_TREE" ]] [[ -z "$(git status --porcelain=v1 --untracked-files=all)" ]] @@ -158,7 +196,7 @@ jobs: rm -rf home (cd inputs && find . -type f -print0 | sort -z | xargs -0 shasum -a 256 > ../SHA256SUMS && mv ../SHA256SUMS .) install -d -m 700 package - tar -cf - inputs | gzip -1 | split -b 2000m -a 3 - package/release-inputs.tar.gz.part + COPYFILE_DISABLE=1 tar -cf - inputs | gzip -1 | split -b 2000m -a 3 - package/release-inputs.tar.gz.part (cd package && shasum -a 256 release-inputs.tar.gz.part* > SHA256SUMS) - id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v4 @@ -171,6 +209,83 @@ jobs: - name: record the artifact run: echo "Mac inputs artifact ${{ steps.upload.outputs.artifact-id }}, zip sha256:${{ steps.upload.outputs.artifact-digest }}" >> "$GITHUB_STEP_SUMMARY" + engine-llama-amd64: + name: pinned AMD64 CPU engine + needs: admit + runs-on: ubuntu-24.04 + timeout-minutes: 45 + # Match ci.yml's Ubuntu 22.04 engine recipe and glibc 2.35 baseline. + container: + image: ubuntu@sha256:5ec03bb3441e8b0bf3b4f9cd4629a1ae763010dc3035bb8da3ae6cf026486401 + defaults: + run: + shell: bash + working-directory: source + env: + SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} + DEBIAN_FRONTEND: noninteractive + BUILD_CONTAINER_IMAGE: ubuntu@sha256:5ec03bb3441e8b0bf3b4f9cd4629a1ae763010dc3035bb8da3ae6cf026486401 + ENGINE_BUILD_TOOLS: build-essential cmake git ca-certificates curl binutils file python3 + steps: + - name: install engine build tools + working-directory: /tmp + run: | + apt-get update -qq + read -r -a tools <<< "$ENGINE_BUILD_TOOLS" + apt-get install -y -qq --no-install-recommends "${tools[@]}" + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ inputs.source_commit }} + path: source + persist-credentials: false + - name: bind the source and approved AMD64 engine + id: engine-input + run: | + set -euo pipefail + [[ "$RUNNER_ENVIRONMENT/$RUNNER_OS/$RUNNER_ARCH" == github-hosted/Linux/X64 ]] + [[ "$(git rev-parse HEAD)/$(git rev-parse 'HEAD^{tree}')" == "$SOURCE_COMMIT/$SOURCE_TREE" ]] + [[ -z "$(git status --porcelain=v1 --untracked-files=all)" ]] + CI_LLAMA_AMD64_SHA256=$(python3 -I -S - <<'PYTHON' + import json + recipes = json.load(open("scripts/release-upstream-recipes.json"))["recipes"] + print(next(r["source"]["checksum"].removeprefix("sha256:") for r in recipes + if r["component"] == "llama-server" and r["platform"] == "linux-amd64")) + PYTHON + ) + echo "CI_LLAMA_AMD64_SHA256=$CI_LLAMA_AMD64_SHA256" >> "$GITHUB_ENV" + - name: bind engine cache to build recipe + id: engine-recipe + run: | + recipe_hash=$( { + cat scripts/build/build-llama-server-bundle.sh + cat scripts/verify-linux-engine.py + printf '\n%s\n%s\n' "$BUILD_CONTAINER_IMAGE" "$ENGINE_BUILD_TOOLS" + } | sha256sum | cut -d ' ' -f 1) + echo "cache-key=develop-llama-amd64-${recipe_hash}" >> "$GITHUB_OUTPUT" + - name: restore pinned AMD64 engine + id: engine-cache + # A miss takes the same verified cold build below. + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/llama-amd64-bundle + key: ${{ steps.engine-recipe.outputs.cache-key }} + - name: build and validate pinned AMD64 engine + id: engine-build + if: steps.engine-cache.outputs.cache-hit != 'true' + run: | + export RECIPE_COMMIT="$SOURCE_COMMIT" + bash scripts/build/build-llama-server-bundle.sh --platform linux-amd64 "$RUNNER_TEMP/llama-amd64-bundle" + - name: verify accepted AMD64 engine archive + run: | + bash scripts/build/build-llama-server-bundle.sh --platform linux-amd64 --verify-archive "$RUNNER_TEMP/llama-amd64-bundle" + [[ -z "$(git status --porcelain=v1 --untracked-files=all)" ]] + - uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v4 + with: + name: release-llama-amd64-${{ inputs.source_commit }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/llama-amd64-bundle + if-no-files-found: error + retention-days: 14 + engine-llama-arm64: name: pinned Jetson CPU engine needs: admit @@ -200,13 +315,13 @@ jobs: ref: ${{ inputs.source_commit }} path: source persist-credentials: false - - name: build and verify the recipe-pinned ARM64 engine + - name: bind the source and approved ARM64 engine + id: engine-input run: | set -euo pipefail [[ "$RUNNER_ENVIRONMENT/$RUNNER_OS/$RUNNER_ARCH" == github-hosted/Linux/ARM64 ]] [[ "$(git rev-parse HEAD)/$(git rev-parse 'HEAD^{tree}')" == "$SOURCE_COMMIT/$SOURCE_TREE" ]] [[ -z "$(git status --porcelain=v1 --untracked-files=all)" ]] - export RECIPE_COMMIT="$SOURCE_COMMIT" CI_LLAMA_ARM64_SHA256=$(python3 -I -S - <<'PYTHON' import json recipes = json.load(open("scripts/release-upstream-recipes.json"))["recipes"] @@ -214,8 +329,31 @@ jobs: if r["component"] == "llama-server" and r["platform"] == "linux-arm64")) PYTHON ) - export CI_LLAMA_ARM64_SHA256 + echo "CI_LLAMA_ARM64_SHA256=$CI_LLAMA_ARM64_SHA256" >> "$GITHUB_ENV" + - name: bind engine cache to build recipe + id: engine-recipe + run: | + recipe_hash=$( { + cat scripts/build/build-llama-server-bundle.sh + cat scripts/verify-linux-engine.py + printf '\n%s\n%s\n' "$BUILD_CONTAINER_IMAGE" "$ENGINE_BUILD_TOOLS" + } | sha256sum | cut -d ' ' -f 1) + echo "cache-key=develop-llama-arm64-${recipe_hash}" >> "$GITHUB_OUTPUT" + - name: restore pinned ARM64 engine + id: engine-cache + # A miss takes the same verified cold build below. + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/llama-arm64-bundle + key: ${{ steps.engine-recipe.outputs.cache-key }} + - name: build and validate pinned ARM64 engine + id: engine-build + if: steps.engine-cache.outputs.cache-hit != 'true' + run: | + export RECIPE_COMMIT="$SOURCE_COMMIT" bash scripts/build/build-llama-server-bundle.sh "$RUNNER_TEMP/llama-arm64-bundle" + - name: verify accepted ARM64 engine archive + run: | bash scripts/build/build-llama-server-bundle.sh --verify-archive "$RUNNER_TEMP/llama-arm64-bundle" [[ -z "$(git status --porcelain=v1 --untracked-files=all)" ]] - uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v4 @@ -227,9 +365,11 @@ jobs: linux: name: ${{ matrix.platform }} N and N+1 - needs: [admit, engine-llama-arm64] + needs: [admit, engine-llama-arm64, engine-llama-amd64] runs-on: ${{ matrix.os }} timeout-minutes: 300 + permissions: + contents: read strategy: fail-fast: false matrix: @@ -273,9 +413,13 @@ jobs: targets: wasm32-unknown-unknown,${{ matrix.target }} - name: install host prerequisites timeout-minutes: 15 - run: | - sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 update - sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 install -y build-essential cmake coturn e2fsprogs ffmpeg musl-tools nasm pkg-config + run: bash scripts/release-host-prerequisites.sh linux + - name: download pinned AMD64 engine input + if: matrix.platform == 'x86_64-linux' + uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5 + with: + name: release-llama-amd64-${{ inputs.source_commit }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/llama-amd64-bundle - name: download pinned ARM64 engine input if: matrix.platform == 'aarch64-linux' uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5 @@ -288,14 +432,17 @@ jobs: set -euo pipefail umask 077 export CARGO_HOME="${CARGO_HOME:-$HOME/.cargo}" RUSTUP_HOME="${RUSTUP_HOME:-$HOME/.rustup}" + export ELASTOS_LLAMA_AMD64_BUNDLE="$RUNNER_TEMP/llama-amd64-bundle/llama-b10516-bin-ubuntu22.04-amd64-cpu.tar.gz" export ELASTOS_LLAMA_ARM64_BUNDLE="$RUNNER_TEMP/llama-arm64-bundle/llama-b10516-bin-ubuntu22.04-arm64-cpu.tar.gz" inputs="$RELEASE_ROOT/inputs" + # Fresh Cargo directories for each version; removed after each build. for build in "N $INSTALL_VERSION" "N1 $UPDATE_VERSION"; do read -r name version <<< "$build" - export CARGO_TARGET_DIR="$RELEASE_ROOT/cargo-$name" CARGO_BUILD_BUILD_DIR="$RELEASE_ROOT/cargo-build-$name" - [[ ! -e "$CARGO_TARGET_DIR" && ! -e "$CARGO_BUILD_BUILD_DIR" ]] + export CARGO_TARGET_DIR="$RUNNER_TEMP/release-cargo-target" CARGO_BUILD_BUILD_DIR="$RUNNER_TEMP/release-cargo-build" + [[ ! -e "$CARGO_TARGET_DIR" && ! -L "$CARGO_TARGET_DIR" && ! -e "$CARGO_BUILD_BUILD_DIR" && ! -L "$CARGO_BUILD_BUILD_DIR" ]] reuse=() [[ "$name" == N ]] || reuse=(--reuse-support "$inputs/N") + # Browser is Mac-only until #90: Linux builds take no image input. HOME="$RELEASE_ROOT/home" scripts/prepare-release-platform.sh \ --version "$version" --output "$inputs/$name" ${reuse[@]+"${reuse[@]}"} python3 -I -S scripts/release-platform-input.py verify "$inputs/$name" > /dev/null @@ -346,7 +493,7 @@ jobs: if [[ "$RELEASE_PLATFORM" == aarch64-linux ]]; then cp jetson-*.receipt.json package/ fi - tar -cf - inputs | gzip -1 | split -b 2000m -a 3 - package/release-inputs.tar.gz.part + COPYFILE_DISABLE=1 tar -cf - inputs | gzip -1 | split -b 2000m -a 3 - package/release-inputs.tar.gz.part (cd package && shasum -a 256 -- * > SHA256SUMS) - id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v4 @@ -365,6 +512,8 @@ jobs: if: inputs.seed_package runs-on: ubuntu-24.04 timeout-minutes: 90 + permissions: + contents: read env: SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} # The seed Runtime embeds its build path and runs the release helpers @@ -412,6 +561,21 @@ jobs: grep -qaF "$SEED_SOURCE_ROOT/elastos/crates/elastos-server" "$package/elastos" if ldd "$package/elastos" "$package/ipfs-provider" | grep 'not found'; then exit 1; fi tar -czf "$package/source.tar.gz" -C "$SEED_SOURCE_ROOT" . + python3 -I -S - "$package" "$SOURCE_COMMIT" "$SOURCE_TREE" "$INSTALL_VERSION" <<'PYTHON' + import hashlib, json, pathlib, sys + root = pathlib.Path(sys.argv[1]) + files = {} + for name in ("elastos", "ipfs-provider", "source.tar.gz"): + path = root / name + digest = hashlib.sha256() + with path.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + files[name] = {"sha256": digest.hexdigest(), "size": path.stat().st_size} + receipt = {"schema": "elastos.release-seed-input/v1", "source": {"commit": sys.argv[2], "tree": sys.argv[3]}, + "version": sys.argv[4], "files": files} + (root / "seed-input.json").write_text(json.dumps(receipt, sort_keys=True) + "\n") + PYTHON (cd "$package" && sha256sum elastos ipfs-provider source.tar.gz > SHA256SUMS) - id: upload uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v4 @@ -422,3 +586,102 @@ jobs: retention-days: 14 - name: record the artifact run: echo "Seed package artifact ${{ steps.upload.outputs.artifact-id }}, zip sha256:${{ steps.upload.outputs.artifact-digest }}" >> "$GITHUB_STEP_SUMMARY" + + attest-platform: + name: attest inert ${{ matrix.platform }} receipts + needs: [admit, mac, linux] + runs-on: ubuntu-24.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - platform: aarch64-darwin + prefix: release-mac + - platform: x86_64-linux + prefix: release-x86_64-linux + - platform: aarch64-linux + prefix: release-aarch64-linux + permissions: + contents: read + actions: read + id-token: write + attestations: write + steps: + # This fresh runner executes W helpers only. Candidate H owns build + # bytes, while W and the original dispatch inputs own these assertions. + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: hash native payloads and seal original-input receipts + env: + GH_TOKEN: ${{ github.token }} + SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} + RELEASE_PLATFORM: ${{ matrix.platform }} + RELEASE_PREFIX: ${{ matrix.prefix }} + run: | + set -euo pipefail + [[ "$RUNNER_ENVIRONMENT" == github-hosted ]] + python3 -I -S scripts/release-provenance-seal.py attest \ + --source-commit "$SOURCE_COMMIT" --source-tree "$SOURCE_TREE" \ + --workflow-commit "$GITHUB_SHA" --workflow-ref "$GITHUB_REF" \ + --run "$GITHUB_RUN_ID" --attempt "$GITHUB_RUN_ATTEMPT" \ + --platform "$RELEASE_PLATFORM" --prefix "$RELEASE_PREFIX" \ + --install-version "$INSTALL_VERSION" --update-version "$UPDATE_VERSION" \ + --output "$RUNNER_TEMP/proof-$RELEASE_PLATFORM" + - id: provenance + uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3 + with: + subject-path: ${{ runner.temp }}/proof-${{ matrix.platform }}/*.platform-input.json + - name: keep the receipt bundle + run: install -m 600 '${{ steps.provenance.outputs.bundle-path }}' "$RUNNER_TEMP/proof-${{ matrix.platform }}/provenance.jsonl" + - uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v4 + with: + name: release-proof-${{ matrix.platform == 'aarch64-darwin' && 'mac' || matrix.platform }}-${{ inputs.source_commit }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/proof-${{ matrix.platform }} + if-no-files-found: error + retention-days: 14 + + attest-seed: + name: attest inert seed receipt + needs: [admit, seed] + if: inputs.seed_package + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + actions: read + id-token: write + attestations: write + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: hash seed payloads and seal original-input receipt + env: + GH_TOKEN: ${{ github.token }} + SOURCE_TREE: ${{ needs.admit.outputs.source_tree }} + run: | + set -euo pipefail + [[ "$RUNNER_ENVIRONMENT" == github-hosted ]] + python3 -I -S scripts/release-provenance-seal.py attest \ + --source-commit "$SOURCE_COMMIT" --source-tree "$SOURCE_TREE" \ + --workflow-commit "$GITHUB_SHA" --workflow-ref "$GITHUB_REF" \ + --run "$GITHUB_RUN_ID" --attempt "$GITHUB_RUN_ATTEMPT" \ + --platform seed --prefix release-seed \ + --install-version "$INSTALL_VERSION" --update-version "$UPDATE_VERSION" \ + --output "$RUNNER_TEMP/proof-seed" + - id: provenance + uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3 + with: + subject-path: ${{ runner.temp }}/proof-seed/seed-input.json + - name: keep the receipt bundle + run: install -m 600 '${{ steps.provenance.outputs.bundle-path }}' "$RUNNER_TEMP/proof-seed/provenance.jsonl" + - uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v4 + with: + name: release-proof-seed-${{ inputs.source_commit }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/proof-seed + if-no-files-found: error + retention-days: 14 diff --git a/.gitignore b/.gitignore index c3f55c911..1bd57991e 100644 --- a/.gitignore +++ b/.gitignore @@ -150,3 +150,6 @@ scripts/full-check-inventory.sh scripts/control_graph_cron.py scripts/status.sh scripts/dev/dkms-docker/shared + +# Local rehearsal and review output; never part of the repository. +/output/ diff --git a/AGENTS.md b/AGENTS.md index 4b8be546f..5de78154e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,27 +7,28 @@ are the only place for work status, acceptance criteria and proof. ## Work Tracking And Acceptance - GitHub issues own the work queue. In each lane, take the lowest-numbered open - task whose dependencies are satisfied and which has no active blocker. Keep - at most one task issue In progress per lane. Parent issues group the lane; + task in the current release milestone (see Milestones under + [Releases](#releases)) whose dependencies are satisfied and + which has no active blocker. Keep at most one task issue In progress per + lane. Parent issues group the lane; they do not authorize a second active task. User messages approve, redirect or reorder work; they do not create a parallel task list. - Close a task only when its Done means is proven and its PR has the required reviews and is merged. Until then, keep verified work open in QA / Review. Take the next unblocked task in that lane; starting it does not complete its predecessor. Keep blocked work open with its blocker in the issue. -- While CI runs after a push, start or continue the next eligible issue in the - other lane. Keep the one-active-task limit in each lane. Read CI results when - they finish; do not watch or poll CI. If both lanes are blocked, record the - blockers in their issues. +- At the first CI failure caused by your candidate, cancel its remaining jobs + and repair the cause before another push. Continue eligible work while CI + runs. If CI is the only remaining work, end the turn and check again in + 15 minutes. Record an external blocker in the owning issue. - Run at most one heavy local build on this Mac at a time. Workers agree which issue owns that build before starting it. CI builds do not count toward this local limit. Continue reviews, source work or other light checks in parallel. -- Update the owning GitHub issue before reporting progress. State what changed, - link the PR, and record the exact candidate, checks, results and remaining - work. The report names the issue, PR, proof and next issue. -- Keep one work record. Do not create briefings, plans, gists or notes files. - Existing `state.md`, `TASKS.md` and dated audits are historical references; - move useful open work to its issue instead of maintaining a parallel queue. +- Comment on GitHub only for a decision, a result with its link, a blocker or a review verdict. + Keep comments to at most 3 lines: no narration, hashes, receipts or agent-to-agent coordination. + The checklist states what must be true; the Acceptance record below is the only place for current status and evidence. +- Do not create briefings, plans, gists or notes files. + Move useful open work from dated audits to its issue. - Keep seed security details, credentials and private operator data out of public issues, PRs and logs. Give the public issue only a safe summary and the approval or verification still needed. Retain sensitive raw evidence @@ -40,6 +41,17 @@ are the only place for work status, acceptance criteria and proof. - Durable product instructions, licences, test fixtures and artifact provenance stay with their code or package. They do not carry a second work queue. +### Acceptance record + +The owning issue keeps one record, edited in place, with these six items: + +- Candidate: PR head and tested merge SHA, or one release source. +- Exercised checks and the reason for each skipped check. +- Review links with the reviewed SHA. +- Installed release evidence. +- Remaining gate. +- Next owner. + ## User-Facing Communication - Use ASD-STE100 Simplified Technical English for user-facing communication. @@ -58,50 +70,47 @@ are the only place for work status, acceptance criteria and proof. ## Branch Roles -- `main` is the stable source line. -- `upstream/-dev` branches are development integration lines. The - owning GitHub issue records the approved task base; fetched refs verify it. - This replaces the old rule to choose the active line from `state.md` and fetched refs. +- `main` is the release line. It changes only through the weekly release PR. +- `develop` is the integration line. Task PRs merge into it when their checks + and reviews pass (see Review And Commit Discipline). - Feature and fix branches remain unpublished working lines until they are explicitly pushed for review. - Do not assume a `review/*` or `live` ref exists. Identify the exact public review or deployed commit from fetched refs and target-host evidence before making either claim. -- Treat any other local branch or target-host checkout as evidence only after - reporting its exact branch, commit, tree id, dirty status, and verification - command. +- Verify the exact branch, commit, tree id, dirty status and command before + treating a local branch or target-host checkout as evidence. Keep these + identities in the lifecycle inventory or the installed-artifact receipt; + routine check-ins link the related PR, CI run and review. - Always report remote divergence. A local branch being green is not the same as - `elacity/` being up to date. + the remote branch being up to date. ## Creating Work Branches -Every 0.7.1 task branch uses [feat/0.7.1-models](https://github.com/Elacity/elastos-runtime/tree/feat/0.7.1-models) as its base and PR target unless -the owning issue specifies another base. This is standing approval; do not ask -for each task. Fetch the current base before branching and record it in the issue. -Tasks that use this default base depend on the models branch and merge back into -it. Exceptions follow the base and target recorded in their issue. If the base -moves, check compatibility before merging; history rewrite still needs approval. -This standing approval takes precedence over the branching skill's per-task -base question for 0.7.1. - -For other work without an approved issue base, use a user-selected -`upstream/XX-dev` integration branch. The current checkout and `main` are not -implicit bases: - -- Run `git fetch origin --prune`, then list `upstream/*-dev` lines and active - `feat/*`/`fix/*` branches before proposing bases. -- Ask the user which base to start from, offering each `upstream/XX-dev` - (newest recommended) plus "an existing working branch" for work that depends - on another in-flight branch. Ask even when only one dev line exists. -- If the chosen base is a working branch rather than `upstream/XX-dev`, warn - immediately: the new branch must merge back only after (or together with) - its parent, merging it into `upstream/XX-dev` may conflict with the parent's - changes, and it needs a rebase if the parent moves. -- Name branches `feat/` or `fix/`. Pushes and upstream tracking - follow the Push Approval Levels below. +Every task branch uses [develop](https://github.com/Elacity/elastos-runtime/tree/develop) +as its base and PR target unless the owning issue names another base. This is +standing approval; do not ask for each task. Fetch the current base before +branching. If the base moves, check compatibility before merging; history +rewrite still needs approval. A branch that depends on another in-flight branch +says so in its PR and merges after its parent. Name branches `feat/` or +`fix/`. Pushes and upstream tracking follow the Push Approval Levels below. Canonical workflow: [.claude/skills/branching-strategy/SKILL.md](.claude/skills/branching-strategy/SKILL.md). +## Releases + +- Test releases (`X.Y.Z-alpha.N`, or `X.Y.Z-rc.N` for a candidate; canary channel) are built from a + `develop` merge commit through `.github/workflows/release-package.yml` + (dispatched from `develop`) and published with `scripts/release-publish.sh` + (see [Publishing a release](docs/VERSIONING.md#publishing-a-release)). Each one + gets one comment on #93 naming its commit and accepted scope. +- Milestones: `2.0.0` (the five first-release goals, phones, isolation S0-S2 and + the release gates in #93) and `After 2.0.0`. There are no weekly milestones. +- `main` changes only when a stable release is tagged: a release PR from the + accepted `develop` commit, then `vX.Y.Z` on the merge commit, then `main` + merges back into `develop`. +- 2.0.0 ships when every result in the 2.0.0 milestone meets its Done means. + ## Branch Lifecycle Retire a branch or close a PR only with its owner's agreement. A green check, @@ -183,9 +192,9 @@ them creates a cleanup obligation; "temporary" is not a lifecycle. condition, and must be removed when that gate closes. Do not recursively copy a live data root without an explicit size estimate and exclusion list for existing backups, VM images, caches, identity state, and user data. -- Maintain at least 10% free space on development and staging volumes. If free - space falls below that threshold, stop creating worktrees, builds, VM images, - and backups until the ledger is reconciled and safe reclaim has completed. +- Before creating a worktree, build, VM image or backup, check that its bytes + plus 2 GiB fit in the volume's free space (the product's own rule). If they do + not, stop until the ledger is reconciled and safe reclaim has completed. - Before handoff, rerun the branch/worktree inventory, check every touched worktree for dirt, report local/remote divergence, and update the local ledger. Do not describe a cleanup as complete while an unexplained ref, @@ -210,14 +219,12 @@ target before acting. - **No approval needed:** fast-forward pushes to the branch of the active task or its existing draft PR; opening draft PRs; rerunning checks; reading logs. Report what was pushed, including the remote, branch, commits and check results. -- **Standing task-merge permission:** merge a task PR only into the repository - and target branch explicitly approved by the user for that task. - Check that approval before merging. A change to the approved target requires - explicit user approval. The current candidate must pass all required checks, - independent review must be complete, required human reviews must approve the - candidate, all findings must be resolved, and its dependencies must be integrated. - Check compatibility with the current base and report the PR, source and merge - commits, review and checks. Use a normal merge; history rewrite needs approval. +- **Standing task-merge permission:** merge your task PR into `develop`, or + into the user-approved base named in its issue, when all current checks pass, + the independent reviews below pass, findings are resolved, dependencies are + integrated, and any explicit human acceptance gate passes. Check current-base + compatibility and report links to the merged PR, CI run and reviews. Use a + normal merge; history rewrite needs approval. - **Standing test-key permission:** create and use disposable keys and signatures for a named, isolated test fixture. Keep its trust store separate from real Homes and production keys. Record its owner and cleanup condition; keep private @@ -227,7 +234,10 @@ target before acting. keys; changes on the seed or existing installed Homes; deleting branches; other secrets and credentials. -Signing runs outside CI. Fork PRs and publication jobs use GitHub-hosted runners. +The operator runs production signing with Anders's approval. Named isolated +fixtures may generate disposable keys and signatures in CI; their trust stays +separate from real Homes and production keys. Fork PRs and publication jobs use +GitHub-hosted runners. These levels replace blanket push-approval requirements. Verification and the agreed publication scope still apply. Keep unrelated work and private operational @@ -241,6 +251,18 @@ git diff --stat ...HEAD git rev-list --left-right --count ...HEAD ``` +Before each push, commit the candidate and check it with +`just ci-local-prepush`. The committed pre-push hook checks the exact pushed +HEAD and refuses a base that conflicts or shares changed files with develop. +It runs formatting, workspace/all-targets checks, Clippy for touched crates, and +their unit targets. +Use the [local pre-push procedure](scripts/README.md#local-pre-push-gate) to +activate the hook and share the local heavy-build lease across worktrees. +Reproduce an unclear failed Mac install, update, or Home startup step locally +under that lease before pushing. Review a large diff with Opus before long Mac +CI. Record the command and result in the owning issue; source checks and an +operator reminder alone do not prove that installed step. + Before deploying public Home, show the exact commit being deployed, confirm that `live` either already points to that commit or will be moved only after successful verification, and preserve a rollback path for the installed binary, @@ -251,10 +273,22 @@ capsules, provider config, and `components.json`. - Keep review requests off draft PRs. When a PR leaves draft, request the required reviewers on GitHub yourself and name them in the report. Keep an existing request instead of sending a duplicate. -- For a PR authored by Anders that touches signing, update checks, Inbox - approvals, keys, sandboxing or seed publishing, name `irzhywau` as a required - human reviewer. Also name the feature owner when the task requires that review. - Independent agent review and required human review are separate evidence. +- Each task change needs one independent development review marked PASS. + Security code, including gateway, auth, provider launchers, confinement, + signing, publish/update, install.sh and workflows, also needs a posted + `Independent adversarial review ... VERDICT: PASS` from a different model + family than its author. Codex authors run `elastos-pr-review ` themselves + and verify that the posted verdict covers the current candidate. +- Agents merge their own task PRs after the current checks and reviews pass. + Keep explicit human acceptance gates recorded in the owning issue. Request + `irzhywau` for security follow-up: he reviews merged security task PRs, and a + finding goes into an existing issue or a revert when it reopens a hole. + When he authors a security task PR, Anders conducts the follow-up review. + Weekly release PRs still need his approval before merge and tag; when he is + the author, Anders reviews. Also request the feature owner when required. +- Use one development review round per coherent change. Resolve findings in + that round and fix their cause before requesting the current verdict. Scope + decisions belong to Anders. Ask before adding new diagnostic tooling. - Keep commits authority-bound and reviewable: one coherent concern per commit, with its own verification commands. - Preserve commit history by default. Ask before amending, squashing, rebasing @@ -264,8 +298,14 @@ capsules, provider config, and `components.json`. - Do not delete or rewrite dirty worktrees unless the user explicitly approves it. If duplicate trees exist, prove byte identity and clean status before recommending deletion. -- Put work status and proof in the owning GitHub issue. Keep release history in - `elastos/CHANGELOG.md` and product instructions in the relevant documentation. +- Before a PASS is carried to a new head (merge, rebase, push), confirm that the + reviewed commit is an ancestor of that head and diff the reviewed paths + between the two. Any lost change voids the PASS. Give each review finding a + disposition tied to the published head: fixed in `` with test ``, + moved to #N, or rejected because ``. Report author checks, + independent review and installed acceptance separately. +- Keep release history in `elastos/CHANGELOG.md` and product instructions in + the relevant documentation. - Keep product documentation release-neutral. Use version numbers only for exact release state, compatibility or migration, release notes or changelogs, manifests, and exact Git refs or evidence. Keep standing instructions, @@ -282,7 +322,8 @@ basic gate before handing work back: ```bash git diff --check -node scripts/home-entropy-check.mjs +node scripts/check-product-data.mjs +node --test scripts/check-product-data.test.mjs (cd elastos && cargo fmt --all -- --check) cargo fmt --manifest-path capsules/chain-provider/Cargo.toml -- --check ``` @@ -295,7 +336,7 @@ for touched crates or scripts, for example: cargo test --manifest-path capsules/chain-provider/Cargo.toml -- --nocapture ``` -For Browser-facing changes, include the relevant Browser entropy/smoke gates and +For Browser-facing changes, include the relevant Browser behaviour/smoke gates and do not claim product readiness unless `scripts/browser-objective-audit.mjs` passes with accepted product media plus matching manual UX evidence. @@ -312,6 +353,12 @@ path, installed artifact path, SHA-256 of the built and installed artifact, restart or stale-process cleanup performed, and the live localhost proof command and result. +Prove installed behavior on the CI install jobs (GitHub-hosted Linux x86-64, +Linux ARM64 and macOS machines) when they cover the journey, and link that CI +run as the proof. Otherwise use the installed-proof steps above. The Jetson is +checked on the weekly candidate. A PR that changes what users see links the CI +screenshots at desktop and phone width. + ## Journey Register Gate Use [docs/audits/ElastOS-Home-Journey-Audit.xlsx](docs/audits/ElastOS-Home-Journey-Audit.xlsx) @@ -382,12 +429,13 @@ Use target roles consistently: - Mac: staging, macOS VZ Browser proof, and cross-platform proof; - Jetson: Linux/crosvm native Browser target and intended main device proof. -Mac staging requires durable SSH before serious testing. `tmate` is acceptable +Browser staging on this local Mac uses direct execution. Remote Mac staging +requires durable SSH before serious testing. `tmate` is acceptable only as a break-glass bootstrap channel. During that bootstrap, create or reuse a dedicated staging account, install an agent-owned public key in the target account's authorized-keys file, disable password assumptions, record a local SSH host alias, and verify non-interactive commands work. If no durable SSH is available, -say the Mac is blocked instead of implying it was verified. +say remote Mac staging is blocked instead of implying it was verified. Do not commit staging aliases, private key names, reverse-tunnel ports, local worktree paths, or operator usernames. Keep those details in private operational @@ -437,10 +485,8 @@ Rust target; do not re-document dependency installation here. use. `wasm32-unknown-unknown` is the capsule Component target; the release scripts also add it on demand via `ensure_rust_target_installed`. - Core gate has no JS/Python package deps: the `.mjs` checks in `just verify` - (`home-entropy-check.mjs`, `browser-entropy-check.mjs`, - `browser-window-close-handshake.test.mjs`, etc.) and the Python smokes use - only stdlib/`node --test`. `playwright` appears only as a scanned string in - entropy checks and as an import in Browser/GUI headless smokes that are NOT + (`check-product-data.mjs`, `browser-window-close-handshake.test.mjs`, etc.) and the Python smokes use + only stdlib/`node --test`. `playwright` appears as an import in Browser/GUI headless smokes that are NOT part of the core gate, so no `npm install` is needed for build/lint/test. - Build/lint/test run from the repo root (the recipes `cd elastos` themselves): `just build`, `just lint`, `just test`. A cold `just build` is diff --git a/DEBUG.md b/DEBUG.md index 78521ce32..5481f3fa6 100644 --- a/DEBUG.md +++ b/DEBUG.md @@ -8,28 +8,25 @@ work log. 1. Reproduce the failure with a concrete command, URL, or user journey. 2. Write the smallest falsifiable hypothesis. 3. Run one experiment that can prove or disprove that hypothesis. -4. Record durable findings in the issue, PR, commit message, `state.md`, - `TASKS.md`, or the relevant `docs/` file after verification. +4. Record verified findings in the owning GitHub issue. ## Verification - Prefer product-level smoke tests for Home, app launch, Browser, Wallet, pairing, sharing, and mobile/touch behavior. - Prefer focused tests for the authority boundary being changed. -- Run `node scripts/home-entropy-check.mjs` after UI, naming, routing, token, - People, Services, or ontology changes. -- Run `node scripts/browser-entropy-check.mjs` after Browser, Browser Engine, - Exit, WebRTC, VM, or wallet-bridge changes. +- Run `node scripts/check-product-data.mjs` after capsule manifest, component, + model catalog, or install asset changes. Run the relevant behaviour tests + after Home, Browser, provider, or authority changes. - Run `git diff --check` and Rust/JS syntax checks before handing off. - Keep historical transcripts out of active docs. Git history already preserves them. ## Where Notes Belong -- Temporary debugging notes belong in the active issue, review thread, or an - untracked local note. -- Release truth belongs in `state.md`, `TASKS.md`, `elastos/CHANGELOG.md`, or a - receipt under the documented proof path. +- Debugging findings and proof belong in the owning GitHub issue. Use + [#89](https://github.com/Elacity/elastos-runtime/issues/89) for install and update. +- Release history belongs in `elastos/CHANGELOG.md`. - Durable architecture guidance belongs in `docs/`. - Stable local-debugging invariants belong here. @@ -108,11 +105,6 @@ Capability tokens belong in the Runtime/provider envelope. Provider JSON bodies must not carry duplicate token fields unless a provider explicitly validates that field as part of a reviewed protocol. -## Active Work Logs - -Do not add running debug notes or host transcripts to this file. Promote only -stable invariants here after the relevant code and tests are updated. - ## Browser Address Navigation Invariant Address-bar navigation may use in-place Browser control while the active page is diff --git a/README.md b/README.md index 9ccfd4f10..787ac0814 100644 --- a/README.md +++ b/README.md @@ -4,27 +4,75 @@ ElastOS is a local-first runtime for Apps and services. Runtime checks the authority of each caller before allowing an effect. People sign in to Home with passkeys. -For released versions, supported installation targets and known limitations, -see [state.md](state.md). A source checkout and a published installation have +For release history, see [elastos/CHANGELOG.md](elastos/CHANGELOG.md). +[GitHub issues](https://github.com/Elacity/elastos-runtime/issues) own current +acceptance and verification. A source checkout and a published installation have separate artifact identities and verification records. +## Current isolation and target boundary + +First-party apps run as web projections in the browser's opaque sandboxed +frames. Runtime checks each app's signed launch token and actor before it performs an effect. +Home can currently obtain every app's capability, so a compromised Home can +reach those apps' authority. The target limits Home to delegation and gives each +app a separate, revocable capability. The WASM Component authoring path runs in +Wasmtime with memory and fuel limits and Runtime Bus hostcalls. + +Providers run as native operating-system processes with the Runtime user's +rights. Only the model provider is partly confined. The trusted shell helper +also runs as a native host process. The web Terminal is disabled by default; +host developer mode and closed guest registration are required to enable it. +An enabled Terminal runs commands with the host user's rights. + +The seed operator can read hosted data, wallet keys and recovery material. +Passkeys control sign-in; stored data and keys remain accessible to the Runtime +account and root while Home is locked. Protection against hosted operators and +root, and against other software or OS users while a self-hosted Home is locked, +is the target of [hosted protection](https://github.com/Elacity/elastos-runtime/issues/209) +and [locked Home protection](https://github.com/Elacity/elastos-runtime/issues/210). +An unlocked self-hosted Home trusts its owner and their host software. Recovery +from a stolen device or profile key requires a new identity. + +The [isolation plan](https://github.com/Elacity/elastos-runtime/issues/173) +records the remaining gates. Source checks describe this source tree. Accepted +installed proof binds the exact Runtime, components and app assets to the +journeys tested on that device. + ## Install from the publisher The public installer looks up signed releases for Linux x86_64/aarch64 and macOS Apple silicon. Intel Mac and other OS families fail closed. +The maintainer release DID is +`did:key:z6MkgwHd2BCWe1jHMXPiR6H1q1RFPcv1YzhMbK5G1kBarbfe`. Compare the +installer's `Maintainer DID:` line with this complete DID. Stop if they differ. + +The maintainer changed the release signing key because the previous key was +stored on the public server. + ```bash curl -fsSL https://elastos.elacitylabs.com/install.sh | bash ``` -The installer installs Runtime, sets up the Home profile, and opens Home. Keep -the terminal open while you use Home. Add `$HOME/.local/bin` to PATH when you +For an existing Home, re-trust the maintainer once by running the same installer +over the old installation: + +```bash +curl -fsSL https://elastos.elacitylabs.com/install.sh | bash +``` + +The installer trusts the new DID, installs the release and keeps your existing +identity, accounts and user files. Homes that already trust this DID can use +normal updates. See [release signer recovery](docs/INSTALL.md#compare-and-change-the-release-signer). + +The installer installs Runtime, sets up the Home profile, and opens Home. Its +release acceptance evidence lives in GitHub issues. Keep the terminal open while you use Home. Add `$HOME/.local/bin` to PATH when you later run `elastos` from a new shell. You do not need a separate `elastos serve` process for this path. Home is the user-facing front door to the managed Runtime. Only one live host may own an ElastOS data home at a time. Stop Home before using the separate operator runtime in the same home. See [Installing -ElastOS](docs/INSTALL.md) for profiles, updates, trust verification, and +ElastOS](docs/INSTALL.md) for updates, trust verification, and operator setup. See the [Mac staging runbook](docs/MAC.md) for source-home staging and Browser VM work. @@ -44,8 +92,9 @@ build, and capsule development. Run `just verify` before handing off a change. ## System model -Runtime is the trusted core. Home and shells show state and collect intent, but -they cannot grant themselves authority. Executable capsules request effects +Runtime is the trusted core. Home and shells show state and collect intent. +The target limits their authority to Runtime-approved delegation. Executable +capsules request effects through typed Runtime resources. Components use ElastOS Bus. Web projections use narrow, capsule-scoped Runtime adapters. Both enter Runtime's authority and routing boundary. Runtime handles core operations directly and selects a @@ -73,13 +122,14 @@ admission is a separate, node-local verification decision. See the ## Status and verification -Use [state.md](state.md) as the authority for current behavior and known gaps. -It distinguishes implemented behavior from source-only paths and unverified -product claims. Browser source and proof tooling alone do not establish -complete Browser product support. +Use [GitHub issues](https://github.com/Elacity/elastos-runtime/issues) for current +behavior, known gaps and proof. [Install and update #89](https://github.com/Elacity/elastos-runtime/issues/89) +owns installed release acceptance. A source checkout and a published install +have separate artifact identities; source checks alone do not prove installed +product or Browser support. -Use [TASKS.md](TASKS.md) for open work, [ROADMAP.md](ROADMAP.md) for future -direction, and [elastos/CHANGELOG.md](elastos/CHANGELOG.md) for release history. +[ROADMAP.md](ROADMAP.md) links planned work; +[elastos/CHANGELOG.md](elastos/CHANGELOG.md) records release history. For command ownership across Home and operator lanes, see the [command matrix](docs/COMMAND_MATRIX.md). @@ -98,7 +148,7 @@ elastos-runtime/ - [Getting started](docs/GETTING_STARTED.md): install, build, and create a capsule - [Documentation map](docs/README.md): complete guide and contract index -- [State](state.md): verified behavior and known gaps +- [Isolation plan](https://github.com/Elacity/elastos-runtime/issues/173): current boundaries and acceptance gates - [Principles](PRINCIPLES.md): decision constraints - [Architecture](docs/ARCHITECTURE.md): trust and responsibility boundaries - [Capsule authoring](docs/CAPSULE_AUTHORING.md): supported Component and web-projection paths diff --git a/ROADMAP.md b/ROADMAP.md index cdd7ce3b1..f1e197500 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,527 +1,30 @@ # ElastOS Runtime roadmap -This roadmap describes future work. See [TASKS.md](TASKS.md) for active work, -[deferred work](docs/DEFERRED_WORK.md) for the open backlog, and -[state.md](state.md) for current behavior. - -## Mission - -Make this repository the trusted local runtime layer for ElastOS: - -- execute capsules predictably -- expose one coherent local object model -- route Component effects through ElastOS Bus and web-projection effects - through narrow, capsule-scoped Runtime adapters -- make local and remote effects follow the same authority model -- keep release, install, update, share, and site flows boring -- give ElastOS a stable default Home without weakening the Runtime boundary - -## Non-goals - -The broader SmartWeb stack is outside this repository. Blockchain and payment -remain separate layers. Carrier and Boson have broader programs beyond this -repository's Runtime integration. All integrations use explicit boundaries. - -This repository owns the Runtime and Home contract. That includes the default -local front door, capsule execution, authority, and the object boundaries that -Home and other host adapters must obey. - -## Constraints and order - -[PRINCIPLES.md](PRINCIPLES.md) owns the implementation constraints. -[Architecture](docs/ARCHITECTURE.md#elastos-four-quadrants) owns the -responsibility model. This roadmap orders outcomes; it does not redefine either -document. - -The numbered outcomes below define the order. This keeps one substrate from -becoming the root of trust. Token economics, public storage markets, broad dDRM -economics, and specialized device products come after principals, capabilities, -packages, availability, and spaces work end to end. - -### Planning review gate - -Future plans should answer these questions before implementation: - -- Does the work strengthen explicit authority and avoid ambient access? -- What is the smallest complete Runtime behavior or user journey? -- Which quadrant changes, and which quadrants do not? -- Does provider-specific behavior stay behind a provider contract? -- What source, artifact, or manual evidence will prove the result? -- Which existing truth surface owns the contract, state, task, and history? - -## Near-term direction - -### 0. Enforce capsule authority at every Runtime ingress - -Components request effects through typed ElastOS Bus resources. Web projections -and MicroVMs use narrow, capsule-scoped Runtime adapters. Every surface enters -Runtime's authority and routing boundary without exposing local or remote -topology. Runtime handles core operations directly and sends provider-backed -effects through the provider registry. Each substrate keeps its documented -lifecycle and cleanup contract. No executable substrate receives guest network, -host process execution, raw transport, direct provider API, or host filesystem -authority. Content capsules carry portable data under a data contract. They do -not execute or request effects. - -Provider capsules are narrow exceptions. Their manifests define an upper bound, -not a self-grant. Explicit Runtime system services require registered policy. -Runtime verifies authority before dispatch, and unknown operations fail closed. -Gateways authenticate and route host projections; they do not reimplement -provider policy. - -The normative authority rules live in [PRINCIPLES.md](PRINCIPLES.md), -[ESP v0](docs/ESP_V0.md), and the -[Capsule interface contract](docs/CAPSULE_INTERFACE_CONTRACT.md). Capsule -packaging and interface rules live in -[Capsule authoring](docs/CAPSULE_AUTHORING.md) and -[Capsule interface contract](docs/CAPSULE_INTERFACE_CONTRACT.md). -The current Component/Bus v1 path is implemented and conformance-tested, while -shipped first-party UI Apps remain web projections. Keep Bus v1 bounded and do -not claim product adoption until a shipped first-party Component proves it. -Define Bus v2 only for a tested product need such as resident lifecycle, -cancellation, or streams. - -### 1. Finish passkey-first authority and recovery - -Home should start with passkey-backed principals. The first owner controls local -enrollment policy. Other people create and control their own authenticators, -principal roots, and recovery material. An administrator can operate the -Runtime and revoke access policy, but cannot silently decrypt another person's -root. - -Removing a passkey revokes its proof bindings and sessions. It does not delete -the principal root or attach it to a new passkey. Recovery is an explicit, -audited reassignment that verifies the root and its protectors before mutation. -Hosted, loopback, native, and mobile hosts need explicit origin or host-auth -policy; none may gain authority from a trusted header. - -Public first-owner enrollment must start from one-use local operator authority -and bind one exact HTTPS origin and RP before the ceremony begins. Adding a -credential to an existing owner requires explicit self-link consent and keeps -the same principal and protected root. Both flows reuse Runtime auth state and -produce typed denial, replay, expiry, concurrency, and audit results. - -Principal-root protection should use random per-principal data keys. Protectors -may include a Recovery Kit, client-side WebAuthn PRF wrapping, DID-backed -recovery, and future quantum-resistant envelopes. Runtime stores wrapped -envelopes and protector metadata. Raw PRF output and recovery secrets never -cross into ordinary Runtime routes. - -Agents use their own principals, keys, and short-lived grants. They do not -borrow human cookies or automate a person's passkey. High-risk effects still -require human review through the authority-owning surface. - -### 2. Build content availability - -Publishing packages an object, retains it under local policy, submits it to -configured availability providers, and records signed receipts. Calculating a -CID alone is not publication. - -The capsule-facing contract is `elastos://content/*`. IPFS, Kubo, Carrier, -cluster services, storage markets, and repair workers are provider -implementations under that boundary. Capsules should not know which backend -stored a block or which transport reached a peer. - -Availability grows in this order: - -- local packaging, verification, pinning, and unpublishing -- peer discovery, replication, and repair through configured providers -- quotas, abuse controls, health reporting, and operator alerts -- storage offers and settlement after receipts and enforcement are credible - -Receipts must distinguish local retention from independent remote availability. -They must not turn configured endpoints or test fixtures into a claim of a -production storage network. - -Publish, open, share, and repair remain operations on one content object. A -working copy can gain a published identity without becoming a different object -in the UI. Recipients verify it before retaining, mounting, or forking it. - -The contract and its limits live in -[Content availability](docs/CONTENT_AVAILABILITY.md). - -The first package-delivery milestone was planned around a signed, -CID-identified Qwen content capsule. That wording is historical: later -receipts record installed Qwen and SmolLM2 journeys on named Homes. Current -acceptance and target limits are in [state.md](state.md#current-model-foundation-23-september-2026-utc) -and [TASKS Now](TASKS.md#now). The intended experience uses Marketplace -discovery and exact handoff into Assistant, keeps the selected local model, -and provides recoverability-aware removal in System. The contract lives in -[Content capsule distribution](docs/CONTENT_CAPSULE_DISTRIBUTION.md). -Execution and proof dependencies live in -[TASKS Now](TASKS.md#now). - -### 3. Build Runtime-mediated protected content - -The target protected-content design uses the same effect path as ordinary -content: - -`viewer -> Runtime -> custody nodes (node-local rights) -> decrypt provider` - -Runtime will resolve the content object, check availability, load the exact -Chain policy, and ask each selected custody node to evaluate rights locally -before it returns a recipient-encrypted contribution. Runtime then creates a -scoped decrypt or render session and records the result. Each dependency has a -typed contract. Every invalid or unavailable dependency fails closed. Viewers -will receive scoped output or a scoped session, not content keys, custody shares, -chain RPC, Wallet authority, storage APIs, provider routes, network locations, -or credentials. - -The dependency order is contracts and cryptographic review, private provider -protocols, Wallet/Chain authority, durable Runtime coordination, then installed -mint-to-play acceptance. Activation requires evidence for the exact installed -artifacts, signed custody composition, deployed Chain reads and purchase, -replication and repair, restart, replay, tamper rejection and cleanup. - -The creator Runtime owns provisioning. A buyer Runtime must import and verify -an immutable listing and complete purchase and playback with its own Profile, -Wallet and device identity. Shared listing links precede global discovery and -public custody governance. - -PQ-hybrid confidentiality does not establish quantum-safe authority signatures. -Authorization policy and external cryptographic review are separate activation -gates. Current implementation evidence and outstanding decisions belong in -[state.md](state.md) and [TASKS.md](TASKS.md). - -Carrier remains transport only throughout that sequence. It carries -Runtime-selected traffic, but it does not define rights authority, custody -policy, or capsule-visible contract meaning. - -New protected objects should carry encrypted payload identity, rights policy, -algorithm metadata, provenance, availability receipts, declared viewer -interface, CEK commitment, and object-bound pool/epoch/committee-authorization -identities. Public metadata must not carry custody shares. `CustodyEnvelopeV1` -remains a private ephemeral provisioning bundle; durable custody storage is one -node-sealed share per selected custody node. The first product proof must use -three distinct custody provider identities and state roots for a 2-of-3 -committee. First minted objects use PQ-hybrid envelopes. Later cryptographic -successors use versioned envelopes and migration rules rather than creating -classical-only objects for later migration. -A permissioned key service can precede a public network, but production claims -require independent review and operational evidence. - -The canonical contracts and acceptance requirements are in -[Protected-content v1 contracts](docs/PROTECTED_CONTENT_CONTRACTS_V1.md), -[Protected content](docs/PROTECTED_CONTENT.md) and -[the acceptance checklist](docs/RUNTIME_REPO_USER_STORY_CHECKLIST.md). -Installed proof must connect Runtime, providers, Library, Wallet, Chain, -custody, decrypt output and the viewer through one authority path. - -### 4. Add wallet, DID, and node proofs behind Runtime authority - -Wallet accounts and DIDs can link proofs or identities to a Runtime principal. -They do not replace or mint it. - -Wallet Provider owns keys, linked accounts, signing, proof verification, and -approval execution. Runtime owns launch authority, capability checks, -orchestration, durable effect state, and audit. Connector capsules own only the -browser or device interaction needed to reach an external wallet. - -Wallet shows accounts and approval methods. Inbox reviews effects that need a -person. System shows policy and provider health. Apps receive typed results -after approval, never raw wallet or node RPC. - -Chain Provider owns typed reads, transaction preparation, broadcast, sync -status, and approved node lifecycle operations. Backend URLs, credentials, and -ports stay hidden from capsules. Price and oracle data also belongs behind a -provider contract with configured sources and auditable receipts. - -EID, `did:key`, chain accounts, external wallets, and future global names are -proof or resolver adapters. Each needs a verification policy. No adapter mints -a Runtime principal, session, or privileged capability on its own. - -See [Wallet Provider](docs/WALLET_PROVIDER.md) and -[Chain Provider](docs/CHAIN_PROVIDER.md). - -### 5. Build Spaces on one rooted object model - -Home is the friendly view of the active principal's local object root. Spaces -add mounted local, shared, and provider-backed views without exposing raw host -paths or other principals. - -Keep these concepts separate: - -- `localhost://` identifies Runtime-authorized local objects and mounted views -- `elastos://` identifies global content and capability resources -- a path is a projection over an object, not its immutable identity -- Public is a placement under a principal root, not automatic publication - -Spaces need typed object metadata, signed mutable heads, access policy, -watch and sync behavior, conflict handling, and provider health. Local editing -must remain fast and usable without a remote round trip. Carrier and providers -carry remote synchronization, sharing, and repair. - -The namespace contract lives in [Namespaces](docs/NAMESPACES.md). Open syntax -and provider questions stay in [deferred work](docs/DEFERRED_WORK.md). - -### 6. Establish signed capsule publication and installation - -An installable capsule needs identity for the complete package. A manifest or -entrypoint alone is insufficient. The install contract should bind: - -- the full bundle root and publisher -- signatures, revocation, and trust policy -- required and provided interface versions -- immutable dependencies and compatible Runtime versions -- state schema, migration rules, and install receipts -- update, rollback, removal, and availability policy - -Runtime should reject missing interfaces, incompatible versions, incomplete -packages, and untrusted publishers before launch. The same verified package -should be admissible on another compatible node without depending on the -original source checkout. - -Checked-in source packages and development web projections are build inputs, -not complete signed Digital Capsules. Development tooling may launch them from -a local source path, but it must not present that result as signed distribution, -portable installation, or Runtime admission. - -Marketplace can browse verified installed capsules before remote installation -exists. Remote install, update, and removal come only after the signed package -and receipt contract is complete. The install contract should define the CLI -and UI actions instead of the roadmap inventing a command in advance. - -Executable capsule isolation remains governed by -[Principle 18](PRINCIPLES.md#18-executable-capsules-are-isolated-execution-environments) -and [Capsule model](docs/CAPSULE_MODEL.md). - -The gateway already serves read-only content by CID at `/s//`. Once -capsule packages are signed and content-addressed, opening a capsule's CID -should load the capsule itself: the gateway resolves the package, verifies -it, and boots it with whatever host it declares — a game capsule loads its -emulator, and the Home GUI capsule loads the Home host first, the same way -today's launch path binds a viewer to its executable actor. A capsule's CID -then works as a shareable link to the running thing, not just to its files. -This depends on the signed package contract above; an unsigned directory -served by CID must stay inert content. - -### 7. Keep Home as the Runtime-owned front door - -Home is the default user surface. Runtime owns identity, object access, -capabilities, hosted-route policy, and capsule lifecycle. Home consumes those -contracts. System is a separate app launched through the same authority model. - -The main path should stay simple: - -1. sign in -2. find an app, person, or object -3. open it through Runtime authority -4. focus, close, or return Home cleanly - -The graphical and terminal shells should share Runtime facts and explicit shell -switching while owning different presentation surfaces. Neither shell gains -provider authority from its role. Host adapters for server, desktop, mobile, -and kiosk deployments must preserve the same Home and capsule contracts. - -Home should grow from an app launcher into an object browser with useful People, -Spaces, Apps, and System surfaces. It should hide provider names and transport -details unless the user opens technical inspection. - -The host boundary is defined in -[Home shell host contract](docs/HOME_SHELL_HOST_CONTRACT.md). - -### 8. Complete Browser behind one Browser, Net, and Exit contract - -Browser is one dangerous capsule that must remain contained. It is not the -platform and it must not become an ambient escape to host networking. - -Browser asks Runtime for a page and display session. Runtime authorizes Net and -Exit effects, selects a Browser Engine, and returns only the scoped page, -display, input, profile, and Wallet bridge surfaces. The engine has no direct -wallet, chain, storage, DNS, or off-box network authority. - -Every host adapter must implement the same Browser, Net, Exit, Wallet, and -lifecycle contracts. Native and microVM adapters are the preferred performance -path for local devices. Hosted engines are valid for web deployments only when -they pass the same isolation, audio, video, input, navigation, Wallet, -lifecycle, and manual UX gates. - -Browser profile state belongs to the active principal. Cookies, storage, -permissions, bookmarks, history, and downloads must not leak through a shared -engine profile. Recovery and migration should eventually cover that state under -the same principal-root policy as other personal objects. - -Web pages use a constrained Runtime-mediated wallet bridge. Account discovery, -chain selection, signing, and transaction effects retain their normal Wallet -and Inbox approval rules. The page receives the approved result, not Runtime -tokens, provider credentials, or connector authority. - -Product readiness requires real target evidence for frame continuity, audio, -input, resize, reconnect, concurrent use where claimed, explicit close, and -orphan cleanup. Diagnostic frames and source-only helpers cannot substitute for -the product display path. - -Browser work should stop at the contract/gate layer when the current host -cannot produce that target evidence. Do not keep tuning a hosted proof baseline -as if it were the product architecture. - -The hosted operator-image and durable service wrapper path now exists for -deployments that select Selkies. Its presence is packaging evidence, not -Browser product acceptance. - -[Browser capsule](docs/BROWSER_CAPSULE.md) owns the product contract. -[Browser VM target](docs/BROWSER_VM_TARGET.md) owns the substrate contract. -[Browser provider acceptance](docs/BROWSER_PROVIDER_BAKEOFF.md) compares hosted -display candidates. [Scripts](scripts/README.md) maps the executable proof and -operator commands; current acceptance and known limits belong in -[state.md](state.md). - -### 9. Build People and collaboration around durable objects - -People is the trust surface for profiles, contacts, requests, device bindings, -and service discovery. Chat owns direct, group, and public conversations. -Inbox owns review of contact, conversation, and capability requests. - -The identity split must stay explicit: - -- passkeys authorize a local principal; they are never the network identity; -- a principal-owned Profile DID is the stable person/contact identity; -- a device DID is endpoint and signing identity only; -- signed profile documents authorize the current delivery device bindings and - must be retained by highest accepted revision plus previous-hash linkage; -- direct conversations are scoped to Profile DIDs, not to device rotation. - -The product must distinguish people from devices and contacts from -conversations. Discovery is opt-in and describes its actual network scope. -Deterministic signed invites remain available as an explicit alternate -onboarding path. -Stable transport identifiers stay out of ordinary UI. - -Service offers can arrive through trusted People and Carrier relationships, but -People does not become the provider control plane. Enabling an offer creates or -selects a principal-scoped provider grant. Providers continue to enforce quota, -expiry, policy, and audit. - -Conversation objects need stable identity, participant and device bindings, -message order, attachment references, delivery state, and revocation policy. -Direct messages cannot be presented as private unless their transport and -storage enforce that claim. Local composition and reading should remain usable -without waiting for remote transport. - -Profile identity and transport routing must not drift: - -- the signed public profile document is the public identity truth; -- older or conflicting profile revisions must fail closed once a newer accepted - revision is retained; -- device revocation becomes effective when the newer signed profile revision is - observed, not by transport metadata alone; -- direct messages need both proofs: the device signature proves the sending - endpoint, and the retained signed profile document proves that device is - currently authorized for the participant Profile DID; -- Carrier/bootstrap configuration remains connectivity only and never becomes - person, contact, or conversation authority. - -The target contract carries authenticated messages, object updates, presence, -and attachments between runtimes. Runtime must verify the sender, capability, -replay policy, and destination object. Unauthenticated raw gossip does not meet -that contract. Compatibility bridges may map external systems into the target -contract, but they do not define the native model. - -See [People and conversations](docs/PEOPLE_CONVERSATIONS.md) for the target -model and ordered implementation slices, and -[deferred work](docs/DEFERRED_WORK.md#collaboration-and-messaging) for later outcomes. - -### 10. Keep release, install, share, and sites on truthful paths - -Release and installation should use one signed source and one component -identity. A public manifest must describe the artifacts that setup installs. -Update must fail closed when trust, checksums, interfaces, or required artifacts -do not match. - -Sharing and sites use the same object model as local content. A public link, -channel head, or site deployment is an explicit promotion of a verified object, -not a hidden side effect of moving a file. Activation and rollback must preserve -the prior good head until the new head is verified. - -Operator and debug paths can exist, but they remain secondary and clearly named. -Current release proof belongs in [State](state.md), open release work belongs in -[Tasks](TASKS.md), and command inventory belongs in -[Command matrix](docs/COMMAND_MATRIX.md). - -Version, package identity, channel head, and installed artifact are different -facts. Release tooling should derive them from one reviewed candidate and reject -partial publication. The version contract lives in -[Runtime versioning](docs/VERSIONING.md). - -## Later direction - -### Cross-platform Runtime and host adapters - -Server, desktop, mobile, and kiosk hosts present different surfaces over one -Runtime contract. Capsules do not branch on host mode. A host changes how a -surface appears, not identity, capability, object access, or provider effects. - -Use Linux as the full-runtime baseline until another platform earns equivalent -evidence. macOS, Windows, mobile, and remote hosts can support useful subsets -without claiming Linux or KVM parity. - -The first Windows product should be WSL2, not a rushed native Runtime. Keep the -Linux Runtime and provider stack inside WSL, add a small signed Windows launcher -for start, stop, update, health checks, and Home opening, and keep Runtime -state in the Linux filesystem with explicit storage budgets and cleanup. -Native Windows remains later host-adapter work behind the same Runtime and -Browser contracts. - -### Native object model and content-first design - -Packaging existing web apps helps bring software into ElastOS, but the native -model starts with objects. A photo, document, model, video, or published package -has a typed Runtime identity and one or more compatible viewers. Apps view and -edit objects through capabilities instead of owning isolated data silos. - -Keep three axes separate: - -- execution substrate, such as Component, native process, VM, or data -- product role, such as shell, app, viewer, provider, or content -- launch exposure and orchestration rights - -Home organizes around authorized objects and lets Runtime select a compatible -viewer. People owns relationships, Spaces owns mounted views, Apps shows -installed tools, and System owns policy and diagnostics. A role, filename -extension, or manifest field never grants authority. - -Marketplace is a catalog over signed capsule packages. Remote mutation waits -for package identity, publisher trust, interface compatibility, applicable -rights, and rollback receipts. - -Free games, GGUF models, and similar downloads should enter as signed content -capsules identified by bundle CID. A community-controlled ElastOS catalog can -index those CIDs while availability providers retain and replicate the bytes. -External repositories such as Hugging Face belong behind optional gateway -provider capsules that import approved artifacts into the same native content -path. They must not become direct Home URLs or a parallel install system. - -### Identity evolution - -Keep `did:key` as the device and node foundation, not the human account root. -Local people remain Runtime principals unlocked by passkeys. Add persona -separation, EID linking, credentials, global names, and cross-device recovery -only through explicit proof and resolver contracts. - -### Stronger protection and attestation - -Future work includes stronger package attestation, reproducible-build policy, -TPM or TEE evidence, protected-content provider deployment, and public key -services. Each feature extends the existing capability and object contracts. -It must not create a separate trust root or expose key material to apps. - -### AI and operator surfaces - -AI providers and agents need explicit identity, capabilities, budget policy, -data access, and audit. Hosted credentials stay inside configured providers. -Local and hosted models use the same typed Runtime contract. Chat Completions -and Responses adapters have fixture coverage; real configured provider -compatibility and installed lifecycle proof remain open. -Installed provider acceptance precedes service publication. Runtime publishes -the operator-selected signed offer and owns principal-scoped grants. The -destination Runtime authorizes each remote request, and Carrier transports only -the route that Runtime selected. Local-engine sharing and hosted-API sharing -have separate acceptance tracks in [Model provider](docs/MODEL_PROVIDER.md). -Carrier ingress bounds and destination-owned remote authority precede peer -acceptance. Hosted-sharing policy and full Jetson target proof remain requested -work with credential, terms, access and hardware prerequisites, even when source -review publication occurs earlier. - -Operator tools should derive decisions from source, signed artifacts, and -machine-readable evidence. Durable docs should record contracts and current -truth, not terminal transcripts or machine-specific paths. +GitHub issues own scope, order, status and acceptance. This page links planned +outcomes; it does not assign work or set release dates. +[Principles](PRINCIPLES.md) and [Architecture](docs/ARCHITECTURE.md) define the +constraints and responsibility boundaries. + +## Release and installation + +- [Install, sign in and recover (#88)](https://github.com/Elacity/elastos-runtime/issues/88) + and [signed update (#89)](https://github.com/Elacity/elastos-runtime/issues/89). +- [Installed journeys in CI (#150)](https://github.com/Elacity/elastos-runtime/issues/150) + and [release acceptance (#93)](https://github.com/Elacity/elastos-runtime/issues/93). +- [Publisher key rotation (#213)](https://github.com/Elacity/elastos-runtime/issues/213) + and [signed third-party capsules over Carrier (#217)](https://github.com/Elacity/elastos-runtime/issues/217). + +## Product work + +- [Local AI (#84)](https://github.com/Elacity/elastos-runtime/issues/84) + and [hosted AI with owner approval (#85)](https://github.com/Elacity/elastos-runtime/issues/85). +- [Chat and People (#86)](https://github.com/Elacity/elastos-runtime/issues/86) + and [Browser and Wallet on Mac (#87)](https://github.com/Elacity/elastos-runtime/issues/87). +- [Jetson support (#90)](https://github.com/Elacity/elastos-runtime/issues/90) + and [Home on phones (#92)](https://github.com/Elacity/elastos-runtime/issues/92). +- [Capsule isolation (#173)](https://github.com/Elacity/elastos-runtime/issues/173) + and [user keys and data the host cannot read (#209)](https://github.com/Elacity/elastos-runtime/issues/209). +- [Protected content (#91)](https://github.com/Elacity/elastos-runtime/issues/91), + including [external cryptographic review (#48)](https://github.com/Elacity/elastos-runtime/issues/48). +- [Resident WASM components (#181)](https://github.com/Elacity/elastos-runtime/issues/181) + and [VM capsules beyond Browser (#182)](https://github.com/Elacity/elastos-runtime/issues/182). diff --git a/SECURITY.md b/SECURITY.md index 7eae3db73..8447d0cd7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,6 +4,52 @@ If you find a security vulnerability, please report it privately via [GitHub Security Advisories](https://github.com/Elacity/elastos-runtime/security/advisories/new). Do not open a public issue. +Do not describe an unfixed issue in a public issue, pull request, commit message, or branch name. + +## Current isolation and target boundary + +First-party apps run as web projections in the browser's opaque sandboxed +frames. Runtime checks each app's signed launch token and actor before it performs an effect. +Home can currently obtain every app's capability, so a compromised Home can +reach those apps' authority. The target limits Home to delegation and gives each +app a separate, revocable capability. The WASM Component authoring path runs in +Wasmtime with memory and fuel limits and Runtime Bus hostcalls. Components run +inside the Runtime process: separate linear memories, but the same operating +system process as Runtime keys. Installed Homes admit only release-path +capsules matched by signed CID receipts and capsules signed by the release +publisher, so third-party executable capsules need key-free, confined +worker processes before they are admitted +([World Computer plan](https://github.com/Elacity/elastos-runtime/issues/285)). + +Providers run as native operating-system processes with the Runtime user's +rights. Only the model provider is partly confined. The trusted shell helper +also runs as a native host process. The web Terminal is disabled by default; +host developer mode and closed guest registration are required to enable it. +An enabled Terminal runs commands with the host user's rights. + +The seed operator can read hosted data, wallet keys and recovery material. +Passkeys control sign-in; stored data and keys remain accessible to the Runtime +account and root while Home is locked. Protection against hosted operators and +root, and against other software or OS users while a self-hosted Home is locked, +is the target of [hosted protection](https://github.com/Elacity/elastos-runtime/issues/209) +and [locked Home protection](https://github.com/Elacity/elastos-runtime/issues/210). +An unlocked self-hosted Home trusts its owner and their host software. Recovery +from a stolen device or profile key requires a new identity. + +The [isolation plan](https://github.com/Elacity/elastos-runtime/issues/173) +records the remaining gates. Source checks describe this source tree. Accepted +installed proof binds the exact Runtime, components and app assets to the +journeys tested on that device. + +## Stored keys and recovery + +Keys are stored next to the data they protect. Full data-home backups include +all keys. Protect those backups and your Recovery Kit as secrets. Encryption +with keys stored on the same host leaves those secrets accessible to its +operator. Use hosted accounts only for public demos; keep wallets, private data +and recovery material on your own device until hosted protection passes its +acceptance gate. Independent review and installed proof remain security gates. + ## Open Findings The following security-relevant findings remain open in the current runtime and are documented here for transparency. @@ -22,32 +68,92 @@ key and revocation state are committed atomically, operators must verify the persisted key and restart result instead of treating command completion as a durable rotation receipt. -### Host-plane Carrier providers use Runtime admission +### Runtime owns Carrier admission **Severity:** Medium -**Files:** `elastos/crates/elastos-server/src/carrier_service.rs` +**Files:** `elastos/crates/elastos-server/src/carrier.rs`, `elastos/crates/elastos-server/src/carrier_service.rs` +**Status:** Open (host-plane envelope) + +Runtime identifies each Carrier peer by its endpoint key. A key alone gives no +authority. A Home serves a peer's `content/fetch` only for a CID that an active +publication on it lists, and a Library publication only to a peer whose +authenticated device belongs to an accepted contact of the person who +published it, as receiving Homes take files only from contacts. A protected +listing's sealed payload is served to any peer; opening it needs the key +release a purchase grants. A pin is only local storage: files received in +Chat, models and withdrawn publications stay pinned, and pinned alone is never +served to peers. Unpublish withdraws the record, which stops new transfers of +that file at once, unless another file still shared on this Home (yours or +another person's) has the same contents. The pin stays until a later cleanup. +A Home answers a peer's read in one message and checks again just before +sending it, so a read under way when the publication is withdrawn is refused +on the same terms. Bytes already sent can't be recalled. +Over HTTP, an ordinary Home's raw CID routes (`/content/`, `/ipfs/`, +`/s/`) answer only its own Home and app sessions; a seed keeps its public +CID gateway. +Only a node that serves publisher content (a seed) answers the raw +`content_fetch` byte operation or serves without these checks. In this +release a seed accepts no new copies from other Homes; copies it already holds +stay. A Home accepts a new copy from a peer only if the owner gave that peer +the `content.replica` permission; copies it already holds stay. The owner +trusts such a peer like an own device: it can ask the Home to pin content, +import complete content and read storage status. An import pins only the CID +it was asked for and never removes an existing pin. No peer can publish, +remove or repair content on a Home or a seed. Peers cannot use the +availability provider. A Home signs an availability announcement only from its +own pin state. Peers cannot push or read gossip messages directly. Only topics +that a Home joins keep messages, to a maximum of 100 topics. A granted peer's +`ensure` (once the pin succeeds) announces the CID and joins its topic, so a +granted peer shares that limit with the Home's own topics. A granted peer's +`import_exact`, `admission` and `status`, and any peer's `fetch`, join no +topic. No peer can push a whole object with `import_object`. + +Host-process provider capsules use a raw operation and path envelope without a +capsule capability token. Runtime owns admission for this trusted provider +class. Manifests and audit output must show this boundary. The envelope does +not grant capsule authority. + +### I/O bridge line reads are not bounded while reading + +**Files:** `elastos/crates/elastos-runtime/src/handler/io_bridge.rs` **Status:** Open -Host-plane Carrier service requests use a raw operation/path envelope without -a capsule capability-token field. Runtime owns admission for this trusted -provider class. Its trust boundary must remain explicit in manifests and audit -output; the envelope is not an independent grant of capsule authority. +The I/O bridge rejects complete lines above 1 MiB, but its line readers +allocate before that check. Size checks after reading do not bound memory use +or an incomplete frame's lifetime. Add bounds while reading, with oversized +and slow-frame tests. -### Request framing remains incompletely bounded +### Whole-object Carrier fetch replies are held in memory -**Files:** `elastos/crates/elastos-server/src/carrier.rs`, `elastos/crates/elastos-runtime/src/handler/io_bridge.rs` -**Status:** Open +**Files:** `elastos/crates/elastos-server/src/carrier.rs` +**Status:** Open ([#341](https://github.com/Elacity/elastos-runtime/issues/341)) + +A whole-object content fetch reply arrives as one line. It is refused while +reading once it passes one 200 MiB file as base64 (about 268 MiB), the largest +file Runtime downloads whole. Only two such fetches run at once, and one per +peer. + +### Contact requests by DID -The incoming Carrier request handler reads a line before parsing without a -request-size cap or read deadline at that boundary. The I/O bridge rejects -complete lines above 1 MiB, but its line readers allocate before that check. -Size checks after reading do not bound memory use or an incomplete frame's -lifetime. Add bounds while reading, with oversized and slow-frame tests; -the Carrier integration task is tracked in [deferred work](docs/DEFERRED_WORK.md#retained-source-integration). +**Severity:** Low +**Files:** `elastos/crates/elastos-server/src/collaboration_discovery_runtime.rs`, `elastos/crates/elastos-server/src/collaboration_contact_store.rs` +**Status:** Open ([#86](https://github.com/Elacity/elastos-runtime/issues/86)) + +Anyone who has a Profile's DID can send it one contact request through the +seed's Community node, whether or not that Profile is visible in Discovery. +The node learns which Profile asked which and holds the requester's signed +Profile; it learns nothing more about the recipient until the recipient +answers in Inbox. Only the device that signed a request, answer or mailbox +read may submit it, and the recipient's Home checks every request and answer +itself. Profiles and devices are free to create, so the per-sender and +per-device limits bound one identity only: many new identities can fill one +person's 16 request slots on the node until those requests expire after +24 hours, and that person's other requests wait meanwhile. Leave Community +stops all requests. ## Resolved Findings -These findings are fixed in the current branch but remain listed as security history because they shaped the runtime contract. +These findings are resolved in source but remain listed as security history because they shaped the runtime contract. ### I/O bridge parse-size check @@ -59,15 +165,29 @@ The I/O bridge rejects complete request lines above 1 MiB before parsing. The old `carrier_bridge.rs` has been removed. This resolved parse-size check does not close the read-time framing gap above. -## Architecture +### Carrier and operator peer reads + +**Files:** `elastos/crates/elastos-server/src/carrier.rs`, `elastos/crates/elastos-server/src/operator_control.rs` +**Status:** Fixed -The runtime enforces a capability-based security model: +Lines from peers are read with a size cap and a deadline, and longer lines are +refused before they are buffered. Incoming Carrier requests allow one provider +request or one gossip message plus envelope, within 10 seconds. Operator +requests, read before their signature is checked, allow 64 KiB within 10 +seconds. Replies are capped by what the request can return: a full gossip +topic for a pull, one importable object for a provider call, update metadata +for an operator answer. Provider replies share a 256 MiB in-flight budget. +Whole-object content fetch replies allow one 200 MiB file as base64; the open +item above tracks streaming them. Relays close after five minutes without bytes +in either direction, and stream acknowledgements have deadlines. + +## Architecture -- **Capsules** run sandboxed (WASM or microVM) with zero ambient authority -- **Capability tokens** are Ed25519-signed by the runtime and validated on every resource access -- **12-point token validation** covers version, signature, issuer, caller, action, resource, epoch, revocation, timing, use-count, and classification -- **Audit events** are emitted at every security-critical operation -- **Carrier** authenticates transport endpoints. Runtime verifies product - identity and signed message authority before exposing typed app projections. +Runtime validates signed capability tokens against the caller, action, +resource, epoch, revocation and token constraints. It checks principal and +session authority separately. Carrier authenticates transport endpoints; +Runtime verifies product identity and signed message authority before exposing +typed app projections. These checks complement the current browser boundary +and do not establish provider process confinement or a separate Home authority. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for the full trust model. diff --git a/TASKS.md b/TASKS.md deleted file mode 100644 index 9d51809fc..000000000 --- a/TASKS.md +++ /dev/null @@ -1,60 +0,0 @@ -# Tasks - -This is the ordered open release queue. The -[0.7.1 release plan](https://app.notion.com/p/3d6b682adcca81948f78d12abcd677b9) -owns release scope and acceptance. [State](state.md#current-model-foundation-24-september-2026-utc) -owns exact source, installed and public evidence. -[Deferred and future work](docs/DEFERRED_WORK.md) has open work outside this -queue. Dated queues remain available at commit `f0fae26f` and in the linked -audits; they do not assign a current target or owner. - -Model work in J3, MA, AI, CR and SEC1 is the implementation priority. Codex owns the current bounded SEC1 source closeout. The next installed proof is one isolated Mac Home exact-origin Inbox approval, validation, model effect, End and zero later dispatch on matching artifacts. The J3 two-Home End/refusal proof follows that authority gate. J1 was the first journey published for review under decision D1; it remains open. Record a missing publisher, authority, resource or exact approval and advance independent work without changing the acceptance criterion. - -## Now - -Each row requires a receipt with source/tree, dirty patch, built and installed hashes, target identity, operation, result and next proof. Ports are observations, not installation IDs. Preserve human Homes, keys, pins, data and the 10% disk floor. Publication and public mutation require separate exact-candidate approval. - -| Order | Open gate and owner | Next proof and stop condition | -| --- | --- | --- | -| 1 | **J3 / MA1 / MA4 / AI1–AI3 / M01–M06 — shared local model.** Execution owner: Codex; use the named isolated target lease. | The matching-build isolated pair passed Consumer seed-route SmolLM2 Get, exact Owner catalogue/grant and one bound remote Assistant reply. Owner Inbox End propagated to Consumer Services as Denied and removed the shared model; one stale-selected attempt caused zero new Owner service/provider runs but Assistant reported unknown acceptance. A fresh Assistant chat then offered only Consumer's local SmolLM2: the ordinary post-End path has no approved grant to route a new create to Owner. A separate fresh Mac receiver now passed one ordinary signed SmolLM2 Get from the isolated Owner holder over direct Carrier: all 144,835,448 package bytes match the signed manifest, and Marketplace/System show the model ready. [State](state.md#current-model-foundation-24-september-2026-utc) records both results and their limits. Keep authenticated Owner pre-dispatch refusal open; choose and review an acceptance-compatible bounded experiment before another invocation. Then prove second-principal denial, restart dispatch, safe Stop, failed transfer, retry and recovery with small fixtures. Receiver inference and restart reuse remain separate. Before claiming wider readiness, clear or correctly present stale `activation_pending` after startup recovery. Stop on a missing grant, resource floor or unmatched artifact. | -| 2 | **SEC1 / Jev — hosted network and human authority.** Execution owner: Codex for the bounded connection-authority source slice; wider implementation unassigned. | The existing exact-route Inbox decision and broker pass their unpaid fixtures. Source commit `e2e228df` stages a stable provider connection before key validation, stores versioned exact-origin authority in the existing protected decision store, and keeps staged setup visible across reloads. System lets the owner keep or discard a staged key; source tests cover that lifecycle, the discard/validation race, truthful validation errors, same-origin effects, key rotation, End and a fresh request. The broker now marks its own refusals, so Assistant can distinguish pending, denied, ended or generic Runtime refusal from a provider 401/403; unpaid socket tests cover the run message and sequential post-End zero dispatch. This is source evidence only. Connection configuration means provider, exact HTTPS origin, credential/account, trust root and Runtime's route/effect policy version; a selected model remains an effect parameter checked separately at dispatch. The temporary Mac operator route remains for existing Homes. **Linux hosted dispatch remains paused**, and Mac/Linux installed consent, broker, socket confinement and shared-run proof remain open. The final grant check and outbound send can overlap a concurrent Inbox End; coordinate that admission with End before claiming strict zero dispatch after End. Prove validation/save, Assistant and shared owner runs, redirects, DNS/TLS, active jobs, cancel/retry and unknown-create reconciliation on matching Mac and Linux artifacts. Pin OpenRouter and Venice to exact selectors, terms/privacy facts, limits and an unknown-cost stop rule before provider calls. **Jev/Approval Lens is optional for 0.7.1, off by default, and visible only for a compatible OpenRouter/Jev connection.** If shipped, prove typed advice on a real Inbox request and a human decision. Prove zero external dispatch before approval and after End. Keep hosted dispatch paused where authority or confinement is absent. | -| 3 | **J3 / MA4 / AI1–AI3 — owner-funded hosted sharing.** Execution owner: Unassigned; depends on SEC1. | On matching isolated owner and consumer builds, prove a fresh six-hour exact-offer Marketplace/Services/Inbox grant, a consumer Assistant turn and a bound terminal owner-funded hosted reply over the approved direct route. The owner keeps the API key. Verify pause, End, refusal, second-principal denial, Busy/retry and loss recovery. A refusal needs zero new dispatch; uncertain settlement stays Outcome unknown. Keep provider calls within the existing $1 total cap. Then obtain signed-in product and human acceptance on the named candidate. | -| 4 | **MA1 / MA3 / AI / CR1–CR2 — remaining J3 model acceptance.** Execution owner: Unassigned. | With named publisher authority, prove signed catalogue succession and both Qwen acquisition orders, full Qwen distribution/benchmark and a terminal reply, retention and sole-copy wording, frozen-provider cancellation, independent holders and direct Carrier boundaries. Record transfer time, cold start, peak RAM and token rate on a named target; define pass criteria before benchmark acceptance. Classify the two extra public admission aliases and later runs before treating them as user journeys. Obtain the seed plan/capacity facts before sustained inference; one bounded reply is already in State. CR3 remains a required C6 Carrier gate before relay support can be claimed. Use SmolLM2 or small fixtures for failure tests. Complete each original criterion or record an explicit scope decision. | -| 5 | **J1 / J2 — install, sign in and update.** Execution owner: Unassigned; Anders owns human acceptance. | Qualify signed Linux x86-64, Linux ARM64 and Apple Silicon fresh installs, visible passkey action/progress/recovery help, Profile and Recovery Kit. Prove the actual stamped 0.7.0 → 0.7.1 first hop, interruption, rollback and preserved identity, content and drafts. J1 remains open until human sign-in and shared Home acceptance pass. J1 is still the first review-publication journey under D1. | -| 6 | **J6 / CH1–CH8 — Community Chat.** Execution owner: Unassigned. | Use the existing Profile, Chat, Content/Carrier and Inbox contracts. On the named signed candidate, acquire Chat through Marketplace, join with explicit room authority, exchange signed messages, recover retained public-room history after an offline interval, and preserve membership, draft and unread state through restart and update. Prove the bounded two-Home journey and human narrow-screen use. Mailboxes, attachments and private groups remain in the [future backlog](docs/DEFERRED_WORK.md#collaboration-identity-and-carrier-boundary). | -| 7 | **J4 / B01–B16 — Browser.** Execution owner: Unassigned. | Reconcile exact local and remote artifacts, then complete both required placements with input, audio/video, actual viewer reload, Wallet, profile and authority checks, all close effects, measured responsiveness and the B16 campaign. Preserve source versus installed proof. The [Browser contract](docs/BROWSER_ACCEPTANCE.md) owns detailed criteria. | -| 8 | **J5 / MC1–MC3 — protected media.** Execution owner: Unassigned; Irzhy supplies contributor inputs. | Review the selected PR60/59/62 heads and authority cutover, then prove signed media package/discovery/acquisition and a bounded two-principal Base mainnet mint → list → buy → open → play → close journey. Obtain an external crypto-review owner and disposition. The [protected-content contract](docs/PROTECTED_CONTENT.md) and Notion J5 hold full criteria. | -| 9 | **C5–C7 — freeze, accept, release.** Execution owner: Unassigned; Anders approves exact publication. | Assemble one reviewed candidate. C6 requires signed three-platform J1–J6, CH1–CH8, SA1–SA6, CA1, CR1–CR3, applicable SEC1–SEC3, first-hop and capsule update/recovery, shared Home/app regression, Browser qualification, independent review and human acceptance. Turn the [journey audit register](docs/audits/ElastOS-Home-Journey-Audit.xlsx) into a pre-release gate without replacing installed/human verdicts. Review the PR15 `has_access_by_content_id` selector with J5. C7 needs explicit approval before merge, tag, push or public cutover. | - -## Browser maturity workstream - -The [Browser acceptance contract](docs/BROWSER_ACCEPTANCE.md) defines B01–B16. These open boxes track full qualification; a partial source or installed result does not check them. J4 in [Now](#now) is the current execution handoff. One Browser/Net/Exit ABI governs local and remote placements. The current Selkies path is a proof baseline, not product audio acceptance. The operator decision report supplies a structured `next_action`; do not spend more branch time tuning Selkies as the product path when a hosted or native target is required. - -- [ ] [B01: One Browser contract and an explicit support matrix](docs/BROWSER_ACCEPTANCE.md#b01). -- [ ] [B02: A fresh installation opens a usable Browser](docs/BROWSER_ACCEPTANCE.md#b02). -- [ ] [B03: Every failure has an actionable diagnosis](docs/BROWSER_ACCEPTANCE.md#b03). -- [ ] [B04: People and agents have equal Browser capabilities](docs/BROWSER_ACCEPTANCE.md#b04). -- [ ] [B05: Input and navigation feel like a browser](docs/BROWSER_ACCEPTANCE.md#b05). -- [ ] [B06: Sessions recover from normal interruptions](docs/BROWSER_ACCEPTANCE.md#b06). -- [ ] [B07: One slow session cannot block the others](docs/BROWSER_ACCEPTANCE.md#b07). -- [ ] [B08: Remote Engine is an ordinary Runtime service](docs/BROWSER_ACCEPTANCE.md#b08). -- [ ] [B09: Exit has identical local and remote network semantics](docs/BROWSER_ACCEPTANCE.md#b09). -- [ ] [B10: Prove independent placement of UI, Engine, and Exit](docs/BROWSER_ACCEPTANCE.md#b10). -- [ ] [B11: Meet measured responsiveness and media budgets](docs/BROWSER_ACCEPTANCE.md#b11). -- [ ] [B12: Profiles and user state survive safely](docs/BROWSER_ACCEPTANCE.md#b12). -- [ ] [B13: Complete daily browser workflows and accessibility](docs/BROWSER_ACCEPTANCE.md#b13). -- [ ] [B14: Preserve authority, privacy, and bounded revocation](docs/BROWSER_ACCEPTANCE.md#b14). -- [ ] [B15: Updates and repair preserve a working installation](docs/BROWSER_ACCEPTANCE.md#b15). -- [ ] [B16: Release only from repeatable product evidence](docs/BROWSER_ACCEPTANCE.md#b16). - -## Open verification controls - -The checks below stay open with their owning journey. They are not additional product scope. Use `scripts/public-install-operator-smoke.sh`, `scripts/public-install-identity-smoke.sh`, `scripts/audit-linux-runtime-portability.sh` and the provisional `scripts/protected-content-provider-contract-smoke.sh` at their applicable installed/release boundaries. Keep source/local Carrier setup proof green with `scripts/local-carrier-setup-smoke.sh`; publish the approved version's binary/artifact set so no-override public installed-path smokes use current code. - -For J4, retain `scripts/browser-native-supervisor-smoke.sh`, `scripts/browser-native-proxy-engine-smoke.sh`, `scripts/browser-native-supervisor-proxy-smoke.sh`, `scripts/browser-native-operator-config.mjs`, `scripts/browser-native-target-preflight.sh` and `scripts/wallet-connector-transaction-smoke.mjs` for their target proofs. Use artifact-aware `scripts/browser-provider-runbook.mjs --hosted-bakeoff/--native-preflight --manual-ux` and `scripts/browser-provider-runbook-smoke.sh`; `scripts/browser-objective-audit.mjs` remains the completion gate. Freeze new Browser provider implementation until the current blockers are cleared. The deferred provider comparison and current-host stop condition remain in [future work](docs/DEFERRED_WORK.md). - -Remote Carrier Exit two-runtime evidence must cite the exact source/exit runtime DIDs and endpoint evidence, an installed artifact readiness report, evidence for route readiness, installed artifact readiness and cleanup, and a local Browser machine-proof artifact must cite the reviewed route target or target host. Compose Inspector, typed Runtime authority, route-readiness, operator evidence, Browser handoff and redacted artifacts are required before a remote-path claim. - -## Deferred open work - -[Deferred and future work](docs/DEFERRED_WORK.md) preserves open follow-up outside this execution queue. It does not change the Required/Optional/Later labels in Notion. Keep first-party capsule projection validation covered when that work resumes. The production multi-peer availability/storage market and Component Bus v2 remain future work, with their exact open clauses in the linked backlog. diff --git a/capsules/_shared/elastos-drawer.js b/capsules/_shared/elastos-drawer.js new file mode 100644 index 000000000..dfad1a2eb --- /dev/null +++ b/capsules/_shared/elastos-drawer.js @@ -0,0 +1,130 @@ +/* ElastOS UI — phone push drawer (the Assistant's saved-chats pattern). + * + * On the phone stage (html[data-el-form-factor="phone"], see elastos-theme.js) + * a capsule's sidebar leaves the layout and becomes a drawer: the sidebar + * slides in from the leading edge and the main view slides aside with a + * rounded edge; tapping that view, Escape, or picking an item closes it. On + * tablet and desktop this module does nothing and the sidebar stays a column. + * + * Markup contract (no capsule JS needed): + * - - - + + + diff --git a/capsules/chat-room/browser/style.css b/capsules/chat-room/browser/style.css index fa3f41526..8d4896b26 100644 --- a/capsules/chat-room/browser/style.css +++ b/capsules/chat-room/browser/style.css @@ -84,6 +84,24 @@ p { font-weight: 600; } +.reconnect { + flex: 0 0 auto; + align-self: flex-start; + margin: 0 1rem 0.55rem; +} + +.community-presence-request { + flex: 0 0 auto; + align-self: flex-start; + margin: 0 1rem 0.55rem; +} + +.community-presence-hidden { + flex: 0 0 auto; + margin: 0 0.5rem 0 0; + white-space: nowrap; +} + .chat-sidebar, .chat-people, .messages { @@ -136,7 +154,7 @@ p { flex-direction: column; gap: 0.45rem; /* Unified-sidebar chrome paints the traffic lights over the first 52px; - capsule-local value on purpose (see home-entropy-check: Chat/Inbox). */ + capsule-local value on purpose. */ padding: 52px 10px 14px; overflow: auto; border-right: 1px solid color-mix(in srgb, var(--line) 55%, transparent); @@ -355,15 +373,13 @@ body[data-room-access-mode="gateway"][data-room-session-active="false"] .browser } .browser-access-copy, -.conversation-join-copy, .browser-access-form, .stack { display: grid; gap: 0.45rem; } -.browser-access-copy h2, -.conversation-join-copy h2 { +.browser-access-copy h2 { font-size: 1.05rem; font-weight: 700; } @@ -385,23 +401,6 @@ body[data-room-access-mode="gateway"][data-room-session-active="false"] .browser gap: 0.4rem; } -.conversation-join { - display: grid; - gap: 0.55rem; - margin: 0.75rem 1rem 0; - padding: 0.85rem 0.9rem; - border: 1px solid var(--line); - border-radius: 8px; - background: var(--panel-strong); -} - -.conversation-join-copy p { - color: var(--muted); - font-size: 0.78rem; - line-height: 1.4; -} - -.conversation-join-form, .join-link-output { display: grid; grid-template-columns: minmax(0, 1fr) auto; @@ -783,6 +782,17 @@ button.secondary { background: var(--accent-soft); } +.link-body a, +.message-link { + cursor: pointer; +} + +.message-link { + color: inherit; + text-decoration: underline; + overflow-wrap: anywhere; +} + .attachment-card { padding: 0.55rem 0.6rem; border: 1px solid color-mix(in srgb, var(--line) 70%, transparent); @@ -828,6 +838,36 @@ button.secondary { text-decoration: none; } +/* A Library file Community is about to post publicly, and how it went. */ +.library-post { + display: grid; + flex: 0 0 auto; + gap: 0.45rem; + margin: 0 0.75rem 0.55rem; + padding: 0.75rem 0.9rem; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--el-surface-raised); + overflow-wrap: anywhere; +} + +.library-post h2 { + font-size: 0.95rem; +} + +#library-post-lines { + display: grid; + gap: 0.25rem; + font-size: 0.85rem; +} + +.library-post-actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 0.45rem; +} + /* Published compact composer and emoji popover. */ .composer { display: flex; @@ -926,6 +966,18 @@ button.secondary { font-weight: 650; } +/* Home's phone stage keeps the composer easy to tap in either orientation. */ +:root[data-el-form-factor="phone"] .composer-icon, +:root[data-el-form-factor="phone"] .composer-field .composer-emoji-toggle { + width: 44px; + height: 44px; +} + +:root[data-el-form-factor="phone"] .composer-field #message-input, +:root[data-el-form-factor="phone"] #send-button { + min-height: 44px; +} + .emoji-popover { position: absolute; bottom: calc(100% + 0.45rem); @@ -960,11 +1012,6 @@ button.secondary { outline: none; } -body[data-room-access-mode="shell"][data-room-join-visible="true"] .messages, -body[data-room-access-mode="shell"][data-room-join-visible="true"] .composer { - display: none; -} - body[data-room-access-mode="shell"][data-room-session-active="false"] .roster-head { display: none; } @@ -1043,3 +1090,119 @@ body[data-room-access-mode="shell"][data-room-session-active="false"] .roster-he animation: none; } } + +/* Profile cards: any name with a card opens one. */ +.participant-clickable, +.message-sender-link { + cursor: pointer; +} + +.participant-clickable:hover, +.participant-clickable:focus-visible { + background: var(--accent-soft); +} + +.message-sender-link:hover, +.message-sender-link:focus-visible { + text-decoration: underline; +} + +.participant-clickable:focus-visible, +.message-sender-link:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +.participant-card { + position: relative; + display: grid; + justify-items: center; + gap: 0.5rem; + margin: 0.75rem; + padding: 1rem 1rem 1.1rem; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--panel-strong); + color: var(--ink); + text-align: center; +} + +.participant-card[hidden] { + display: none; +} + +.participant-card-avatar { + width: 3rem; + height: 3rem; + flex-basis: 3rem; + font-size: 1.1rem; +} + +.participant-card-name { + margin: 0; + font-size: 1rem; + font-weight: 700; + overflow-wrap: anywhere; +} + +.participant-card-state { + margin: 0; + color: var(--muted); + font-size: 0.85rem; +} + +.participant-card-action { + min-width: 8rem; +} + +.participant-card-close { + position: absolute; + top: 0.35rem; + right: 0.45rem; + padding: 0.1rem 0.45rem; + border: 0; + background: transparent; + color: var(--muted); + font-size: 1.1rem; + line-height: 1; + cursor: pointer; +} + +/* Day separators between messages from different local days. */ +.day-separator { + display: flex; + align-items: center; + gap: 0.75rem; + margin: 0.75rem 0 0.25rem; + color: var(--muted); + font-size: 0.75rem; + font-weight: 600; + list-style: none; +} + +.day-separator::before, +.day-separator::after { + content: ""; + flex: 1; + border-top: 1px solid var(--line); +} + +/* Unread direct conversations in the rail. */ +.conversation-choice { + position: relative; +} + +.conversation-choice.unread .conversation-choice-name { + font-weight: 800; +} + +.conversation-unread-dot { + position: absolute; + top: 50%; + right: 0.75rem; + width: 0.55rem; + height: 0.55rem; + border-radius: 999px; + background: var(--accent); + transform: translateY(-50%); +} diff --git a/capsules/content-block-graph-provider/Cargo.lock b/capsules/content-block-graph-provider/Cargo.lock index 6fd4a60d8..a33c42f4a 100644 --- a/capsules/content-block-graph-provider/Cargo.lock +++ b/capsules/content-block-graph-provider/Cargo.lock @@ -300,9 +300,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.40" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", @@ -324,9 +324,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -498,14 +498,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.7", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.7" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] diff --git a/capsules/content-block-graph-provider/src/main.rs b/capsules/content-block-graph-provider/src/main.rs index 56eb5e920..6cbb8e051 100644 --- a/capsules/content-block-graph-provider/src/main.rs +++ b/capsules/content-block-graph-provider/src/main.rs @@ -19,10 +19,7 @@ const GRAPH_ENCODING: &str = "base64-car"; const DEFAULT_MAX_GRAPH_BYTES: usize = 64 * 1024 * 1024; const HTTP_TIMEOUT: Duration = Duration::from_secs(30); const LARGE_HTTP_TIMEOUT: Duration = Duration::from_secs(300); -const PROVIDER_VERSION: &str = match option_env!("ELASTOS_RELEASE_VERSION") { - Some(version) => version, - None => concat!(env!("CARGO_PKG_VERSION"), "-dev"), -}; +const PROVIDER_VERSION: &str = env!("CARGO_PKG_VERSION"); #[derive(Debug, Deserialize)] struct CoordFile { @@ -458,19 +455,19 @@ fn read_coord_file(data_dir: &Path) -> Option { serde_json::from_str(&content).ok() } +/// Refreshes `last_used` and keeps every other field ipfs-provider wrote, +/// such as `offline`, which marks a daemon it may keep borrowing. fn update_coord_last_used(data_dir: &Path) { - let Some(mut coord) = read_coord_file(data_dir) else { + let path = coord_file_path(data_dir); + let Some(mut coord) = fs::read(&path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(Value::is_object) + else { return; }; - coord.last_used = now_unix_secs(); - let path = coord_file_path(data_dir); - let Ok(json) = serde_json::to_string_pretty(&json!({ - "kubo_pid": coord.kubo_pid, - "api_port": coord.api_port, - "gateway_port": coord.gateway_port, - "started_at": coord.started_at, - "last_used": coord.last_used, - })) else { + coord["last_used"] = json!(now_unix_secs()); + let Ok(json) = serde_json::to_string_pretty(&coord) else { return; }; let tmp = path.with_extension("tmp"); @@ -486,6 +483,44 @@ fn now_unix_secs() -> u64 { .as_secs() } +fn main() { + eprintln!("{PROVIDER_ID}: starting v{PROVIDER_VERSION}"); + let stdin = io::stdin(); + let mut stdout = io::stdout(); + let mut provider = ContentBlockGraphProvider::default(); + + for line in stdin.lock().lines() { + let line = match line { + Ok(line) => line, + Err(err) => { + eprintln!("{PROVIDER_ID} read error: {err}"); + break; + } + }; + if line.trim().is_empty() { + continue; + } + + let request = match serde_json::from_str::(&line) { + Ok(request) => request, + Err(err) => { + let response = error("invalid_request", &err.to_string()); + writeln!(stdout, "{}", serde_json::to_string(&response).unwrap()).unwrap(); + stdout.flush().unwrap(); + continue; + } + }; + let is_shutdown = matches!(request, Request::Shutdown); + let response = provider.handle(request); + writeln!(stdout, "{}", serde_json::to_string(&response).unwrap()).unwrap(); + stdout.flush().unwrap(); + if is_shutdown { + break; + } + } + + eprintln!("{PROVIDER_ID}: exiting"); +} #[cfg(test)] mod tests { use super::*; @@ -596,43 +631,20 @@ mod tests { }); assert_eq!(response["code"], "cid_mismatch"); } -} - -fn main() { - eprintln!("{PROVIDER_ID}: starting v{PROVIDER_VERSION}"); - let stdin = io::stdin(); - let mut stdout = io::stdout(); - let mut provider = ContentBlockGraphProvider::default(); - - for line in stdin.lock().lines() { - let line = match line { - Ok(line) => line, - Err(err) => { - eprintln!("{PROVIDER_ID} read error: {err}"); - break; - } - }; - if line.trim().is_empty() { - continue; - } - let request = match serde_json::from_str::(&line) { - Ok(request) => request, - Err(err) => { - let response = error("invalid_request", &err.to_string()); - writeln!(stdout, "{}", serde_json::to_string(&response).unwrap()).unwrap(); - stdout.flush().unwrap(); - continue; - } - }; - let is_shutdown = matches!(request, Request::Shutdown); - let response = provider.handle(request); - writeln!(stdout, "{}", serde_json::to_string(&response).unwrap()).unwrap(); - stdout.flush().unwrap(); - if is_shutdown { - break; - } + #[test] + fn last_used_refresh_keeps_the_offline_mark() { + let data_dir = temp_dir("coord-offline"); + fs::write( + coord_file_path(&data_dir), + r#"{"kubo_pid":1,"api_port":2,"gateway_port":3,"started_at":4,"last_used":5,"offline":true}"#, + ) + .unwrap(); + update_coord_last_used(&data_dir); + let coord: Value = + serde_json::from_slice(&fs::read(coord_file_path(&data_dir)).unwrap()).unwrap(); + assert_eq!(coord["offline"], true); + assert_eq!(coord["api_port"], 2); + assert!(coord["last_used"].as_u64().unwrap() > 5); } - - eprintln!("{PROVIDER_ID}: exiting"); } diff --git a/capsules/custody-provider/Cargo.lock b/capsules/custody-provider/Cargo.lock index 1595d7174..2c859d044 100644 --- a/capsules/custody-provider/Cargo.lock +++ b/capsules/custody-provider/Cargo.lock @@ -321,9 +321,9 @@ dependencies = [ [[package]] name = "crypto-bigint" -version = "0.7.5" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +checksum = "6bb08299a6046833a879ace115697f12fd2bd6c8d3e93c909ffc9e0738e7cae0" dependencies = [ "cpubits", "ctutils", @@ -368,9 +368,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.2" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0" dependencies = [ "cmov", "subtle", @@ -529,7 +529,7 @@ dependencies = [ [[package]] name = "elastos-auth" -version = "0.7.1" +version = "2.0.0" dependencies = [ "chrono", "hex", @@ -541,7 +541,7 @@ dependencies = [ [[package]] name = "elastos-identity" -version = "0.7.1" +version = "2.0.0" dependencies = [ "aes-gcm", "anyhow", @@ -566,7 +566,7 @@ dependencies = [ [[package]] name = "elastos-protected-content-contracts" -version = "0.7.1" +version = "2.0.0" dependencies = [ "curve25519-dalek 5.0.0", "ed25519-dalek", @@ -582,7 +582,7 @@ dependencies = [ [[package]] name = "elastos-protected-content-custody" -version = "0.7.1" +version = "2.0.0" dependencies = [ "aes", "aes-gcm", @@ -608,7 +608,7 @@ dependencies = [ [[package]] name = "elastos-protected-content-provider-contracts" -version = "0.7.1" +version = "2.0.0" dependencies = [ "elastos-protected-content-contracts", "serde", @@ -618,7 +618,7 @@ dependencies = [ [[package]] name = "elastos-protected-content-rights" -version = "0.7.1" +version = "2.0.0" dependencies = [ "ed25519-dalek", "elastos-protected-content-contracts", @@ -656,7 +656,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" dependencies = [ "base16ct 1.0.0", - "crypto-bigint 0.7.5", + "crypto-bigint 0.7.6", "crypto-common 0.2.2", "ff 0.14.0", "group 0.14.0", @@ -1704,7 +1704,7 @@ version = "6.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bfc736cfd88115aedb95ba84bc2d428fe351e92a56f69fce090af301402d91" dependencies = [ - "crypto-bigint 0.7.5", + "crypto-bigint 0.7.6", "elliptic-curve 0.14.1", "elliptic-curve-tools", "ff 0.14.0", diff --git a/capsules/custody-provider/src/lib.rs b/capsules/custody-provider/src/lib.rs index c93dd9fd6..de7c16490 100644 --- a/capsules/custody-provider/src/lib.rs +++ b/capsules/custody-provider/src/lib.rs @@ -21,6 +21,9 @@ const TRUSTED_RUNTIME_ISSUER_FILE: &str = "trusted-runtime-issuer"; const NODE_CUSTODY_SECRET_FILE: &str = "node-custody-secret"; const NODE_SIGNING_KEY_FILE: &str = "node-signing-key"; const DATA_ROOT_DIR: &str = "data"; +// The Runtime keeps custody state at DATA/protected-content/custody-provider/ +// (elastos-server INACTIVE_CUSTODY_ROOT); that layout names the data root. +const STATE_PARENT_IN_DATA: &str = "protected-content/custody-provider"; #[derive(Debug, Clone, PartialEq, Eq)] pub enum CustodyProviderStateRootError { @@ -437,7 +440,16 @@ fn validate_absolute_path_syntax(path: &Path) -> Result<(), CustodyProviderState Ok(()) } +/// The Runtime data directory holding `path`, when `path` follows the custody +/// state layout; otherwise none, and every component keeps the strict rule. +fn data_root_of(path: &Path) -> Option<&Path> { + path.ancestors() + .find(|ancestor| ancestor.ends_with(STATE_PARENT_IN_DATA)) + .and_then(|parent| parent.parent()?.parent()) +} + fn validate_existing_path_components(path: &Path) -> Result<(), CustodyProviderStateRootError> { + let data_root = data_root_of(path); let mut current = PathBuf::new(); for component in path.components() { match component { @@ -449,7 +461,9 @@ fn validate_existing_path_components(path: &Path) -> Result<(), CustodyProviderS if metadata.file_type().is_symlink() { return Err(CustodyProviderStateRootError::MissingOrUnsafe); } - validate_component_owner_and_mode(&metadata)?; + let shared = data_root.is_some_and(|data| data.starts_with(¤t)); + let below_data = data_root.is_some_and(|data| current.starts_with(data) && !shared); + validate_component_owner_and_mode(&metadata, shared, below_data)?; } Component::Prefix(_) | Component::CurDir | Component::ParentDir => { return Err(CustodyProviderStateRootError::MissingOrUnsafe) @@ -557,8 +571,15 @@ fn validate_owner_mode_and_links( Ok(()) } +/// `shared` marks the data directory and its ancestors: they keep their +/// owner's group permissions (Ubuntu umask 002 makes ~/.local group-writable). +/// Directories below the data directory (`below_data`) are ElastOS's own and +/// stay closed to group writes, sticky or not. Outside the custody layout no +/// data directory is known and the original rule applies to every folder. fn validate_component_owner_and_mode( metadata: &fs::Metadata, + shared: bool, + below_data: bool, ) -> Result<(), CustodyProviderStateRootError> { #[cfg(unix)] { @@ -570,9 +591,12 @@ fn validate_component_owner_and_mode( return Err(CustodyProviderStateRootError::MissingOrUnsafe); } let mode = metadata.mode() & 0o7777; - let writable_by_others = mode & 0o022 != 0; + let refused = if shared { 0o002 } else { 0o022 }; + let writable_by_others = mode & refused != 0; + // The sticky exception (root-owned /tmp, a user's sticky folder) is for + // OS folders only: below DATA a sticky folder is still refused. let sticky = mode & 0o1000 != 0; - if writable_by_others && !sticky { + if writable_by_others && (below_data || !sticky) { return Err(CustodyProviderStateRootError::MissingOrUnsafe); } } @@ -669,6 +693,67 @@ mod tests { fs::set_permissions(path, fs::Permissions::from_mode(0o700)).unwrap(); } + #[cfg(unix)] + #[test] + fn path_components_accept_group_writable_data_ancestors_only() { + let temp = tempfile::tempdir().unwrap(); + let temp_root = fs::canonicalize(temp.path()).unwrap(); + let shared = temp_root.join("local"); + let data = shared.join("elastos"); + let custody = data.join("protected-content/custody-provider"); + let root = custody.join("inactive"); + owner_only_dir(&root); + owner_only_dir(&custody); + owner_only_dir(&data.join("protected-content")); + fs::set_permissions(&data, fs::Permissions::from_mode(0o770)).unwrap(); + fs::set_permissions(&shared, fs::Permissions::from_mode(0o775)).unwrap(); + validate_existing_path_components(&root).unwrap(); + validate_existing_path_components(&custody).unwrap(); + // Below the data root ElastOS owns the folders; group write stays refused. + for below in [&data.join("protected-content"), &custody] { + fs::set_permissions(below, fs::Permissions::from_mode(0o770)).unwrap(); + assert!(matches!( + validate_existing_path_components(&root), + Err(CustodyProviderStateRootError::MissingOrUnsafe) + )); + fs::set_permissions(below, fs::Permissions::from_mode(0o700)).unwrap(); + } + // Outside the custody layout no data root is known: every folder stays strict. + let other = data.join("other"); + owner_only_dir(&other); + assert!(validate_existing_path_components(&other).is_err()); + // Sticky does not excuse group or world write below DATA. + for below in [&data.join("protected-content"), &custody, &root] { + for mode in [0o1770, 0o1777] { + fs::set_permissions(below, fs::Permissions::from_mode(mode)).unwrap(); + assert!(matches!( + validate_existing_path_components(&root), + Err(CustodyProviderStateRootError::MissingOrUnsafe) + )); + } + fs::set_permissions(below, fs::Permissions::from_mode(0o700)).unwrap(); + } + // A /tmp-like sticky folder above DATA stays accepted. + fs::set_permissions(&shared, fs::Permissions::from_mode(0o1777)).unwrap(); + validate_existing_path_components(&root).unwrap(); + fs::set_permissions(&shared, fs::Permissions::from_mode(0o777)).unwrap(); + assert!(matches!( + validate_existing_path_components(&root), + Err(CustodyProviderStateRootError::MissingOrUnsafe) + )); + fs::set_permissions(&shared, fs::Permissions::from_mode(0o755)).unwrap(); + // Outside the custody layout a /tmp-like sticky folder is accepted as + // before; without the sticky bit the same folder is refused. + let sticky_tmp = temp_root.join("tmp"); + let state = sticky_tmp.join("state"); + owner_only_dir(&state); + fs::set_permissions(&sticky_tmp, fs::Permissions::from_mode(0o1777)).unwrap(); + validate_existing_path_components(&state).unwrap(); + fs::set_permissions(&sticky_tmp, fs::Permissions::from_mode(0o777)).unwrap(); + assert!(validate_existing_path_components(&state).is_err()); + fs::set_permissions(&sticky_tmp, fs::Permissions::from_mode(0o755)).unwrap(); + } + #[cfg(target_os = "linux")] #[test] fn rename_without_replacement_preserves_collision_and_moves_new_root() { diff --git a/capsules/custody-provider/src/main.rs b/capsules/custody-provider/src/main.rs index 3d7150482..455f734ff 100644 --- a/capsules/custody-provider/src/main.rs +++ b/capsules/custody-provider/src/main.rs @@ -34,10 +34,7 @@ use elastos_protected_content_rights::{ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; -const PROVIDER_VERSION: &str = match option_env!("ELASTOS_RELEASE_VERSION") { - Some(version) => version, - None => concat!(env!("CARGO_PKG_VERSION"), "-dev"), -}; +const PROVIDER_VERSION: &str = env!("CARGO_PKG_VERSION"); const INIT_ERROR_CODE: &str = "invalid_config"; const REQUEST_ERROR_CODE: &str = "invalid_request"; const BACKEND_ERROR_CODE: &str = "backend_unavailable"; diff --git a/capsules/decrypt-provider/Cargo.lock b/capsules/decrypt-provider/Cargo.lock index d30c47e84..9a2d74d92 100644 --- a/capsules/decrypt-provider/Cargo.lock +++ b/capsules/decrypt-provider/Cargo.lock @@ -57,9 +57,10 @@ dependencies = [ [[package]] name = "elastos-common" -version = "0.7.1" +version = "2.0.0" dependencies = [ "hex", + "libc", "serde", "serde_json", "sha2", diff --git a/capsules/decrypt-provider/src/main.rs b/capsules/decrypt-provider/src/main.rs index f0e5c271d..8055e6bba 100644 --- a/capsules/decrypt-provider/src/main.rs +++ b/capsules/decrypt-provider/src/main.rs @@ -13,10 +13,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::io::{self, BufRead, Write}; -const PROVIDER_VERSION: &str = match option_env!("ELASTOS_RELEASE_VERSION") { - Some(version) => version, - None => concat!(env!("CARGO_PKG_VERSION"), "-dev"), -}; +const PROVIDER_VERSION: &str = env!("CARGO_PKG_VERSION"); #[derive(Debug, Deserialize)] #[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] diff --git a/capsules/did-provider/Cargo.lock b/capsules/did-provider/Cargo.lock index 90c5728f2..db8927f03 100644 --- a/capsules/did-provider/Cargo.lock +++ b/capsules/did-provider/Cargo.lock @@ -347,9 +347,10 @@ dependencies = [ [[package]] name = "elastos-common" -version = "0.7.1" +version = "2.0.0" dependencies = [ "hex", + "libc", "serde", "serde_json", "sha2", @@ -367,7 +368,7 @@ dependencies = [ [[package]] name = "elastos-identity" -version = "0.7.1" +version = "2.0.0" dependencies = [ "aes-gcm", "anyhow", diff --git a/capsules/did-provider/src/main.rs b/capsules/did-provider/src/main.rs index 60ef9e100..dae6dc441 100644 --- a/capsules/did-provider/src/main.rs +++ b/capsules/did-provider/src/main.rs @@ -23,10 +23,7 @@ use zeroize::Zeroize; const NONCE_LEN: usize = 12; const DID_RECOVERY_PROOF_SCHEMA: &str = "elastos.did.recovery-proof/v1"; const DID_RECOVERY_MAX_TTL_SECS: u64 = 15 * 60; -const PROVIDER_VERSION: &str = match option_env!("ELASTOS_RELEASE_VERSION") { - Some(version) => version, - None => concat!(env!("CARGO_PKG_VERSION"), "-dev"), -}; +const PROVIDER_VERSION: &str = env!("CARGO_PKG_VERSION"); // === Wire protocol types === @@ -450,10 +447,7 @@ impl DidProvider { Ok(did) => did, Err(e) => return Response::error("invalid_did", &e), }; - let owner_did = match self.signing_key.as_ref() { - Some(signing_key) => Some(encode_signing_key_did(signing_key)), - None => None, - }; + let owner_did = self.signing_key.as_ref().map(encode_signing_key_did); Response::ok(serde_json::json!({ "did": persona_did, @@ -577,8 +571,7 @@ fn validate_did_recovery_request( recovery: &DidRecoveryPayload<'_>, now: u64, ) -> Result<(), String> { - decode_did_key(recovery.did) - .map_err(|e| format!("invalid DID recovery subject: {e}"))?; + decode_did_key(recovery.did).map_err(|e| format!("invalid DID recovery subject: {e}"))?; validate_token_like_id(recovery.principal_id, "principal_id")?; validate_principal_localhost_root(recovery.principal_id, recovery.localhost_root)?; validate_token_like_id(recovery.protector_id, "protector_id")?; @@ -807,9 +800,7 @@ mod tests { fn test_resolve_rejects_overlong_did_via_shared_codec() { let signing_key = SigningKey::generate(&mut OsRng); let provider = DidProvider::new(); - assert_invalid_did(provider.resolve(&overlong_did(&encode_signing_key_did( - &signing_key, - )))); + assert_invalid_did(provider.resolve(&overlong_did(&encode_signing_key_did(&signing_key)))); } #[test] diff --git a/capsules/documents/browser/README.md b/capsules/documents/browser/README.md index f7996e418..054bb7d9f 100644 --- a/capsules/documents/browser/README.md +++ b/capsules/documents/browser/README.md @@ -2,10 +2,11 @@ `Documents` is the built-in capsule for local-first Markdown documents. -- Open it from Home to create, edit, save, and publish Markdown documents. +- Open it from Home to create, edit and save Markdown and text documents. To + share a document with your contacts, use Share with contacts in Library. - Runtime binds provider requests to the signed Home launch-token principal. - Documents are addressed as `localhost://ElastOS/Documents/`. - Working copies live under the Runtime principal root: `localhost://Users//Documents/...`. -- Publish and unpublish update content availability through the provider. The - capsule does not publish directly to IPFS. +- Unpublish withdraws an earlier publication through the provider. The capsule + does not publish directly to IPFS. diff --git a/capsules/documents/browser/documents.js b/capsules/documents/browser/documents.js new file mode 100644 index 000000000..97ba32179 --- /dev/null +++ b/capsules/documents/browser/documents.js @@ -0,0 +1,2760 @@ +import { createHomeNavigationClient } from "/apps/home/home-navigation-client.js"; + +const state = { + homeToken: new URLSearchParams(window.location.hash.replace(/^#/, "")).get("home_token") || "", + initialDocDid: new URLSearchParams(window.location.search).get("doc") || "", + initialCid: new URLSearchParams(window.location.search).get("cid") || "", + // A shared file's stated name: its title and default save name only. + initialName: sharedFileName(new URLSearchParams(window.location.search).get("name")), + initialLibraryObjectUri: + new URLSearchParams(window.location.search).get("objectUri") || + new URLSearchParams(window.location.search).get("object_uri") || + "", + initialView: new URLSearchParams(window.location.search).get("view") || "", + initialIntent: new URLSearchParams(window.location.search).get("intent") || "", + mode: "share", + documents: [], + current: null, + currentSessionId: 0, + dirty: false, + // "Save automatically"; Home remembers the person's choice (off by default). + autosave: false, + workspaceView: "write", + inspectorView: "preview", + sidebarCollapsed: false, + filterQuery: "", + pendingConfirmation: null, + pendingChatAttachmentId: "", +}; +// Launched by Home: framed, with the Home token Home put in the launch +// address. Decided once here; the current address may change later. +const DOCUMENTS_INSIDE_HOME = window.top !== window && !!state.homeToken; +const homeOrigin = new URLSearchParams(window.location.search).get("home_origin") || ""; +const homeNavigation = createHomeNavigationClient({ homeToken: state.homeToken, homeOrigin }); +const DOCUMENTS_WINDOW_CLOSE_REQUEST_TYPE = + "elastos.documents.window-close.request/v1"; +const DOCUMENTS_WINDOW_CLOSE_RESULT_TYPE = + "elastos.documents.window-close.result/v1"; +const DOCUMENTS_PREFERENCES_REQUEST_TYPE = + "elastos.documents.preferences.request/v1"; +const DOCUMENTS_PREFERENCES_SET_TYPE = + "elastos.documents.preferences.set/v1"; +const DOCUMENTS_PREFERENCES_TYPE = + "elastos.documents.preferences/v1"; + +const elements = { + documentsShell: document.getElementById("documents-shell"), + documentsList: document.getElementById("documents-list"), + sidebarSearch: document.getElementById("sidebar-search"), + titleInput: document.getElementById("title-input"), + sidebarToggle: document.getElementById("sidebar-toggle"), + sidebarShow: document.getElementById("sidebar-show"), + saveButton: document.getElementById("save-button"), + saveToLibrary: document.getElementById("save-to-library"), + autosaveToggle: document.getElementById("autosave-toggle"), + saveAsButton: document.getElementById("save-as-button"), + deleteButton: document.getElementById("delete-button"), + statusRow: document.getElementById("status-row"), + statusText: document.getElementById("status-text"), + statusAction: document.getElementById("status-action"), + findBar: document.getElementById("find-bar"), + findInput: document.getElementById("find-input"), + findCount: document.getElementById("find-count"), + findPrev: document.getElementById("find-prev"), + findNext: document.getElementById("find-next"), + findClose: document.getElementById("find-close"), + contextMenu: document.getElementById("context-menu"), + editor: document.getElementById("editor"), + preview: document.getElementById("preview"), + previewPanel: document.getElementById("preview-panel"), + outlinePanel: document.getElementById("outline-panel"), + newButton: document.getElementById("new-document"), + modeWrite: document.getElementById("mode-write"), + modeSplit: document.getElementById("mode-split"), + toolbarMore: document.querySelector(".toolbar-more"), + moreButton: document.getElementById("more-button"), + modeRead: document.getElementById("mode-read"), + panePreview: document.getElementById("pane-preview"), + paneOutline: document.getElementById("pane-outline"), + shareShell: document.getElementById("share-shell"), + shareSidebar: document.getElementById("share-sidebar"), + shareSidebarMeta: document.getElementById("share-sidebar-meta"), + shareDocList: document.getElementById("share-doc-list"), + shareTopline: document.getElementById("share-topline"), + shareTitle: document.getElementById("share-title"), + shareSubtitle: document.getElementById("share-subtitle"), + sharePreview: document.getElementById("share-preview"), + saveAsModal: document.getElementById("save-as-modal"), + saveAsForm: document.getElementById("save-as-form"), + saveAsTitleInput: document.getElementById("save-as-title-input"), + saveAsFileInput: document.getElementById("save-as-file-input"), + saveAsCancel: document.getElementById("save-as-cancel"), + confirmModal: document.getElementById("confirm-modal"), + confirmTitle: document.getElementById("confirm-title"), + confirmMessage: document.getElementById("confirm-message"), + confirmCancel: document.getElementById("confirm-cancel"), + confirmSecondaryAction: document.getElementById("confirm-secondary-action"), + confirmAction: document.getElementById("confirm-action"), +}; + +let autosaveTimerId = 0; +let saveInFlight = null; +let autosaveQueued = false; +let queuedSaveTarget = null; +let savedWorkingCopy = null; +let saveRecovery = null; +let documentSelectionSequence = 0; +let pendingHomeWindowCloseTarget = null; +let homeChromeReady = false; +let lastHomeMenuManifestSignature = ""; +let findMatches = []; +let findIndex = -1; +let previewFindMarks = []; +let contextMenuDocDid = ""; + +function escapeHtml(value) { + return value + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/\"/g, """); +} + +function hasExactKeys(value, expectedKeys) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return false; + } + const actual = Object.keys(value).sort(); + const expected = [...expectedKeys].sort(); + return actual.length === expected.length && + actual.every((key, index) => key === expected[index]); +} + +function renderInlineMarkdown(text) { + const tokens = /`([^`]+)`|\*\*([^*]+)\*\*|\*([^*]+)\*|\[([^\]]+)\]\(([^)]+)\)/g; + let html = ""; + let offset = 0; + for (const match of text.matchAll(tokens)) { + html += escapeHtml(text.slice(offset, match.index)); + if (match[1] !== undefined) { + html += "" + escapeHtml(match[1]) + ""; + } else if (match[2] !== undefined) { + html += "" + renderInlineMarkdown(match[2]) + ""; + } else if (match[3] !== undefined) { + html += "" + renderInlineMarkdown(match[3]) + ""; + } else { + html += renderMarkdownLink(match[5], renderInlineMarkdown(match[4])); + } + offset = match.index + match[0].length; + } + return html + escapeHtml(text.slice(offset)); +} + +// Inside Home rendered Markdown has no href at all: any navigation would +// replace the Documents frame (or its address), and a replaced frame cannot +// answer Home's close request. A web link (same origin included) asks Home +// through `activateMarkdownLink` (#436, as Chat); a link to a place in the +// document scrolls there without touching the address; every other link +// (relative paths, elastos://, localhost://, refused addresses) is plain +// text. Outside Home links are normal anchors. `DOCUMENTS_INSIDE_HOME` is +// decided once at launch, never from the current address. +function renderMarkdownLink(value, labelHtml) { + const href = markdownHref(value); + if (!DOCUMENTS_INSIDE_HOME) { + return '' + labelHtml + ""; + } + if (/^https?:\/\//i.test(href)) { + return '' + labelHtml + ""; + } + if (href.length > 1 && href.startsWith("#")) { + return '' + labelHtml + ""; + } + return "" + labelHtml + ""; +} + +// Browsers drop tabs and newlines from an address and read "\" as "/", so +// spellings such as "/\host", "//host" or "\\host" would reach another +// host; any address with a control character or backslash is refused. +function markdownHref(value) { + const href = String(value || "").trim(); + if (/[\u0000-\u001f\u007f\\]/.test(href)) { + return "#"; + } + return /^(https?:\/\/|elastos:\/\/|localhost:\/\/|#|\/(?!\/)|\.{1,2}\/)/i.test(href) ? href : "#"; +} + +function headingSlug(text, number) { + const slug = String(text || "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + return (slug || "section") + "-" + number; +} + +function renderMarkdownDocument(source, options) { + const interactiveTasks = !!(options && options.interactiveTasks); + const inline = (text) => renderInlineMarkdown(text); + const lines = String(source || "").replace(/\r\n/g, "\n").split("\n"); + const blocks = []; + const outline = []; + let index = 0; + let headingIndex = 0; + + while (index < lines.length) { + const line = lines[index]; + + if (/^```/.test(line)) { + const fenceInfo = line.slice(3).trim(); + const language = /^[A-Za-z0-9+#-]+$/.test(fenceInfo) ? fenceInfo : ""; + const code = []; + index += 1; + while (index < lines.length && !/^```/.test(lines[index])) { + code.push(escapeHtml(lines[index])); + index += 1; + } + index += 1; + blocks.push('
" + code.join("\n") + "
"); + continue; + } + + if (/^(\*{3,}|-{3,}|_{3,})\s*$/.test(line)) { + blocks.push("
"); + index += 1; + continue; + } + + const heading = /^(#{1,6})\s+(.+)$/.exec(line); + if (heading) { + headingIndex += 1; + const title = heading[2].trim(); + const id = headingSlug(title, headingIndex); + blocks.push("' + inline(title) + ""); + outline.push({ depth: heading[1].length, title: title, id: id }); + index += 1; + continue; + } + + if (/^>\s?/.test(line)) { + const quote = []; + while (index < lines.length && /^>\s?/.test(lines[index])) { + quote.push(inline(lines[index].replace(/^>\s?/, ""))); + index += 1; + } + blocks.push("

" + quote.join("
") + "

"); + continue; + } + + if (/^[-*]\s+\[( |x|X)\]\s+/.test(line)) { + const items = []; + while (index < lines.length && /^[-*]\s+\[( |x|X)\]\s+/.test(lines[index])) { + const taskLine = lines[index]; + const taskMatch = /^[-*]\s+\[( |x|X)\]\s+([\s\S]+)$/.exec(taskLine); + const checked = !!taskMatch && String(taskMatch[1]).toLowerCase() === "x"; + const label = taskMatch ? taskMatch[2] : taskLine.replace(/^[-*]\s+/, ""); + const checkbox = interactiveTasks + ? '" + : '' + inline((checked ? "[x] " : "[ ] ") + label) + ""; + items.push('
  • ' + checkbox + "
  • "); + index += 1; + } + blocks.push("
      " + items.join("") + "
    "); + continue; + } + + if (/^[-*]\s+/.test(line)) { + const items = []; + while (index < lines.length && /^[-*]\s+/.test(lines[index])) { + items.push("
  • " + inline(lines[index].replace(/^[-*]\s+/, "")) + "
  • "); + index += 1; + } + blocks.push("
      " + items.join("") + "
    "); + continue; + } + + if (/^\d+\.\s+/.test(line)) { + const items = []; + while (index < lines.length && /^\d+\.\s+/.test(lines[index])) { + items.push("
  • " + inline(lines[index].replace(/^\d+\.\s+/, "")) + "
  • "); + index += 1; + } + blocks.push("
      " + items.join("") + "
    "); + continue; + } + + if (/^\|.*\|$/.test(line) && index + 1 < lines.length && /^\|?[\s:-]+\|[\s|:-]*$/.test(lines[index + 1])) { + const headerCells = line.split("|").slice(1, -1).map((cell) => "" + inline(cell.trim()) + ""); + index += 2; + const rows = []; + while (index < lines.length && /^\|.*\|$/.test(lines[index])) { + const cells = lines[index].split("|").slice(1, -1).map((cell) => "" + inline(cell.trim()) + ""); + rows.push("" + cells.join("") + ""); + index += 1; + } + blocks.push("" + headerCells.join("") + "" + rows.join("") + "
    "); + continue; + } + + if (!line.trim()) { + index += 1; + continue; + } + + const paragraph = []; + while (index < lines.length && lines[index].trim() && !/^(#{1,6})\s+/.test(lines[index]) && !/^```/.test(lines[index]) && !/^>\s?/.test(lines[index]) && !/^[-*]\s+/.test(lines[index]) && !/^\d+\.\s+/.test(lines[index]) && !/^(\*{3,}|-{3,}|_{3,})\s*$/.test(lines[index])) { + paragraph.push(inline(lines[index])); + index += 1; + } + if (!paragraph.length) { + blocks.push("

    " + inline(line) + "

    "); + index += 1; + continue; + } + blocks.push("

    " + paragraph.join("
    ") + "

    "); + } + + return { + html: blocks.join("\n"), + outline: outline, + }; +} + +function documentUri(docDid) { + return docDid ? "localhost://ElastOS/Documents/" + docDid : ""; +} + +function documentIdentity(document) { + if (!document) { + return ""; + } + if (isLibraryFileProjection(document)) { + return "library:" + String(document.library_object_uri || document.document_uri || document.working_copy_uri || ""); + } + if (document.doc_did) { + return "document:" + String(document.doc_did); + } + return "draft"; +} + +// The same rule as Home's sharedFileName (home-external-link.js, which names +// the Runtime limit it follows): no path separators, control characters or +// leading dots, at most 200 UTF-8 bytes, cut before the extension. +function sharedFileName(value) { + if (typeof value !== "string" || /[/\\]/.test(value)) return ""; + const name = value.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").replace(/^[.\s]+/, "").trimEnd(); + const encoder = new TextEncoder(); + const bytes = (text) => encoder.encode(text).length; + if (bytes(name) <= 200) return name; + const dot = name.lastIndexOf("."); + const extension = dot > 0 && bytes(name.slice(dot)) <= 16 ? name.slice(dot) : ""; + let stem = ""; + let used = bytes(extension); + for (const character of extension ? name.slice(0, dot) : name) { + used += bytes(character); + if (used > 200) break; + stem += character; + } + stem = stem.replace(/[\s.]+$/, ""); + return stem ? stem + extension : ""; +} + +function baseName(uri) { + const clean = String(uri || "").replace(/\/+$/, ""); + const name = clean.split("/").pop() || "Document"; + try { + return decodeURIComponent(name); + } catch (_error) { + return name; + } +} + +function looksLikeTextContent(contentType, buffer) { + const lower = String(contentType || "").toLowerCase(); + if ( + lower.startsWith("text/") || + lower.includes("json") || + lower.includes("markdown") || + lower.includes("xml") || + lower.includes("javascript") + ) { + return true; + } + const bytes = new Uint8Array(buffer); + if (bytes.length === 0) { + return true; + } + const sample = bytes.subarray(0, Math.min(bytes.length, 4096)); + if (sample.includes(0)) { + return false; + } + try { + new TextDecoder("utf-8", { fatal: true }).decode(sample); + return true; + } catch (_error) { + return false; + } +} + +function isTextMimeType(mime) { + const lower = String(mime || "").toLowerCase(); + return lower.startsWith("text/") || + lower.includes("json") || + lower.includes("markdown") || + lower.includes("xml") || + lower.includes("javascript"); +} + +function dataUrlToUtf8(dataUrl) { + const value = String(dataUrl || ""); + const match = /^data:([^;,]*)(;base64)?,([\s\S]*)$/i.exec(value); + if (!match) { + throw new Error("Chat attachment payload is not a data URL."); + } + if (match[2]) { + return base64ToUtf8(match[3] || ""); + } + return decodeURIComponent(match[3] || ""); +} + +function isLibraryFileProjection(document) { + return !!document && !!document.library_object_uri; +} + +function isDraftDocument(document) { + return !!document && !document.doc_did && !isLibraryFileProjection(document); +} + +let draftSerial = 0; + +function createDraftDocument() { + draftSerial += 1; + return { + doc_did: "", + document_uri: "", + draft_key: "draft-" + draftSerial, + title: "", + file_name: "", + working_copy_uri: "", + body: "", + created_at: 0, + updated_at: 0, + latest_published_cid: null, + }; +} + +// A list row's title: the document's title, or a plain file's name, without a +// .md or .txt ending, the same rule for both. +function listTitle(item) { + const title = String(item.title || "").trim(); + return title.replace(/\.(md|txt)$/i, "") || title || "Untitled"; +} + +// The folder a file sits in, when that is a folder inside Documents. +function listFolder(item) { + const parts = String(item.file_name || "").split("/"); + return parts.length > 1 ? parts[parts.length - 2] : ""; +} + +// When a row last changed, short: "Today 4:41 PM", "Yesterday", "Oct 26" +// (with the year when it is not this year). +function shortTime(timestamp, now = new Date()) { + if (!timestamp) { + return ""; + } + const date = new Date(timestamp * 1000); + const startOfDay = (value) => new Date(value.getFullYear(), value.getMonth(), value.getDate()).getTime(); + const daysAgo = Math.round((startOfDay(now) - startOfDay(date)) / 86_400_000); + if (daysAgo === 0) { + return "Today " + date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" }); + } + if (daysAgo === 1) { + return "Yesterday"; + } + return date.toLocaleDateString(undefined, date.getFullYear() === now.getFullYear() + ? { month: "short", day: "numeric" } + : { month: "short", day: "numeric", year: "numeric" }); +} + +function preferredWorkspaceView(view) { + return view === "read" ? "read" : view === "split" ? "split" : "write"; +} + +function clearStatus() { + elements.statusText.textContent = ""; + elements.statusRow.classList.add("hidden"); + elements.statusAction.classList.add("hidden"); +} + +// A Library file whose save failed (most often because it changed in another +// window) can be reloaded from what is stored, here or from its list row. +function libraryFileSaveFailed() { + return isLibraryFileProjection(state.current) && state.dirty && + saveRecovery?.phase === "library" && isCurrentSessionTarget(saveRecovery.target); +} + +async function loadSavedLibraryVersion() { + const current = state.current; + if (!isLibraryFileProjection(current)) { + return; + } + const confirmed = await confirmInCapsule({ + title: "Load the saved version?", + message: "Your edits to " + (current.file_name || "this file") + " will be lost.", + confirmLabel: "Load saved version", + danger: true, + }); + if (!confirmed || state.current !== current) { + return; + } + unsavedDocuments.delete(unsavedKey(current)); + state.dirty = false; + await loadLibraryObject(current.library_object_uri).catch((error) => { + showError(readableDocumentsError(error, "This file could not be opened.")); + }); +} + +// Save as copy for a Library file: the edits become a new file in Documents, +// through the same import Chat attachments use, and that copy opens. +async function saveLibraryFileCopy(fileName) { + const target = { sessionId: state.currentSessionId, identity: documentIdentity(state.current) }; + const name = String(fileName || "").trim() || suggestedDuplicateFileName(state.current) || "Copy.txt"; + const requestedTitle = elements.titleInput.value; + const requestedBody = elements.editor.value; + const response = await documentsProviderApi("import_chat_attachment", { + attachment_id: "copy-" + window.crypto.randomUUID(), + file_name: name, + mime: /\.md$/i.test(name) ? "text/markdown" : "text/plain", + body: requestedBody, + }); + const copy = requireSavedWorkingCopy(response.document); + upsertDocumentListItem(copy); + renderDocumentsList(); + if (!isCurrentDocumentTarget(target)) return; + // As ordinary Save As: edits typed while the copy saved stay here, unsaved. + if (elements.titleInput.value !== requestedTitle || elements.editor.value !== requestedBody) { + showError("Copy saved. Newer edits are kept in this document."); + return; + } + // The edits now live in the copy; the original file keeps what is stored. + replaceCurrentDocument(copy); + renderCurrentDocument(); +} + +function clearAutosaveTimer() { + if (autosaveTimerId) { + window.clearTimeout(autosaveTimerId); + autosaveTimerId = 0; + } +} + +function resetPendingSaveIntent() { + clearAutosaveTimer(); + autosaveQueued = false; +} + +function replaceCurrentDocument(document) { + resetPendingSaveIntent(); + queuedSaveTarget = null; + saveRecovery = null; + savedWorkingCopy = document ? { ...document } : null; + documentSelectionSequence += 1; + state.current = document; + state.currentSessionId += 1; + updateDocumentsNavigation(document); +} + +function updateDocumentsNavigation(document) { + // A settled editor selection replaces the hint; initial loading stays null. + let query = {}; + if (document?.library_object_uri && typeof document.revision === "string" && document.revision) { + query = { objectUri: document.library_object_uri }; + } else if (document?.doc_did && /^[0-9a-f]{64}$/.test(document.revision || "")) { + query = { doc: document.doc_did }; + } else if (document?.doc_did || document?.library_object_uri) { + return; // An unverified result does not replace the last settled hint. + } + homeNavigation.setQuery(query); +} + +function isCurrentSessionTarget(target) { + return !!target && state.currentSessionId === target.sessionId; +} + +function isCurrentDocumentTarget(target) { + return isCurrentSessionTarget(target) && documentIdentity(state.current) === target.identity; +} + +function scheduleAutosave() { + clearAutosaveTimer(); + if ( + !state.autosave || + !state.current || + state.mode !== "shell" || + !state.dirty || + saveRecovery?.target.sessionId === state.currentSessionId || + pendingHomeWindowCloseTarget?.sessionId === state.currentSessionId + ) { + return; + } + autosaveTimerId = window.setTimeout(() => { + void saveCurrent({ autosave: true }).catch((error) => { + reportSaveFailure(error, "Autosave failed."); + }); + }, 900); +} + +function applyAutosavePreference(enabled) { + state.autosave = enabled === true; + if (elements.autosaveToggle) { + elements.autosaveToggle.setAttribute("aria-checked", String(state.autosave)); + } + scheduleAutosave(); +} + +function toggleAutosavePreference() { + const enabled = !state.autosave; + applyAutosavePreference(enabled); + if (state.homeToken && window.parent !== window) { + window.parent.postMessage({ type: DOCUMENTS_PREFERENCES_SET_TYPE, homeToken: state.homeToken, autosave: enabled }, "*"); + } +} + +function requestAutosavePreference() { + if (state.homeToken && window.parent !== window) { + window.parent.postMessage({ type: DOCUMENTS_PREFERENCES_REQUEST_TYPE, homeToken: state.homeToken }, "*"); + } +} + +function handleAutosavePreferenceMessage(data) { + if (!hasExactKeys(data, ["type", "homeToken", "autosave"]) || + data.type !== DOCUMENTS_PREFERENCES_TYPE || + data.homeToken !== state.homeToken || + typeof data.autosave !== "boolean") { + return false; + } + applyAutosavePreference(data.autosave); + return true; +} + +function unsavedDocumentName() { + return elements.titleInput.value.trim() || state.current?.file_name || "Untitled"; +} + +// Unsaved edits ask before they leave the editor: Save keeps them, Don't save +// drops them, Cancel stays. Resolves true when the caller may go on. +async function resolveUnsavedChanges() { + if (!state.current || !state.dirty) return true; + const sessionId = state.currentSessionId; + clearAutosaveTimer(); + const choice = await chooseInCapsule({ + title: "Save changes to " + unsavedDocumentName() + "?", + message: "Your changes will be lost if you don't save them.", + confirmLabel: "Save", + secondaryLabel: "Don't save", + defaultFocus: "cancel", + }); + if (sessionId !== state.currentSessionId) return false; + if (choice === "secondary") return true; + if (choice !== "confirm") { + scheduleAutosave(); + return false; + } + try { + await saveCurrent(); + } catch (error) { + reportSaveFailure(error, "Save failed."); + return false; + } + return sessionId === state.currentSessionId && !state.dirty; +} + +// Unsaved documents this window holds while another one is open, keyed by +// document. Switching documents, New and opening a file keep the text here +// instead of asking; switching back brings it back. Only closing the window, +// Lock and sign-out ask, since only they would lose it. +const unsavedDocuments = new Map(); + +function unsavedKey(document) { + if (!document) return ""; + return isDraftDocument(document) ? "draft:" + (document.draft_key || "") : documentIdentity(document); +} + +function listItemUnsavedKey(item) { + if (item.draft_key) return "draft:" + item.draft_key; + return item.library_object_uri ? "library:" + item.library_object_uri : "document:" + item.doc_did; +} + +function hasUnsavedDocuments() { + return (state.dirty && !!state.current && !state.current.shared) || unsavedDocuments.size > 0; +} + +// Keeps the open document's unsaved text just before another replaces it. +function keepUnsavedCurrent() { + const current = state.current; + if (!current || !state.dirty || current.shared) return; + unsavedDocuments.set(unsavedKey(current), { + document: { ...current, title: elements.titleInput.value, body: elements.editor.value }, + savedWorkingCopy: savedWorkingCopy ? { ...savedWorkingCopy } : null, + saveRecovery: saveRecovery && isCurrentSessionTarget(saveRecovery.target) ? { ...saveRecovery } : null, + }); +} + +// Before leaving a document: a new one still being created finishes first, +// so it is not created twice; with Save automatically on and no save under +// way, the document saves now, as it would have anyway. A save under way for +// a stored document finishes on its own (reconcileKeptAfterSave). +async function prepareToLeaveCurrent() { + if (saveInFlight && isDraftDocument(state.current)) { + await saveInFlight.catch(() => {}); + } + if (!saveInFlight && state.autosave && state.dirty && state.current && !state.current.shared) { + await saveCurrent({ autosave: true }).catch((error) => { + reportSaveFailure(error, "Autosave failed."); + }); + } +} + +// A save that finishes after its document was left: the kept text is saved +// if it is what was sent, or else now builds on the saved revision. +function reconcileKeptAfterSave(identity, persistedDocument, requestedTitle, requestedBody) { + const kept = unsavedDocuments.get(identity); + if (!kept) { + return; + } + if (kept.document.body === requestedBody && kept.document.title === requestedTitle) { + unsavedDocuments.delete(identity); + } else { + kept.document = { ...kept.document, revision: persistedDocument.revision }; + kept.savedWorkingCopy = { ...persistedDocument }; + kept.saveRecovery = null; + } + renderDocumentsList(); +} + +// Brings back a document's unsaved text, keeping the open one's first. +function restoreUnsavedDocument(key) { + const kept = unsavedDocuments.get(key); + if (!kept) return false; + keepUnsavedCurrent(); + unsavedDocuments.delete(key); + replaceCurrentDocument({ ...kept.document }); + savedWorkingCopy = kept.savedWorkingCopy; + if (kept.saveRecovery) { + saveRecovery = { ...kept.saveRecovery, + target: { sessionId: state.currentSessionId, identity: documentIdentity(state.current) } }; + } + state.mode = "shell"; + elements.shareShell.classList.add("hidden"); + elements.documentsShell.classList.remove("hidden"); + renderCurrentDocument(); + setDirty(true); + scheduleAutosave(); + return true; +} + +async function openKeptDraft(draftKey) { + await prepareToLeaveCurrent(); + restoreUnsavedDocument("draft:" + draftKey); +} + +function unsavedDocumentNames() { + const names = state.dirty && state.current && !state.current.shared ? [unsavedDocumentName()] : []; + for (const kept of unsavedDocuments.values()) { + names.push(kept.document.title.trim() || kept.document.file_name || "Untitled"); + } + return names; +} + +// Save all, from closing the window: the open document, then each kept one. +// Stops at the first that does not save, which stays open with its text. +async function saveAllUnsaved() { + // Edits made while a save runs, in any document, are saved too: close only + // when nothing in the window is left unsaved. Each round saves one document. + for (let round = 0; round < 100; round += 1) { + if (state.dirty && state.current && !state.current.shared) { + await saveCurrent(); + continue; + } + const key = unsavedDocuments.keys().next().value; + if (key === undefined) { + return true; + } + restoreUnsavedDocument(key); + } + return !hasUnsavedDocuments(); +} + +function reportSaveFailure(error, fallback) { + if (error?.documentsTarget && !isCurrentDocumentTarget(error.documentsTarget)) return; + showError(readableDocumentsError(error, fallback)); + if (libraryFileSaveFailed()) { + elements.statusAction.textContent = "Load saved version"; + elements.statusAction.classList.remove("hidden"); + } +} + +function canAnnounceHomeChrome() { + return !!state.homeToken && !!homeOrigin && window.top !== window; +} + +function buildHomeMenuManifest() { + return { + menus: [ + { + title: "File", + items: [ + { label: "New Document", cmd: "file-new-document" }, + { label: "Save", cmd: "file-save" }, + { label: "Save As", cmd: "file-save-as" }, + { label: "Delete Document", cmd: "file-delete-document" }, + { label: "Close Window", cmd: "__close-window" }, + ], + }, + { + title: "View", + items: [ + { label: "Write", cmd: "view-write" }, + { label: "Split", cmd: "view-split" }, + { label: "Read", cmd: "view-read" }, + { label: "Find", cmd: "view-find" }, + ], + }, + ], + }; +} + +function syncHomeMenuManifest() { + if (!canAnnounceHomeChrome() || !homeChromeReady) { + return; + } + const manifest = buildHomeMenuManifest(); + const signature = JSON.stringify(manifest); + if (signature === lastHomeMenuManifestSignature) { + return; + } + lastHomeMenuManifestSignature = signature; + window.top.postMessage({ + type: "home:menu-manifest", + homeToken: state.homeToken, + ...manifest, + }, homeOrigin); +} + +function announceHomeChrome() { + if (!canAnnounceHomeChrome() || homeChromeReady) { + return; + } + window.top.postMessage({ type: "home:app-ready", homeToken: state.homeToken }, homeOrigin); + homeChromeReady = true; + syncHomeMenuManifest(); +} + +// Home frames apps without popups or top navigation, so inside Home a web +// link in a Markdown view has no href (renderMarkdownLink) and asks Home to +// show the exact address and open it only when the person chooses Open +// (#436, the same request as Chat's links). Without the Home session it +// refuses and says so. A link to a place in the document scrolls there. +// Nothing navigates either way. +function activateMarkdownLink(event) { + if (event.type === "keydown" && event.key !== "Enter" && event.key !== " ") { + return; + } + const link = event.target instanceof Element ? event.target.closest("[data-open-external], [data-scroll-to]") : null; + if (!link) { + return; + } + event.preventDefault(); + const selection = window.getSelection(); + if (event.type === "click" && selection && !selection.isCollapsed && selection.containsNode(link, true)) { + return; + } + if (link.hasAttribute("data-scroll-to")) { + const target = document.getElementById(link.getAttribute("data-scroll-to") || ""); + if (target) { + target.scrollIntoView({ block: "start" }); + } + return; + } + if (!canAnnounceHomeChrome()) { + const message = "Open Documents from Home to open web links."; + if (state.mode === "share") { + elements.shareSubtitle.textContent = message; + } else { + showError(message); + } + return; + } + const url = link.getAttribute("data-open-external") || ""; + window.top.postMessage({ type: "home:open-external", url, homeToken: state.homeToken }, homeOrigin); +} + +// Every Markdown view renders through here, so each one gets the inside-Home +// link policy (renderMarkdownLink) and the handlers for its controls. +const markdownLinkContainers = new WeakSet(); +function renderMarkdownInto(container, markdown, options) { + const rendered = renderMarkdownDocument(markdown, options); + container.innerHTML = rendered.html; + if (!markdownLinkContainers.has(container)) { + markdownLinkContainers.add(container); + container.addEventListener("click", activateMarkdownLink); + container.addEventListener("keydown", activateMarkdownLink); + } + return rendered; +} + +function chooseInCapsule(options) { + if (state.pendingConfirmation) { + closeConfirmModal("cancel"); + } + const title = options && Object.prototype.hasOwnProperty.call(options, "title") + ? String(options.title || "") + : "Continue?"; + const message = options && options.message ? options.message : ""; + const confirmLabel = options && options.confirmLabel ? options.confirmLabel : "Continue"; + const secondaryLabel = options && options.secondaryLabel ? String(options.secondaryLabel) : ""; + const danger = !!(options && options.danger); + const hasTitle = title.length > 0; + const dialog = elements.confirmModal.querySelector(".modal-card"); + elements.confirmTitle.textContent = title; + elements.confirmTitle.hidden = !hasTitle; + if (dialog) { + if (hasTitle) { + dialog.setAttribute("aria-labelledby", "confirm-title"); + dialog.removeAttribute("aria-label"); + } else { + dialog.removeAttribute("aria-labelledby"); + dialog.setAttribute("aria-label", confirmLabel); + } + } + elements.confirmMessage.textContent = message; + elements.confirmAction.textContent = confirmLabel; + elements.confirmAction.classList.toggle("action-danger-solid", danger); + elements.confirmSecondaryAction.hidden = !secondaryLabel; + elements.confirmSecondaryAction.textContent = secondaryLabel || "Discard"; + elements.confirmModal.classList.add("open"); + elements.confirmModal.setAttribute("aria-hidden", "false"); + const focusTarget = + options && options.defaultFocus === "cancel" + ? elements.confirmCancel + : elements.confirmAction; + window.setTimeout(() => focusTarget.focus(), 10); + return new Promise((resolve) => { + state.pendingConfirmation = { resolve }; + }); +} + +function closeContextMenu() { + contextMenuDocDid = ""; + elements.contextMenu.classList.add("hidden"); + elements.contextMenu.setAttribute("aria-hidden", "true"); + elements.contextMenu.innerHTML = ""; +} + +function openContextMenu(x, y, docDid) { + const documentItem = state.documents.find((item) => item.doc_did === docDid) || null; + contextMenuDocDid = docDid || ""; + const actions = []; + if (!documentItem) { + actions.push({ action: "new", label: "New note" }); + } else { + actions.push({ action: "duplicate", label: "Duplicate" }); + if (documentItem.latest_published_cid) { + actions.push({ action: "unpublish", label: "Unpublish" }); + } + actions.push({ action: "delete", label: "Delete", danger: true }); + } + elements.contextMenu.innerHTML = actions.map((item) => + '" + ).join(""); + elements.contextMenu.style.left = "8px"; + elements.contextMenu.style.top = "8px"; + elements.contextMenu.classList.remove("hidden"); + elements.contextMenu.setAttribute("aria-hidden", "false"); + const menuWidth = elements.contextMenu.offsetWidth; + const menuHeight = elements.contextMenu.offsetHeight; + const maxLeft = Math.max(8, window.innerWidth - menuWidth - 8); + const maxTop = Math.max(8, window.innerHeight - menuHeight - 8); + const left = Math.min(Math.max(8, Math.round(x)), maxLeft); + const top = Math.min(Math.max(8, Math.round(y)), maxTop); + elements.contextMenu.style.left = left + "px"; + elements.contextMenu.style.top = top + "px"; +} + +function clearPreviewFindHighlights() { + elements.preview.querySelectorAll("mark.find-highlight").forEach((mark) => { + const parent = mark.parentNode; + if (!parent) { + return; + } + parent.replaceChild(document.createTextNode(mark.textContent || ""), mark); + parent.normalize(); + }); + previewFindMarks = []; +} + +function isEditorVisible() { + return state.workspaceView !== "read"; +} + +function isPreviewVisible() { + return state.workspaceView !== "write" && state.inspectorView === "preview"; +} + +function currentFindQuery() { + return String(elements.findInput.value || "").trim(); +} + +function computeSourceFindMatches(query) { + if (!query) { + return []; + } + const source = String(elements.editor.value || ""); + const lowerSource = source.toLowerCase(); + const lowerQuery = query.toLowerCase(); + const matches = []; + let offset = 0; + while (offset <= lowerSource.length) { + const matchIndex = lowerSource.indexOf(lowerQuery, offset); + if (matchIndex === -1) { + break; + } + matches.push({ + start: matchIndex, + end: matchIndex + query.length, + }); + offset = matchIndex + Math.max(1, query.length); + } + return matches; +} + +function syncFindCount(query) { + if (!query) { + elements.findCount.textContent = ""; + return; + } + if (!findMatches.length || findIndex < 0) { + elements.findCount.textContent = "0 / 0"; + return; + } + elements.findCount.textContent = String(findIndex + 1) + " / " + String(findMatches.length); +} + +function selectEditorFindMatch(match) { + if (!match || !isEditorVisible()) { + return; + } + elements.editor.focus(); + elements.editor.setSelectionRange(match.start, match.end, "forward"); + const beforeMatch = String(elements.editor.value || "").slice(0, match.start); + const lineNumber = beforeMatch.split("\n").length; + const lineHeight = Number.parseFloat(window.getComputedStyle(elements.editor).lineHeight) || 26; + elements.editor.scrollTop = Math.max(0, (lineNumber - 2) * lineHeight); +} + +function applyPreviewFindHighlights() { + clearPreviewFindHighlights(); + const query = currentFindQuery(); + if (!query || !isPreviewVisible()) { + return; + } + const lowerQuery = query.toLowerCase(); + const walker = document.createTreeWalker(elements.preview, NodeFilter.SHOW_TEXT, { + acceptNode(node) { + if (!node || !node.nodeValue || !node.nodeValue.trim()) { + return NodeFilter.FILTER_REJECT; + } + if (node.parentElement && node.parentElement.closest("mark.find-highlight")) { + return NodeFilter.FILTER_REJECT; + } + return NodeFilter.FILTER_ACCEPT; + }, + }); + const textNodes = []; + while (walker.nextNode()) { + textNodes.push(walker.currentNode); + } + textNodes.forEach((node) => { + const text = node.nodeValue || ""; + const lowerText = text.toLowerCase(); + let searchIndex = 0; + let matchIndex = lowerText.indexOf(lowerQuery, searchIndex); + if (matchIndex === -1) { + return; + } + const fragment = document.createDocumentFragment(); + while (matchIndex !== -1) { + if (matchIndex > searchIndex) { + fragment.appendChild(document.createTextNode(text.slice(searchIndex, matchIndex))); + } + const mark = document.createElement("mark"); + mark.className = "find-highlight"; + mark.textContent = text.slice(matchIndex, matchIndex + query.length); + fragment.appendChild(mark); + previewFindMarks.push(mark); + searchIndex = matchIndex + query.length; + matchIndex = lowerText.indexOf(lowerQuery, searchIndex); + } + if (searchIndex < text.length) { + fragment.appendChild(document.createTextNode(text.slice(searchIndex))); + } + node.parentNode.replaceChild(fragment, node); + }); + previewFindMarks.forEach((match, matchNumber) => { + match.classList.toggle("active", matchNumber === findIndex); + }); + const activePreviewMatch = previewFindMarks[findIndex]; + if (activePreviewMatch) { + activePreviewMatch.scrollIntoView({ block: "center", behavior: "smooth" }); + } +} + +function activateFindMatch(index) { + const query = currentFindQuery(); + if (!query) { + findIndex = -1; + syncFindCount(query); + clearPreviewFindHighlights(); + return; + } + if (!findMatches.length) { + findIndex = -1; + syncFindCount(query); + applyPreviewFindHighlights(); + return; + } + findIndex = ((index % findMatches.length) + findMatches.length) % findMatches.length; + syncFindCount(query); + selectEditorFindMatch(findMatches[findIndex]); + applyPreviewFindHighlights(); +} + +function updateFindMatches(options) { + const preserveIndex = !!(options && options.preserveIndex); + const query = currentFindQuery(); + findMatches = computeSourceFindMatches(query); + if (!query) { + findIndex = -1; + syncFindCount(query); + clearPreviewFindHighlights(); + return; + } + if (!findMatches.length) { + findIndex = -1; + syncFindCount(query); + applyPreviewFindHighlights(); + return; + } + const nextIndex = preserveIndex && findIndex >= 0 + ? Math.min(findIndex, findMatches.length - 1) + : 0; + activateFindMatch(nextIndex); +} + +function openFindBar() { + elements.findBar.classList.remove("hidden"); + elements.findInput.focus(); + elements.findInput.select(); + updateFindMatches(); +} + +function closeFindBar() { + elements.findBar.classList.add("hidden"); + elements.findInput.value = ""; + findMatches = []; + findIndex = -1; + clearPreviewFindHighlights(); + elements.findCount.textContent = ""; +} + +function refreshPreviewFromEditor() { + const rendered = renderMarkdownInto(elements.preview, elements.editor.value || "", { interactiveTasks: true }); + renderOutline(rendered.outline); + if (!elements.findBar.classList.contains("hidden")) { + updateFindMatches({ preserveIndex: true }); + } +} + +function syncEditorMutation() { + if (state.current) { + state.current.body = elements.editor.value; + } + refreshPreviewFromEditor(); + setDirty(true); + scheduleAutosave(); +} + +function setTaskLineChecked(lineNumber, checked) { + if (state.current?.shared) { + refreshPreviewFromEditor(); + return; + } + const lines = String(elements.editor.value || "").replace(/\r\n/g, "\n").split("\n"); + if (lineNumber < 0 || lineNumber >= lines.length) { + return; + } + const updated = lines[lineNumber].replace(/^([-*]\s+\[)( |x|X)(\]\s+.*)$/, (_match, start, _mark, end) => { + return start + (checked ? "x" : " ") + end; + }); + if (updated === lines[lineNumber]) { + return; + } + lines[lineNumber] = updated; + elements.editor.value = lines.join("\n"); + syncEditorMutation(); +} + +function toggleTaskAtCursor() { + if (state.current?.shared) return; + const source = String(elements.editor.value || ""); + const selectionStart = elements.editor.selectionStart || 0; + const selectionEnd = elements.editor.selectionEnd || selectionStart; + const lineStart = source.lastIndexOf("\n", Math.max(0, selectionStart - 1)) + 1; + const lineEndIndex = source.indexOf("\n", selectionEnd); + const lineEnd = lineEndIndex === -1 ? source.length : lineEndIndex; + const line = source.slice(lineStart, lineEnd); + const taskLine = /^([-*]\s+\[)( |x|X)(\]\s+.*)$/.exec(line); + let nextLine = line; + let nextSelectionStart = selectionStart; + let nextSelectionEnd = selectionEnd; + if (taskLine) { + nextLine = taskLine[1] + (String(taskLine[2]).toLowerCase() === "x" ? " " : "x") + taskLine[3]; + } else { + const prefix = "- [ ] "; + nextLine = prefix + line; + nextSelectionStart += prefix.length; + nextSelectionEnd += prefix.length; + } + if (nextLine === line) { + return; + } + elements.editor.value = source.slice(0, lineStart) + nextLine + source.slice(lineEnd); + elements.editor.focus(); + elements.editor.setSelectionRange(nextSelectionStart, nextSelectionEnd, "forward"); + syncEditorMutation(); +} + +function sortDocuments() { + state.documents.sort((left, right) => { + return (right.updated_at || 0) - (left.updated_at || 0) || left.title.localeCompare(right.title); + }); +} + +// A shared file shows the reading view and Save to Library only; every other +// document gets Write, Split and Save back. +function setSharedChrome(shared) { + elements.modeWrite.classList.toggle("hidden", shared); + elements.modeSplit.classList.toggle("hidden", shared); + elements.saveButton.classList.toggle("hidden", shared); + elements.saveToLibrary.classList.toggle("hidden", !shared); + if (shared) { + setWorkspaceView("read"); + } +} + +function setWorkspaceView(view) { + // A shared read-only file has the reading view only. + state.workspaceView = state.current?.shared ? "read" : preferredWorkspaceView(view); + if (state.workspaceView === "read") { + setInspectorView("preview"); + } + elements.documentsShell.dataset.workspaceView = state.workspaceView; + elements.modeWrite.classList.toggle("active", state.workspaceView === "write"); + elements.modeSplit.classList.toggle("active", state.workspaceView === "split"); + elements.modeRead.classList.toggle("active", state.workspaceView === "read"); + elements.modeWrite.setAttribute("aria-pressed", String(state.workspaceView === "write")); + elements.modeSplit.setAttribute("aria-pressed", String(state.workspaceView === "split")); + elements.modeRead.setAttribute("aria-pressed", String(state.workspaceView === "read")); + if (!elements.findBar.classList.contains("hidden")) { + updateFindMatches({ preserveIndex: true }); + } +} + +function setSidebarCollapsed(collapsed) { + state.sidebarCollapsed = !!collapsed; + elements.documentsShell.dataset.sidebarCollapsed = state.sidebarCollapsed ? "true" : "false"; +} + +function setInspectorView(view) { + state.inspectorView = view === "outline" ? "outline" : "preview"; + elements.previewPanel.classList.toggle("hidden", state.inspectorView !== "preview"); + elements.outlinePanel.classList.toggle("hidden", state.inspectorView !== "outline"); + elements.panePreview.classList.toggle("active", state.inspectorView === "preview"); + elements.paneOutline.classList.toggle("active", state.inspectorView === "outline"); + if (!elements.findBar.classList.contains("hidden")) { + updateFindMatches({ preserveIndex: true }); + } +} + +// The line under the title carries errors only; saving and other progress stay +// quiet (the Save button and the list's "unsaved" marker show the dirty state). +function showError(message) { + elements.statusText.textContent = readableDocumentsError(message, "Documents action could not be completed."); + elements.statusRow.classList.remove("hidden"); +} + +function setDirty(dirty) { + state.dirty = !!dirty; + const hasCurrent = !!state.current; + const hasPersistedCurrent = hasCurrent && !isDraftDocument(state.current); + const isLibraryFile = isLibraryFileProjection(state.current); + elements.saveButton.disabled = !hasCurrent || !state.dirty || !!state.current.shared; + // The Save button itself shows that this document has unsaved changes. + const unsaved = !elements.saveButton.disabled; + elements.saveButton.classList.toggle("has-unsaved", unsaved); + elements.saveButton.title = unsaved ? "Save (unsaved changes)" : "Save"; + elements.saveAsButton.disabled = !hasPersistedCurrent; + elements.deleteButton.disabled = !hasPersistedCurrent || isLibraryFile; + if (hasCurrent && !state.dirty) { + clearStatus(); + } + renderDocumentsList(); +} + +function renderOutline(outline) { + elements.outlinePanel.innerHTML = ""; + if (!outline.length) { + elements.outlinePanel.innerHTML = ''; + return; + } + const list = window.document.createElement("div"); + list.className = "outline-list"; + outline.forEach((item) => { + const wrapper = window.document.createElement("div"); + wrapper.className = "outline-item"; + wrapper.style.marginLeft = Math.max(0, item.depth - 1) * 12 + "px"; + wrapper.innerHTML = + '' + + 'H' + escapeHtml(String(item.depth)) + "" + + '' + escapeHtml(item.title) + "" + + ""; + wrapper.querySelector("a").addEventListener("click", (event) => { + event.preventDefault(); + const heading = elements.preview.querySelector("#" + CSS.escape(item.id)); + if (heading) { + heading.scrollIntoView({ block: "start", behavior: "smooth" }); + } + setInspectorView("preview"); + }); + list.appendChild(wrapper); + }); + elements.outlinePanel.appendChild(list); +} + +function renderCurrentDocument() { + if (!state.current) { + clearAutosaveTimer(); + elements.titleInput.value = ""; + elements.titleInput.disabled = true; + elements.editor.value = ""; + elements.editor.disabled = true; + setSharedChrome(false); + elements.preview.innerHTML = '
    Create or open a document.
    '; + renderOutline([]); + clearStatus(); + setDirty(false); + return; + } + + const shared = !!state.current.shared; + elements.titleInput.disabled = isLibraryFileProjection(state.current); + elements.titleInput.readOnly = shared; + elements.editor.disabled = false; + elements.editor.readOnly = shared; + setSharedChrome(shared); + elements.titleInput.value = state.current.title; + elements.editor.value = state.current.body; + refreshPreviewFromEditor(); + + clearStatus(); + setDirty(false); +} + +function renderDocumentsList() { + elements.documentsList.innerHTML = ""; + const query = state.filterQuery.trim().toLowerCase(); + // New documents kept unsaved in this window list first, until saved. + const keptDrafts = [...unsavedDocuments.values()] + .filter((kept) => isDraftDocument(kept.document)) + .map((kept) => ({ draft_key: kept.document.draft_key, title: kept.document.title.trim() || "Untitled", + file_name: "", updated_at: 0 })); + const visibleDocuments = [...keptDrafts, ...state.documents].filter((item) => { + if (!query) { + return true; + } + return item.title.toLowerCase().includes(query) || item.file_name.toLowerCase().includes(query); + }); + if (!visibleDocuments.length) { + elements.documentsList.innerHTML = '"; + return; + } + + const currentKey = state.current ? state.current.library_object_uri || state.current.doc_did : ""; + visibleDocuments.forEach((item) => { + const button = window.document.createElement("button"); + button.type = "button"; + const classes = ["document-list-item"]; + const isCurrent = !!currentKey && currentKey === (item.library_object_uri || item.doc_did); + if (isCurrent) { + classes.push("active"); + } + button.className = classes.join(" "); + if (item.draft_key) { + button.dataset.draftKey = item.draft_key; + } else if (item.library_object_uri) { + button.dataset.objectUri = item.library_object_uri; + } else { + button.dataset.docDid = item.doc_did; + } + const unsaved = (isCurrent && state.dirty) || unsavedDocuments.has(listItemUnsavedKey(item)); + const meta = [listFolder(item), shortTime(item.updated_at)].filter(Boolean).join(" · "); + if (item.file_name) { + button.title = item.file_name; + } + button.innerHTML = + '' + escapeHtml(listTitle(item)) + "" + + (unsaved ? '' : "") + + "" + + (meta ? '' + escapeHtml(meta) + "" : ""); + button.addEventListener("click", () => item.draft_key + ? openKeptDraft(item.draft_key) + : item.library_object_uri + ? selectLibraryFile(item.library_object_uri) + : selectDocument(item.doc_did)); + elements.documentsList.appendChild(button); + }); +} + +// Every Documents request ends within this deadline, so a save that never +// answers fails, keeps the edits (a later Save checks what was stored), and +// frees a Lock or sign-out that waits on it. +const DOCUMENTS_REQUEST_DEADLINE_MS = 20_000; + +async function documentsApi(path, options) { + const request = { method: "GET", ...(options || {}) }; + request.headers = { + ...(request.headers || {}), + "x-elastos-home-token": state.homeToken, + }; + if (request.body && !request.headers["content-type"]) { + request.headers["content-type"] = "application/json"; + } + const controller = new AbortController(); + const deadline = window.setTimeout(() => controller.abort(), DOCUMENTS_REQUEST_DEADLINE_MS); + try { + const response = await fetch(path, { ...request, signal: controller.signal }); + if (!response.ok) { + const text = await response.text(); + throw new Error(text || "Documents request failed"); + } + if (response.status === 204) { + return null; + } + const contentType = response.headers.get("content-type") || ""; + if (contentType.includes("application/json")) { + return await response.json(); + } + return await response.text(); + } catch (error) { + if (controller.signal.aborted) { + throw new Error("Documents did not answer in time. Your edits are kept."); + } + throw error; + } finally { + window.clearTimeout(deadline); + } +} + +async function documentsProviderApi(op, payload) { + const response = await documentsApi("/api/provider/documents/" + encodeURIComponent(op), { + method: "POST", + body: payload ? JSON.stringify(payload) : "", + }); + if (response && response.status === "error") { + throw new Error(response.message || "Documents request failed"); + } + return response && typeof response === "object" && "data" in response ? response.data : response; +} + +async function libraryObjectApi(op, payload) { + const uri = payload && payload.uri ? String(payload.uri) : ""; + const endpoint = "/api/viewers/documents/library-object?uri=" + encodeURIComponent(uri); + const response = op === "write" + ? await documentsApi(endpoint, { + method: "PUT", + body: JSON.stringify({ + data: payload.data || "", + mime: payload.mime || null, + if_revision: payload.if_revision || null, + }), + }) + : await documentsApi(endpoint, { method: "GET" }); + if (response && response.status === "error") { + throw new Error(response.message || "Library request failed"); + } + return response && typeof response === "object" && "data" in response ? response.data : response; +} + +function base64ToUtf8(data) { + const binary = atob(data || ""); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i += 1) { + bytes[i] = binary.charCodeAt(i); + } + return new TextDecoder().decode(bytes); +} + +function utf8ToBase64(text) { + const bytes = new TextEncoder().encode(String(text || "")); + let binary = ""; + for (let i = 0; i < bytes.length; i += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + } + return btoa(binary); +} + +function upsertDocumentListItem(document) { + const listItem = { + doc_did: document.doc_did, + title: document.title, + file_name: document.file_name, + working_copy_uri: document.working_copy_uri, + updated_at: document.updated_at, + latest_published_cid: document.latest_published_cid || null, + }; + const index = state.documents.findIndex((item) => item.doc_did === listItem.doc_did); + if (index === -1) { + state.documents.unshift(listItem); + } else { + state.documents[index] = listItem; + } + sortDocuments(); +} + +function startDraftDocument(options) { + replaceCurrentDocument(createDraftDocument()); + renderDocumentsList(); + renderCurrentDocument(); + clearStatus(); + if (options && options.focusTitle) { + window.setTimeout(() => elements.titleInput.focus(), 10); + } else if (options && options.focusEditor) { + window.setTimeout(() => elements.editor.focus(), 10); + } +} + +// Documents' own objects, then plain .md and .txt files in the Documents +// folder that have none (made in Library, say); those open as Library files +// and are known by their URI only (no doc_did, which a new draft also lacks). +function summaryListItems(summary) { + const files = (summary.files || []).map((file) => ({ + library_object_uri: file.uri, + title: file.name, + file_name: file.path, + updated_at: file.updated_at, + latest_published_cid: null, + })); + return [...(summary.documents || []), ...files]; +} + +async function loadSummary() { + const summary = await documentsProviderApi("summary"); + state.documents = summaryListItems(summary); + sortDocuments(); + renderDocumentsList(); + if (state.initialIntent === "new") { + state.initialIntent = ""; + await createDocument(""); + return; + } + if (state.initialLibraryObjectUri) { + const requestedUri = state.initialLibraryObjectUri.trim(); + state.initialLibraryObjectUri = ""; + await loadLibraryObject(requestedUri); + setWorkspaceView(preferredWorkspaceView(state.initialView)); + return; + } + if (state.initialCid) { + const requestedCid = state.initialCid.trim(); + state.initialCid = ""; + const requested = state.documents.find((item) => item.latest_published_cid === requestedCid); + if (requested) { + await selectDocument(requested.doc_did); + setWorkspaceView(preferredWorkspaceView(state.initialView)); + } else { + await loadSharedFile(requestedCid); + setWorkspaceView(preferredWorkspaceView(state.initialView)); + } + return; + } + if (state.initialDocDid) { + const requested = state.documents.find((item) => item.doc_did === state.initialDocDid); + if (requested) { + await selectDocument(requested.doc_did); + } else { + const requestedUri = documentUri(state.initialDocDid); + replaceCurrentDocument(null); + renderDocumentsList(); + renderCurrentDocument(); + elements.preview.innerHTML = '
    Document not found. Nothing opened.
    '; + showError("Document not found: " + requestedUri + ". Nothing opened."); + } + state.initialDocDid = ""; + return; + } + if (state.current) { + renderDocumentsList(); + renderCurrentDocument(); + return; + } + startDraftDocument({ focusTitle: true }); +} + +async function loadLibraryObject(uri) { + const sequence = ++documentSelectionSequence; + const sessionId = state.currentSessionId; + const title = elements.titleInput.value; + const body = elements.editor.value; + const response = await libraryObjectApi("read", { uri }); + // Edits made while the file was read stay; the file does not replace them. + if (sequence !== documentSelectionSequence || sessionId !== state.currentSessionId || + title !== elements.titleInput.value || body !== elements.editor.value) return; + const object = response.object || {}; + const name = object.name || baseName(object.uri || uri); + keepUnsavedCurrent(); + replaceCurrentDocument({ + doc_did: "", + document_uri: object.uri || uri, + library_object_uri: object.uri || uri, + revision: object.revision || "", + title: name, + file_name: name, + working_copy_uri: object.uri || uri, + body: base64ToUtf8(response.data || ""), + mime: object.mime || "text/markdown", + created_at: object.created_at || 0, + updated_at: object.modified_at || 0, + latest_published_cid: null, + }); + renderDocumentsList(); + renderCurrentDocument(); +} + +// A file shared in Chat opens in the normal layout as a read-only copy; Save +// to Library keeps a private copy. Documents shows the content and the file +// name the Chat post states, if any: no CID, +// address, type or size. Home opens Documents for a shared file only after it +// read the bytes as text (home-external-link.js), so the bytes are the file. +async function readSharedText(cid) { + // Home serves stored content only to its own apps, so the read carries the + // launch token like every other Documents request. + const response = await fetch("/content/" + encodeURIComponent(cid), { + cache: "no-store", + headers: { "x-elastos-home-token": state.homeToken }, + }); + if (!response.ok) { + throw new Error("This shared file could not be opened."); + } + const buffer = await response.arrayBuffer(); + if (!looksLikeTextContent(response.headers.get("content-type") || "", buffer)) { + throw new Error("Documents can open text files only."); + } + return new TextDecoder("utf-8").decode(buffer); +} + +async function loadSharedFile(cid) { + const sessionId = state.currentSessionId; + let body; + try { + body = await readSharedText(cid); + } catch (error) { + if (sessionId !== state.currentSessionId) return; + replaceCurrentDocument(null); + renderDocumentsList(); + renderCurrentDocument(); + showError(readableDocumentsError(error, "This shared file could not be opened.")); + return; + } + if (sessionId !== state.currentSessionId) return; + replaceCurrentDocument({ ...createDraftDocument(), title: state.initialName || "Shared file", body, shared: true, shared_cid: cid }); + renderDocumentsList(); + renderCurrentDocument(); +} + +// The default name for a saved shared file: .md and .txt stay, anything else +// becomes a .txt file, since Documents keeps text only. +function sharedSaveFileName(title) { + return sharedFileName(/\.(md|txt)$/i.test(title) ? title : title + ".txt"); +} + +// Save to Library keeps the shared file under its own name in the Documents +// folder, through the same import Chat attachments use; saving the same file +// again opens the copy already kept. +async function saveSharedCopy() { + const shared = state.current; + if (!shared?.shared) return; + const sessionId = state.currentSessionId; + const fileName = sharedSaveFileName(shared.title); + const response = await documentsProviderApi("import_chat_attachment", { + attachment_id: "shared-" + shared.shared_cid, + file_name: fileName, + mime: /\.md$/i.test(fileName) ? "text/markdown" : "text/plain", + body: shared.body, + }); + if (sessionId !== state.currentSessionId) return; + const document = requireSavedWorkingCopy(response.document); + replaceCurrentDocument(document); + upsertDocumentListItem(document); + renderDocumentsList(); + renderCurrentDocument(); +} + +async function selectLibraryFile(uri) { + if (state.current && state.current.library_object_uri === uri) { + // The open file's own row reloads it only after its save failed. + if (libraryFileSaveFailed()) { + await loadSavedLibraryVersion(); + } + return; + } + await prepareToLeaveCurrent(); + if (restoreUnsavedDocument("library:" + uri)) { + return; + } + await loadLibraryObject(uri).catch((error) => { + showError(readableDocumentsError(error, "This file could not be opened.")); + }); +} + +async function openChatAttachment(payload) { + const attachmentId = String(payload && payload.attachmentId ? payload.attachmentId : "").trim(); + if (attachmentId && state.pendingChatAttachmentId === attachmentId) { + return false; + } + state.pendingChatAttachmentId = attachmentId; + try { + await prepareToLeaveCurrent(); + resetPendingSaveIntent(); + const mime = String(payload && payload.mimeType ? payload.mimeType : "application/octet-stream"); + if (!isTextMimeType(mime)) { + throw new Error("Documents can open text attachments only."); + } + const fileName = String(payload && payload.fileName ? payload.fileName : "Chat attachment").trim() || "Chat attachment"; + const body = dataUrlToUtf8(payload && payload.dataUrl); + const response = await documentsProviderApi("import_chat_attachment", { + attachment_id: attachmentId, + file_name: fileName, + mime, + body, + }); + const document = response.document; + if (!document || !document.doc_did) { + throw new Error("Documents could not import this file."); + } + if (state.current && state.current.doc_did === document.doc_did) { + return true; + } + state.mode = "shell"; + elements.shareShell.classList.add("hidden"); + elements.documentsShell.classList.remove("hidden"); + if (restoreUnsavedDocument("document:" + document.doc_did)) { + return true; + } + keepUnsavedCurrent(); + replaceCurrentDocument(document); + upsertDocumentListItem(document); + renderDocumentsList(); + renderCurrentDocument(); + setWorkspaceView(preferredWorkspaceView(state.initialView)); + return true; + } finally { + state.pendingChatAttachmentId = ""; + } +} + +function sendChatAttachmentOpenResult({ attachmentId, ok, message }) { + const homeOrigin = new URLSearchParams(window.location.search).get("home_origin") || ""; + if (!state.homeToken || !homeOrigin || window.top === window) { + return; + } + const payload = { + type: "chat-room:attachment-open-result", + attachmentId: String(attachmentId || ""), + ok: ok === true, + message: String(message || ""), + }; + window.top.postMessage({ + type: "home:deliver-to-target", + target: "chat-room", + homeToken: state.homeToken, + payload, + }, homeOrigin); +} + +async function selectDocument(docDid, options) { + const sequence = ++documentSelectionSequence; + const force = !!(options && options.force); + const sameDocument = !!state.current && state.current.doc_did === docDid; + // Clicking the open document keeps the editor as it is. An explicit reload, + // or opening the stored copy after a save conflict, replaces the text here, + // so it asks first; any other switch keeps the unsaved text in this window. + const storedCopyWanted = sameDocument && state.dirty && + saveRecovery?.target.sessionId === state.currentSessionId; + if (sameDocument && !force && !storedCopyWanted) { + return; + } + const replacesText = sameDocument && state.dirty; + if (replacesText) { + const sessionBeforePrompt = state.currentSessionId; + const proceed = await resolveUnsavedChanges(); + if (!proceed || sequence !== documentSelectionSequence || sessionBeforePrompt !== state.currentSessionId) { + return; + } + } else { + await prepareToLeaveCurrent(); + if (sequence !== documentSelectionSequence) { + return; + } + if (restoreUnsavedDocument("document:" + docDid)) { + return; + } + } + const sessionId = state.currentSessionId; + const title = elements.titleInput.value; + const body = elements.editor.value; + resetPendingSaveIntent(); + const response = await documentsProviderApi("get", { doc_did: docDid }).catch((error) => { + if (sequence !== documentSelectionSequence || sessionId !== state.currentSessionId) return null; + throw error; + }); + if (sequence !== documentSelectionSequence || sessionId !== state.currentSessionId || + title !== elements.titleInput.value || body !== elements.editor.value) return; + requireSavedWorkingCopy(response.document, docDid); + if (!replacesText) { + keepUnsavedCurrent(); + } + replaceCurrentDocument(response.document); + upsertDocumentListItem(response.document); + renderDocumentsList(); + renderCurrentDocument(); +} + +async function createDocument(title) { + await prepareToLeaveCurrent(); + keepUnsavedCurrent(); + startDraftDocument({ focusTitle: !title, focusEditor: !!title }); + if (title) { + elements.titleInput.value = title; + setDirty(true); + } + clearStatus(); +} + +function applySavedDocumentState(persistedDocument, saveTarget, requestedTitle, requestedBody) { + if (!isCurrentDocumentTarget(saveTarget)) { + reconcileKeptAfterSave(saveTarget.identity, persistedDocument, requestedTitle, requestedBody); + return; + } + const libraryProjection = isLibraryFileProjection(persistedDocument); + if (libraryProjection) { + const listItem = state.documents.find((item) => item.library_object_uri === persistedDocument.library_object_uri); + if (listItem) { + listItem.updated_at = persistedDocument.updated_at; + sortDocuments(); + } + } else { + upsertDocumentListItem(persistedDocument); + } + renderDocumentsList(); + if (!isCurrentDocumentTarget(saveTarget)) { + return; + } + savedWorkingCopy = { ...persistedDocument }; + saveRecovery = null; + const changedDuringSave = + elements.titleInput.value !== requestedTitle || + elements.editor.value !== requestedBody; + state.current = { + ...persistedDocument, + title: changedDuringSave ? elements.titleInput.value : (persistedDocument.title || requestedTitle), + body: changedDuringSave ? elements.editor.value : requestedBody, + file_name: persistedDocument.file_name || state.current?.file_name || "", + }; + updateDocumentsNavigation(persistedDocument); + if (changedDuringSave) { + refreshPreviewFromEditor(); + setDirty(true); + scheduleAutosave(); + return; + } + renderCurrentDocument(); +} + +function requireSavedWorkingCopy(document, expectedId) { + if (!document || typeof document.doc_did !== "string" || !document.doc_did || + (expectedId && document.doc_did !== expectedId) || + !/^[0-9a-f]{64}$/.test(document.revision || "") || + typeof document.title !== "string" || typeof document.body !== "string") { + throw new Error("Save result could not be confirmed. Your edits are kept."); + } + return document; +} + +async function saveCurrent(options) { + if (!state.current || state.current.shared) return; + const saveTarget = { + sessionId: state.currentSessionId, + identity: documentIdentity(state.current), + }; + if (saveInFlight) { + autosaveQueued = true; + queuedSaveTarget = saveTarget; + return saveInFlight; + } + if (options?.autosave && saveRecovery?.target.sessionId === saveTarget.sessionId) { + throw new Error("Automatic saving is paused. Choose Save to check the stored document."); + } + let saveDocument = { ...state.current }; + const baseline = { ...(savedWorkingCopy || saveDocument) }; + clearAutosaveTimer(); + const requestedTitle = elements.titleInput.value; + const requestedBody = elements.editor.value; + saveInFlight = (async () => { + if (isLibraryFileProjection(saveDocument)) { + // A write whose reply was lost (or timed out) may have landed. Check the + // stored file before writing again, as ordinary saves do. + if (saveRecovery?.phase === "library" && isCurrentDocumentTarget(saveRecovery.target)) { + const recovery = saveRecovery; + const stored = await libraryObjectApi("read", { uri: saveDocument.library_object_uri }); + if (!isCurrentDocumentTarget(saveTarget)) return; + const storedObject = stored?.object || {}; + const storedBody = base64ToUtf8(stored?.data || ""); + if (storedObject.revision && storedBody === recovery.body) { + saveDocument = { ...saveDocument, revision: storedObject.revision }; + } else if (storedObject.revision !== recovery.revision) { + throw new Error("The file changed since you opened it. Your edits are kept here."); + } + saveRecovery = null; + } + saveRecovery = { target: { ...saveTarget }, phase: "library", revision: saveDocument.revision, body: requestedBody }; + const response = await libraryObjectApi("write", { + uri: saveDocument.library_object_uri, + data: utf8ToBase64(requestedBody), + mime: saveDocument.mime || "text/markdown", + if_revision: saveDocument.revision || null, + }); + const object = response.object || {}; + applySavedDocumentState({ + ...saveDocument, + document_uri: object.uri || saveDocument.document_uri, + library_object_uri: object.uri || saveDocument.library_object_uri, + revision: object.revision || saveDocument.revision, + title: object.name || requestedTitle || saveDocument.title, + file_name: object.name || saveDocument.file_name, + body: requestedBody, + mime: object.mime || saveDocument.mime, + updated_at: object.modified_at || saveDocument.updated_at, + }, saveTarget, requestedTitle, requestedBody); + return; + } + if (saveRecovery && isCurrentDocumentTarget(saveRecovery.target)) { + const recovery = saveRecovery; + if (recovery.phase === "create") { + const choice = await chooseInCapsule({ + title: "Save result unknown", + message: "A document may already exist. Check Documents before saving again. Creating a copy may make a duplicate.", + confirmLabel: "Check Documents", + secondaryLabel: "Create copy", + defaultFocus: "cancel", + }); + if (!isCurrentDocumentTarget(saveTarget)) return; + if (choice === "confirm") { + const response = await documentsProviderApi("summary", {}); + if (!isCurrentDocumentTarget(saveTarget)) return; + state.documents = summaryListItems(response); + renderDocumentsList(); + throw new Error("Your draft is kept. Select the stored document to check it, or choose Save to create a copy."); + } + if (choice !== "secondary") throw new Error("Your draft is kept. Saving remains paused."); + saveRecovery = null; + } else { + const response = await documentsProviderApi("get", { doc_did: recovery.base.doc_did }); + if (!isCurrentDocumentTarget(saveTarget)) return; + const observed = requireSavedWorkingCopy(response.document, recovery.base.doc_did); + if (observed.title === recovery.title && observed.body === recovery.body) { + applySavedDocumentState(observed, saveTarget, recovery.inputTitle, recovery.body); + return; + } + if (observed.revision !== recovery.base.revision || + observed.title !== recovery.base.title || observed.body !== recovery.base.body) { + throw new Error("The stored document changed. Your edits are kept. Use Save As for a copy, or open the stored document."); + } + saveDocument = observed; + saveRecovery = null; + } + } + if (!isCurrentDocumentTarget(saveTarget)) return; + if (isDraftDocument(saveDocument)) { + saveRecovery = { target: { ...saveTarget }, phase: "create" }; + const created = await documentsProviderApi("create", { title: requestedTitle || null }); + saveDocument = requireSavedWorkingCopy(created.document); + if (!isCurrentDocumentTarget(saveTarget)) return; + // Retain the observed identity before a follow-up write can lose its reply. + state.current = { ...saveDocument, title: elements.titleInput.value, body: elements.editor.value }; + savedWorkingCopy = { ...saveDocument }; + saveTarget.identity = documentIdentity(state.current); + updateDocumentsNavigation(saveDocument); + // Listed from now on, so its text stays reachable if the save below fails. + upsertDocumentListItem(saveDocument); + renderDocumentsList(); + } + requireSavedWorkingCopy(saveDocument); + saveRecovery = { + target: { ...saveTarget }, phase: "save", + base: isDraftDocument(baseline) ? { ...saveDocument } : baseline, + title: requestedTitle.trim() || "Untitled", inputTitle: requestedTitle, body: requestedBody, + }; + const response = await documentsProviderApi("save", { + doc_did: saveDocument.doc_did, + title: requestedTitle, + body: requestedBody, + if_revision: saveDocument.revision, + }); + const persisted = requireSavedWorkingCopy(response.document, saveDocument.doc_did); + if (persisted.title !== (requestedTitle.trim() || "Untitled") || persisted.body !== requestedBody) { + throw new Error("Save result could not be confirmed. Your edits are kept."); + } + applySavedDocumentState(persisted, saveTarget, requestedTitle, requestedBody); + })(); + try { + await saveInFlight; + } catch (error) { + error.documentsTarget = { ...saveTarget }; + throw error; + } finally { + saveInFlight = null; + if (autosaveQueued) { + autosaveQueued = false; + const queued = queuedSaveTarget; + queuedSaveTarget = null; + if ( + isCurrentDocumentTarget(queued) && state.dirty && + saveRecovery?.target.sessionId !== state.currentSessionId && + pendingHomeWindowCloseTarget?.sessionId !== state.currentSessionId + ) { + void saveCurrent({ autosave: true }).catch((error) => { + reportSaveFailure(error, "Autosave failed."); + }); + } + } + } +} + +function openSaveAsModal() { + if (!state.current || isDraftDocument(state.current)) { + return; + } + elements.saveAsTitleInput.value = elements.titleInput.value || state.current.title || ""; + // A Library file is saved as a copy beside the others in Documents. + elements.saveAsFileInput.value = isLibraryFileProjection(state.current) + ? suggestedDuplicateFileName(state.current) + : state.current.file_name || ""; + elements.saveAsModal.classList.add("open"); + elements.saveAsModal.setAttribute("aria-hidden", "false"); + window.setTimeout(() => elements.saveAsTitleInput.focus(), 10); +} + +function closeSaveAsModal() { + elements.saveAsModal.classList.remove("open"); + elements.saveAsModal.setAttribute("aria-hidden", "true"); +} + +function confirmInCapsule(options) { + return chooseInCapsule(options).then((result) => result === "confirm"); +} + +function closeConfirmModal(result) { + const pending = state.pendingConfirmation; + state.pendingConfirmation = null; + elements.confirmModal.classList.remove("open"); + elements.confirmModal.setAttribute("aria-hidden", "true"); + elements.confirmAction.classList.remove("action-danger-solid"); + elements.confirmSecondaryAction.hidden = true; + if (pending) { + pending.resolve(result || "cancel"); + } +} + +function sameHomeWindowCloseTarget(target) { + return !!target && target.sessionId === state.currentSessionId; +} + +function suspendAutosaveForHomeWindowClose(target) { + if (!sameHomeWindowCloseTarget(target)) { + return null; + } + const suspension = { + sessionId: target.sessionId, + queued: autosaveQueued, + }; + pendingHomeWindowCloseTarget = { sessionId: target.sessionId }; + clearAutosaveTimer(); + autosaveQueued = false; + return suspension; +} + +function resumeAutosaveForHomeWindowClose(suspension) { + if ( + suspension && + pendingHomeWindowCloseTarget?.sessionId === suspension.sessionId + ) { + pendingHomeWindowCloseTarget = null; + } + if (!suspension || !sameHomeWindowCloseTarget(suspension)) { + return; + } + autosaveQueued = autosaveQueued || suspension.queued; + if (!state.dirty) { + return; + } + if (!saveInFlight) { + scheduleAutosave(); + } +} + +async function requestHomeWindowCloseDecision(closeTarget) { + const autosaveSuspension = suspendAutosaveForHomeWindowClose(closeTarget); + if (saveInFlight) { + try { + await saveInFlight; + } catch (error) { + reportSaveFailure(error, "Save failed."); + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: false, reason: "save_failed" }; + } + if (!sameHomeWindowCloseTarget(closeTarget)) { + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: false, reason: "stale_request" }; + } + if (!hasUnsavedDocuments()) { + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: true, reason: "" }; + } + } + if (!sameHomeWindowCloseTarget(closeTarget)) { + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: false, reason: "stale_request" }; + } + if (!hasUnsavedDocuments()) { + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: true, reason: "" }; + } + if (!sameHomeWindowCloseTarget(closeTarget)) { + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: false, reason: "stale_request" }; + } + // One question for every unsaved document in this window. + const names = unsavedDocumentNames(); + const decision = await chooseInCapsule({ + title: names.length === 1 + ? "Save changes to " + names[0] + "?" + : "Save changes to " + names.length + " documents?", + message: "Your changes will be lost if you don't save them.", + confirmLabel: names.length === 1 ? "Save" : "Save all", + secondaryLabel: "Don't save", + defaultFocus: "cancel", + }); + if (!sameHomeWindowCloseTarget(closeTarget)) { + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: false, reason: "stale_request" }; + } + if (decision === "secondary") { + return { ok: true, reason: "discarded" }; + } + if (decision !== "confirm") { + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: false, reason: "cancelled" }; + } + try { + // Saving every document switches between them on purpose, so the window's + // own session check does not apply here. + if (!(await saveAllUnsaved())) { + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: false, reason: "save_incomplete" }; + } + return { ok: true, reason: "" }; + } catch (error) { + reportSaveFailure(error, "Save failed."); + resumeAutosaveForHomeWindowClose(autosaveSuspension); + return { ok: false, reason: "save_failed" }; + } +} + +function postHomeWindowCloseResult(requestId, ok, phase, reason, closeTarget) { + if (!state.homeToken || window.parent === window) { + return; + } + window.parent.postMessage( + { + type: DOCUMENTS_WINDOW_CLOSE_RESULT_TYPE, + requestId, + homeToken: state.homeToken, + state: phase, + ok: ok === true, + reason: typeof reason === "string" ? reason : "", + sessionId: closeTarget?.sessionId ?? state.currentSessionId, + }, + "*", + ); +} + +async function handleHomeWindowCloseRequest(event) { + const data = event.data; + if ( + event.origin !== "null" || + event.source !== window.parent || + !hasExactKeys(data, ["type", "requestId", "homeToken"]) || + data.type !== DOCUMENTS_WINDOW_CLOSE_REQUEST_TYPE || + typeof data.requestId !== "string" || + !data.requestId || + data.homeToken !== state.homeToken + ) { + return false; + } + const closeTarget = { sessionId: state.currentSessionId }; + postHomeWindowCloseResult( + data.requestId, + false, + "pending", + "awaiting_decision", + closeTarget, + ); + const outcome = await requestHomeWindowCloseDecision(closeTarget); + postHomeWindowCloseResult( + data.requestId, + outcome.ok, + "terminal", + outcome.reason, + closeTarget, + ); + return true; +} + +async function saveAsCurrent(title, fileName) { + if (!state.current || isDraftDocument(state.current)) { + return; + } + if (isLibraryFileProjection(state.current)) { + await saveLibraryFileCopy(fileName); + return; + } + const target = { sessionId: state.currentSessionId, identity: documentIdentity(state.current) }; + const requestedTitle = elements.titleInput.value; + const requestedBody = elements.editor.value; + const response = await documentsProviderApi("save_as", { + doc_did: state.current.doc_did, + title: title || null, + file_name: fileName || null, + body: requestedBody, + }); + if (!isCurrentDocumentTarget(target)) return; + requireSavedWorkingCopy(response.document); + if (elements.titleInput.value !== requestedTitle || elements.editor.value !== requestedBody) { + upsertDocumentListItem(response.document); + renderDocumentsList(); + showError("Copy saved. Newer edits are kept in this document."); + return; + } + replaceCurrentDocument(response.document); + upsertDocumentListItem(response.document); + renderDocumentsList(); + renderCurrentDocument(); +} + +async function unpublishCurrent() { + if ( + !state.current || + isDraftDocument(state.current) || + isLibraryFileProjection(state.current) || + !state.current.latest_published_cid + ) { + return; + } + try { + await documentsProviderApi("unpublish", { + doc_did: state.current.doc_did, + }); + await selectDocument(state.current.doc_did, { force: true }); + } catch (error) { + console.error("documents unpublish failed", error); + showError(readableDocumentsError(error, "Unpublish failed.")); + } +} + +async function requestDeleteCurrent() { + if (!state.current || isDraftDocument(state.current) || isLibraryFileProjection(state.current)) { + return; + } + const deletedDocDid = state.current.doc_did; + const title = state.current.title || "this document"; + const confirmed = await confirmInCapsule({ + title: "", + message: 'Delete "' + title + '" from this device?', + confirmLabel: "Delete", + danger: true, + }); + if (!confirmed || !state.current || state.current.doc_did !== deletedDocDid) { + return; + } + try { + await documentsProviderApi("delete", { doc_did: deletedDocDid }); + state.documents = state.documents.filter((document) => document.doc_did !== deletedDocDid); + // A deleted document keeps no unsaved text; whatever is open now (another + // document, perhaps with edits) stays as it is. + unsavedDocuments.delete("document:" + deletedDocDid); + if (state.current && state.current.doc_did === deletedDocDid) { + replaceCurrentDocument(createDraftDocument()); + renderCurrentDocument(); + } + renderDocumentsList(); + } catch (error) { + console.error("documents delete failed", error); + showError(readableDocumentsError(error, "Document could not be deleted.")); + } +} + +function suggestedDuplicateFileName(document) { + const fileName = String(document?.file_name || "").trim(); + if (!fileName) { + return ""; + } + const extMatch = /(\.[^.]+)$/.exec(fileName); + if (!extMatch) { + return fileName + " copy"; + } + const ext = extMatch[1]; + return fileName.slice(0, -ext.length) + " copy" + ext; +} + +async function ensureContextDocumentSelected(docDid) { + if (!docDid) { + return null; + } + if (!state.current || state.current.doc_did !== docDid) { + await selectDocument(docDid); + } + return state.current?.doc_did === docDid ? state.current : null; +} + +async function runContextMenuAction(action) { + // Closing the menu forgets its row, so the row's document is taken first. + const docDid = contextMenuDocDid; + closeContextMenu(); + if (action === "new") { + await createDocument(""); + return; + } + const current = await ensureContextDocumentSelected(docDid); + if (!current) { + return; + } + if (action === "duplicate") { + await saveAsCurrent((current.title || "Untitled document") + " copy", suggestedDuplicateFileName(current)); + return; + } + if (action === "unpublish") { + await unpublishCurrent(); + return; + } + if (action === "delete") { + await requestDeleteCurrent(); + } +} + +function handleHomeMenuCommand(command) { + switch (command) { + case "file-new-document": + void createDocument(""); + break; + case "file-save": + void saveCurrent().catch((error) => { + reportSaveFailure(error, "Save failed."); + }); + break; + case "file-save-as": + openSaveAsModal(); + break; + case "file-delete-document": + void requestDeleteCurrent(); + break; + case "view-write": + setWorkspaceView("write"); + break; + case "view-split": + setWorkspaceView("split"); + break; + case "view-read": + setWorkspaceView("read"); + break; + case "view-find": + openFindBar(); + break; + default: + break; + } +} + +function readableDocumentsError(error, defaultMessage) { + const message = String(error && error.message ? error.message : error || "").trim(); + if (!message || /\b(schema|projection|provider|adapter|capability|affordance|runtime-owned|launch token|hostcall|request failed|failed to fetch|unauthorized|forbidden|[45]\d\d)\b|engine_[a-z_]+/i.test(message)) { + return defaultMessage; + } + return message; +} + +function wireShellEvents() { + elements.titleInput.addEventListener("input", () => { + if (state.current) { + state.current.title = elements.titleInput.value; + const listItem = state.documents.find((item) => item.doc_did === state.current.doc_did); + if (listItem) { + listItem.title = elements.titleInput.value; + } + } + setDirty(true); + scheduleAutosave(); + }); + elements.editor.addEventListener("input", () => { + syncEditorMutation(); + }); + elements.newButton.addEventListener("click", () => createDocument("")); + elements.saveButton.addEventListener("click", () => { + void saveCurrent().catch((error) => { + reportSaveFailure(error, "Save failed."); + }); + }); + elements.autosaveToggle.addEventListener("click", toggleAutosavePreference); + elements.saveToLibrary.addEventListener("click", () => { + void saveSharedCopy().catch((error) => { + reportSaveFailure(error, "Save failed."); + }); + }); + elements.saveAsButton.addEventListener("click", openSaveAsModal); + elements.statusAction.addEventListener("click", () => { + void loadSavedLibraryVersion(); + }); + elements.deleteButton.addEventListener("click", requestDeleteCurrent); + elements.sidebarToggle.addEventListener("click", () => { + setSidebarCollapsed(true); + elements.sidebarShow.focus({ preventScroll: true }); + }); + elements.sidebarShow.addEventListener("click", () => { + setSidebarCollapsed(false); + elements.sidebarToggle.focus({ preventScroll: true }); + }); + wireMoreMenu(); + elements.sidebarSearch.addEventListener("input", () => { + state.filterQuery = elements.sidebarSearch.value || ""; + renderDocumentsList(); + }); + elements.modeWrite.addEventListener("click", () => setWorkspaceView("write")); + elements.modeSplit.addEventListener("click", () => setWorkspaceView("split")); + elements.modeRead.addEventListener("click", () => setWorkspaceView("read")); + elements.findInput.addEventListener("input", () => updateFindMatches()); + elements.findPrev.addEventListener("click", () => activateFindMatch(findIndex - 1)); + elements.findNext.addEventListener("click", () => activateFindMatch(findIndex + 1)); + elements.findClose.addEventListener("click", closeFindBar); + elements.panePreview.addEventListener("click", () => setInspectorView("preview")); + elements.paneOutline.addEventListener("click", () => setInspectorView("outline")); + elements.preview.addEventListener("change", (event) => { + const target = event.target; + if (!(target instanceof HTMLInputElement) || !target.classList.contains("task-checkbox")) { + return; + } + setTaskLineChecked(Number.parseInt(target.dataset.sourceLine || "-1", 10), target.checked); + }); + elements.documentsList.addEventListener("contextmenu", (event) => { + const button = event.target instanceof Element ? event.target.closest(".document-list-item") : null; + event.preventDefault(); + openContextMenu(event.clientX, event.clientY, button?.dataset.docDid || ""); + }); + elements.contextMenu.addEventListener("click", (event) => { + const button = event.target instanceof Element ? event.target.closest("[data-menu-action]") : null; + if (!button) { + return; + } + void runContextMenuAction(button.dataset.menuAction || "").catch((error) => { + reportSaveFailure(error, "Documents action could not be completed."); + }); + }); + document.addEventListener("click", (event) => { + if (event.target instanceof Element && event.target.closest("#context-menu")) { + return; + } + closeContextMenu(); + }); + elements.saveAsCancel.addEventListener("click", closeSaveAsModal); + elements.saveAsModal.addEventListener("click", (event) => { + if (event.target === elements.saveAsModal) { + closeSaveAsModal(); + } + }); + elements.confirmCancel.addEventListener("click", () => closeConfirmModal("cancel")); + elements.confirmSecondaryAction.addEventListener("click", () => closeConfirmModal("secondary")); + elements.confirmAction.addEventListener("click", () => closeConfirmModal("confirm")); + elements.confirmModal.addEventListener("click", (event) => { + if (event.target === elements.confirmModal) { + closeConfirmModal("cancel"); + } + }); + window.addEventListener("message", (event) => { + const data = event.data; + if (event.origin === homeOrigin && event.source === window.top) { + if (!data || typeof data !== "object" || data.type !== "documents:open-chat-attachment") { + return; + } + (async () => { + try { + const opened = await openChatAttachment(data); + if (opened === false) { + return; + } + sendChatAttachmentOpenResult({ + attachmentId: data.attachmentId, + ok: true, + message: "Opened attachment in Documents.", + }); + } catch (error) { + console.error("documents open chat attachment failed", error); + const message = readableDocumentsError(error, "Could not open Chat attachment."); + showError(message); + sendChatAttachmentOpenResult({ + attachmentId: data.attachmentId, + ok: false, + message, + }); + } + })(); + return; + } + if (event.origin !== "null" || event.source !== window.parent) { + return; + } + if (data && typeof data === "object" && data.type === DOCUMENTS_WINDOW_CLOSE_REQUEST_TYPE) { + void handleHomeWindowCloseRequest(event); + return; + } + if (data && typeof data === "object" && data.type === DOCUMENTS_PREFERENCES_TYPE) { + handleAutosavePreferenceMessage(data); + return; + } + if (!data || typeof data !== "object" || data.type !== "elastos:menu-command" || typeof data.cmd !== "string") { + return; + } + handleHomeMenuCommand(data.cmd); + }); + elements.saveAsForm.addEventListener("submit", async (event) => { + event.preventDefault(); + const title = elements.saveAsTitleInput.value.trim(); + const fileName = elements.saveAsFileInput.value.trim(); + closeSaveAsModal(); + try { + await saveAsCurrent(title, fileName); + } catch (error) { + showError(error.message || "Save as failed."); + } + }); + document.addEventListener("keydown", async (event) => { + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "s") { + event.preventDefault(); + try { + await saveCurrent(); + } catch (error) { + reportSaveFailure(error, "Save failed."); + } + } + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "f") { + event.preventDefault(); + openFindBar(); + } + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "g") { + event.preventDefault(); + if (elements.findBar.classList.contains("hidden")) { + openFindBar(); + } else { + activateFindMatch(findIndex + (event.shiftKey ? -1 : 1)); + } + } + if ((event.metaKey || event.ctrlKey) && event.key === "Enter" && event.target === elements.editor) { + event.preventDefault(); + toggleTaskAtCursor(); + } + if (event.key === "Escape" && elements.saveAsModal.classList.contains("open")) { + closeSaveAsModal(); + } + if (event.key === "Escape" && elements.confirmModal.classList.contains("open")) { + closeConfirmModal("cancel"); + } + if (event.key === "Escape" && !elements.findBar.classList.contains("hidden")) { + closeFindBar(); + } + if (event.key === "Escape" && !elements.contextMenu.classList.contains("hidden")) { + closeContextMenu(); + } + }); + window.addEventListener("beforeunload", (event) => { + if (!hasUnsavedDocuments()) { + return; + } + event.preventDefault(); + event.returnValue = ""; + }); +} + +function setMoreMenuOpen(open) { + elements.toolbarMore.dataset.open = String(open); + elements.moreButton.setAttribute("aria-expanded", String(open)); +} + +// Phone-only disclosure for the secondary actions; the actions keep their own +// handlers, so picking one also closes the menu. +function wireMoreMenu() { + elements.moreButton.addEventListener("click", () => { + setMoreMenuOpen(elements.toolbarMore.dataset.open !== "true"); + }); + document.getElementById("more-menu").addEventListener("click", (event) => { + if (event.target instanceof Element && event.target.closest("button")) { + setMoreMenuOpen(false); + } + }); + document.addEventListener("pointerdown", (event) => { + if (!elements.toolbarMore.contains(event.target)) { + setMoreMenuOpen(false); + } + }); + document.addEventListener("keydown", (event) => { + if (event.key === "Escape" && elements.toolbarMore.dataset.open === "true") { + setMoreMenuOpen(false); + elements.moreButton.focus(); + } + }); +} + +async function loadShellMode() { + state.mode = "shell"; + elements.documentsShell.classList.remove("hidden"); + setSidebarCollapsed(window.innerWidth <= 720); + setWorkspaceView(preferredWorkspaceView(state.initialView)); + setInspectorView("preview"); + wireShellEvents(); + announceHomeChrome(); + requestAutosavePreference(); + try { + await loadSummary(); + } catch (error) { + elements.documentsList.innerHTML = ""; + const message = readableDocumentsError(error, "Documents could not be loaded."); + elements.preview.innerHTML = '
    ' + escapeHtml(message) + "
    "; + showError(message); + } +} + +async function loadText(path) { + const response = await fetch(path, { cache: "no-store" }); + if (!response.ok) { + throw new Error("Could not load " + path); + } + return response.text(); +} + +async function loadJson(path) { + const response = await fetch(path, { cache: "no-store" }); + if (!response.ok) { + throw new Error("Could not load " + path); + } + return response.json(); +} + +function setSharePreview(title, markdown, subtitle, pills) { + document.title = title ? title + " · Documents" : "Documents"; + elements.shareTitle.textContent = title || "Documents"; + elements.shareSubtitle.textContent = subtitle || "Read-only markdown surface."; + const article = document.createElement("article"); + article.className = "markdown-body"; + elements.sharePreview.replaceChildren(article); + renderMarkdownInto(article, markdown || ""); + elements.shareTopline.innerHTML = ""; + (pills || []).forEach((pill) => { + const span = document.createElement("span"); + span.className = "share-token"; + span.innerHTML = "" + escapeHtml(pill.label) + "" + escapeHtml(pill.value) + ""; + elements.shareTopline.appendChild(span); + }); +} + +// Outside Home, a published revision's folder: its files, read relative to +// this page, each linked by ?file=. +async function loadShareMode() { + state.mode = "share"; + elements.shareShell.classList.remove("hidden"); + const requestedFile = new URLSearchParams(window.location.search).get("file"); + try { + const files = await loadJson("_files.json"); + const shareMeta = await loadJson("_share.json").catch(() => null); + if (!Array.isArray(files) || files.length === 0) { + throw new Error("Shared revision has no documents."); + } + if (requestedFile && !files.includes(requestedFile)) { + throw new Error("Shared document not found."); + } + const activeFile = requestedFile || files[0]; + elements.shareSidebar.classList.toggle("hidden", files.length <= 1); + elements.shareSidebarMeta.textContent = shareMeta ? "Version " + shareMeta.version : ""; + elements.shareDocList.innerHTML = ""; + + files.forEach((file) => { + const link = document.createElement("a"); + link.className = "share-doc-link" + (file === activeFile ? " active" : ""); + const linkParams = new URLSearchParams(window.location.search); + linkParams.set("file", file); + link.href = window.location.pathname + "?" + linkParams.toString(); + link.innerHTML = + '" + + '"; + elements.shareDocList.appendChild(link); + }); + + const markdown = await loadText(encodeURIComponent(activeFile)); + const title = markdown.match(/^#\s+(.+)$/m)?.[1]?.trim() || activeFile.replace(/\.md$/i, ""); + const pills = []; + if (shareMeta && shareMeta.share_id) { + pills.push({ label: "Document", value: shareMeta.share_id }); + } + if (shareMeta && shareMeta.version) { + pills.push({ label: "Version", value: String(shareMeta.version) }); + } + setSharePreview(title, markdown, "Immutable shared revision.", pills); + } catch (error) { + elements.sharePreview.innerHTML = '
    ' + escapeHtml(readableDocumentsError(error, "Shared document could not be loaded.")) + "
    "; + } +} + +function loadLockedMode() { + state.mode = "locked"; + document.title = "Open Documents from Home · ElastOS"; + elements.shareShell.classList.remove("hidden"); + elements.shareSidebar.classList.add("hidden"); + elements.shareTopline.innerHTML = ''; + elements.shareTitle.textContent = "Open Documents from Home"; + elements.shareSubtitle.textContent = "Documents needs a Home launch to edit local markdown."; + elements.sharePreview.innerHTML = + '

    Documents is ready.

    Open it from Home to create or edit documents.

    '; +} + +(async function init() { + if (state.homeToken) { + await loadShellMode(); + } else if (window.location.pathname.startsWith("/apps/documents")) { + loadLockedMode(); + } else { + await loadShareMode(); + } +})(); diff --git a/capsules/documents/browser/elastos-drawer.js b/capsules/documents/browser/elastos-drawer.js new file mode 100644 index 000000000..dfad1a2eb --- /dev/null +++ b/capsules/documents/browser/elastos-drawer.js @@ -0,0 +1,130 @@ +/* ElastOS UI — phone push drawer (the Assistant's saved-chats pattern). + * + * On the phone stage (html[data-el-form-factor="phone"], see elastos-theme.js) + * a capsule's sidebar leaves the layout and becomes a drawer: the sidebar + * slides in from the leading edge and the main view slides aside with a + * rounded edge; tapping that view, Escape, or picking an item closes it. On + * tablet and desktop this module does nothing and the sidebar stays a column. + * + * Markup contract (no capsule JS needed): + * -
    +
    + +
    @@ -1362,32 +1480,37 @@ - - - +
    -
    - - - +
    +
    + +
    +
    + +
    +
    + +
    +
    -
    @@ -1497,2414 +1618,6 @@

    Continue?

    - + diff --git a/capsules/documents/capsule.json b/capsules/documents/capsule.json index 4093bb974..8cab68f35 100644 --- a/capsules/documents/capsule.json +++ b/capsules/documents/capsule.json @@ -2,7 +2,7 @@ "schema": "elastos.capsule/v1", "name": "documents", "version": "0.2.0", - "description": "Create, edit, and publish markdown documents", + "description": "Create, edit, and save markdown and text documents", "role": "viewer", "window_policy": "hybrid", "type": "wasm", @@ -17,7 +17,7 @@ { "id": "elastos.documents.editor", "version": "0.5.0", - "description": "Create, edit, and publish markdown documents", + "description": "Create, edit, and save markdown and text documents", "methods": [ { "id": "document.open", diff --git a/capsules/drm-provider/Cargo.lock b/capsules/drm-provider/Cargo.lock index f3d247736..42f69da94 100644 --- a/capsules/drm-provider/Cargo.lock +++ b/capsules/drm-provider/Cargo.lock @@ -57,9 +57,10 @@ dependencies = [ [[package]] name = "elastos-common" -version = "0.7.1" +version = "2.0.0" dependencies = [ "hex", + "libc", "serde", "serde_json", "sha2", diff --git a/capsules/drm-provider/src/main.rs b/capsules/drm-provider/src/main.rs index 31fe1cdb1..c59bd5825 100644 --- a/capsules/drm-provider/src/main.rs +++ b/capsules/drm-provider/src/main.rs @@ -12,10 +12,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::io::{self, BufRead, Write}; -const PROVIDER_VERSION: &str = match option_env!("ELASTOS_RELEASE_VERSION") { - Some(version) => version, - None => concat!(env!("CARGO_PKG_VERSION"), "-dev"), -}; +const PROVIDER_VERSION: &str = env!("CARGO_PKG_VERSION"); #[derive(Debug, Deserialize)] #[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] enum Request { diff --git a/capsules/exit-provider/Cargo.lock b/capsules/exit-provider/Cargo.lock index da48ffbbc..f6faa4e15 100644 --- a/capsules/exit-provider/Cargo.lock +++ b/capsules/exit-provider/Cargo.lock @@ -294,9 +294,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.40" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", @@ -318,9 +318,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -490,14 +490,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.7", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.7" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] diff --git a/capsules/exit-provider/src/main.rs b/capsules/exit-provider/src/main.rs index b6c89d8be..65b3eb12a 100644 --- a/capsules/exit-provider/src/main.rs +++ b/capsules/exit-provider/src/main.rs @@ -15,10 +15,7 @@ use url::Url; const DEFAULT_REMOTE_CARRIER_EXIT_SERVICE: &str = "elastos://exit/open_stream"; const MAX_CARRIER_CONNECT_TICKET_BYTES: usize = 8192; -const PROVIDER_VERSION: &str = match option_env!("ELASTOS_RELEASE_VERSION") { - Some(version) => version, - None => concat!(env!("CARGO_PKG_VERSION"), "-dev"), -}; +const PROVIDER_VERSION: &str = env!("CARGO_PKG_VERSION"); #[derive(Debug, Deserialize)] #[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] diff --git a/capsules/gba-emulator/browser/elastos-theme.js b/capsules/gba-emulator/browser/elastos-theme.js index cbaec4163..24e9e2cbb 100644 --- a/capsules/gba-emulator/browser/elastos-theme.js +++ b/capsules/gba-emulator/browser/elastos-theme.js @@ -206,6 +206,27 @@ }); } + // The shell's size class (`elastos:shell-layout`): phone means the shell's + // own title bar sits above the frame and no window controls overlay it, so + // elastos-ui.css drops the desktop chrome safe areas and capsules take + // their phone layout. Unknown values clear the attribute (desktop). + const FORM_FACTORS = ["phone", "tablet", "desktop"]; + const POINTERS = ["coarse", "fine"]; + + function setOrClear(name, value, allowed) { + if (allowed.includes(value)) { + document.documentElement.setAttribute(name, value); + } else { + document.documentElement.removeAttribute(name); + } + } + + function applyShellLayout(layout) { + const value = layout && typeof layout === "object" ? layout : {}; + setOrClear("data-el-form-factor", value.formFactor, FORM_FACTORS); + setOrClear("data-el-pointer", value.pointer, POINTERS); + } + // Opaque-sandboxed frames (no allow-same-origin) own no browser-profile // storage, so persistence stays with the host and the shell relays // preferences by message instead. Cross-frame updates arrive as @@ -216,6 +237,10 @@ return; } const message = event.data || {}; + if (message.type === "elastos:shell-layout") { + applyShellLayout(message.layout); + return; + } if (message.type !== "elastos:ui-preference") { return; } diff --git a/capsules/gba-emulator/browser/elastos-ui.css b/capsules/gba-emulator/browser/elastos-ui.css index 158930d22..64917ee6a 100644 --- a/capsules/gba-emulator/browser/elastos-ui.css +++ b/capsules/gba-emulator/browser/elastos-ui.css @@ -4,11 +4,12 @@ * This file lives at capsules/_shared/elastos-ui.css and is VENDORED into each * participating capsule's browser/ dir by `just vendor-ui` (no gateway route, * no shared runtime surface — capsules stay self-contained). Edit THIS file, - * then run `just vendor-ui`; `just alignment-check` fails on drift. + * then run `just vendor-ui`; `scripts/vendor-ui-tokens.sh --check` fails on drift. * * Contents: Inter (OFL, latin variable subset), palette, type scale, radii, - * hairlines, blur/elevation steps, motion tokens, and minimal control - * primitives. Layout is each app's business — tokens only. + * hairlines, blur/elevation steps, motion tokens, minimal control + * primitives, and the phone push drawer (with elastos-drawer.js). Layout is + * otherwise each app's business — tokens only. */ @font-face { @@ -386,6 +387,108 @@ display: none; } +/* Phone stage (html[data-el-form-factor="phone"], set from the shell's + `elastos:shell-layout` message by elastos-theme.js). The shell's own 44 px + title bar sits above the frame and no traffic lights overlay it, so the + desktop chrome safe areas are zero. The drawer tokens are the Assistant's + push-sidebar values, so every capsule's sidebar moves the same way. */ +:root { + --el-drawer-w: min(300px, 82vw); + --el-drawer-ms: 420ms; + --el-drawer-ease: cubic-bezier(0.22, 1, 0.36, 1); + --el-drawer-room-radius: 28px; + --el-touch-target: 44px; +} + +:root[data-el-form-factor="phone"] { + --window-chrome-safe-top: 0px; + --window-chrome-safe-leading: 0px; +} + +@media (prefers-reduced-motion: reduce) { + :root { + --el-drawer-ms: 1ms; + } +} + +/* Phone push drawer (elastos-drawer.js): the sidebar leaves the layout and + sits under the leading edge; opening slides it in and pushes the room + aside by the same width with a rounded edge. Transform only — no reflow of + the room while it moves. */ +.el-drawer-toggle { + display: none; +} + +:root[data-el-form-factor="phone"] .el-drawer-toggle { + display: inline-grid; + place-items: center; + flex: 0 0 auto; + width: var(--el-touch-target); + height: var(--el-touch-target); + padding: 0; + border: 0; + border-radius: var(--el-radius-md); + background: transparent; + color: var(--el-text); + cursor: pointer; +} + +:root[data-el-form-factor="phone"] .el-drawer-toggle::before { + content: ""; + width: 22px; + height: 22px; + background: currentColor; + -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='16' rx='3'/%3E%3Cpath d='M9 4v16'/%3E%3C/svg%3E") center / contain no-repeat; + mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='16' rx='3'/%3E%3Cpath d='M9 4v16'/%3E%3C/svg%3E") center / contain no-repeat; +} + +:root[data-el-form-factor="phone"] .el-drawer-toggle:active { + background: var(--el-lift); +} + +:root[data-el-form-factor="phone"] .el-drawer-toggle:focus-visible { + outline: 2px solid var(--el-focus); + outline-offset: -2px; +} + +:root[data-el-form-factor="phone"] [data-el-drawer] { + position: fixed; + top: 0; + bottom: 0; + left: 0; + z-index: 40; + width: var(--el-drawer-w); + max-width: none; + overflow-y: auto; + overscroll-behavior: contain; + outline: none; + transform: translateX(-105%); + visibility: hidden; + transition: + transform var(--el-drawer-ms) var(--el-drawer-ease), + visibility 0s linear var(--el-drawer-ms); +} + +:root[data-el-form-factor="phone"] [data-el-drawer][data-el-drawer-state="open"] { + transform: none; + visibility: visible; + transition: transform var(--el-drawer-ms) var(--el-drawer-ease); +} + +:root[data-el-form-factor="phone"] [data-el-drawer-room] { + transition: + transform var(--el-drawer-ms) var(--el-drawer-ease), + border-radius var(--el-drawer-ms) var(--el-drawer-ease); +} + +:root[data-el-form-factor="phone"] [data-el-drawer-room][data-el-drawer-state="open"] { + transform: translateX(var(--el-drawer-w)); + border-radius: var(--el-drawer-room-radius) 0 0 var(--el-drawer-room-radius); + overflow: hidden; + box-shadow: -1px 0 0 var(--el-hairline); + cursor: pointer; +} + @media (prefers-reduced-motion: reduce) { .el-app *, .el-app *::before, diff --git a/capsules/home-cli/browser/commands.json b/capsules/home-cli/browser/commands.json index df137fe39..c3559b089 100644 --- a/capsules/home-cli/browser/commands.json +++ b/capsules/home-cli/browser/commands.json @@ -16,7 +16,7 @@ "aliases": ["status", "summary", "whoami"], "usage": "home", "summary": "Home dashboard summary", - "description": "Show Home status, the active view, Inbox, apps, and services.", + "description": "Show Home status, the active view, Inbox, and apps.", "surface": ["home-cli"] }, { @@ -31,8 +31,8 @@ "name": "people", "aliases": ["contacts", "contact", "discovery"], "usage": "people", - "summary": "People and discovery", - "description": "Show your profile, contacts, pending requests, discovery, and People actions.", + "summary": "People and Public", + "description": "Show your profile, contacts, pending requests, Public, and People actions.", "surface": ["home-cli"] }, { @@ -51,14 +51,6 @@ "description": "Show Home view, update, profile, and device status. Technical details stay under debug topics.", "surface": ["home-cli"] }, - { - "name": "mywebsite", - "aliases": ["site", "website", "spaces"], - "usage": "mywebsite [status|stage |preview|publish|open]", - "summary": "Advanced MyWebSite tasks", - "description": "Advanced command for MyWebSite status, staging a local directory, starting a local preview, publishing a temporary public URL, or explicitly opening the preview in a browser.", - "surface": ["home-cli"] - }, { "name": "wallet", "aliases": ["wallets"], @@ -86,7 +78,7 @@ { "name": "debug", "aliases": ["dev"], - "usage": "debug [capsules|inspect |affordances [capsule]|gates [capsule]|audit |people|spaces [root]|services|browser|terminal|contract]", + "usage": "debug [capsules|inspect |affordances [capsule]|gates [capsule]|audit |people|spaces [root]|browser|terminal|contract]", "summary": "Developer facts and projections", "description": "Debug command for diagnostics hidden from the default Home CLI product surface. Debug rows are declared capability descriptors, not grants.", "surface": ["home-cli"] diff --git a/capsules/home-cli/browser/home-cli-people-message.test.mjs b/capsules/home-cli/browser/home-cli-people-message.test.mjs new file mode 100644 index 000000000..1818a2af6 --- /dev/null +++ b/capsules/home-cli/browser/home-cli-people-message.test.mjs @@ -0,0 +1,159 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +// Drives home-cli.js with the host intent Home emits for People "Message" and +// checks that the Desktop is asked to open Chat at the direct conversation. + +const parentMessages = []; +const eventSources = []; +const intentRequests = []; + +class FakeElement { + constructor() { + this.children = []; + this.dataset = {}; + this.hidden = false; + this.textContent = ""; + this.clientWidth = 1000; + this.clientHeight = 520; + this.parentElement = null; + } + addEventListener() {} + focus() {} + replaceChildren(...children) { + this.children = children; + } + getBoundingClientRect() { + return { width: this.clientWidth, height: this.clientHeight }; + } +} + +class FakeEventSource { + constructor(url) { + this.url = String(url || ""); + this.listeners = new Map(); + eventSources.push(this); + } + addEventListener(type, callback) { + this.listeners.set(type, [...(this.listeners.get(type) || []), callback]); + } + close() {} + emit(type, payload) { + for (const listener of this.listeners.get(type) || []) { + listener({ data: JSON.stringify(payload) }); + } + } +} + +class FakeWebSocket { + static CONNECTING = 0; + static OPEN = 1; + static CLOSED = 3; + constructor() { + this.readyState = FakeWebSocket.OPEN; + } + send() {} + close() {} +} + +class FakeXtermTerminal { + open() {} + resize() {} + write() {} + onData() { + return { dispose() {} }; + } + focus() {} + dispose() {} +} + +const elements = new Map(); +const element = (selector) => { + if (!elements.has(selector)) elements.set(selector, new FakeElement()); + return elements.get(selector); +}; + +const json = (value) => ({ ok: true, status: 200, json: async () => value, text: async () => JSON.stringify(value) }); +const SESSION = "/api/apps/home-cli/terminal/sessions/term-people"; + +globalThis.document = { + activeElement: null, + body: element("body"), + createElement: () => new FakeElement(), + querySelector: element, + querySelectorAll: () => [], + referrer: "http://localhost:61180/apps/home/", +}; +globalThis.window = { + location: { + href: "http://localhost:61180/apps/home-cli/?shell_mode=root&home_origin=http%3A%2F%2Flocalhost%3A61180#home_token=cli-token", + hash: "#home_token=cli-token", + origin: "null", + }, + parent: { postMessage: (message, origin) => parentMessages.push({ message, origin }) }, +}; +globalThis.EventSource = FakeEventSource; +globalThis.WebSocket = FakeWebSocket; +globalThis.ResizeObserver = class { + observe() {} + disconnect() {} +}; +globalThis.__ELASTOS_TEST_XTERM__ = FakeXtermTerminal; +globalThis.fetch = async (url, init = {}) => { + const body = init.body ? JSON.parse(init.body) : null; + if (url === "/api/apps/home-cli/terminal/sessions") { + return json({ + schema: "elastos.home-cli.terminal-session/v1", + session_id: "term-people", + stream: { + events_url: `${SESSION}/events?ticket=t`, + input_socket_url: `${SESSION}/input?ticket=t`, + resize_url: `${SESSION}/resize`, + intent_url: `${SESSION}/intent`, + close_url: `${SESSION}/close`, + }, + }); + } + if (url === `${SESSION}/intent`) { + intentRequests.push(body); + // The gateway returns the authorized intent it accepted. + return json({ schema: "elastos.home-cli.terminal-intent/v1", session_id: "term-people", intent: body }); + } + return json({}); +}; + +const settle = async () => { + for (let i = 0; i < 20; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); +}; + +test("terminal People Message opens Chat on the Desktop at the direct conversation", async () => { + await import("./home-cli.js?people-message-test"); + await settle(); + assert.equal(eventSources.length, 1, "home-cli did not attach the terminal"); + + const intent = { + schema: "elastos.home.terminal-host-intent/v1", + action: "switch-shell-open-target", + action_id: "people-message:contact-alice", + target: "chat-room", + source: "people-contact", + contact_id: "contact-alice", + query: { conversation_id: "direct:sha256:abc" }, + }; + eventSources[0].emit("terminal", { + schema: "elastos.home-cli.terminal-event/v1", + session_id: "term-people", + stream: "stdout", + data: `\u001b]777;elastos-home-intent=${JSON.stringify(intent)}\u0007`, + }); + await settle(); + + assert.deepEqual(intentRequests, [intent]); + const launches = parentMessages + .map(({ message }) => message) + .filter((message) => message.type === "home:switch-shell-and-open-target"); + assert.equal(launches.length, 1, JSON.stringify(parentMessages)); + assert.equal(launches[0].target, "chat-room"); + assert.deepEqual(launches[0].query, { conversation_id: "direct:sha256:abc" }); + assert.equal(launches[0].homeToken, "cli-token"); +}); diff --git a/capsules/home-cli/browser/home-cli.js b/capsules/home-cli/browser/home-cli.js index 4fe7f687e..e5a649b1d 100644 --- a/capsules/home-cli/browser/home-cli.js +++ b/capsules/home-cli/browser/home-cli.js @@ -58,12 +58,7 @@ globalThis.addEventListener?.("pagehide", () => { setRuntimeTerminalMode(false); boot().catch((error) => { console.error("Home CLI terminal could not start", error); - showFallback("Home CLI could not start. Return to the Desktop and try again.", { - allowDesktopRecovery: true, - allowRefresh: true, - focusDesktopRecovery: true, - includeRetainedTerminalOutput: true, - }); + showTerminalStartFailure(error, "Home CLI could not start. Return to the Desktop and try again."); }); async function boot() { @@ -164,6 +159,18 @@ function notifyHomeShellReady() { }, homeParentOrigin); } +// Home CLI has no popup permission. Home shows the exact address and opens a +// terminal web link only when the person chooses Open link. +const homeLinkHandler = { + activate(event, url) { + event?.preventDefault?.(); + if (!homeToken || !homeParentOrigin || !window.parent || window.parent === window) { + return; + } + window.parent.postMessage({ type: "home:open-external", url, homeToken }, homeParentOrigin); + }, +}; + async function attachXtermTerminal(size) { if (!xtermNode) { throw new Error("Home CLI display is unavailable."); @@ -181,6 +188,7 @@ async function attachXtermTerminal(size) { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace', fontSize: 14, scrollback: 5000, + linkHandler: homeLinkHandler, theme: { background: "#050608", foreground: "#d7f5ea", @@ -441,12 +449,7 @@ function reattachHomeCliTerminal(message = "") { globalThis.setTimeout?.(() => { startRuntimeTerminal().catch((error) => { console.error("Home CLI could not restart", error); - showFallback("Home CLI could not reconnect. Return to the Desktop and try again.", { - allowDesktopRecovery: true, - allowRefresh: true, - focusDesktopRecovery: true, - includeRetainedTerminalOutput: true, - }); + showTerminalStartFailure(error, "Home CLI could not reconnect. Return to the Desktop and try again."); }); }, 0); } @@ -458,12 +461,19 @@ function retryHomeCliTerminalFromFallback() { showFallback("Starting Home CLI terminal...", { includeRetainedTerminalOutput: false }); startRuntimeTerminal().catch((error) => { console.error("Home CLI retry failed", error); - showFallback("Home CLI could not start. Return to the Desktop and try again.", { - allowDesktopRecovery: true, - allowRefresh: true, - focusDesktopRecovery: true, - includeRetainedTerminalOutput: true, - }); + showTerminalStartFailure(error, "Home CLI could not start. Return to the Desktop and try again."); + }); +} + +function showTerminalStartFailure(error, message) { + const refused = error?.status === 403; + showFallback(refused + ? "Runtime refused web terminal access. The host operator can check developer mode and guest registration. Return to the Desktop." + : message, { + allowDesktopRecovery: true, + allowRefresh: !refused, + focusDesktopRecovery: true, + includeRetainedTerminalOutput: true, }); } @@ -687,7 +697,9 @@ async function fetchJson(url, init = {}) { const response = await fetch(url, init); if (!response.ok) { const detail = await response.text().catch(() => ""); - throw new Error(detail || `request failed: ${response.status}`); + const error = new Error(detail || `request failed: ${response.status}`); + error.status = response.status; + throw error; } return response.json(); } diff --git a/capsules/home-cli/src/line_views.rs b/capsules/home-cli/src/line_views.rs index db79dc83f..51df14170 100644 --- a/capsules/home-cli/src/line_views.rs +++ b/capsules/home-cli/src/line_views.rs @@ -1,10 +1,7 @@ fn render_line_dashboard(snapshot: &HomeSnapshot) -> Result<()> { print_cli_page_header(snapshot, "Home"); println!("A compact Home shell for working CLI journeys."); - println!( - "Version: runtime {} home {}", - snapshot.version, DASHBOARD_VERSION - ); + println!("Version: runtime {}", snapshot.version); println!(); println!("Now"); @@ -359,14 +356,11 @@ fn handle_shared_line_command(input: &str, snapshot: &HomeSnapshot) -> Result { print_cli_people(snapshot); } - "mywebsite" => { - print_cli_mywebsite(snapshot); - } "wallet" => { print_cli_wallet(snapshot); } "exits" => { - print_cli_services(snapshot, "remote_exit"); + print_cli_exits(snapshot); } "system" => { print_cli_system(snapshot, &arg); @@ -439,38 +433,6 @@ fn line_arg_tail(args: &[&str], start: usize) -> Option { } } -fn mywebsite_line_action(input: &str) -> Result> { - let mut parts = input.split_whitespace(); - let Some(raw_name) = parts.next() else { - return Ok(None); - }; - if normalize_contract_command(raw_name) != "mywebsite" { - return Ok(None); - } - - let Some(raw_verb) = parts.next() else { - return Ok(None); - }; - let verb = normalize_lookup(raw_verb); - match verb.as_str() { - "status" => Ok(None), - "stage" => { - let path = parts.collect::>().join(" "); - let path = path.trim(); - if path.is_empty() { - anyhow::bail!("usage: mywebsite stage "); - } - Ok(Some(format!("site-stage:{path}"))) - } - "preview" | "serve" => Ok(Some("site-local".to_string())), - "publish" | "public" | "go-public" => Ok(Some("site-ephemeral".to_string())), - "open" => Ok(Some("site-open".to_string())), - _ => anyhow::bail!( - "unknown MyWebSite command: {raw_verb}. Try status, stage , preview, publish, or open" - ), - } -} - fn system_line_action(input: &str, snapshot: &HomeSnapshot) -> Result> { let mut parts = input.split_whitespace(); let Some(raw_name) = parts.next() else { @@ -581,7 +543,6 @@ fn print_cli_debug(snapshot: &HomeSnapshot, arg: &str) { print_cli_contacts(snapshot); } "spaces" => print_cli_spaces(snapshot, raw_name, &rest), - "services" => print_cli_services(snapshot, ""), "browser" => print_cli_browser(snapshot), "contract" => print_cli_contract(snapshot), "terminal" => print_cli_terminal_contract(snapshot), @@ -605,7 +566,6 @@ fn print_cli_debug_help(snapshot: &HomeSnapshot) { println!(" debug audit provenance and trust facts"); println!(" debug people People internals, room, and transport facts"); println!(" debug spaces [root] root and WebSpace projection"); - println!(" debug services local and remote service offers"); println!(" debug browser Browser target and exit facts"); println!(" debug terminal Runtime PTY terminal contract"); println!(" debug contract shared capsule interface model"); @@ -617,7 +577,7 @@ fn normalize_debug_command(input: &str) -> String { "affordance" | "interface" | "interfaces" | "ifaces" => "affordances".to_string(), "gate" => "gates".to_string(), "trust" | "provenance" => "audit".to_string(), - "roots" | "places" | "mywebsite" | "public" | "local" | "webspaces" => "spaces".to_string(), + "roots" | "places" | "public" | "local" | "webspaces" => "spaces".to_string(), "shortcuts" | "keys" => "terminal".to_string(), "model" | "interface-contract" => "contract".to_string(), other => other.to_string(), @@ -1201,7 +1161,7 @@ fn print_cli_system_section(snapshot: &HomeSnapshot, title: &str, lines: &[Strin fn print_cli_spaces(snapshot: &HomeSnapshot, raw_name: &str, arg: &str) { let query = space_query_for_command(raw_name, arg); if query.is_empty() { - print_cli_section(snapshot, "Spaces", &spaces_summary_lines(snapshot)); + print_cli_section(snapshot, "Spaces", &spaces_summary_lines()); return; } @@ -1214,12 +1174,12 @@ fn print_cli_spaces(snapshot: &HomeSnapshot, raw_name: &str, arg: &str) { print_cli_page_header(snapshot, "Spaces"); println!("Spaces"); println!(" Unknown root: {}", query.trim()); - println!(" Try: MyWebSite, Public, Local, WebSpaces"); + println!(" Try: Public, Local, WebSpaces"); return; }; let title = format!("Spaces / {}", root.name); - print_cli_section(snapshot, &title, &space_detail_lines(root, snapshot, 80)); + print_cli_section(snapshot, &title, &space_detail_lines(root, 80)); } fn space_query_for_command(raw_name: &str, arg: &str) -> String { @@ -1230,7 +1190,6 @@ fn space_query_for_command(raw_name: &str, arg: &str) -> String { let normalized = normalize_lookup(raw_name); match normalized.as_str() { - "mywebsite" => "MyWebSite".to_string(), "public" => "Public".to_string(), "local" => "Local".to_string(), "webspaces" => "WebSpaces".to_string(), @@ -1238,51 +1197,6 @@ fn space_query_for_command(raw_name: &str, arg: &str) -> String { } } -fn print_cli_mywebsite(snapshot: &HomeSnapshot) { - print_cli_section(snapshot, "MyWebSite", &mywebsite_task_lines(snapshot)); -} - -fn mywebsite_task_lines(snapshot: &HomeSnapshot) -> Vec { - let mut lines = vec![ - format!("Status {}", website_summary(snapshot)), - "Stage mywebsite stage ".to_string(), - format!( - "Preview mywebsite preview ({})", - action_state_label(action_by_id(snapshot, "site-local")) - ), - format!( - "Publish mywebsite publish ({})", - action_state_label(action_by_id(snapshot, "site-ephemeral")) - ), - format!( - "Open mywebsite open ({})", - action_state_label(action_by_id(snapshot, "site-open")) - ), - ]; - - if let Some(url) = snapshot.site.local_url.as_deref() { - lines.push(format!("Preview {}", url.trim_end_matches('/'))); - } - if let Some(release) = snapshot.site.active_release.as_deref() { - let live = snapshot - .site - .active_channel - .as_deref() - .map(|channel| format!("{} on {}", release, channel)) - .unwrap_or_else(|| release.to_string()); - lines.push(format!("Live {live}")); - } else if snapshot.site.release_count > 0 { - lines.push(format!("Releases {}", snapshot.site.release_count)); - } - if let Some(cid) = snapshot.site.active_bundle_cid.as_deref() { - lines.push(format!("Bundle elastos://{}", cid)); - } - if !snapshot.site.staged { - lines.push("Next stage a directory containing index.html".to_string()); - } - lines -} - fn print_cli_inbox(snapshot: &HomeSnapshot) { print_cli_page_header(snapshot, "Inbox"); println!("Inbox"); @@ -1388,68 +1302,35 @@ fn print_cli_wallet(snapshot: &HomeSnapshot) { } } -fn print_cli_services(snapshot: &HomeSnapshot, kind_filter: &str) { - let offers = cli_service_offers(snapshot, kind_filter); - let title = if kind_filter == "remote_exit" { - "Browser Exits" - } else { - "Services" - }; - print_cli_page_header(snapshot, title); - println!("{title}"); - if offers.is_empty() { - if kind_filter == "remote_exit" { - println!(" No Browser Exit offers visible in this snapshot."); - } else { - println!(" No service offers visible in this snapshot."); - } +fn print_cli_exits(snapshot: &HomeSnapshot) { + let exits = cli_service_offers(snapshot, "remote_exit"); + print_cli_page_header(snapshot, "Browser Exits"); + println!("Browser Exits"); + if exits.is_empty() { + println!(" No Browser Exit offers visible in this snapshot."); return; } - for offer in offers.iter().take(12) { - let id = first_json_text(offer, &["offer_id", "id"]); - let kind = first_json_text(offer, &["service_kind", "kind"]); - let name = first_json_text(offer, &["service_display_name", "display_name"]); - let status = first_json_text(offer, &["status"]); - let route = first_json_text(offer, &["route"]); - if kind_filter == "remote_exit" { - println!( - " {:<30} {}", - if name.is_empty() { - if id.is_empty() { - "Browser Exit" - } else { - id - } - } else { - name - }, - if status.is_empty() { - "available" - } else { - status - } - ); - continue; - } + for exit in exits.iter().take(12) { + let id = first_json_text(exit, &["offer_id", "id"]); + let name = first_json_text(exit, &["service_display_name", "display_name"]); + let status = first_json_text(exit, &["status"]); + let name = match (name.is_empty(), id.is_empty()) { + (false, _) => name, + (true, false) => id, + (true, true) => "Browser Exit", + }; println!( - " {:<30} {:<12} {:<12} {}{}", - if id.is_empty() { "offer" } else { id }, - if kind.is_empty() { "service" } else { kind }, + " {:<30} {}", + name, if status.is_empty() { "available" } else { status - }, - if name.is_empty() { id } else { name }, - if route.is_empty() { - String::new() - } else { - format!(" -> {route}") } ); } - if offers.len() > 12 { - println!(" ... {} more offers", offers.len() - 12); + if exits.len() > 12 { + println!(" ... {} more offers", exits.len() - 12); } } diff --git a/capsules/home-cli/src/main.rs b/capsules/home-cli/src/main.rs index 6b921b2f9..548348518 100644 --- a/capsules/home-cli/src/main.rs +++ b/capsules/home-cli/src/main.rs @@ -22,10 +22,6 @@ use terminal::{ ESCAPE_SEQUENCE_MAX_BYTES, }; -const DASHBOARD_VERSION: &str = match option_env!("ELASTOS_RELEASE_VERSION") { - Some(version) => version, - None => concat!(env!("CARGO_PKG_VERSION"), "-dev"), -}; thread_local! { static CLIENT: RefCell = RefCell::new(RuntimeClient::new()); } @@ -52,9 +48,6 @@ struct HomeSnapshot { runtime: RuntimeStatus, #[serde(default)] services: Option, - site: SiteStatus, - #[serde(default)] - shares: ShareStatus, #[serde(default)] room: RoomStatus, #[serde(default)] @@ -114,28 +107,6 @@ struct HomeTargetStatus { viewer_title: Option, } -#[derive(Debug, Clone, Deserialize, Default)] -struct ShareStatus { - #[serde(default)] - channel_count: usize, - #[serde(default)] - active_count: usize, - #[serde(default)] - author_did: Option, - #[serde(default)] - channels: Vec, -} - -#[derive(Debug, Clone, Deserialize)] -struct ShareChannelStatus { - name: String, - latest_cid: String, - latest_version: u64, - status: String, - #[serde(default)] - head_cid: Option, -} - #[derive(Debug, Clone, Deserialize, Default)] struct RoomStatus { #[serde(default)] @@ -206,8 +177,6 @@ struct PeopleStatus { contact_count: usize, #[serde(default)] contacts: Vec, - #[serde(default)] - service_offer_count: usize, } #[derive(Debug, Clone, Deserialize, Default)] @@ -220,7 +189,7 @@ struct PeopleContactStatus { #[serde(default)] relationship: String, #[serde(default)] - route: String, + conversation_id: Option, #[serde(default)] can_message: bool, #[serde(default)] @@ -285,21 +254,6 @@ struct RuntimeStatus { running_capsules: Vec, } -#[derive(Debug, Clone, Deserialize)] -struct SiteStatus { - staged: bool, - #[serde(default)] - local_url: Option, - #[serde(default)] - active_release: Option, - #[serde(default)] - active_channel: Option, - #[serde(default)] - active_bundle_cid: Option, - #[serde(default)] - release_count: usize, -} - #[derive(Debug, Clone, Deserialize)] struct RootStatus { name: String, @@ -349,7 +303,7 @@ enum Tab { } const DEFAULT_TABS: &[Tab] = &[Tab::Home, Tab::Inbox, Tab::People, Tab::Apps, Tab::System]; -const HOME_ACTION_IDS: &[&str] = &["chat", "room-approve", "room-deny", "room-revoke-all"]; +const HOME_ACTION_IDS: &[&str] = &["room-approve", "room-deny", "room-revoke-all"]; #[derive(Debug, Clone)] struct TuiState { @@ -438,7 +392,7 @@ struct ControlSpec { const HELP_TAB_COMMANDS: &[&str] = &["home", "inbox", "people", "apps", "system"]; const HELP_CONTROL_COMMANDS: &[&str] = &["refresh", "help", "exit"]; -const HELP_ADVANCED_COMMANDS: &[&str] = &["mywebsite", "wallet", "exits", "invoke"]; +const HELP_ADVANCED_COMMANDS: &[&str] = &["wallet", "exits", "invoke"]; const HELP_DEBUG_COMMANDS: &[&str] = &["debug"]; include!("runtime_io.rs"); diff --git a/capsules/home-cli/src/runtime_io.rs b/capsules/home-cli/src/runtime_io.rs index 482c2c602..758e3c18a 100644 --- a/capsules/home-cli/src/runtime_io.rs +++ b/capsules/home-cli/src/runtime_io.rs @@ -296,7 +296,8 @@ fn dashboard_tui_loop( needs_render = true; } UiKey::Enter => { - state.notice = None; + state.notice = state.desktop_only_notice(&snapshot); + needs_render = true; if let Some(action_id) = state.activate(&snapshot) { write_intent(write_token, intent_path, &action_id)?; return Ok(()); @@ -419,20 +420,6 @@ fn dashboard_line_loop( } } - match mywebsite_line_action(trimmed) { - Ok(Some(action_id)) => { - write_intent(write_token, intent_path, &action_id)?; - return Ok(()); - } - Ok(None) => {} - Err(error) => { - println!(); - println!("mywebsite: {}", error); - wait_for_enter()?; - continue; - } - } - match system_line_action(trimmed, &snapshot) { Ok(Some(action_id)) => { write_intent(write_token, intent_path, &action_id)?; diff --git a/capsules/home-cli/src/tests.rs b/capsules/home-cli/src/tests.rs index 5b720c219..27635d5d3 100644 --- a/capsules/home-cli/src/tests.rs +++ b/capsules/home-cli/src/tests.rs @@ -124,7 +124,6 @@ fn command_contract_is_home_cli_and_terminal_scoped() { "people".to_string(), "apps".to_string(), "system".to_string(), - "mywebsite".to_string(), "wallet".to_string(), "exits".to_string(), "invoke".to_string(), @@ -139,7 +138,6 @@ fn command_contract_is_home_cli_and_terminal_scoped() { assert_eq!(normalize_contract_command("approvals"), "inbox"); assert_eq!(normalize_contract_command("approve"), "inbox"); assert_eq!(normalize_contract_command("contacts"), "people"); - assert_eq!(normalize_contract_command("spaces"), "mywebsite"); assert_eq!(normalize_contract_command("exit-nodes"), "exits"); assert_eq!(normalize_contract_command("settings"), "system"); assert_eq!(normalize_contract_command("dev"), "debug"); @@ -246,7 +244,6 @@ fn first_run_help_matches_five_tabs_without_power_user_noise() { assert!(help.contains("help advanced")); assert!(help.contains("help debug")); for hidden in [ - "mywebsite", "wallet", "exits", "invoke ", @@ -274,7 +271,6 @@ fn advanced_and_debug_help_keep_contract_commands_available() { let invoke = help_lines("invoke").join("\n"); assert!(advanced.contains("Advanced Commands")); - assert!(advanced.contains("mywebsite [status|stage |preview|publish|open]")); assert!(advanced.contains("wallet")); assert!(advanced.contains("exits")); assert!(advanced.contains("invoke [list [capsule] | [json|target]]")); @@ -304,7 +300,6 @@ fn dashboard_commands_match_five_tabs_without_power_user_noise() { assert!(commands.contains("help debug")); for hidden in [ "Other Commands", - "mywebsite", "wallet", "exits", "invoke ", @@ -327,11 +322,6 @@ fn home_cli_line_mode_accepts_shared_snapshot_backed_commands() { "apps", "inbox", "people", - "mywebsite", - "mywebsite status", - "site", - "website", - "spaces", "wallet", "exits", "debug", @@ -345,7 +335,6 @@ fn home_cli_line_mode_accepts_shared_snapshot_backed_commands() { "debug spaces", "debug spaces webspaces", "debug webspaces", - "debug services", "debug browser", "debug terminal", "debug contract", @@ -383,6 +372,11 @@ fn home_cli_line_mode_accepts_shared_snapshot_backed_commands() { ); } assert_eq!(normalize_contract_command("call"), "invoke"); + // Services is hidden, so neither the debug help nor the dashboard summary offers it. + let debug_help = help_lines("debug").join("\n"); + assert!(debug_help.contains("debug [capsules")); + assert!(!debug_help.contains("services")); + assert!(!help_lines("home").join("\n").contains("services")); } #[test] @@ -507,7 +501,7 @@ fn people_line_mode_emits_snapshot_backed_people_actions() { contact_id: "contact-alice".to_string(), display_name: "Alice".to_string(), relationship: "connected".to_string(), - route: "/apps/chat-room/".to_string(), + conversation_id: Some("direct:sha256:alice".to_string()), can_message: true, ..PeopleContactStatus::default() }], @@ -539,7 +533,7 @@ fn people_line_mode_resolves_visible_contacts_and_requires_message_route() { display_name: "Alice".to_string(), handle: Some("@alice".to_string()), relationship: "conversation".to_string(), - route: "/apps/chat-room/".to_string(), + conversation_id: Some("direct:sha256:alice".to_string()), can_message: true, profile_card: Some(PeopleProfileCardStatus { display_name: "Alice A.".to_string(), @@ -563,7 +557,7 @@ fn people_line_mode_resolves_visible_contacts_and_requires_message_route() { Some("people-remove-contact:contact-alice".to_string()) ); - snapshot.people.contacts[0].route = "elastos://peer/peer-alice".to_string(); + snapshot.people.contacts[0].conversation_id = None; assert!( people_line_action("people message contact-alice", &snapshot) .unwrap_err() @@ -586,7 +580,7 @@ fn tui_snapshot_refresh_picks_up_people_changes() { contact_id: "contact-alice".to_string(), display_name: "Alice".to_string(), relationship: "connected".to_string(), - route: "/apps/chat-room/".to_string(), + conversation_id: Some("direct:sha256:alice".to_string()), can_message: true, ..PeopleContactStatus::default() }], @@ -607,32 +601,6 @@ fn tui_snapshot_refresh_picks_up_people_changes() { assert!(after.contains("connected")); } -#[test] -fn mywebsite_line_mode_emits_explicit_site_actions() { - assert_eq!(mywebsite_line_action("mywebsite").unwrap(), None); - assert_eq!(mywebsite_line_action("spaces status").unwrap(), None); - assert_eq!( - mywebsite_line_action("mywebsite stage /tmp/my site").unwrap(), - Some("site-stage:/tmp/my site".to_string()) - ); - assert_eq!( - mywebsite_line_action("site preview").unwrap(), - Some("site-local".to_string()) - ); - assert_eq!( - mywebsite_line_action("website publish").unwrap(), - Some("site-ephemeral".to_string()) - ); - assert_eq!( - mywebsite_line_action("spaces open").unwrap(), - Some("site-open".to_string()) - ); - assert!(mywebsite_line_action("mywebsite stage") - .unwrap_err() - .to_string() - .contains("stage ")); -} - #[test] fn home_cli_pages_keep_context_header() { let snapshot = sample_snapshot(); @@ -661,7 +629,6 @@ fn system_pages_hide_peer_context_in_header() { #[test] fn debug_spaces_aliases_resolve_to_selected_roots() { assert_eq!(space_query_for_command("webspaces", ""), "WebSpaces"); - assert_eq!(space_query_for_command("mywebsite", ""), "MyWebSite"); assert_eq!(space_query_for_command("spaces", "public"), "public"); let snapshot = sample_snapshot(); @@ -670,7 +637,7 @@ fn debug_spaces_aliases_resolve_to_selected_roots() { .iter() .find(|root| root.name == "WebSpaces") .expect("sample WebSpaces root missing"); - let lines = space_detail_lines(webspaces, &snapshot, 80); + let lines = space_detail_lines(webspaces, 80); assert!(lines.iter().any(|line| line == "Group Spaces")); assert!(lines @@ -679,21 +646,6 @@ fn debug_spaces_aliases_resolve_to_selected_roots() { assert!(lines.iter().any(|line| line.contains("elastos webspace"))); } -#[test] -fn mywebsite_page_is_task_oriented_and_hides_space_roots() { - let snapshot = sample_snapshot(); - let lines = mywebsite_task_lines(&snapshot); - let text = lines.join("\n"); - - assert!(text.contains("Stage mywebsite stage ")); - assert!(text.contains("Preview mywebsite preview")); - assert!(text.contains("Publish mywebsite publish")); - assert!(text.contains("Open mywebsite open")); - assert!(!text.contains("WebSpaces")); - assert!(!text.contains("scratch space")); - assert!(!text.contains("localhost://Local")); -} - #[test] fn home_cli_line_mode_reads_browser_exit_service_offers() { let snapshot = sample_snapshot(); @@ -841,15 +793,6 @@ fn sample_snapshot() -> HomeSnapshot { "status": "available" }] })), - site: SiteStatus { - staged: true, - local_url: None, - active_release: None, - active_channel: None, - active_bundle_cid: None, - release_count: 0, - }, - shares: ShareStatus::default(), room: RoomStatus { room_slug: "chat-room".to_string(), title: "Room".to_string(), @@ -895,15 +838,6 @@ fn sample_snapshot() -> HomeSnapshot { description: "AI root".to_string(), example: "localhost://UsersAI/self".to_string(), }, - RootStatus { - name: "MyWebSite".to_string(), - kind: "file-backed".to_string(), - uri: "localhost://MyWebSite".to_string(), - path: Some("/tmp/MyWebSite".to_string()), - exists: true, - description: "Site root".to_string(), - example: "localhost://MyWebSite/index.html".to_string(), - }, RootStatus { name: "Public".to_string(), kind: "file-backed".to_string(), @@ -942,46 +876,6 @@ fn sample_snapshot() -> HomeSnapshot { }, ], actions: vec![ - ActionInfo { - id: "chat".to_string(), - label: "Chat".to_string(), - description: String::new(), - command: "home: open Chat".to_string(), - ready: true, - reason: None, - }, - ActionInfo { - id: "site-local".to_string(), - label: "Preview".to_string(), - description: String::new(), - command: "home: start MyWebSite local preview".to_string(), - ready: true, - reason: None, - }, - ActionInfo { - id: "site-ephemeral".to_string(), - label: "Publish".to_string(), - description: String::new(), - command: "home: publish a temporary HTTPS URL for MyWebSite".to_string(), - ready: true, - reason: None, - }, - ActionInfo { - id: "site-open".to_string(), - label: "Open".to_string(), - description: String::new(), - command: "home: open MyWebSite preview in browser".to_string(), - ready: true, - reason: None, - }, - ActionInfo { - id: "shares-list".to_string(), - label: "Shared".to_string(), - description: String::new(), - command: "elastos shares list".to_string(), - ready: true, - reason: None, - }, ActionInfo { id: "capsule-gba-ucity".to_string(), label: "gba-ucity".to_string(), @@ -1526,7 +1420,7 @@ fn home_actions_stay_task_focused() { .into_iter() .map(|idx| snapshot.actions[idx].id.as_str()) .collect(); - assert_eq!(ids, vec!["chat"]); + assert!(ids.is_empty(), "{ids:?}"); } #[test] @@ -1538,12 +1432,6 @@ fn quit_action_switches_browser_pty_back_to_home_gui_only() { assert_eq!(quit_action(&snapshot), "quit"); } -#[test] -fn default_home_selection_activates_chat_on_first_enter() { - let state = TuiState::default(); - assert_eq!(state.activate(&sample_snapshot()), Some("chat".to_string())); -} - #[test] fn apps_use_runtime_targets_but_only_cli_native_or_explicit_open_entries_are_actionable() { let snapshot = sample_snapshot(); @@ -1577,28 +1465,25 @@ fn apps_use_runtime_targets_but_only_cli_native_or_explicit_open_entries_are_act assert!(!labels.contains(&"Home CLI")); assert!(!labels.contains(&"Full-screen Chat")); assert!(!labels.contains(&"Shared Conversation")); - assert!(!labels.contains(&"Shared")); - let chat_index = labels.iter().position(|label| *label == "Chat").unwrap(); - assert_eq!( - selected_app_action(&snapshot, chat_index).map(|action| action.id.as_str()), - Some("chat") - ); - for read_only in ["Browser", "uCity", "GBA Emulator"] { + for read_only in ["Browser", "Chat", "uCity", "GBA Emulator"] { let index = labels.iter().position(|label| *label == read_only).unwrap(); let entry = &entries[index]; assert_eq!(entry.action_id, None); assert!(selected_app_action(&snapshot, index).is_none()); assert!(entry.command.contains("Desktop")); - assert_eq!( - TuiState { - tab: Tab::Apps, - app_index: index, - ..TuiState::default() - } - .activate(&snapshot), - None - ); + let state = TuiState { + tab: Tab::Apps, + app_index: index, + ..TuiState::default() + }; + assert_eq!(state.activate(&snapshot), None); + if entry.category == "Apps" { + assert_eq!( + state.desktop_only_notice(&snapshot), + Some(format!("Open {read_only} on the Desktop")) + ); + } } let gba_index = labels .iter() @@ -1661,13 +1546,12 @@ fn quick_launch_only_includes_working_home_actions() { .into_iter() .map(|idx| snapshot.actions[idx].id.as_str()) .collect(); - assert_eq!(ids, vec!["chat"]); + assert!(ids.is_empty(), "{ids:?}"); } #[test] fn every_visible_default_menu_item_is_actionable_or_has_next_step() { let mut snapshot = sample_snapshot(); - snapshot.site.staged = false; snapshot.actions.insert( 1, ActionInfo { @@ -1706,7 +1590,10 @@ fn every_visible_default_menu_item_is_actionable_or_has_next_step() { ); } else { assert!( - matches!(entry.state.as_str(), "gui-only" | "read-only" | "setup"), + matches!( + entry.state.as_str(), + "gui-only" | "read-only" | "setup" | "active" + ), "read-only app must say why Enter will not launch it: {} [{}]", entry.label, entry.state @@ -1722,10 +1609,9 @@ fn every_visible_default_menu_item_is_actionable_or_has_next_step() { } let screen = build_tui_screen(&snapshot, &TuiState::default(), 120, 40); - assert!(screen.contains("1 Chat [ready]")); + assert!(!screen.contains("Chat [ready]")); assert!(!screen.contains("Approve access [setup]")); assert!(screen.contains("Approve access: open Inbox and review the request first")); - assert!(!screen.contains("elastos site stage")); for hidden in [ "Spaces", "Full-screen Chat", @@ -1740,44 +1626,6 @@ fn every_visible_default_menu_item_is_actionable_or_has_next_step() { } } -#[test] -fn blocked_mywebsite_is_not_a_default_home_action() { - let mut snapshot = sample_snapshot(); - snapshot.site.staged = false; - if let Some(action) = snapshot - .actions - .iter_mut() - .find(|action| action.id == "site-local") - { - action.ready = false; - action.reason = Some("stage a site first".to_string()); - } - let ids: Vec<&str> = home_action_indices(&snapshot) - .into_iter() - .map(|idx| snapshot.actions[idx].id.as_str()) - .collect(); - assert_eq!(ids, vec!["chat"]); - assert!(!alerts_lines(&snapshot, 120, None) - .iter() - .any(|line| line.contains("elastos site stage"))); - assert!(mywebsite_task_lines(&snapshot) - .join("\n") - .contains("Stage mywebsite stage ")); -} - -#[test] -fn shared_catalog_entries_stay_out_of_default_home_actions() { - let mut snapshot = sample_snapshot(); - snapshot.shares.channel_count = 1; - snapshot.shares.active_count = 1; - - let ids: Vec<&str> = home_action_indices(&snapshot) - .into_iter() - .map(|idx| snapshot.actions[idx].id.as_str()) - .collect(); - assert_eq!(ids, vec!["chat"]); -} - #[test] fn pending_browser_access_surfaces_approval_actions_on_home() { let mut snapshot = sample_snapshot(); @@ -1824,7 +1672,7 @@ fn pending_browser_access_surfaces_approval_actions_on_home() { .into_iter() .map(|idx| snapshot.actions[idx].id.as_str()) .collect(); - assert_eq!(ids, vec!["chat", "room-approve", "room-deny"]); + assert_eq!(ids, vec!["room-approve", "room-deny"]); let alerts = alerts_lines(&snapshot, 120, None); assert!(alerts .iter() @@ -1861,7 +1709,7 @@ fn active_browser_sessions_surface_disconnect_action_on_home() { .into_iter() .map(|idx| snapshot.actions[idx].id.as_str()) .collect(); - assert_eq!(ids, vec!["chat", "room-revoke-all"]); + assert_eq!(ids, vec!["room-revoke-all"]); let alerts = alerts_lines(&snapshot, 120, None); assert!(alerts @@ -1914,13 +1762,12 @@ fn people_tab_uses_people_model_and_keeps_transport_in_debug() { display_name: "Alice".to_string(), handle: Some("@alice".to_string()), relationship: "connected".to_string(), - route: "/apps/chat-room/".to_string(), + conversation_id: Some("direct:sha256:alice".to_string()), can_message: true, device_label: Some("peer-alice".to_string()), profile_card: None, last_seen_at: Some(10), }], - service_offer_count: 0, }; let ids: Vec = people_actions(&snapshot) @@ -1974,7 +1821,8 @@ fn people_tab_uses_people_model_and_keeps_transport_in_debug() { assert!(debug.contains("RoomWeb")); assert!(debug.contains("ContactsSchema")); assert!(debug.contains("Source")); - assert!(debug.contains("Services")); + // Services is hidden, so People's debug view does not count its offers. + assert!(!debug.contains("Services")); } #[test] @@ -2358,6 +2206,43 @@ fn stale_direct_request_stays_unavailable_in_inbox() { assert!(buf.contains("Action no longer available")); } +#[test] +fn live_direct_message_and_service_requests_hand_off_to_desktop_in_native_terminal() { + for action_id in [ + "chat-open-direct:direct:sha256:abc", + "service-approve-request:req-1", + "service-deny-request:req-1", + ] { + let mut snapshot = sample_snapshot(); + snapshot.session.mode = "native".to_string(); + snapshot.notifications.entries = vec![NotificationEntryStatus { + id: "notice-1".to_string(), + source_app: "inbox".to_string(), + kind: "request".to_string(), + title: "Pending".to_string(), + body: "Someone is waiting.".to_string(), + action_ref: Some(NotificationActionRefStatus { + app: "inbox".to_string(), + action_id: action_id.to_string(), + }), + read: false, + severity: "attention".to_string(), + }]; + let state = TuiState { + tab: Tab::Inbox, + ..TuiState::default() + }; + + let mut buf = String::new(); + render_inbox_tab(&mut buf, &snapshot, &state, 120); + assert!( + buf.contains("Open Inbox on the Desktop to answer this."), + "{action_id}" + ); + assert!(!buf.contains("no longer available"), "{action_id}"); + } +} + #[test] fn tabs_keep_people_between_inbox_and_apps() { let mut state = TuiState::default(); @@ -2373,21 +2258,6 @@ fn tabs_keep_people_between_inbox_and_apps() { assert_eq!(state.tab, Tab::Inbox); } -#[test] -fn shared_catalog_entries_stay_out_of_default_apps() { - let mut snapshot = sample_snapshot(); - assert!(!app_entries(&snapshot) - .iter() - .any(|entry| entry.label == "Shared")); - - snapshot.shares.channel_count = 1; - snapshot.shares.active_count = 1; - - assert!(!app_entries(&snapshot) - .iter() - .any(|entry| entry.label == "Shared")); -} - #[test] fn blocked_home_action_becomes_next_step_not_primary_action() { let mut snapshot = sample_snapshot(); @@ -2407,8 +2277,8 @@ fn blocked_home_action_becomes_next_step_not_primary_action() { ..TuiState::default() }; - assert_eq!(home_action_indices(&snapshot).len(), 1); - assert_eq!(state.activate(&snapshot), Some("chat".to_string())); + assert!(home_action_indices(&snapshot).is_empty()); + assert_eq!(state.activate(&snapshot), None); assert!( !render_home_actions(&snapshot, &home_action_indices(&snapshot), 1, 120) .join("\n") @@ -2565,12 +2435,9 @@ fn home_screen_stays_compact() { assert!(!screen.contains("-- Status --")); assert!(screen.starts_with("\x1b[H\x1b[J")); assert!(!screen.ends_with("\r\n")); - assert!(screen.contains("1 Chat [ready]")); + assert!(!screen.contains("Chat [ready]")); assert!(screen.contains("Next")); - assert!(!screen.contains("MyWebSite [ready]")); - assert!(!screen.contains("MyWebSite is empty.")); assert!(!screen.contains("Updates [ready]")); - assert!(!screen.contains("Shared [ready]")); assert!(screen.contains("Up/Down select")); assert!(screen.contains("q/Esc Desktop")); assert!(screen.contains("? help")); @@ -2730,7 +2597,6 @@ fn tui_starts_at_tab_row_without_summary_header() { assert!(!first_line.contains("Home CLI")); assert!(!first_line.contains("identity ready")); assert!(!first_line.contains("bootstrap ready")); - assert!(!first_line.contains("site empty")); } #[test] @@ -2765,75 +2631,6 @@ fn tui_lines_do_not_trigger_terminal_autowrap() { } } -#[test] -fn mywebsite_notice_surfaces_only_after_explicit_home_action() { - let snapshot = sample_snapshot(); - let notice = - "MyWebSite is empty. Stage a local directory with `elastos site stage `. Then reopen MyWebSite from Home to preview or go public."; - let screen = build_tui_screen( - &snapshot, - &TuiState { - notice: Some(notice.to_string()), - ..TuiState::default() - }, - 100, - 32, - ); - - assert_eq!( - alerts_lines(&snapshot, 100, Some(notice)) - .join("\n") - .matches("MyWebSite is empty.") - .count(), - 1 - ); - assert!(screen.contains("MyWebSite is empty.")); - assert!(screen.contains("Needs attention")); -} - -#[test] -fn staged_site_summary_and_banner_stay_honest() { - let mut snapshot = sample_snapshot(); - snapshot.site.local_url = None; - snapshot.site.active_release = None; - if let Some(action) = snapshot - .actions - .iter_mut() - .find(|action| action.id == "site-local") - { - action.ready = false; - action.reason = - Some("missing site-provider -- run: elastos setup --profile demo".to_string()); - } - - assert_eq!( - website_summary(&snapshot), - "staged at localhost://MyWebSite" - ); -} - -#[test] -fn mywebsite_tasks_show_staged_site_and_next_steps() { - let mut snapshot = sample_snapshot(); - snapshot.site.local_url = None; - if let Some(action) = snapshot - .actions - .iter_mut() - .find(|action| action.id == "site-local") - { - action.ready = false; - action.reason = - Some("missing site-provider -- run: elastos setup --profile demo".to_string()); - } - - let screen = mywebsite_task_lines(&snapshot).join("\n"); - assert!(screen.contains("Status staged at localhost://MyWebSite")); - assert!(screen.contains("Stage mywebsite stage ")); - assert!(screen.contains("Preview mywebsite preview (blocked")); - assert!(screen.contains("Open mywebsite open")); - assert!(!screen.contains("press Enter")); -} - #[test] fn system_tab_stays_short_and_actionable() { let snapshot = sample_snapshot(); diff --git a/capsules/home-cli/src/tui_render.rs b/capsules/home-cli/src/tui_render.rs index cae7b40e7..3846b082c 100644 --- a/capsules/home-cli/src/tui_render.rs +++ b/capsules/home-cli/src/tui_render.rs @@ -196,7 +196,13 @@ fn render_inbox_tab(buf: &mut String, snapshot: &HomeSnapshot, state: &TuiState, format!("State {}", if entry.read { "read" } else { "unread" }), ]; details.extend(wrap_with_label("Body", &entry.body, column_width)); - if let Some(action) = selected_notification_action(snapshot, state.inbox_index) { + let action = selected_notification_action(snapshot, state.inbox_index); + let desktop_only = action.as_ref().is_some_and(|action| { + !action.ready && action.id.starts_with(INBOX_NOTIFICATION_HANDOFF_ACTION_PREFIX) + }); + if desktop_only { + details.push("Action Open Inbox on the Desktop to answer this.".to_string()); + } else if let Some(action) = action { details.push(format!("Action {}", action.label)); details.push(format!( "ActionUse {}", @@ -568,7 +574,7 @@ fn people_contact_lines(snapshot: &HomeSnapshot, width: usize) -> Vec { { details.push(device.to_string()); } - if people_contact_message_target(contact).is_some() { + if people_contact_conversation(contact).is_some() { lines.push(format!(" Message people message {}", contact.contact_id)); } if !contact.contact_id.trim().is_empty() { @@ -589,7 +595,6 @@ fn people_debug_lines(snapshot: &HomeSnapshot) -> Vec { format!("Identity {}", identity_summary(snapshot)), format!("ContactsSchema {}", snapshot.people.schema), format!("Contacts {}", snapshot.people.contact_count), - format!("Services {}", snapshot.people.service_offer_count), format!("Network {}", network_summary(snapshot)), format!( "Source {}", @@ -603,10 +608,6 @@ fn people_debug_lines(snapshot: &HomeSnapshot) -> Vec { "Profile {}", action_state_label(action_by_id(snapshot, "identity-nickname-set")) ), - format!( - "Chat {}", - action_state_label(action_by_id(snapshot, "chat")) - ), format!( "Peers {}", format!( @@ -651,18 +652,9 @@ fn people_debug_lines(snapshot: &HomeSnapshot) -> Vec { lines } -fn spaces_summary_lines(snapshot: &HomeSnapshot) -> Vec { +fn spaces_summary_lines() -> Vec { vec![ - format!("MyWebSite {}", website_summary(snapshot)), - format!( - "Public {} shared channel{} ready to open", - snapshot.shares.channel_count, - if snapshot.shares.channel_count == 1 { - "" - } else { - "s" - } - ), + "Public shared files root for things you want to open or pass around".to_string(), "Local scratch space for temporary work and session state".to_string(), "WebSpaces named handles into content, peers, identity, and AI".to_string(), ] @@ -830,7 +822,7 @@ fn active_shell_candidate_launchable(snapshot: &HomeSnapshot, name: &str) -> boo fn root_group_name(root: &str) -> &'static str { match root { "Users" | "UsersAI" => "People", - "Local" | "Public" | "MyWebSite" | "WebSpaces" => "Spaces", + "Local" | "Public" | "WebSpaces" => "Spaces", "AppCapsules" => "Apps", "ElastOS" => "System", _ => "World", @@ -877,41 +869,6 @@ fn display_name(snapshot: &HomeSnapshot) -> String { .to_string() } -fn website_summary(snapshot: &HomeSnapshot) -> String { - let mut parts = Vec::new(); - if let Some(url) = snapshot.site.local_url.as_deref() { - parts.push(format!("preview at {}", url.trim_end_matches('/'))); - } else if snapshot.site.staged { - parts.push("staged at localhost://MyWebSite".to_string()); - } else { - parts.push("not staged locally".to_string()); - } - - if let Some(release) = snapshot.site.active_release.as_deref() { - if let Some(channel) = snapshot.site.active_channel.as_deref() { - parts.push(format!("live {} on {}", release, channel)); - } else { - parts.push(format!("release {}", release)); - } - } else if snapshot.site.release_count > 0 { - let suffix = if snapshot.site.release_count == 1 { - "" - } else { - "s" - }; - parts.push(format!( - "{} saved release{}", - snapshot.site.release_count, suffix - )); - } - - if let Some(cid) = snapshot.site.active_bundle_cid.as_deref() { - parts.push(format!("elastos://{}", truncate(cid, 18))); - } - - parts.join(" - ") -} - fn source_label(snapshot: &HomeSnapshot) -> String { match &snapshot.source { Some(source) => { diff --git a/capsules/home-cli/src/tui_state.rs b/capsules/home-cli/src/tui_state.rs index d931218c7..4d64287ee 100644 --- a/capsules/home-cli/src/tui_state.rs +++ b/capsules/home-cli/src/tui_state.rs @@ -115,6 +115,18 @@ impl TuiState { } } + /// The one-line hand-off shown when Enter has nothing to run in the + /// terminal because the selected app only opens on the Desktop. + fn desktop_only_notice(&self, snapshot: &HomeSnapshot) -> Option { + if self.tab != Tab::Apps { + return None; + } + let entries = app_entries(snapshot); + let entry = entries.get(self.app_index.min(entries.len().saturating_sub(1)))?; + (entry.action_id.is_none() && entry.category == "Apps") + .then(|| format!("Open {} on the Desktop", entry.label)) + } + fn handle_mouse(&mut self, event: MouseEvent, cols: usize, snapshot: &HomeSnapshot) -> bool { if event.released { return false; diff --git a/capsules/home-cli/src/view_models.rs b/capsules/home-cli/src/view_models.rs index d0c870417..c7f46a80a 100644 --- a/capsules/home-cli/src/view_models.rs +++ b/capsules/home-cli/src/view_models.rs @@ -6,7 +6,7 @@ fn people_actions(snapshot: &HomeSnapshot) -> Vec { let mut actions = Vec::new(); for contact in &snapshot.people.contacts { let name = people_contact_display_name(contact, "Person"); - if people_contact_message_target(contact).is_some() && !contact.contact_id.trim().is_empty() + if people_contact_conversation(contact).is_some() && !contact.contact_id.trim().is_empty() { actions.push(PeopleAction { id: format!("people-message:{}", contact.contact_id), @@ -105,21 +105,16 @@ fn selected_system_action(snapshot: &HomeSnapshot, selected: usize) -> Option Option { - let rest = route.trim().strip_prefix("/apps/")?; - let target = rest.split(['/', '?', '#']).next().unwrap_or("").trim(); - if target.is_empty() { - None - } else { - Some(target.to_string()) - } -} - -fn people_contact_message_target(contact: &PeopleContactStatus) -> Option { +/// The direct Chat conversation of a contact that can be messaged. +fn people_contact_conversation(contact: &PeopleContactStatus) -> Option<&str> { if !contact.can_message { return None; } - home_app_target_from_route(&contact.route) + contact + .conversation_id + .as_deref() + .map(str::trim) + .filter(|id| !id.is_empty()) } fn people_contact_id_for_reference(snapshot: &HomeSnapshot, contact_ref: &str) -> Option { @@ -271,9 +266,7 @@ fn inbox_review_handoff_action( description: "Open Inbox on the Home Desktop to review this pending request.".to_string(), command: "home: open Inbox".to_string(), ready, - reason: (!ready).then(|| { - "Open Inbox from the Home Desktop to review this pending request.".to_string() - }), + reason: (!ready).then(|| "Open Inbox on the Desktop to answer this.".to_string()), }) } @@ -285,6 +278,9 @@ fn notification_action_uses_inbox_review(action_id: &str) -> bool { "capability-approve-request:", "inspect-approve-request:", "wallet-price-http-approve:", + "chat-open-direct:", + "service-approve-request:", + "service-deny-request:", ] .iter() .any(|prefix| action_id.starts_with(prefix)) @@ -312,12 +308,6 @@ fn action_state_label(action: Option<&ActionInfo>) -> String { } } -fn next_step_command(reason: &str) -> Option<&str> { - reason - .split_once("run: ") - .map(|(_, command)| command.trim()) -} - fn render_home_actions( snapshot: &HomeSnapshot, indices: &[usize], @@ -327,7 +317,7 @@ fn render_home_actions( let mut lines = Vec::new(); for (slot, action_idx) in indices.iter().take(5).enumerate() { let action = &snapshot.actions[*action_idx]; - let state = home_action_state(action, snapshot); + let state = home_action_state(action); let summary = home_action_summary(action); let label = action_display_label(action); lines.push(format!( @@ -348,55 +338,28 @@ fn render_home_actions( lines } -fn home_action_state<'a>(action: &'a ActionInfo, snapshot: &HomeSnapshot) -> &'a str { - match action.id.as_str() { - "site-local" => { - if snapshot.site.local_url.is_some() { - "preview" - } else if snapshot.site.staged && !action.ready { - "staged" - } else if !snapshot.site.staged { - "empty" - } else if action.ready { - "ready" - } else { - "setup" - } - } - _ => { - if action.ready { - "ready" - } else { - "setup" - } - } +fn home_action_state(action: &ActionInfo) -> &'static str { + if action.ready { + "ready" + } else { + "setup" } } fn home_action_summary(action: &ActionInfo) -> &str { match action.id.as_str() { - "chat" => "Send a message and return home", "room-approve" => "Approve the next pending Chat web guest request", "room-deny" => "Deny the next pending Chat web guest request", "room-revoke-all" => "Disconnect active Chat web guest sessions", - "site-local" => "Start or reuse the local MyWebSite preview", - "site-ephemeral" => "Publish a temporary public HTTPS URL for MyWebSite", - "site-open" => "Open the MyWebSite preview in a browser", - "shares-list" => "Review shared channels, open links, and next steps", _ => action.description.as_str(), } } fn action_display_label(action: &ActionInfo) -> &str { match action.id.as_str() { - "chat" => "Chat", "room-approve" => "Approve access", "room-deny" => "Deny access", "room-revoke-all" => "Disconnect browsers", - "site-local" => "Preview", - "site-ephemeral" => "Publish", - "site-open" => "Open", - "shares-list" => "Shared", _ => action.label.as_str(), } } @@ -417,12 +380,6 @@ fn alerts_lines(snapshot: &HomeSnapshot, width: usize, notice: Option<&str>) -> .to_string(), ); } - if site_workflow_started(snapshot) && !snapshot.site.staged { - alerts.push( - "MyWebSite is empty. Stage a local directory with `elastos site stage `." - .to_string(), - ); - } for entry in snapshot.notifications.entries.iter().take(3) { alerts.push(entry.body.clone()); } @@ -473,11 +430,6 @@ fn home_next_step(snapshot: &HomeSnapshot, notice: Option<&str>) -> Option` when you are ready to publish a site.".to_string(), - ); - } if quick_launch_action_indices(snapshot).is_empty() { return Some("Use Tab to choose Inbox, People, Apps, or System.".to_string()); } @@ -493,15 +445,6 @@ fn first_blocked_home_action(snapshot: &HomeSnapshot) -> Option<&ActionInfo> { }) } -fn site_workflow_started(snapshot: &HomeSnapshot) -> bool { - snapshot.site.staged - || snapshot.site.local_url.is_some() - || snapshot.site.active_release.is_some() - || snapshot.site.active_channel.is_some() - || snapshot.site.active_bundle_cid.is_some() - || snapshot.site.release_count > 0 -} - fn notice_covers_alert(notice: &str, alert: &str) -> bool { if notice.is_empty() { return false; @@ -510,10 +453,7 @@ fn notice_covers_alert(notice: &str, alert: &str) -> bool { let notice = notice.trim(); let alert = alert.trim(); - notice == alert - || notice.starts_with(alert) - || alert.starts_with(notice) - || (notice.contains("MyWebSite is empty.") && alert.contains("MyWebSite is empty.")) + notice == alert || notice.starts_with(alert) || alert.starts_with(notice) } fn format_room_participants(participants: &[RoomParticipantStatus]) -> String { @@ -560,7 +500,7 @@ fn should_render_notice(notice: &str) -> bool { && !trimmed.starts_with("Returned home from ") } -fn space_detail_lines(root: &RootStatus, snapshot: &HomeSnapshot, width: usize) -> Vec { +fn space_detail_lines(root: &RootStatus, width: usize) -> Vec { let mut details = vec![ format!("Group {}", root_group_name(&root.name)), format!("Kind {}", root.kind), @@ -573,79 +513,6 @@ fn space_detail_lines(root: &RootStatus, snapshot: &HomeSnapshot, width: usize) details.extend(wrap_with_label("Meaning", &root.description, width)); details.extend(wrap_with_label("Example", &root.example, width)); match root.name.as_str() { - "MyWebSite" => { - details.push(format!("State {}", website_summary(snapshot))); - if let Some(url) = snapshot.site.local_url.as_deref() { - details.push(format!("Preview {}", url.trim_end_matches('/'))); - } else if let Some(action) = action_by_id(snapshot, "site-local") { - if action.ready { - details.push("Preview mywebsite preview".to_string()); - } else if let Some(reason) = action.reason.as_deref() { - if let Some(command) = next_step_command(reason) { - details.push(format!("Next {}", command)); - } else { - details.extend(wrap_with_label("Setup", reason, width)); - } - } - } else { - details.push("Next elastos site stage ".to_string()); - } - if let Some(release) = snapshot.site.active_release.as_deref() { - let live = snapshot - .site - .active_channel - .as_deref() - .map(|channel| format!("{} on {}", release, channel)) - .unwrap_or_else(|| release.to_string()); - details.push(format!("Live {}", live)); - } else if snapshot.site.release_count > 0 { - details.push(format!("Releases {}", snapshot.site.release_count)); - } - if let Some(cid) = snapshot.site.active_bundle_cid.as_deref() { - details.push(format!("Bundle elastos://{}", cid)); - } - details.push("Public mywebsite publish gives a temporary HTTPS URL".to_string()); - details.extend(wrap_with_label( - "Commands", - "mywebsite stage - mywebsite preview - mywebsite publish - mywebsite open - elastos site publish --release - elastos site activate --channel live - elastos site rollback --target publisher", - width, - )); - } - "Public" => { - details.push(format!( - "Channels {} total - {} active", - snapshot.shares.channel_count, snapshot.shares.active_count - )); - if let Some(author_did) = snapshot.shares.author_did.as_deref() { - details.push(format!( - "Signer {}", - truncate(author_did, width.saturating_sub(13).max(16)) - )); - } - if let Some(channel) = snapshot.shares.channels.first() { - details.push(format!( - "Latest {} v{} {}", - channel.name, channel.latest_version, channel.status - )); - details.push(format!( - "Open elastos://{}", - truncate(&channel.latest_cid, width.saturating_sub(16).max(16)) - )); - if let Some(head_cid) = channel.head_cid.as_deref() { - details.push(format!( - "Head elastos://{}", - truncate(head_cid, width.saturating_sub(16).max(16)) - )); - } - } else { - details.push("Latest none yet".to_string()); - } - details.extend(wrap_with_label( - "Commands", - "elastos share - elastos shares list - elastos attest - elastos open elastos://", - width, - )); - } "Local" => { details.extend(wrap_with_label( "Commands", @@ -722,9 +589,6 @@ fn canonical_target_title(target: &str, title: &str) -> String { fn app_target_action_id(snapshot: &HomeSnapshot, target: &HomeTargetStatus) -> Option { let target_id = target.target.as_str(); - if target_id == "chat" && action_by_id(snapshot, "chat").is_some() { - return Some("chat".to_string()); - } let explicit_open = format!("open-gui:{target_id}"); action_by_id(snapshot, &explicit_open).map(|_| explicit_open) } diff --git a/capsules/home-gui/browser/elastos-theme.js b/capsules/home-gui/browser/elastos-theme.js index cbaec4163..24e9e2cbb 100644 --- a/capsules/home-gui/browser/elastos-theme.js +++ b/capsules/home-gui/browser/elastos-theme.js @@ -206,6 +206,27 @@ }); } + // The shell's size class (`elastos:shell-layout`): phone means the shell's + // own title bar sits above the frame and no window controls overlay it, so + // elastos-ui.css drops the desktop chrome safe areas and capsules take + // their phone layout. Unknown values clear the attribute (desktop). + const FORM_FACTORS = ["phone", "tablet", "desktop"]; + const POINTERS = ["coarse", "fine"]; + + function setOrClear(name, value, allowed) { + if (allowed.includes(value)) { + document.documentElement.setAttribute(name, value); + } else { + document.documentElement.removeAttribute(name); + } + } + + function applyShellLayout(layout) { + const value = layout && typeof layout === "object" ? layout : {}; + setOrClear("data-el-form-factor", value.formFactor, FORM_FACTORS); + setOrClear("data-el-pointer", value.pointer, POINTERS); + } + // Opaque-sandboxed frames (no allow-same-origin) own no browser-profile // storage, so persistence stays with the host and the shell relays // preferences by message instead. Cross-frame updates arrive as @@ -216,6 +237,10 @@ return; } const message = event.data || {}; + if (message.type === "elastos:shell-layout") { + applyShellLayout(message.layout); + return; + } if (message.type !== "elastos:ui-preference") { return; } diff --git a/capsules/home-gui/browser/elastos-ui.css b/capsules/home-gui/browser/elastos-ui.css index 158930d22..64917ee6a 100644 --- a/capsules/home-gui/browser/elastos-ui.css +++ b/capsules/home-gui/browser/elastos-ui.css @@ -4,11 +4,12 @@ * This file lives at capsules/_shared/elastos-ui.css and is VENDORED into each * participating capsule's browser/ dir by `just vendor-ui` (no gateway route, * no shared runtime surface — capsules stay self-contained). Edit THIS file, - * then run `just vendor-ui`; `just alignment-check` fails on drift. + * then run `just vendor-ui`; `scripts/vendor-ui-tokens.sh --check` fails on drift. * * Contents: Inter (OFL, latin variable subset), palette, type scale, radii, - * hairlines, blur/elevation steps, motion tokens, and minimal control - * primitives. Layout is each app's business — tokens only. + * hairlines, blur/elevation steps, motion tokens, minimal control + * primitives, and the phone push drawer (with elastos-drawer.js). Layout is + * otherwise each app's business — tokens only. */ @font-face { @@ -386,6 +387,108 @@ display: none; } +/* Phone stage (html[data-el-form-factor="phone"], set from the shell's + `elastos:shell-layout` message by elastos-theme.js). The shell's own 44 px + title bar sits above the frame and no traffic lights overlay it, so the + desktop chrome safe areas are zero. The drawer tokens are the Assistant's + push-sidebar values, so every capsule's sidebar moves the same way. */ +:root { + --el-drawer-w: min(300px, 82vw); + --el-drawer-ms: 420ms; + --el-drawer-ease: cubic-bezier(0.22, 1, 0.36, 1); + --el-drawer-room-radius: 28px; + --el-touch-target: 44px; +} + +:root[data-el-form-factor="phone"] { + --window-chrome-safe-top: 0px; + --window-chrome-safe-leading: 0px; +} + +@media (prefers-reduced-motion: reduce) { + :root { + --el-drawer-ms: 1ms; + } +} + +/* Phone push drawer (elastos-drawer.js): the sidebar leaves the layout and + sits under the leading edge; opening slides it in and pushes the room + aside by the same width with a rounded edge. Transform only — no reflow of + the room while it moves. */ +.el-drawer-toggle { + display: none; +} + +:root[data-el-form-factor="phone"] .el-drawer-toggle { + display: inline-grid; + place-items: center; + flex: 0 0 auto; + width: var(--el-touch-target); + height: var(--el-touch-target); + padding: 0; + border: 0; + border-radius: var(--el-radius-md); + background: transparent; + color: var(--el-text); + cursor: pointer; +} + +:root[data-el-form-factor="phone"] .el-drawer-toggle::before { + content: ""; + width: 22px; + height: 22px; + background: currentColor; + -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='16' rx='3'/%3E%3Cpath d='M9 4v16'/%3E%3C/svg%3E") center / contain no-repeat; + mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='16' rx='3'/%3E%3Cpath d='M9 4v16'/%3E%3C/svg%3E") center / contain no-repeat; +} + +:root[data-el-form-factor="phone"] .el-drawer-toggle:active { + background: var(--el-lift); +} + +:root[data-el-form-factor="phone"] .el-drawer-toggle:focus-visible { + outline: 2px solid var(--el-focus); + outline-offset: -2px; +} + +:root[data-el-form-factor="phone"] [data-el-drawer] { + position: fixed; + top: 0; + bottom: 0; + left: 0; + z-index: 40; + width: var(--el-drawer-w); + max-width: none; + overflow-y: auto; + overscroll-behavior: contain; + outline: none; + transform: translateX(-105%); + visibility: hidden; + transition: + transform var(--el-drawer-ms) var(--el-drawer-ease), + visibility 0s linear var(--el-drawer-ms); +} + +:root[data-el-form-factor="phone"] [data-el-drawer][data-el-drawer-state="open"] { + transform: none; + visibility: visible; + transition: transform var(--el-drawer-ms) var(--el-drawer-ease); +} + +:root[data-el-form-factor="phone"] [data-el-drawer-room] { + transition: + transform var(--el-drawer-ms) var(--el-drawer-ease), + border-radius var(--el-drawer-ms) var(--el-drawer-ease); +} + +:root[data-el-form-factor="phone"] [data-el-drawer-room][data-el-drawer-state="open"] { + transform: translateX(var(--el-drawer-w)); + border-radius: var(--el-drawer-room-radius) 0 0 var(--el-drawer-room-radius); + overflow: hidden; + box-shadow: -1px 0 0 var(--el-hairline); + cursor: pointer; +} + @media (prefers-reduced-motion: reduce) { .el-app *, .el-app *::before, diff --git a/capsules/home-gui/browser/home-agent-message-contract.js b/capsules/home-gui/browser/home-agent-message-contract.js index 1c68dc879..a2fdba0a0 100644 --- a/capsules/home-gui/browser/home-agent-message-contract.js +++ b/capsules/home-gui/browser/home-agent-message-contract.js @@ -84,3 +84,51 @@ export function normalizeHomeAgentBrowserUrl(message) { return ""; } } + +const ASSISTANT_DOC_ID = /^[0-9a-f]{32}$/; + +/* Each Assistant document announces itself: hello {docId} when its script + starts, ready {docId} once its workspace has loaded. Messages from one + source arrive in order, so a document's hello always precedes its ready. + A hello means a new document started (also an in-frame reload): hide until + that document's ready. A ready from any other document is ignored. + An Assistant from an earlier release (kept after Undo with the Home tab + open) sends only {type} ready; that shows the room as it always did. + receive() returns "hide", "show" or "" (no change). */ +export function createAssistantFrameReadiness() { + let current = null; + let shown = false; + return Object.freeze({ + receive(message) { + if (hasExactKeys(message, ["type", "docId"]) && + typeof message.docId === "string" && ASSISTANT_DOC_ID.test(message.docId)) { + if (message.type === "home-agent:hello") { + current = message.docId; + shown = false; + return "hide"; + } + if (message.type === "home-agent:ready" && message.docId === current && !shown) { + shown = true; + return "show"; + } + return ""; + } + if (hasExactKeys(message, ["type"]) && message.type === "home-agent:ready") { + /* A legacy document is now active (e.g. Undo, then an in-frame reload + into the old Assistant). One source delivers in order, so an old + document's ready always arrives before the next document's hello and + cannot land late after a current hello; after Home changes src, a + stale legacy ready can at most show the room until the new hello. */ + current = null; + shown = true; + return "show"; + } + return ""; + }, + /* Home is about to set or change the frame src: no document is current. */ + reset() { + current = null; + shown = false; + }, + }); +} diff --git a/capsules/home-gui/browser/home-gui-shell.js b/capsules/home-gui/browser/home-gui-shell.js index 737923255..5cead4926 100644 --- a/capsules/home-gui/browser/home-gui-shell.js +++ b/capsules/home-gui/browser/home-gui-shell.js @@ -5,27 +5,39 @@ import { openHomeGuiTarget, relaunchHomeGuiWindowForToken, renewHomeGuiBrowserWindowAuthority, + renewHomeGuiChatWindowAuthority, restoreHomeGuiSession, setHomeGuiMenuManifest, handleHomeGuiHomeNavigation, setHomeGuiMounted, showHomeGuiDesktop, syncHomeGuiProjection, -} from "./home-gui.js?v=home-20260813a"; +} from "./home-gui.js?v=home-20261101d"; import { acceptHomeBrowserContextId, + desktopBackdrop, hasHomeBrowserContextId, setHomeGuiLaunchToken, -} from "./shell-core.js?v=home-20260813a"; +} from "./shell-core.js?v=home-20261101d"; import { isTrustedHomeGuiMessage, projectHomeGuiAuthority, -} from "./home-gui-authority.js?v=home-20260813a"; +} from "./home-gui-authority.js?v=home-20261101d"; +import { FORM_FACTOR_EVENT, isPhone, relayKeyboardInset } from "./shell-form-factor.js?v=home-20261101d"; +import { applyHomeLinkStatus } from "./shell-link-status.js?v=home-20261101d"; +import { createHomeBackgroundImage } from "/apps/home/home-background-image.js?v=home-20261101d"; const route = new URL(window.location.href); const fragment = new URLSearchParams(route.hash.replace(/^#/, "")); const homeToken = fragment.get("home_token") || ""; const homeOrigin = route.searchParams.get("home_origin") || ""; +const backgroundImage = createHomeBackgroundImage({ homeOrigin, homeToken, + apply: (url) => { + if (!desktopBackdrop) return; + if (url) desktopBackdrop.style.setProperty("--desktop-wallpaper", `url("${url}")`); + else desktopBackdrop.style.removeProperty("--desktop-wallpaper"); + }, +}); const pendingRequests = new Map(); const HOME_GUI_REQUEST_TIMEOUT_MS = 30_000; const consumedAuthorizedAttachmentReceipts = new Set(); @@ -39,7 +51,7 @@ const AUTHORIZED_ATTACHMENT_TARGET_TITLES = Object.freeze({ "wallet-unisat": "UniSat", }); let currentSummary = null; -let restoredSession = false; +let sessionRestore = null; if (!homeToken || !homeOrigin || window.parent === window) { throw new Error("Home GUI requires an isolated Home launch"); @@ -131,20 +143,44 @@ async function applySummary(summary, options = {}) { homeGuiWasMounted: previous !== null, ...options, }); + backgroundImage.update(summary?.authority?.signed_in === true + ? summary?.appearance?.background_image_url : ""); await restoreSessionWhenReady(); document.body.dataset.homeStatus = "ready"; } -async function restoreSessionWhenReady() { +// Home is ready only once saved windows have reopened: every summary waits for +// the one restore. A restore that fails is logged and Home opens without those +// windows; it is never left booting or in error. +function restoreSessionWhenReady() { if ( - restoredSession || - currentSummary?.authority?.signed_in !== true || - !hasHomeBrowserContextId() + !sessionRestore && + currentSummary?.authority?.signed_in === true && + hasHomeBrowserContextId() ) { + sessionRestore = restoreHomeGuiSession().catch((error) => { + console.error("home-gui session restore failed", error); + }); + } + return sessionRestore; +} + +function acceptShellContext(browserContextId) { + if (!acceptHomeBrowserContextId(browserContextId) || sessionRestore) { + return; + } + const restore = restoreSessionWhenReady(); + // A summary applied before the context marked Home ready with nothing + // restored; readiness now waits for the restore that starts here. + if (!restore || document.body.dataset.homeStatus !== "ready") { return; } - restoredSession = true; - await restoreHomeGuiSession(); + document.body.dataset.homeStatus = "booting"; + restore.then(() => { + if (document.body.dataset.homeStatus === "booting") { + document.body.dataset.homeStatus = "ready"; + } + }); } function handleGuiCommand(message) { @@ -158,6 +194,23 @@ function handleGuiCommand(message) { if (command === "renew-browser-authority") { return handleBrowserAuthorityRenewalCommand(message); } + if (command === "renew-chat-authority") { + if (!hasExactKeys(message, ["type", "command", "requestId", "homeToken", "launched", "expiresAt", "phase"]) + || !/^[A-Za-z0-9-]{1,64}$/.test(message.requestId) + || !Number.isSafeInteger(message.expiresAt) || !["prepare", "commit"].includes(message.phase)) return false; + const freshHomeToken = new URLSearchParams(new URL(message.launched?.route, homeOrigin).hash.slice(1)).get("home_token") || ""; + if (message.phase === "commit") { + const ok = renewHomeGuiChatWindowAuthority(message.homeToken, message.launched, homeOrigin); + postToHome({ type: "home:chat-authority-committed", requestId: message.requestId, + oldHomeToken: message.homeToken, freshHomeToken, ok }); + return ok; + } + const ok = message.expiresAt > Date.now() + && renewHomeGuiChatWindowAuthority(message.homeToken, message.launched, homeOrigin, false); + postToHome({ type: "home:chat-authority-renewed", requestId: message.requestId, + oldHomeToken: message.homeToken, freshHomeToken, ok }); + return ok; + } if (command === "open-target") { return openHomeGuiTarget(message.target, { query: message.query || {} }); } @@ -356,18 +409,21 @@ window.addEventListener("message", (event) => { return; } if (message.type === "home:shell-context") { - if (acceptHomeBrowserContextId(message.browserContextId)) { - restoreSessionWhenReady().catch((error) => { - document.body.dataset.homeStatus = "error"; - console.error("home-gui session restore failed", error); - }); - } + acceptShellContext(message.browserContextId); return; } if (message.type === "home:shell-response") { settleRequest(message); return; } + if (message.type === "home:keyboard-inset") { + relayKeyboardInset(message.inset); + return; + } + if (message.type === "home:link-status") { + applyHomeLinkStatus(message); + return; + } if (message.type === "home:shell-summary") { applySummary(message.summary).catch((error) => { document.body.dataset.homeStatus = "error"; @@ -388,6 +444,13 @@ window.addEventListener("message", (event) => { } }); +// The host page owns the top-level viewport tag; it takes the phone variant +// only while this shell's committed form factor is a phone (also at load: +// the first commit happens when the interactions bind). +window.addEventListener(FORM_FACTOR_EVENT, () => { + postToHome({ type: "home:form-factor", phone: isPhone() }); +}); + bindHomeGuiInteractions({ activateHomeGui: () => Promise.resolve(showHomeGuiDesktop()), requestHomeUnlock: () => requestHome("home:request-unlock"), diff --git a/capsules/home-gui/browser/home-gui-template.html b/capsules/home-gui/browser/home-gui-template.html index cdbfbb7a1..c19ef57f7 100644 --- a/capsules/home-gui/browser/home-gui-template.html +++ b/capsules/home-gui/browser/home-gui-template.html @@ -47,7 +47,7 @@ + + + + + + +
    ElastOS + + + +