Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc235fc312 | ||
|
|
249f97d1ed | ||
|
|
3e9310d6cd | ||
|
|
9051c5891e | ||
|
|
56d94e6974 | ||
|
|
e6a96bea47 | ||
|
|
cf82e37c36 | ||
|
|
4fb3e0500a | ||
|
|
9c7d51429e | ||
|
|
c1985443fd | ||
|
|
17a27fd312 | ||
|
|
557ffdbe35 | ||
|
|
e9bfe34850 | ||
|
|
1a4540d386 | ||
|
|
a0c4b1e061 | ||
|
|
e275ba8d2e | ||
|
|
db7eeee07b | ||
|
|
84d5f24f5f | ||
|
|
42948b70e3 | ||
|
|
28d3bd03b2 | ||
|
|
6148f862b9 | ||
|
|
0a32610b37 | ||
|
|
514759bde7 | ||
|
|
2eb27ffb4a | ||
|
|
2ce24fdbf8 | ||
|
|
e9ae10e569 | ||
|
|
a1940418fb | ||
|
|
6fdc62c008 | ||
|
|
5e5cb7a292 | ||
|
|
f5ab3e41c5 | ||
|
|
036bdde764 | ||
|
|
691bf85d7e | ||
|
|
4482965d80 | ||
|
|
fdca8fb592 | ||
|
|
c7c32210e6 | ||
|
|
316a04f606 | ||
|
|
c4da2afb22 | ||
|
|
9eaa45a291 | ||
|
|
81a9439eb2 | ||
|
|
be9b550209 | ||
|
|
6653813cb9 | ||
|
|
cf1278295d | ||
|
|
cdb5ddb2da | ||
|
|
1cdebb68a0 | ||
|
|
fece42ce0a | ||
|
|
c5867b2876 | ||
|
|
43e257e7de | ||
|
|
9dcdeb15ec | ||
|
|
060a209ecb | ||
|
|
e1e3da946f | ||
|
|
49a9f74753 | ||
|
|
74b19843ae | ||
|
|
d691e28675 | ||
|
|
2a5f0d6063 | ||
|
|
66a0813e44 | ||
|
|
64d6d25d65 | ||
|
|
b443c20cef | ||
|
|
5e8c8367f3 | ||
|
|
2b0f846f1b | ||
|
|
e7713a28ae | ||
|
|
7948d071e0 | ||
|
|
fb23717102 | ||
|
|
3d959c46d0 | ||
|
|
4cdd61eb78 | ||
|
|
6d08d84011 | ||
|
|
f6cafd1a15 | ||
|
|
5792887883 | ||
|
|
e82ee731bf | ||
|
|
5e09aae4ca | ||
|
|
740f7b0fb6 | ||
|
|
7510a6f66a | ||
|
|
1ff7d458a5 | ||
|
|
c3528fb201 | ||
|
|
3f5dff35f8 | ||
|
|
08bfe2b263 | ||
|
|
42645a7e0a | ||
|
|
7d4c8ef6b2 | ||
|
|
a1d7b8db6f | ||
|
|
4a3a4558e2 | ||
|
|
1b83fc85cd | ||
|
|
c1a10b6056 | ||
|
|
841a9b4c8a | ||
|
|
f3db02018f | ||
|
|
4cbaee59cd | ||
|
|
0d10aa4098 | ||
|
|
f3f8aa5397 | ||
|
|
4970af6bb9 | ||
|
|
a48aebc78c | ||
|
|
26bbddde8f | ||
|
|
b48a556de5 | ||
|
|
aab5c490dc | ||
|
|
d54cc49d66 | ||
|
|
0cef22ef83 | ||
|
|
7b2f712e20 | ||
|
|
1a92127dfa | ||
|
|
26a05292b9 | ||
|
|
caaa79bb76 | ||
|
|
b80c0d85e0 | ||
|
|
0641281cfe | ||
|
|
f414853d70 | ||
|
|
7c677c5057 | ||
|
|
969c7d1c8e | ||
|
|
b202480a66 | ||
|
|
9e80764c2b | ||
|
|
f5a5320f8f | ||
|
|
7389fc0e25 | ||
|
|
ce915d3438 | ||
|
|
3ef910d23e | ||
|
|
845b26a73b | ||
|
|
e0545e2f94 | ||
|
|
01341d983c | ||
|
|
0d68e10dd7 | ||
|
|
e6a60c0dc5 | ||
|
|
7dbd5acbb1 | ||
|
|
7a87f3cfb8 | ||
|
|
b817225fb8 | ||
|
|
a097c848bb | ||
|
|
a47d3e3e35 | ||
|
|
4d4bcaab1e | ||
|
|
265a3dff27 | ||
|
|
97fe3972c8 | ||
|
|
7c91ce2fa7 | ||
|
|
951993db17 | ||
|
|
357a1a982b | ||
|
|
f6f69b408f | ||
|
|
98399b85e3 | ||
|
|
38a773f245 | ||
|
|
e9e2e5026c | ||
|
|
8649de6199 | ||
|
|
3885a2a20f | ||
|
|
dde9fddae4 | ||
|
|
3a08e6df9d | ||
|
|
f427bec31c | ||
|
|
67e0739bec | ||
|
|
c7022cc139 | ||
|
|
65a0de8979 | ||
|
|
d0134722af | ||
|
|
efc7181aa0 | ||
|
|
3729d269d0 | ||
|
|
7dd8a7f2e3 | ||
|
|
56bbcfc3ee | ||
|
|
eec6212cdf | ||
|
|
a5b3b8743a | ||
|
|
4dd9072a2b | ||
|
|
073285409b | ||
|
|
41da61dd6a | ||
|
|
35e8dae939 | ||
|
|
05e77b69c4 | ||
|
|
745eefe0be | ||
|
|
d7165b4720 | ||
|
|
7b1163f75c | ||
|
|
507f5623f4 | ||
|
|
5ace7c9c66 | ||
|
|
3b35b762cb | ||
|
|
dbd3865e3b | ||
|
|
6bf1e6fa06 | ||
|
|
1c0170554e | ||
|
|
1d79254053 | ||
|
|
974ab5a8dd | ||
|
|
eaebf4b896 | ||
|
|
cf747e1b82 | ||
|
|
455fe15bd1 | ||
|
|
c4d0eb9350 | ||
|
|
10d95348b1 | ||
|
|
f86b1cf6a1 | ||
|
|
259e9cfccf | ||
|
|
7318b20f55 | ||
|
|
322a36f365 | ||
|
|
b8b20eac6d | ||
|
|
1fb123d701 | ||
|
|
138f4bd850 | ||
|
|
20abf31093 | ||
|
|
4abc551f9e | ||
|
|
67707763f7 | ||
|
|
df8915cf5c | ||
|
|
a1d16c61ec | ||
|
|
64b5eb8279 | ||
|
|
c66122c255 | ||
|
|
b792175ec5 | ||
|
|
b944bee121 | ||
|
|
88ff2f79d5 | ||
|
|
c3fa1fb736 | ||
|
|
e9eb9edc23 | ||
|
|
e8018d8008 | ||
|
|
694a10f604 | ||
|
|
b2378c01ea | ||
|
|
e2451484d9 | ||
|
|
dccdc950bf | ||
|
|
dd7be2bfd8 | ||
|
|
66b05163e3 | ||
|
|
7789bf6907 | ||
|
|
8b6abe0151 | ||
|
|
25eb40ab31 | ||
|
|
0336c1fa37 | ||
|
|
09541de076 | ||
|
|
2583fb66cc | ||
|
|
037ea92679 | ||
|
|
38f65e7053 | ||
|
|
ebbc416d4b | ||
|
|
13c4f8da2b | ||
|
|
099b8c9fa5 | ||
|
|
1638d32e1c | ||
|
|
13e1c93c74 | ||
|
|
affbd48a3f | ||
|
|
00f83ca7af | ||
|
|
441bd25f90 | ||
|
|
128df57005 | ||
|
|
a80cd26341 | ||
|
|
700212608a | ||
|
|
8fb064ed70 | ||
|
|
a92eb1f33d | ||
|
|
2454e67e09 | ||
|
|
862a490038 | ||
|
|
ffc57d5f20 | ||
|
|
e96654ced1 | ||
|
|
dd763b45e1 | ||
|
|
2710841801 | ||
|
|
a9e1eabcbd | ||
|
|
30a2e47390 | ||
|
|
f7076c38ea | ||
|
|
e6d522493b | ||
|
|
c286573f5c | ||
|
|
aef18b7359 | ||
|
|
17e183f5cf | ||
|
|
a53d8ed4e4 | ||
|
|
755e329b01 | ||
|
|
765c466d6d | ||
|
|
cf3becfb2e | ||
|
|
b508f642b2 | ||
|
|
3fcee21ff7 | ||
|
|
b01cb41950 | ||
|
|
7642cbb5b7 | ||
|
|
7a6334d920 | ||
|
|
d96bc38bea | ||
|
|
a31a569d52 | ||
|
|
0d3aacd316 | ||
|
|
ece8a3e701 | ||
|
|
ceb3980b93 | ||
|
|
01eba1b8d9 | ||
|
|
cf28ea0d1c | ||
|
|
41dd3b11b7 | ||
|
|
5a1687484c | ||
|
|
6143338116 | ||
|
|
39c232548c | ||
|
|
e2a93e17f9 | ||
|
|
0b990443de | ||
|
|
02fe19effa | ||
|
|
920cc9ac38 | ||
|
|
ba22890205 | ||
|
|
a59cfa7670 | ||
|
|
7cdd7c5333 | ||
|
|
e3379b960e | ||
|
|
7b675864a8 | ||
|
|
3b853b329f | ||
|
|
537c515dde | ||
|
|
238afbc2f8 | ||
|
|
2a71c20ee4 | ||
|
|
40c66b1741 | ||
|
|
94ad808028 | ||
|
|
0c8b5ed59a | ||
|
|
56fe23549c | ||
|
|
867d7e5d25 | ||
|
|
a0cd761c96 | ||
|
|
7c3502f031 | ||
|
|
61ab07ced3 | ||
|
|
281c6d6069 | ||
|
|
82634dfe3b | ||
|
|
9be3394bac | ||
|
|
4228ee326c | ||
|
|
fa1110e4d3 | ||
|
|
050c47d3a7 | ||
|
|
161895ed1a | ||
|
|
aeffdc3632 | ||
|
|
ecf0da1796 | ||
|
|
990fafa988 | ||
|
|
ceb0a8b3e3 | ||
|
|
3b283f3167 | ||
|
|
2b29d08064 | ||
|
|
86ed3de1c1 | ||
|
|
acf035d848 | ||
|
|
cab71c9711 | ||
|
|
c17440f5b4 | ||
|
|
fd566bda14 | ||
|
|
e47dccbe87 | ||
|
|
2a172f9779 | ||
|
|
ce630a6381 | ||
|
|
a882798143 | ||
|
|
44f9327087 | ||
|
|
e654676148 | ||
|
|
840e266b5d | ||
|
|
7d89fa2591 | ||
|
|
5f67c023a2 | ||
|
|
af3e5b299c | ||
|
|
b3b4013637 | ||
|
|
9ad341d668 | ||
|
|
d7a8d9a1c7 | ||
|
|
2d36ae6326 | ||
|
|
208ba02a4a | ||
|
|
4cdb21c5cd | ||
|
|
5d6cc8125b | ||
|
|
237933069e | ||
|
|
99660db73f | ||
|
|
68fa676cbf | ||
|
|
8794f002d5 | ||
|
|
d52ef185b1 | ||
|
|
3ca77c46c7 | ||
|
|
89d5d807ee | ||
|
|
9e3427a37e | ||
|
|
7ce25ecfca | ||
|
|
1ca77bee26 | ||
|
|
5dbc7cc68d | ||
|
|
0d45c78917 | ||
|
|
31fb4f7c8b | ||
|
|
e9acb6fad5 | ||
|
|
ab402e1178 | ||
|
|
293701f520 | ||
|
|
7b38ba0e65 | ||
|
|
5d8ee8fc28 | ||
|
|
3e2e4be680 | ||
|
|
3863fe6412 | ||
|
|
2b71ea21ad | ||
|
|
36f21c5a4f | ||
|
|
cf90bd9c86 | ||
|
|
5f159c43c5 | ||
|
|
c02613e15f | ||
|
|
32cd1175fb | ||
|
|
0152e053e1 | ||
|
|
8d1e73edc7 | ||
|
|
a5f51eadf1 | ||
|
|
4ac21a4f63 | ||
|
|
91fdf2aa25 | ||
|
|
44614d4a7d | ||
|
|
0e9f617667 | ||
|
|
7e7e348a14 | ||
|
|
cc3d0d1ef7 | ||
|
|
5b608718bb | ||
|
|
3a6ab81549 | ||
|
|
c48681b2f0 | ||
|
|
86d786cbc0 | ||
|
|
ec653b7b80 | ||
|
|
cbc34e1c8a | ||
|
|
1f37d94f9e | ||
|
|
3ee0e041fa | ||
|
|
4074f4fffa | ||
|
|
7286fd6e3f | ||
|
|
4b608117a2 | ||
|
|
47b4d245aa | ||
|
|
36ff508fec | ||
|
|
772b5fdf0f | ||
|
|
eace21dcae | ||
|
|
163080b609 | ||
|
|
4938fbffa8 | ||
|
|
d5db20c296 | ||
|
|
415cb857d9 | ||
|
|
a641250da6 | ||
|
|
4d674a3f17 |
No files matched your search
@@ -14,6 +14,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
if: matrix.runtime == 'node'
|
if: matrix.runtime == 'node'
|
||||||
@@ -26,7 +28,9 @@ jobs:
|
|||||||
if: matrix.runtime == 'bun'
|
if: matrix.runtime == 'bun'
|
||||||
uses: oven-sh/setup-bun@v2
|
uses: oven-sh/setup-bun@v2
|
||||||
with:
|
with:
|
||||||
bun-version: "1.3.x"
|
# bun.sh downloads currently fail with:
|
||||||
|
# "Failed to list releases from GitHub: 401" -> "Unexpected HTTP response: 400"
|
||||||
|
bun-download-url: "https://github.com/oven-sh/bun/releases/latest/download/bun-linux-x64.zip"
|
||||||
|
|
||||||
- name: Setup Node.js (tooling for bun)
|
- name: Setup Node.js (tooling for bun)
|
||||||
if: matrix.runtime == 'bun'
|
if: matrix.runtime == 'bun'
|
||||||
@@ -93,15 +97,17 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
- name: Select Xcode 26.1
|
- name: Select Xcode 26.1
|
||||||
run: |
|
run: |
|
||||||
sudo xcode-select -s /Applications/Xcode_26.1.app
|
sudo xcode-select -s /Applications/Xcode_26.1.app
|
||||||
xcodebuild -version
|
xcodebuild -version
|
||||||
|
|
||||||
- name: Install SwiftLint / SwiftFormat
|
- name: Install XcodeGen / SwiftLint / SwiftFormat
|
||||||
run: |
|
run: |
|
||||||
brew install swiftlint swiftformat
|
brew install xcodegen swiftlint swiftformat
|
||||||
|
|
||||||
- name: Show toolchain
|
- name: Show toolchain
|
||||||
run: |
|
run: |
|
||||||
@@ -118,5 +124,171 @@ jobs:
|
|||||||
- name: Swift build (release)
|
- name: Swift build (release)
|
||||||
run: swift build --package-path apps/macos --configuration release
|
run: swift build --package-path apps/macos --configuration release
|
||||||
|
|
||||||
- name: Swift tests
|
- name: Swift tests (coverage)
|
||||||
run: swift test --package-path apps/macos --parallel
|
run: swift test --package-path apps/macos --parallel --enable-code-coverage --show-codecov-path
|
||||||
|
|
||||||
|
- name: Generate iOS project
|
||||||
|
run: |
|
||||||
|
cd apps/ios
|
||||||
|
xcodegen generate
|
||||||
|
|
||||||
|
- name: iOS tests
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
RESULT_BUNDLE_PATH="$RUNNER_TEMP/Clawdis-iOS.xcresult"
|
||||||
|
DEST_ID="$(
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
def sh(args: list[str]) -> str:
|
||||||
|
return subprocess.check_output(args, text=True).strip()
|
||||||
|
|
||||||
|
# Prefer an already-created iPhone simulator if it exists.
|
||||||
|
devices = json.loads(sh(["xcrun", "simctl", "list", "devices", "-j"]))
|
||||||
|
candidates: list[tuple[str, str]] = []
|
||||||
|
for runtime, devs in (devices.get("devices") or {}).items():
|
||||||
|
for dev in devs or []:
|
||||||
|
if not dev.get("isAvailable"):
|
||||||
|
continue
|
||||||
|
name = str(dev.get("name") or "")
|
||||||
|
udid = str(dev.get("udid") or "")
|
||||||
|
if not udid or not name.startswith("iPhone"):
|
||||||
|
continue
|
||||||
|
candidates.append((name, udid))
|
||||||
|
|
||||||
|
candidates.sort(key=lambda it: (0 if "iPhone 16" in it[0] else 1, it[0]))
|
||||||
|
if candidates:
|
||||||
|
print(candidates[0][1])
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
# Otherwise, create one from the newest available iOS runtime.
|
||||||
|
runtimes = json.loads(sh(["xcrun", "simctl", "list", "runtimes", "-j"])).get("runtimes") or []
|
||||||
|
ios = [rt for rt in runtimes if rt.get("platform") == "iOS" and rt.get("isAvailable")]
|
||||||
|
if not ios:
|
||||||
|
print("No available iOS runtimes found.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
def version_key(rt: dict) -> tuple[int, ...]:
|
||||||
|
parts: list[int] = []
|
||||||
|
for p in str(rt.get("version") or "0").split("."):
|
||||||
|
try:
|
||||||
|
parts.append(int(p))
|
||||||
|
except ValueError:
|
||||||
|
parts.append(0)
|
||||||
|
return tuple(parts)
|
||||||
|
|
||||||
|
ios.sort(key=version_key, reverse=True)
|
||||||
|
runtime = ios[0]
|
||||||
|
runtime_id = str(runtime.get("identifier") or "")
|
||||||
|
if not runtime_id:
|
||||||
|
print("Missing iOS runtime identifier.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
supported = runtime.get("supportedDeviceTypes") or []
|
||||||
|
iphones = [dt for dt in supported if dt.get("productFamily") == "iPhone"]
|
||||||
|
if not iphones:
|
||||||
|
print("No iPhone device types for iOS runtime.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
iphones.sort(
|
||||||
|
key=lambda dt: (
|
||||||
|
0 if "iPhone 16" in str(dt.get("name") or "") else 1,
|
||||||
|
str(dt.get("name") or ""),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
device_type_id = str(iphones[0].get("identifier") or "")
|
||||||
|
if not device_type_id:
|
||||||
|
print("Missing iPhone device type identifier.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
sim_name = f"CI iPhone {uuid.uuid4().hex[:8]}"
|
||||||
|
udid = sh(["xcrun", "simctl", "create", sim_name, device_type_id, runtime_id])
|
||||||
|
if not udid:
|
||||||
|
print("Failed to create iPhone simulator.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
print(udid)
|
||||||
|
PY
|
||||||
|
)"
|
||||||
|
echo "Using iOS Simulator id: $DEST_ID"
|
||||||
|
xcodebuild test \
|
||||||
|
-project apps/ios/Clawdis.xcodeproj \
|
||||||
|
-scheme Clawdis \
|
||||||
|
-destination "platform=iOS Simulator,id=$DEST_ID" \
|
||||||
|
-resultBundlePath "$RESULT_BUNDLE_PATH" \
|
||||||
|
-enableCodeCoverage YES
|
||||||
|
|
||||||
|
- name: iOS coverage summary
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
RESULT_BUNDLE_PATH="$RUNNER_TEMP/Clawdis-iOS.xcresult"
|
||||||
|
xcrun xccov view --report --only-targets "$RESULT_BUNDLE_PATH"
|
||||||
|
|
||||||
|
- name: iOS coverage gate (50%)
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
RESULT_BUNDLE_PATH="$RUNNER_TEMP/Clawdis-iOS.xcresult"
|
||||||
|
RESULT_BUNDLE_PATH="$RESULT_BUNDLE_PATH" python3 - <<'PY'
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
target_name = "Clawdis.app"
|
||||||
|
minimum = 0.50
|
||||||
|
|
||||||
|
report = json.loads(
|
||||||
|
subprocess.check_output(
|
||||||
|
["xcrun", "xccov", "view", "--report", "--json", os.environ["RESULT_BUNDLE_PATH"]],
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
target_coverage = None
|
||||||
|
for target in report.get("targets", []):
|
||||||
|
if target.get("name") == target_name:
|
||||||
|
target_coverage = float(target["lineCoverage"])
|
||||||
|
break
|
||||||
|
|
||||||
|
if target_coverage is None:
|
||||||
|
print(f"Could not find coverage for target: {target_name}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"{target_name} line coverage: {target_coverage * 100:.2f}% (min {minimum * 100:.2f}%)")
|
||||||
|
if target_coverage + 1e-12 < minimum:
|
||||||
|
sys.exit(1)
|
||||||
|
PY
|
||||||
|
|
||||||
|
android:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
- name: Setup Java
|
||||||
|
uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: 21
|
||||||
|
|
||||||
|
- name: Setup Android SDK
|
||||||
|
uses: android-actions/setup-android@v3
|
||||||
|
|
||||||
|
- name: Setup Gradle
|
||||||
|
uses: gradle/actions/setup-gradle@v4
|
||||||
|
|
||||||
|
- name: Install Android SDK packages
|
||||||
|
run: |
|
||||||
|
yes | sdkmanager --licenses >/dev/null
|
||||||
|
sdkmanager --install \
|
||||||
|
"platform-tools" \
|
||||||
|
"platforms;android-36" \
|
||||||
|
"build-tools;36.0.0"
|
||||||
|
|
||||||
|
- name: Android unit tests + debug build
|
||||||
|
working-directory: apps/android
|
||||||
|
run: ./gradlew --no-daemon :app:testDebugUnitTest :app:assembleDebug
|
||||||
@@ -4,8 +4,11 @@ dist
|
|||||||
pnpm-lock.yaml
|
pnpm-lock.yaml
|
||||||
coverage
|
coverage
|
||||||
.pnpm-store
|
.pnpm-store
|
||||||
|
.worktrees/
|
||||||
|
.DS_Store
|
||||||
**/.DS_Store
|
**/.DS_Store
|
||||||
apps/macos/.build/
|
apps/macos/.build/
|
||||||
|
apps/shared/ClawdisKit/.build/
|
||||||
bin/clawdis-mac
|
bin/clawdis-mac
|
||||||
apps/macos/.build-local/
|
apps/macos/.build-local/
|
||||||
apps/macos/.swiftpm/
|
apps/macos/.swiftpm/
|
||||||
@@ -13,3 +16,21 @@ Core/
|
|||||||
apps/ios/*.xcodeproj/
|
apps/ios/*.xcodeproj/
|
||||||
apps/ios/*.xcworkspace/
|
apps/ios/*.xcworkspace/
|
||||||
apps/ios/.swiftpm/
|
apps/ios/.swiftpm/
|
||||||
|
|
||||||
|
# Vendor build artifacts
|
||||||
|
vendor/a2ui/renderers/lit/dist/
|
||||||
|
|
||||||
|
# fastlane (iOS)
|
||||||
|
apps/ios/fastlane/README.md
|
||||||
|
apps/ios/fastlane/report.xml
|
||||||
|
apps/ios/fastlane/Preview.html
|
||||||
|
apps/ios/fastlane/screenshots/
|
||||||
|
apps/ios/fastlane/test_output/
|
||||||
|
apps/ios/fastlane/logs/
|
||||||
|
|
||||||
|
# fastlane build artifacts (local)
|
||||||
|
apps/ios/*.ipa
|
||||||
|
apps/ios/*.dSYM.zip
|
||||||
|
|
||||||
|
# provisioning profiles (local)
|
||||||
|
apps/ios/*.mobileprovision
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[submodule "Peekaboo"]
|
||||||
|
path = Peekaboo
|
||||||
|
url = https://github.com/steipete/Peekaboo.git
|
||||||
@@ -48,4 +48,4 @@
|
|||||||
--allman false
|
--allman false
|
||||||
|
|
||||||
# Exclusions
|
# Exclusions
|
||||||
--exclude .build,.swiftpm,DerivedData,node_modules,dist,coverage,xcuserdata
|
--exclude .build,.swiftpm,DerivedData,node_modules,dist,coverage,xcuserdata,apps/macos/Sources/ClawdisProtocol
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
READ ~/Projects/agent-scripts/AGENTS.MD BEFORE ANYTHING (skip if missing).
|
|
||||||
|
|
||||||
# Repository Guidelines
|
# Repository Guidelines
|
||||||
|
|
||||||
## Project Structure & Module Organization
|
## Project Structure & Module Organization
|
||||||
@@ -34,15 +32,17 @@ READ ~/Projects/agent-scripts/AGENTS.MD BEFORE ANYTHING (skip if missing).
|
|||||||
|
|
||||||
## Security & Configuration Tips
|
## Security & Configuration Tips
|
||||||
- Web provider stores creds at `~/.clawdis/credentials/`; rerun `clawdis login` if logged out.
|
- Web provider stores creds at `~/.clawdis/credentials/`; rerun `clawdis login` if logged out.
|
||||||
- Pi/Tau sessions live under `~/.clawdis/sessions/` by default; the base directory is not configurable.
|
- Pi sessions live under `~/.clawdis/sessions/` by default; the base directory is not configurable.
|
||||||
- Never commit or publish real phone numbers, videos, or live configuration values. Use obviously fake placeholders in docs, tests, and examples.
|
- Never commit or publish real phone numbers, videos, or live configuration values. Use obviously fake placeholders in docs, tests, and examples.
|
||||||
|
|
||||||
## Agent-Specific Notes
|
## Agent-Specific Notes
|
||||||
- Gateway currently runs only as the menubar app (launchctl shows `application.com.steipete.clawdis.debug.*`), there is no separate LaunchAgent/helper label installed. Restart via the Clawdis Mac app or `scripts/restart-mac.sh`; to verify/kill use `launchctl print gui/$UID | grep clawdis` rather than expecting `com.steipete.clawdis`. **When debugging on macOS, start/stop the gateway via the app, not ad-hoc tmux sessions; kill any temporary tunnels before handoff.**
|
- Gateway currently runs only as the menubar app (launchctl shows `application.com.steipete.clawdis.debug.*`), there is no separate LaunchAgent/helper label installed. Restart via the Clawdis Mac app or `scripts/restart-mac.sh`; to verify/kill use `launchctl print gui/$UID | grep clawdis` rather than expecting `com.steipete.clawdis`. **When debugging on macOS, start/stop the gateway via the app, not ad-hoc tmux sessions; kill any temporary tunnels before handoff.**
|
||||||
- macOS logs: use `./scripts/clawlog.sh` (aka `vtlog`) to query unified logs for subsystem `com.steipete.clawdis`; it supports follow/tail/category filters and expects passwordless sudo for `/usr/bin/log`.
|
- macOS logs: use `./scripts/clawlog.sh` (aka `vtlog`) to query unified logs for subsystem `com.steipete.clawdis`; it supports follow/tail/category filters and expects passwordless sudo for `/usr/bin/log`.
|
||||||
- Also read the shared guardrails at `~/Projects/oracle/AGENTS.md` and `~/Projects/agent-scripts/AGENTS.MD` before making changes; align with any cross-repo rules noted there.
|
- Also read the shared guardrails at `~/Projects/oracle/AGENTS.md` and `~/Projects/agent-scripts/AGENTS.MD` before making changes; align with any cross-repo rules noted there.
|
||||||
|
- SwiftUI state management (iOS/macOS): prefer the `Observation` framework (`@Observable`, `@Bindable`) over `ObservableObject`/`@StateObject`; don’t introduce new `ObservableObject` unless required for compatibility, and migrate existing usages when touching related code.
|
||||||
- **Multi-agent safety:** do **not** create/apply/drop `git stash` entries unless Peter explicitly asks. Assume other agents may be working; keep unrelated WIP untouched and avoid cross-cutting state changes.
|
- **Multi-agent safety:** do **not** create/apply/drop `git stash` entries unless Peter explicitly asks. Assume other agents may be working; keep unrelated WIP untouched and avoid cross-cutting state changes.
|
||||||
- When asked to open a “session” file, open the Pi/Tau session logs under `~/.tau/agent/sessions/clawdis/*.jsonl` (newest unless a specific ID is given), not the default `sessions.json`.
|
- **Multi-agent safety:** do **not** switch branches / check out a different branch unless Peter explicitly asks.
|
||||||
|
- When asked to open a “session” file, open the Pi session logs under `~/.clawdis/sessions/*.jsonl` (newest unless a specific ID is given), not the default `sessions.json`.
|
||||||
- Menubar dimming + restart flow mirrors Trimmy: use `scripts/restart-mac.sh` (kills all Clawdis variants, runs `swift build`, packages, relaunches). Icon dimming depends on MenuBarExtraAccess wiring in AppMain; keep `appearsDisabled` updates intact when touching the status item.
|
- Menubar dimming + restart flow mirrors Trimmy: use `scripts/restart-mac.sh` (kills all Clawdis variants, runs `swift build`, packages, relaunches). Icon dimming depends on MenuBarExtraAccess wiring in AppMain; keep `appearsDisabled` updates intact when touching the status item.
|
||||||
- Never send streaming/partial replies to external messaging surfaces (WhatsApp, Telegram); only final replies should be delivered there. Streaming/tool events may still go to internal UIs/control channel.
|
- Never send streaming/partial replies to external messaging surfaces (WhatsApp, Telegram); only final replies should be delivered there. Streaming/tool events may still go to internal UIs/control channel.
|
||||||
- Voice wake forwarding tips:
|
- Voice wake forwarding tips:
|
||||||
|
|||||||
@@ -2,19 +2,37 @@
|
|||||||
|
|
||||||
## 2.0.0 — Unreleased
|
## 2.0.0 — Unreleased
|
||||||
|
|
||||||
First Clawdis release post rebrand. This is a semver-major because we dropped legacy providers/agents and moved defaults to new paths while adding a full macOS companion app.
|
### Bug Fixes
|
||||||
|
- macOS: Voice Wake / push-to-talk no longer initialize `AVAudioEngine` at app launch, preventing Bluetooth headphones from switching into headset profile when voice features are unused. (Thanks @Nachx639)
|
||||||
|
|
||||||
|
## 2.0.0-beta1 — 2025-12-14
|
||||||
|
|
||||||
|
First Clawdis release post rebrand. This is a semver-major because we dropped legacy providers/agents and moved defaults to new paths while adding a full macOS companion app, a WebSocket Gateway, and an iOS node (Iris).
|
||||||
|
|
||||||
### Breaking
|
### Breaking
|
||||||
- Renamed to **Clawdis**: defaults now live under `~/.clawdis` (sessions in `~/.clawdis/sessions/`, IPC at `~/.clawdis/clawdis.sock`, logs in `/tmp/clawdis`). Launchd labels and config filenames follow the new name; legacy stores are copied forward on first run.
|
- Renamed to **Clawdis**: defaults now live under `~/.clawdis` (sessions in `~/.clawdis/sessions/`, IPC at `~/.clawdis/clawdis.sock`, logs in `/tmp/clawdis`). Launchd labels and config filenames follow the new name; legacy stores are copied forward on first run.
|
||||||
- Pi/Tau only: `inbound.reply.agent.kind` accepts only `"pi"`, and the agent CLI/CLI flags for Claude/Codex/Gemini were removed. The Pi CLI runs in RPC mode with a persistent worker.
|
- Pi only: `inbound.reply.agent.kind` accepts only `"pi"`, and the agent CLI/CLI flags for Claude/Codex/Gemini were removed. The Pi CLI runs in RPC mode with a persistent worker.
|
||||||
- WhatsApp Web is the only transport; Twilio support and related CLI flags/tests were removed.
|
- WhatsApp Web is the only transport; Twilio support and related CLI flags/tests were removed.
|
||||||
- Direct chats now collapse into a single `main` session by default (no config needed); groups stay isolated as `group:<jid>`.
|
- Direct chats now collapse into a single `main` session by default (no config needed); groups stay isolated as `group:<jid>`.
|
||||||
- Gateway background helpers were removed; run `clawdis gateway --verbose` under your supervisor of choice if you want it detached.
|
- Gateway is now a loopback-only WebSocket daemon (`ws://127.0.0.1:18789`) that owns all providers/state; clients (CLI, WebChat, macOS app, nodes) connect to it. Start it explicitly (`clawdis gateway …`) or via Clawdis.app; helper subcommands no longer auto-spawn a gateway.
|
||||||
|
|
||||||
|
### Gateway, nodes, and automation
|
||||||
|
- New typed Gateway WS protocol (JSON schema validated) with `clawdis gateway {health,status,send,agent,call}` helpers and structured presence/instance updates for all clients.
|
||||||
|
- Optional LAN-facing bridge (`tcp://0.0.0.0:18790`) keeps the Gateway loopback-only while enabling direct Bonjour-discovered connections for paired nodes.
|
||||||
|
- Node pairing + management via `clawdis nodes {pending,approve,reject,invoke}` (used by the iOS node “Iris” and future remote nodes).
|
||||||
|
- Cron jobs are Gateway-owned (`clawdis cron …`) with run history stored as JSONL and support for “isolated summary” posting into the main session.
|
||||||
|
|
||||||
### macOS companion app
|
### macOS companion app
|
||||||
- **Clawdis.app menu bar companion**: packaged, signed bundle with gateway start/stop, launchd toggle, project-root and pnpm/node auto-resolution, live log shortcut, restart button, and status/recipient table plus badges/dimming for attention and paused states.
|
- **Clawdis.app menu bar companion**: packaged, signed bundle with gateway start/stop, launchd toggle, project-root and pnpm/node auto-resolution, live log shortcut, restart button, and status/recipient table plus badges/dimming for attention and paused states.
|
||||||
- **On-device Voice Wake**: Apple speech recognizer with wake-word table, language picker, live mic meter, “hold until silence,” animated ears/legs, and main-session routing that replies on the **last used surface** (WhatsApp/Telegram/WebChat). Delivery failures are logged, and the run remains visible via WebChat/session logs.
|
- **On-device Voice Wake**: Apple speech recognizer with wake-word table, language picker, live mic meter, “hold until silence,” animated ears/legs, and main-session routing that replies on the **last used surface** (WhatsApp/Telegram/WebChat). Delivery failures are logged, and the run remains visible via WebChat/session logs.
|
||||||
- **WebChat & Debugging**: bundled WebChat UI, Debug tab with heartbeat sliders, session-store picker, log opener (`clawlog`), gateway restart, health probes, and scrollable settings panes.
|
- **WebChat & Debugging**: bundled WebChat UI, Debug tab with heartbeat sliders, session-store picker, log opener (`clawlog`), gateway restart, health probes, and scrollable settings panes.
|
||||||
|
- **Browser control**: manage clawd’s dedicated Chrome/Chromium with tab listing/open/focus/close, screenshots, DOM query/dump, and “AI snapshots” (aria/domSnapshot/ai) via `clawdis browser …` and UI controls.
|
||||||
|
- **Remote gateway control**: Bonjour discovery for local masters plus SSH-tunnel fallback for remote control when multicast is unavailable.
|
||||||
|
|
||||||
|
### iOS node (Iris)
|
||||||
|
- New iOS companion app that pairs to the Gateway bridge, reports presence as a node, and exposes a WKWebView “Canvas” for agent-driven UI.
|
||||||
|
- `clawdis nodes invoke` supports `screen.eval` and `screen.snapshot` to drive and verify the iOS Canvas (fails fast when Iris is backgrounded).
|
||||||
|
- Voice wake words are configurable in-app; Iris reconnects to the last bridge when credentials are still present in Keychain.
|
||||||
|
|
||||||
### WhatsApp & agent experience
|
### WhatsApp & agent experience
|
||||||
- Group chats fully supported: mention-gated triggers (including media-only captions), sender attribution, session primer with subject/member roster, allowlist bypass when you’re @‑mentioned, and safer handling of view-once/ephemeral media.
|
- Group chats fully supported: mention-gated triggers (including media-only captions), sender attribution, session primer with subject/member roster, allowlist bypass when you’re @‑mentioned, and safer handling of view-once/ephemeral media.
|
||||||
@@ -27,7 +45,7 @@ First Clawdis release post rebrand. This is a semver-major because we dropped le
|
|||||||
- New `clawdis agent` command plus a persistent Pi RPC worker (auto-started) enables direct agent chats; `clawdis status` renders a colored session/recipient table.
|
- New `clawdis agent` command plus a persistent Pi RPC worker (auto-started) enables direct agent chats; `clawdis status` renders a colored session/recipient table.
|
||||||
- `clawdis health` probes WhatsApp link status, connect latency, heartbeat interval, session-store recency, and IPC socket presence (JSON mode for monitors).
|
- `clawdis health` probes WhatsApp link status, connect latency, heartbeat interval, session-store recency, and IPC socket presence (JSON mode for monitors).
|
||||||
- Added `--help`/`--version` flags; login/logout accept `--provider` (WhatsApp default). Console output is mirrored into pino logs under `/tmp/clawdis`.
|
- Added `--help`/`--version` flags; login/logout accept `--provider` (WhatsApp default). Console output is mirrored into pino logs under `/tmp/clawdis`.
|
||||||
- RPC stability: stdin/stdout loop for Tau/Pi, auto-restart worker, raw error surfacing, and deliver-via-RPC when JSON agent output is returned.
|
- RPC stability: stdin/stdout loop for Pi, auto-restart worker, raw error surfacing, and deliver-via-RPC when JSON agent output is returned.
|
||||||
|
|
||||||
### Security & hardening
|
### Security & hardening
|
||||||
- Media server blocks symlink/path traversal, clears temporary downloads, and rotates logs daily (24h retention).
|
- Media server blocks symlink/path traversal, clears temporary downloads, and rotates logs daily (24h retention).
|
||||||
@@ -36,7 +54,7 @@ First Clawdis release post rebrand. This is a semver-major because we dropped le
|
|||||||
|
|
||||||
### Docs
|
### Docs
|
||||||
- Added `docs/telegram.md` outlining the Telegram Bot API provider (grammY) and how it shares the `main` session. Default grammY throttler keeps Bot API calls under rate limits.
|
- Added `docs/telegram.md` outlining the Telegram Bot API provider (grammY) and how it shares the `main` session. Default grammY throttler keeps Bot API calls under rate limits.
|
||||||
- CLI gateway now auto-starts WhatsApp and Telegram when configured (single `gateway` command with `--provider` selector); text/media sends still use `--provider telegram`; webhook/proxy options documented.
|
- Gateway can run WhatsApp + Telegram together when configured; `clawdis send --provider telegram …` sends via the Telegram bot (webhook/proxy options documented).
|
||||||
|
|
||||||
## 1.5.0 — 2025-12-05
|
## 1.5.0 — 2025-12-05
|
||||||
|
|
||||||
@@ -49,8 +67,8 @@ First Clawdis release post rebrand. This is a semver-major because we dropped le
|
|||||||
- Documentation updated to reflect Pi-only support and to mark legacy Claude paths as historical.
|
- Documentation updated to reflect Pi-only support and to mark legacy Claude paths as historical.
|
||||||
- Status command reports web session health + session recipients; config paths are locked to `~/.clawdis` with session metadata stored under `~/.clawdis/sessions/`.
|
- Status command reports web session health + session recipients; config paths are locked to `~/.clawdis` with session metadata stored under `~/.clawdis/sessions/`.
|
||||||
- Simplified send/agent/gateway/heartbeat to web-only delivery; removed Twilio mocks/tests and dead code.
|
- Simplified send/agent/gateway/heartbeat to web-only delivery; removed Twilio mocks/tests and dead code.
|
||||||
- Tau RPC timeout is now inactivity-based (5m without events) and error messages show seconds only.
|
- Pi RPC timeout is now inactivity-based (5m without events) and error messages show seconds only.
|
||||||
- Pi/Tau sessions now write to `~/.clawdis/sessions/` by default (legacy `~/.tau/agent/sessions/clawdis` files are copied over when present).
|
- Pi sessions now write to `~/.clawdis/sessions/` by default (legacy session logs from older installs are copied over when present).
|
||||||
- Directive triggers (`/think`, `/verbose`, `/stop` et al.) now reply immediately using normalized bodies (timestamps/group prefixes stripped) without waiting for the agent.
|
- Directive triggers (`/think`, `/verbose`, `/stop` et al.) now reply immediately using normalized bodies (timestamps/group prefixes stripped) without waiting for the agent.
|
||||||
- Directive/system acks carry a `⚙️` prefix and verbose parsing rejects typoed `/ver*` strings so unrelated text doesn’t flip verbosity.
|
- Directive/system acks carry a `⚙️` prefix and verbose parsing rejects typoed `/ver*` strings so unrelated text doesn’t flip verbosity.
|
||||||
- Batched history blocks no longer trip directive parsing; `/think` in prior messages won't emit stray acknowledgements.
|
- Batched history blocks no longer trip directive parsing; `/think` in prior messages won't emit stray acknowledgements.
|
||||||
@@ -68,18 +86,18 @@ First Clawdis release post rebrand. This is a semver-major because we dropped le
|
|||||||
## 1.4.0 — 2025-12-03
|
## 1.4.0 — 2025-12-03
|
||||||
|
|
||||||
### Highlights
|
### Highlights
|
||||||
- **Thinking directives & state:** `/t|/think|/thinking <level>` (aliases off|minimal|low|medium|high|max/highest). Inline applies to that message; directive-only message pins the level for the session; `/think:off` clears. Resolution: inline > session override > `inbound.reply.thinkingDefault` > off. Pi/Tau get `--thinking <level>` (except off); other agents append cue words (`think` → `think hard` → `think harder` → `ultrathink`). Heartbeat probe uses `HEARTBEAT /think:high`.
|
- **Thinking directives & state:** `/t|/think|/thinking <level>` (aliases off|minimal|low|medium|high|max/highest). Inline applies to that message; directive-only message pins the level for the session; `/think:off` clears. Resolution: inline > session override > `inbound.reply.thinkingDefault` > off. Pi gets `--thinking <level>` (except off); other agents append cue words (`think` → `think hard` → `think harder` → `ultrathink`). Heartbeat probe uses `HEARTBEAT /think:high`.
|
||||||
- **Group chats (web provider):** Clawdis now fully supports WhatsApp groups: mention-gated triggers (including image-only @ mentions), recent group history injection, per-group sessions, sender attribution, and a first-turn primer with group subject/member roster; heartbeats are skipped for groups.
|
- **Group chats (web provider):** Clawdis now fully supports WhatsApp groups: mention-gated triggers (including image-only @ mentions), recent group history injection, per-group sessions, sender attribution, and a first-turn primer with group subject/member roster; heartbeats are skipped for groups.
|
||||||
- **Group session primer:** The first turn of a group session now tells the agent it is in a WhatsApp group and lists known members/subject so it can address the right speaker.
|
- **Group session primer:** The first turn of a group session now tells the agent it is in a WhatsApp group and lists known members/subject so it can address the right speaker.
|
||||||
- **Media failures are surfaced:** When a web auto-reply media fetch/send fails (e.g., HTTP 404), we now append a warning to the fallback text so you know the attachment was skipped.
|
- **Media failures are surfaced:** When a web auto-reply media fetch/send fails (e.g., HTTP 404), we now append a warning to the fallback text so you know the attachment was skipped.
|
||||||
- **Verbose directives + session hints:** `/v|/verbose on|full|off` mirrors thinking: inline > session > config default. Directive-only replies with an acknowledgement; invalid levels return a hint. When enabled, tool results from JSON-emitting agents (Pi/Tau, etc.) are forwarded as metadata-only `[🛠️ <tool-name> <arg>]` messages (now streamed as they happen), and new sessions surface a `🧭 New session: <id>` hint.
|
- **Verbose directives + session hints:** `/v|/verbose on|full|off` mirrors thinking: inline > session > config default. Directive-only replies with an acknowledgement; invalid levels return a hint. When enabled, tool results from JSON-emitting agents (Pi, etc.) are forwarded as metadata-only `[🛠️ <tool-name> <arg>]` messages (now streamed as they happen), and new sessions surface a `🧭 New session: <id>` hint.
|
||||||
- **Verbose tool coalescing:** successive tool results of the same tool within ~1s are batched into one `[🛠️ tool] arg1, arg2` message to reduce WhatsApp noise.
|
- **Verbose tool coalescing:** successive tool results of the same tool within ~1s are batched into one `[🛠️ tool] arg1, arg2` message to reduce WhatsApp noise.
|
||||||
- **Directive confirmations:** Directive-only messages now reply with an acknowledgement (`Thinking level set to high.` / `Thinking disabled.`) and reject unknown levels with a helpful hint (state is unchanged).
|
- **Directive confirmations:** Directive-only messages now reply with an acknowledgement (`Thinking level set to high.` / `Thinking disabled.`) and reject unknown levels with a helpful hint (state is unchanged).
|
||||||
- **Pi/Tau stability:** RPC replies buffered until the assistant turn finishes; parsers return consistent `texts[]`; web auto-replies keep a warm Tau RPC process to avoid cold starts.
|
- **Pi stability:** RPC replies buffered until the assistant turn finishes; parsers return consistent `texts[]`; web auto-replies keep a warm Pi RPC process to avoid cold starts.
|
||||||
- **Claude prompt flow:** One-time `sessionIntro` with per-message `/think:high` bodyPrefix; system prompt always sent on first turn even with `sendSystemOnce`.
|
- **Claude prompt flow:** One-time `sessionIntro` with per-message `/think:high` bodyPrefix; system prompt always sent on first turn even with `sendSystemOnce`.
|
||||||
- **Heartbeat UX:** Backpressure skips reply heartbeats while other commands run; skips don’t refresh session `updatedAt`; web heartbeats normalize array payloads and optional `heartbeatCommand`.
|
- **Heartbeat UX:** Backpressure skips reply heartbeats while other commands run; skips don’t refresh session `updatedAt`; web heartbeats normalize array payloads and optional `heartbeatCommand`.
|
||||||
- **Control via WhatsApp:** Send `/restart` to restart the launchd service (`com.steipete.clawdis`) from your allowed numbers.
|
- **Control via WhatsApp:** Send `/restart` to restart the launchd service (`com.steipete.clawdis`) from your allowed numbers.
|
||||||
- **Tau completion signal:** RPC now resolves on Tau’s `agent_end` (or process exit) so late assistant messages aren’t truncated; 5-minute hard cap only as a failsafe.
|
- **Pi completion signal:** RPC now resolves on Pi’s `agent_end` (or process exit) so late assistant messages aren’t truncated; 5-minute hard cap only as a failsafe.
|
||||||
|
|
||||||
### Reliability & UX
|
### Reliability & UX
|
||||||
- Outbound chunking prefers newlines/word boundaries and enforces caps (~4000 chars for web/WhatsApp).
|
- Outbound chunking prefers newlines/word boundaries and enforces caps (~4000 chars for web/WhatsApp).
|
||||||
@@ -101,8 +119,8 @@ First Clawdis release post rebrand. This is a semver-major because we dropped le
|
|||||||
- Media-only pings now pick up mentions inside captions (image/video/etc.), so @-mentions on media-only messages trigger replies.
|
- Media-only pings now pick up mentions inside captions (image/video/etc.), so @-mentions on media-only messages trigger replies.
|
||||||
- MIME sniffing and redirect handling for downloads/hosted media.
|
- MIME sniffing and redirect handling for downloads/hosted media.
|
||||||
- Response prefix applied to heartbeat alerts; heartbeat array payloads handled for both providers.
|
- Response prefix applied to heartbeat alerts; heartbeat array payloads handled for both providers.
|
||||||
- Tau RPC typing exposes `signal`/`killed`; NDJSON parsers normalized across agents.
|
- Pi RPC typing exposes `signal`/`killed`; NDJSON parsers normalized across agents.
|
||||||
- Tau (pi) session resumes now append `--continue`, so existing history/think level are reloaded instead of starting empty.
|
- Pi session resumes now append `--continue`, so existing history/think level are reloaded instead of starting empty.
|
||||||
|
|
||||||
### Testing
|
### Testing
|
||||||
- Fixtures isolate session stores; added coverage for thinking directives, stateful levels, heartbeat backpressure, and agent parsing.
|
- Fixtures isolate session stores; added coverage for thinking directives, stateful levels, heartbeat backpressure, and agent parsing.
|
||||||
|
|||||||
@@ -10,18 +10,27 @@
|
|||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/steipete/clawdis/actions/workflows/ci.yml?branch=main"><img src="https://img.shields.io/github/actions/workflow/status/steipete/clawdis/ci.yml?branch=main&style=for-the-badge" alt="CI status"></a>
|
<a href="https://github.com/steipete/clawdis/actions/workflows/ci.yml?branch=main"><img src="https://img.shields.io/github/actions/workflow/status/steipete/clawdis/ci.yml?branch=main&style=for-the-badge" alt="CI status"></a>
|
||||||
<a href="https://www.npmjs.com/package/clawdis"><img src="https://img.shields.io/npm/v/clawdis.svg?style=for-the-badge" alt="npm version"></a>
|
<a href="https://github.com/steipete/clawdis/releases"><img src="https://img.shields.io/github/v/release/steipete/clawdis?include_prereleases&style=for-the-badge" alt="GitHub release"></a>
|
||||||
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge" alt="MIT License"></a>
|
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge" alt="MIT License"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
**CLAWDIS** is a WhatsApp- and Telegram-to-AI gateway. Send a message, get an AI response. It's like having a genius lobster in your pocket 24/7.
|
**CLAWDIS** is a TypeScript/Node gateway that bridges WhatsApp (Web/Baileys) and Telegram (Bot API/grammY) to a local coding agent (**Pi**).
|
||||||
|
It’s like having a genius lobster in your pocket 24/7 — but with a real control plane, companion apps, and a network model that won’t corrupt sessions.
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─────────────┐ ┌──────────┐ ┌─────────────┐
|
WhatsApp / Telegram
|
||||||
│ WhatsApp │ ───▶ │ CLAWDIS │ ───▶ │ AI Agent │
|
│
|
||||||
│ Telegram │ ───▶ │ 🦞⏱️💙 │ ◀─── │ (Pi/Tau) │
|
▼
|
||||||
│ (You) │ ◀─── │ │ │ │
|
┌──────────────────────────┐
|
||||||
└─────────────┘ └──────────┘ └─────────────┘
|
│ Gateway │ ws://127.0.0.1:18789 (loopback-only)
|
||||||
|
│ (single source) │ tcp://0.0.0.0:18790 (optional Bridge)
|
||||||
|
└───────────┬───────────────┘
|
||||||
|
│
|
||||||
|
├─ Pi agent (RPC)
|
||||||
|
├─ CLI (clawdis …)
|
||||||
|
├─ WebChat (loopback UI)
|
||||||
|
├─ macOS app (Clawdis.app)
|
||||||
|
└─ iOS node (Iris) via Bridge + pairing
|
||||||
```
|
```
|
||||||
|
|
||||||
## Why "CLAWDIS"?
|
## Why "CLAWDIS"?
|
||||||
@@ -34,49 +43,67 @@ Because every space lobster needs a time-and-space machine. The Doctor has a TAR
|
|||||||
|
|
||||||
- 📱 **WhatsApp Integration** — Personal WhatsApp Web (Baileys)
|
- 📱 **WhatsApp Integration** — Personal WhatsApp Web (Baileys)
|
||||||
- ✈️ **Telegram (Bot API)** — DMs and groups via grammY
|
- ✈️ **Telegram (Bot API)** — DMs and groups via grammY
|
||||||
- 🤖 **AI Agent Gateway** — Pi/Tau only (Pi CLI in RPC mode)
|
- 🛰️ **Gateway control plane** — One long-lived gateway owns provider state; clients connect over WebSocket
|
||||||
- 💬 **Session Management** — Per-sender conversation context
|
- 🤖 **Agent runtime** — Pi only (Pi CLI in RPC mode), with tool streaming
|
||||||
|
- 💬 **Sessions** — Direct chats collapse into `main` by default; groups are isolated
|
||||||
- 🔔 **Heartbeats** — Periodic check-ins for proactive AI
|
- 🔔 **Heartbeats** — Periodic check-ins for proactive AI
|
||||||
|
- 🧭 **Clawd Browser** — Dedicated Chrome/Chromium profile with tabs + screenshot control (no interference with your daily browser)
|
||||||
- 👥 **Group Chat Support** — Mention-based triggering
|
- 👥 **Group Chat Support** — Mention-based triggering
|
||||||
- 📎 **Media Support** — Images, audio, documents, voice notes
|
- 📎 **Media Support** — Images, audio, documents, voice notes
|
||||||
- 🎤 **Voice Transcription** — Whisper integration
|
- 🎤 **Voice & transcription hooks** — Voice Wake (macOS/iOS) + optional transcription pipeline
|
||||||
- 🔧 **Tool Streaming** — Real-time display (💻📄✍️📝)
|
- 🔧 **Tool Streaming** — Real-time display (💻📄✍️📝)
|
||||||
- 🖥️ **macOS Companion (Clawdis.app)** — Menu bar controls, on-device Voice Wake, model/config editor
|
- 🖥️ **macOS Companion (Clawdis.app)** — Menu bar controls, Voice Wake, WebChat, onboarding, remote gateway control
|
||||||
|
- 📱 **iOS Node (Iris)** — Pairs as a node, exposes a Canvas surface, forwards voice wake transcripts
|
||||||
|
|
||||||
Only the Pi/Tau CLI is supported now; legacy Claude/Codex/Gemini paths have been removed.
|
Only the Pi CLI is supported now; legacy Claude/Codex/Gemini paths have been removed.
|
||||||
|
|
||||||
|
## Network model (the “new reality”)
|
||||||
|
|
||||||
|
- **One Gateway per host**. The Gateway is the only process allowed to own the WhatsApp Web session.
|
||||||
|
- **Loopback-first**: the Gateway WebSocket listens on `ws://127.0.0.1:18789` and is not exposed on the LAN.
|
||||||
|
- **Bridge for nodes**: when enabled, the Gateway also exposes a bridge on `tcp://0.0.0.0:18790` for paired nodes (Bonjour-discoverable). For tailnet-only setups, set `bridge.bind: "tailnet"` in `~/.clawdis/clawdis.json`.
|
||||||
|
- **Remote control**: use a VPN/tailnet or an SSH tunnel (`ssh -N -L 18789:127.0.0.1:18789 user@host`). The macOS app can drive this flow.
|
||||||
|
- **Wide-Area Bonjour (optional)**: for auto-discovery across networks (Vienna ⇄ London) over Tailscale, use unicast DNS-SD on `clawdis.internal.`; see `docs/bonjour.md`.
|
||||||
|
|
||||||
|
## Codebase
|
||||||
|
|
||||||
|
- **TypeScript (ESM)**: CLI + Gateway live in `src/` and run on Node ≥ 22.
|
||||||
|
- **macOS app (Swift)**: menu bar companion lives in `apps/macos/`.
|
||||||
|
- **iOS app (Swift)**: Iris node prototype lives in `apps/ios/`.
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
Mac signing tip: set `SIGN_IDENTITY="Apple Development: Your Name (TEAMID)"` in your shell profile so `scripts/restart-mac.sh` signs with your cert (defaults to ad-hoc). Debug bundle ID remains `com.steipete.clawdis.debug`.
|
|
||||||
|
|
||||||
Runtime requirement: **Node ≥22.0.0** (not bundled). The macOS app and CLI both use the host runtime; install via Homebrew or official installers before running `clawdis`.
|
Runtime requirement: **Node ≥22.0.0** (not bundled). The macOS app and CLI both use the host runtime; install via Homebrew or official installers before running `clawdis`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install
|
# From source (recommended while the npm package is still settling)
|
||||||
npm install -g clawdis
|
pnpm install
|
||||||
|
pnpm build
|
||||||
|
|
||||||
# Link your WhatsApp
|
# Link your WhatsApp (stores creds under ~/.clawdis/credentials)
|
||||||
clawdis login
|
pnpm clawdis login
|
||||||
|
|
||||||
# Send a message
|
|
||||||
clawdis send --to +1234567890 --message "Hello from the CLAWDIS!"
|
|
||||||
|
|
||||||
# Talk directly to the agent (no WhatsApp send)
|
|
||||||
clawdis agent --to +1234567890 --message "Ship checklist" --thinking high
|
|
||||||
|
|
||||||
# Start the gateway (WebSocket control plane)
|
# Start the gateway (WebSocket control plane)
|
||||||
clawdis gateway --port 18789 --verbose
|
pnpm clawdis gateway --port 18789 --verbose
|
||||||
|
|
||||||
|
# Send a WhatsApp message (WhatsApp sends go through the Gateway)
|
||||||
|
pnpm clawdis send --to +1234567890 --message "Hello from the CLAWDIS!"
|
||||||
|
|
||||||
|
# Talk to the agent (optionally deliver back to WhatsApp/Telegram)
|
||||||
|
pnpm clawdis agent --message "Ship checklist" --thinking high
|
||||||
|
|
||||||
# If the port is busy, force-kill listeners then start
|
# If the port is busy, force-kill listeners then start
|
||||||
clawdis gateway --force
|
pnpm clawdis gateway --force
|
||||||
```
|
```
|
||||||
|
|
||||||
## macOS Companion App (Clawdis.app)
|
## Companion Apps
|
||||||
|
|
||||||
- **On-device Voice Wake:** listens for wake words (e.g. “Claude”) using Apple’s on-device speech recognizer (macOS 26+). macOS still shows the standard Speech/Mic permissions prompt, but audio stays on device.
|
### macOS Companion (Clawdis.app)
|
||||||
- **Push-to-talk (Right Option hold):** hold right Option to speak; the voice overlay shows live partials and sends when you release.
|
|
||||||
- **Config tab:** pick the model from your local Pi model catalog (`pi-mono/packages/ai/src/models.generated.ts`), or enter a custom model ID; edit session store path and context tokens.
|
- A menu bar app that can start/stop the Gateway, show health/presence, and provide a local ops UI.
|
||||||
- **Voice settings:** language + additional languages, mic picker, live level meter, trigger-word table, and a built-in test harness.
|
- **Voice Wake** (on-device speech recognition) and Push-to-talk overlay.
|
||||||
- **Menu bar toggle:** enable/disable Voice Wake from the menu bar; respects Dock-icon preference.
|
- **WebChat** embed + debug tooling (logs, status, heartbeats, sessions).
|
||||||
|
- Hosts **PeekabooBridge** for UI automation brokering (for clawd workflows).
|
||||||
|
|
||||||
### Voice Wake reply routing
|
### Voice Wake reply routing
|
||||||
|
|
||||||
@@ -90,6 +117,16 @@ If delivery fails (e.g. WhatsApp disconnected / Telegram token missing), Clawdis
|
|||||||
|
|
||||||
Build/run the mac app with `./scripts/restart-mac.sh` (packages, installs, and launches), or `swift build --package-path apps/macos && open dist/Clawdis.app`.
|
Build/run the mac app with `./scripts/restart-mac.sh` (packages, installs, and launches), or `swift build --package-path apps/macos && open dist/Clawdis.app`.
|
||||||
|
|
||||||
|
### iOS Node (Iris) (internal)
|
||||||
|
|
||||||
|
Iris is an internal/prototype iOS app that connects as a **remote node**:
|
||||||
|
|
||||||
|
- **Voice trigger:** forwards transcripts into the Gateway (agent runs + wakeups).
|
||||||
|
- **Canvas screen:** a WKWebView + `<canvas>` surface the agent can control (via `screen.eval` / `screen.snapshot` over `node.invoke`).
|
||||||
|
- **Discovery + pairing:** finds the bridge via Bonjour (`_clawdis-bridge._tcp`) and uses Gateway-owned pairing (`clawdis nodes pending|approve`).
|
||||||
|
|
||||||
|
Runbook: `docs/ios/connect.md`
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Create `~/.clawdis/clawdis.json`:
|
Create `~/.clawdis/clawdis.json`:
|
||||||
@@ -97,16 +134,19 @@ Create `~/.clawdis/clawdis.json`:
|
|||||||
```json5
|
```json5
|
||||||
{
|
{
|
||||||
inbound: {
|
inbound: {
|
||||||
allowFrom: ["+1234567890"],
|
allowFrom: ["+1234567890"]
|
||||||
reply: {
|
}
|
||||||
mode: "command",
|
}
|
||||||
command: ["tau", "--mode", "json", "{{BodyStripped}}"],
|
```
|
||||||
session: {
|
|
||||||
scope: "per-sender",
|
Optional: enable/configure clawd’s dedicated browser control (defaults are already on):
|
||||||
idleMinutes: 1440
|
|
||||||
},
|
```json5
|
||||||
heartbeatMinutes: 10
|
{
|
||||||
}
|
browser: {
|
||||||
|
enabled: true,
|
||||||
|
controlUrl: "http://127.0.0.1:18791",
|
||||||
|
color: "#FF4500"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -114,12 +154,17 @@ Create `~/.clawdis/clawdis.json`:
|
|||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
- [Configuration Guide](./docs/configuration.md)
|
- [Configuration Guide](./docs/configuration.md)
|
||||||
- [Agent Integration](./docs/agents.md)
|
- [Gateway runbook](./docs/gateway.md)
|
||||||
|
- [Discovery + transports](./docs/discovery.md)
|
||||||
|
- [Bonjour / mDNS + Wide-Area Bonjour](./docs/bonjour.md)
|
||||||
|
- [Agent Runtime](./docs/agent.md)
|
||||||
- [Group Chats](./docs/group-messages.md)
|
- [Group Chats](./docs/group-messages.md)
|
||||||
- [Security](./docs/security.md)
|
- [Security](./docs/security.md)
|
||||||
- [Troubleshooting](./docs/troubleshooting.md)
|
- [Troubleshooting](./docs/troubleshooting.md)
|
||||||
- [The Lore](./docs/lore.md) 🦞
|
- [The Lore](./docs/lore.md) 🦞
|
||||||
- [Telegram (Bot API)](./docs/telegram.md)
|
- [Telegram (Bot API)](./docs/telegram.md)
|
||||||
|
- [iOS node runbook (Iris)](./docs/ios/connect.md)
|
||||||
|
- [macOS app spec](./docs/clawdis-mac.md)
|
||||||
|
|
||||||
## Clawd
|
## Clawd
|
||||||
|
|
||||||
@@ -132,29 +177,33 @@ CLAWDIS was built for **Clawd**, a space lobster AI assistant. See the full setu
|
|||||||
|
|
||||||
## Provider
|
## Provider
|
||||||
|
|
||||||
|
If you’re running from source, use `pnpm clawdis …` instead of `clawdis …`.
|
||||||
|
|
||||||
### WhatsApp Web
|
### WhatsApp Web
|
||||||
```bash
|
```bash
|
||||||
clawdis login # Scan QR code
|
clawdis login # scan QR, store creds
|
||||||
clawdis gateway # Start listening (WS on 127.0.0.1:18789)
|
clawdis gateway # run Gateway (WS on 127.0.0.1:18789)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Telegram (Bot API)
|
### Telegram (Bot API)
|
||||||
Bot-mode support (grammY only) shares the same `main` session as WhatsApp/WebChat, with groups kept isolated. Text and media send work via `clawdis send --provider telegram`. The unified `clawdis gateway` starts WhatsApp and, when `TELEGRAM_BOT_TOKEN` or `telegram.botToken` is set, Telegram too (use `--provider` to force web|telegram|all). Webhook mode: `--webhook --port … --webhook-secret … --webhook-url …` (or register via BotFather). See `docs/telegram.md` for setup and limits.
|
Bot-mode support (grammY only) shares the same `main` session as WhatsApp/WebChat, with groups kept isolated. Text/media sends work via `clawdis send --provider telegram` (reads `TELEGRAM_BOT_TOKEN` or `telegram.botToken`). Webhook mode is supported; see `docs/telegram.md` for setup and limits.
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
| Command | Description |
|
|
||||||
|---------|-------------|
|
|
||||||
| Command | Description |
|
| Command | Description |
|
||||||
|---------|-------------|
|
|---------|-------------|
|
||||||
| `clawdis login` | Link WhatsApp Web via QR |
|
| `clawdis login` | Link WhatsApp Web via QR |
|
||||||
| `clawdis send` | Send a message (WhatsApp default; `--provider telegram` for bot mode). Always uses the Gateway WS; requires a running gateway. |
|
| `clawdis send` | Send a message (WhatsApp default; `--provider telegram` for bot mode). WhatsApp sends go via the Gateway WS; Telegram sends are direct. |
|
||||||
| `clawdis agent` | Talk directly to the agent (no WhatsApp send) |
|
| `clawdis agent` | Talk directly to the agent (no WhatsApp send) |
|
||||||
|
| `clawdis browser ...` | Manage clawd’s dedicated browser (status/tabs/open/screenshot). |
|
||||||
| `clawdis gateway` | Start the Gateway server (WS control plane). Params: `--port`, `--token`, `--force`, `--verbose`. |
|
| `clawdis gateway` | Start the Gateway server (WS control plane). Params: `--port`, `--token`, `--force`, `--verbose`. |
|
||||||
| `clawdis gateway health|status|send|agent|call` | Gateway WS clients; assume a running gateway. |
|
| `clawdis gateway health|status|send|agent|call` | Gateway WS clients; assume a running gateway. |
|
||||||
|
| `clawdis wake` | Enqueue a system event and optionally trigger a heartbeat via the Gateway. |
|
||||||
|
| `clawdis cron ...` | Manage scheduled jobs (via Gateway). |
|
||||||
|
| `clawdis nodes ...` | Manage Gateway-owned node pairing. |
|
||||||
| `clawdis status` | Web session health + session store summary |
|
| `clawdis status` | Web session health + session store summary |
|
||||||
| `clawdis health` | Reports cached provider state from the running gateway. |
|
| `clawdis health` | Reports cached provider state from the running gateway. |
|
||||||
| `clawdis heartbeat` | Trigger a heartbeat |
|
| `clawdis webchat` | Start the loopback-only WebChat HTTP server |
|
||||||
|
|
||||||
#### Gateway client params (WS only)
|
#### Gateway client params (WS only)
|
||||||
- `--url` (default `ws://127.0.0.1:18789`)
|
- `--url` (default `ws://127.0.0.1:18789`)
|
||||||
@@ -174,8 +223,8 @@ In chat, send `/status` to see if the agent is reachable, how much context the s
|
|||||||
|
|
||||||
### Sessions, surfaces, and WebChat
|
### Sessions, surfaces, and WebChat
|
||||||
|
|
||||||
- Direct chats now share a canonical session key `main` by default (configurable via `inbound.reply.session.mainKey`). Groups stay isolated as `group:<jid>`.
|
- Direct chats now share a canonical session key `main` by default (configurable via `inbound.session.mainKey`). Groups stay isolated as `group:<jid>`.
|
||||||
- WebChat always attaches to the `main` session and hydrates the full Tau history from `~/.clawdis/sessions/<SessionId>.jsonl`, so desktop view mirrors WhatsApp/Telegram turns.
|
- WebChat attaches to `main` and hydrates history from `~/.clawdis/sessions/<SessionId>.jsonl`, so desktop view mirrors WhatsApp/Telegram turns.
|
||||||
- Inbound contexts carry a `Surface` hint (e.g., `whatsapp`, `webchat`, `telegram`) for logging; replies still go back to the originating surface deterministically.
|
- Inbound contexts carry a `Surface` hint (e.g., `whatsapp`, `webchat`, `telegram`) for logging; replies still go back to the originating surface deterministically.
|
||||||
- Every inbound message is wrapped for the agent as `[Surface FROM HOST/IP TIMESTAMP] body`:
|
- Every inbound message is wrapped for the agent as `[Surface FROM HOST/IP TIMESTAMP] body`:
|
||||||
- WhatsApp: `[WhatsApp +15551234567 2025-12-09 12:34] …`
|
- WhatsApp: `[WhatsApp +15551234567 2025-12-09 12:34] …`
|
||||||
@@ -186,7 +235,7 @@ In chat, send `/status` to see if the agent is reachable, how much context the s
|
|||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
- **Peter Steinberger** ([@steipete](https://twitter.com/steipete)) — Creator
|
- **Peter Steinberger** ([@steipete](https://twitter.com/steipete)) — Creator
|
||||||
- **Mario Zechner** ([@badlogicgames](https://twitter.com/badlogicgames)) — Tau/Pi, security testing
|
- **Mario Zechner** ([@badlogicgames](https://twitter.com/badlogicgames)) — Pi, security testing
|
||||||
- **Clawd** 🦞 — The space lobster who demanded a better name
|
- **Clawd** 🦞 — The space lobster who demanded a better name
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
.gradle/
|
||||||
|
**/build/
|
||||||
|
local.properties
|
||||||
|
.idea/
|
||||||
|
**/*.iml
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
## Clawdis Node (Android) (internal)
|
||||||
|
|
||||||
|
Modern Android “node” app (Iris parity): connects to the **Gateway-owned bridge** (`_clawdis-bridge._tcp`) over TCP and exposes **Canvas + Chat + Camera**.
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
- The node keeps the connection alive via a **foreground service** (persistent notification with a Disconnect action).
|
||||||
|
- Chat always uses the shared session key **`main`** (same session across iOS/macOS/WebChat/Android).
|
||||||
|
- Supports modern Android only (`minSdk 31`, Kotlin + Jetpack Compose).
|
||||||
|
|
||||||
|
## Open in Android Studio
|
||||||
|
- Open the folder `apps/android`.
|
||||||
|
|
||||||
|
## Build / Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd apps/android
|
||||||
|
./gradlew :app:assembleDebug
|
||||||
|
./gradlew :app:installDebug
|
||||||
|
./gradlew :app:testDebugUnitTest
|
||||||
|
```
|
||||||
|
|
||||||
|
`gradlew` auto-detects the Android SDK at `~/Library/Android/sdk` (macOS default) if `ANDROID_SDK_ROOT` / `ANDROID_HOME` are unset.
|
||||||
|
|
||||||
|
## Connect / Pair
|
||||||
|
|
||||||
|
1) Start the gateway (on your “master” machine):
|
||||||
|
```bash
|
||||||
|
pnpm clawdis gateway --port 18789 --verbose
|
||||||
|
```
|
||||||
|
|
||||||
|
2) In the Android app:
|
||||||
|
- Open **Settings**
|
||||||
|
- Either select a discovered bridge under **Discovered Bridges**, or use **Advanced → Manual Bridge** (host + port).
|
||||||
|
|
||||||
|
3) Approve pairing (on the gateway machine):
|
||||||
|
```bash
|
||||||
|
clawdis nodes pending
|
||||||
|
clawdis nodes approve <requestId>
|
||||||
|
```
|
||||||
|
|
||||||
|
More details: `docs/android/connect.md`.
|
||||||
|
|
||||||
|
## Permissions
|
||||||
|
|
||||||
|
- Discovery:
|
||||||
|
- Android 13+ (`API 33+`): `NEARBY_WIFI_DEVICES`
|
||||||
|
- Android 12 and below: `ACCESS_FINE_LOCATION` (required for NSD scanning)
|
||||||
|
- Foreground service notification (Android 13+): `POST_NOTIFICATIONS`
|
||||||
|
- Camera:
|
||||||
|
- `CAMERA` for `camera.snap` and `camera.clip`
|
||||||
|
- `RECORD_AUDIO` for `camera.clip` when `includeAudio=true`
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application")
|
||||||
|
id("org.jetbrains.kotlin.android")
|
||||||
|
id("org.jetbrains.kotlin.plugin.compose")
|
||||||
|
id("org.jetbrains.kotlin.plugin.serialization")
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "com.steipete.clawdis.node"
|
||||||
|
compileSdk = 36
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "com.steipete.clawdis.node"
|
||||||
|
minSdk = 31
|
||||||
|
targetSdk = 36
|
||||||
|
versionCode = 1
|
||||||
|
versionName = "0.1"
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = "17"
|
||||||
|
}
|
||||||
|
|
||||||
|
packaging {
|
||||||
|
resources {
|
||||||
|
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
val composeBom = platform("androidx.compose:compose-bom:2025.12.00")
|
||||||
|
implementation(composeBom)
|
||||||
|
androidTestImplementation(composeBom)
|
||||||
|
|
||||||
|
implementation("androidx.core:core-ktx:1.17.0")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.10.0")
|
||||||
|
implementation("androidx.activity:activity-compose:1.12.1")
|
||||||
|
|
||||||
|
implementation("androidx.compose.ui:ui")
|
||||||
|
implementation("androidx.compose.ui:ui-tooling-preview")
|
||||||
|
implementation("androidx.compose.material3:material3")
|
||||||
|
implementation("androidx.navigation:navigation-compose:2.9.6")
|
||||||
|
|
||||||
|
debugImplementation("androidx.compose.ui:ui-tooling")
|
||||||
|
|
||||||
|
// Material Components (XML theme + resources)
|
||||||
|
implementation("com.google.android.material:material:1.13.0")
|
||||||
|
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
|
||||||
|
|
||||||
|
implementation("androidx.security:security-crypto:1.1.0")
|
||||||
|
|
||||||
|
// CameraX (for node.invoke camera.* parity)
|
||||||
|
implementation("androidx.camera:camera-core:1.5.2")
|
||||||
|
implementation("androidx.camera:camera-camera2:1.5.2")
|
||||||
|
implementation("androidx.camera:camera-lifecycle:1.5.2")
|
||||||
|
implementation("androidx.camera:camera-video:1.5.2")
|
||||||
|
implementation("androidx.camera:camera-view:1.5.2")
|
||||||
|
|
||||||
|
// Unicast DNS-SD (Wide-Area Bonjour) for tailnet discovery domains.
|
||||||
|
implementation("dnsjava:dnsjava:3.6.3")
|
||||||
|
|
||||||
|
testImplementation("junit:junit:4.13.2")
|
||||||
|
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.NEARBY_WIFI_DEVICES"
|
||||||
|
android:usesPermissionFlags="neverForLocation" />
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.ACCESS_FINE_LOCATION"
|
||||||
|
android:maxSdkVersion="32" />
|
||||||
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:name=".NodeApp"
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.ClawdisNode">
|
||||||
|
<service
|
||||||
|
android:name=".NodeForegroundService"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="dataSync" />
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package com.steipete.clawdis.node
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.viewModels
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.steipete.clawdis.node.ui.RootScreen
|
||||||
|
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
private val viewModel: MainViewModel by viewModels()
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
requestDiscoveryPermissionsIfNeeded()
|
||||||
|
requestNotificationPermissionIfNeeded()
|
||||||
|
NodeForegroundService.start(this)
|
||||||
|
viewModel.camera.attachLifecycleOwner(this)
|
||||||
|
setContent {
|
||||||
|
MaterialTheme {
|
||||||
|
Surface(modifier = Modifier) {
|
||||||
|
RootScreen(viewModel = viewModel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStart() {
|
||||||
|
super.onStart()
|
||||||
|
viewModel.setForeground(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStop() {
|
||||||
|
viewModel.setForeground(false)
|
||||||
|
super.onStop()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun requestDiscoveryPermissionsIfNeeded() {
|
||||||
|
if (Build.VERSION.SDK_INT >= 33) {
|
||||||
|
val ok =
|
||||||
|
ContextCompat.checkSelfPermission(
|
||||||
|
this,
|
||||||
|
Manifest.permission.NEARBY_WIFI_DEVICES,
|
||||||
|
) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
if (!ok) {
|
||||||
|
requestPermissions(arrayOf(Manifest.permission.NEARBY_WIFI_DEVICES), 100)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val ok =
|
||||||
|
ContextCompat.checkSelfPermission(
|
||||||
|
this,
|
||||||
|
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||||
|
) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
if (!ok) {
|
||||||
|
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 101)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun requestNotificationPermissionIfNeeded() {
|
||||||
|
if (Build.VERSION.SDK_INT < 33) return
|
||||||
|
val ok =
|
||||||
|
ContextCompat.checkSelfPermission(
|
||||||
|
this,
|
||||||
|
Manifest.permission.POST_NOTIFICATIONS,
|
||||||
|
) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
|
if (!ok) {
|
||||||
|
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 102)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.steipete.clawdis.node
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import androidx.lifecycle.AndroidViewModel
|
||||||
|
import com.steipete.clawdis.node.bridge.BridgeEndpoint
|
||||||
|
import com.steipete.clawdis.node.node.CameraCaptureManager
|
||||||
|
import com.steipete.clawdis.node.node.CanvasController
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
class MainViewModel(app: Application) : AndroidViewModel(app) {
|
||||||
|
private val runtime: NodeRuntime = (app as NodeApp).runtime
|
||||||
|
|
||||||
|
val canvas: CanvasController = runtime.canvas
|
||||||
|
val camera: CameraCaptureManager = runtime.camera
|
||||||
|
|
||||||
|
val bridges: StateFlow<List<BridgeEndpoint>> = runtime.bridges
|
||||||
|
|
||||||
|
val isConnected: StateFlow<Boolean> = runtime.isConnected
|
||||||
|
val statusText: StateFlow<String> = runtime.statusText
|
||||||
|
val serverName: StateFlow<String?> = runtime.serverName
|
||||||
|
val remoteAddress: StateFlow<String?> = runtime.remoteAddress
|
||||||
|
|
||||||
|
val instanceId: StateFlow<String> = runtime.instanceId
|
||||||
|
val displayName: StateFlow<String> = runtime.displayName
|
||||||
|
val cameraEnabled: StateFlow<Boolean> = runtime.cameraEnabled
|
||||||
|
val wakeWords: StateFlow<List<String>> = runtime.wakeWords
|
||||||
|
val manualEnabled: StateFlow<Boolean> = runtime.manualEnabled
|
||||||
|
val manualHost: StateFlow<String> = runtime.manualHost
|
||||||
|
val manualPort: StateFlow<Int> = runtime.manualPort
|
||||||
|
|
||||||
|
val chatMessages: StateFlow<List<NodeRuntime.ChatMessage>> = runtime.chatMessages
|
||||||
|
val chatError: StateFlow<String?> = runtime.chatError
|
||||||
|
val pendingRunCount: StateFlow<Int> = runtime.pendingRunCount
|
||||||
|
|
||||||
|
fun setForeground(value: Boolean) {
|
||||||
|
runtime.setForeground(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setDisplayName(value: String) {
|
||||||
|
runtime.setDisplayName(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setCameraEnabled(value: Boolean) {
|
||||||
|
runtime.setCameraEnabled(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualEnabled(value: Boolean) {
|
||||||
|
runtime.setManualEnabled(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualHost(value: String) {
|
||||||
|
runtime.setManualHost(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualPort(value: Int) {
|
||||||
|
runtime.setManualPort(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setWakeWords(words: List<String>) {
|
||||||
|
runtime.setWakeWords(words)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun resetWakeWordsDefaults() {
|
||||||
|
runtime.resetWakeWordsDefaults()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connect(endpoint: BridgeEndpoint) {
|
||||||
|
runtime.connect(endpoint)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connectManual() {
|
||||||
|
runtime.connectManual()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun disconnect() {
|
||||||
|
runtime.disconnect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadChat(sessionKey: String = "main") {
|
||||||
|
runtime.loadChat(sessionKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendChat(sessionKey: String = "main", message: String) {
|
||||||
|
runtime.sendChat(sessionKey, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.steipete.clawdis.node
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
|
||||||
|
class NodeApp : Application() {
|
||||||
|
val runtime: NodeRuntime by lazy { NodeRuntime(this) }
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package com.steipete.clawdis.node
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.Service
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.ServiceInfo
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
class NodeForegroundService : Service() {
|
||||||
|
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||||
|
private var notificationJob: Job? = null
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
ensureChannel()
|
||||||
|
val initial = buildNotification(title = "Clawdis Node", text = "Starting…")
|
||||||
|
if (Build.VERSION.SDK_INT >= 29) {
|
||||||
|
startForeground(NOTIFICATION_ID, initial, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||||
|
} else {
|
||||||
|
startForeground(NOTIFICATION_ID, initial)
|
||||||
|
}
|
||||||
|
|
||||||
|
val runtime = (application as NodeApp).runtime
|
||||||
|
notificationJob =
|
||||||
|
scope.launch {
|
||||||
|
combine(runtime.statusText, runtime.serverName, runtime.isConnected) { status, server, connected ->
|
||||||
|
Triple(status, server, connected)
|
||||||
|
}.collect { (status, server, connected) ->
|
||||||
|
val title = if (connected) "Clawdis Node · Connected" else "Clawdis Node"
|
||||||
|
val text = server?.let { "$status · $it" } ?: status
|
||||||
|
updateNotification(buildNotification(title = title, text = text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
when (intent?.action) {
|
||||||
|
ACTION_STOP -> {
|
||||||
|
(application as NodeApp).runtime.disconnect()
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Keep running; connection is managed by NodeRuntime (auto-reconnect + manual).
|
||||||
|
return START_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
notificationJob?.cancel()
|
||||||
|
scope.cancel()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?) = null
|
||||||
|
|
||||||
|
private fun ensureChannel() {
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||||
|
val mgr = getSystemService(NotificationManager::class.java)
|
||||||
|
val channel =
|
||||||
|
NotificationChannel(
|
||||||
|
CHANNEL_ID,
|
||||||
|
"Connection",
|
||||||
|
NotificationManager.IMPORTANCE_LOW,
|
||||||
|
).apply {
|
||||||
|
description = "Clawdis node connection status"
|
||||||
|
setShowBadge(false)
|
||||||
|
}
|
||||||
|
mgr.createNotificationChannel(channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildNotification(title: String, text: String): Notification {
|
||||||
|
val stopIntent = Intent(this, NodeForegroundService::class.java).setAction(ACTION_STOP)
|
||||||
|
val flags =
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||||
|
} else {
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT
|
||||||
|
}
|
||||||
|
val stopPending = PendingIntent.getService(this, 2, stopIntent, flags)
|
||||||
|
|
||||||
|
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||||
|
.setSmallIcon(R.mipmap.ic_launcher)
|
||||||
|
.setContentTitle(title)
|
||||||
|
.setContentText(text)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setOnlyAlertOnce(true)
|
||||||
|
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
|
||||||
|
.addAction(0, "Disconnect", stopPending)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateNotification(notification: Notification) {
|
||||||
|
val mgr = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
mgr.notify(NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val CHANNEL_ID = "connection"
|
||||||
|
private const val NOTIFICATION_ID = 1
|
||||||
|
|
||||||
|
private const val ACTION_STOP = "com.steipete.clawdis.node.action.STOP"
|
||||||
|
|
||||||
|
fun start(context: Context) {
|
||||||
|
val intent = Intent(context, NodeForegroundService::class.java)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
context.startForegroundService(intent)
|
||||||
|
} else {
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop(context: Context) {
|
||||||
|
val intent = Intent(context, NodeForegroundService::class.java).setAction(ACTION_STOP)
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,496 @@
|
|||||||
|
package com.steipete.clawdis.node
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.steipete.clawdis.node.bridge.BridgeDiscovery
|
||||||
|
import com.steipete.clawdis.node.bridge.BridgeEndpoint
|
||||||
|
import com.steipete.clawdis.node.bridge.BridgePairingClient
|
||||||
|
import com.steipete.clawdis.node.bridge.BridgeSession
|
||||||
|
import com.steipete.clawdis.node.node.CameraCaptureManager
|
||||||
|
import com.steipete.clawdis.node.node.CanvasController
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.collect
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.JsonArray
|
||||||
|
import kotlinx.serialization.json.JsonElement
|
||||||
|
import kotlinx.serialization.json.JsonNull
|
||||||
|
import kotlinx.serialization.json.JsonObject
|
||||||
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
|
|
||||||
|
class NodeRuntime(context: Context) {
|
||||||
|
private val appContext = context.applicationContext
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
|
||||||
|
val prefs = SecurePrefs(appContext)
|
||||||
|
val canvas = CanvasController()
|
||||||
|
val camera = CameraCaptureManager(appContext)
|
||||||
|
private val json = Json { ignoreUnknownKeys = true }
|
||||||
|
|
||||||
|
private val discovery = BridgeDiscovery(appContext, scope = scope)
|
||||||
|
val bridges: StateFlow<List<BridgeEndpoint>> = discovery.bridges
|
||||||
|
|
||||||
|
private val _isConnected = MutableStateFlow(false)
|
||||||
|
val isConnected: StateFlow<Boolean> = _isConnected.asStateFlow()
|
||||||
|
|
||||||
|
private val _statusText = MutableStateFlow("Not connected")
|
||||||
|
val statusText: StateFlow<String> = _statusText.asStateFlow()
|
||||||
|
|
||||||
|
private val _serverName = MutableStateFlow<String?>(null)
|
||||||
|
val serverName: StateFlow<String?> = _serverName.asStateFlow()
|
||||||
|
|
||||||
|
private val _remoteAddress = MutableStateFlow<String?>(null)
|
||||||
|
val remoteAddress: StateFlow<String?> = _remoteAddress.asStateFlow()
|
||||||
|
|
||||||
|
private val _isForeground = MutableStateFlow(true)
|
||||||
|
val isForeground: StateFlow<Boolean> = _isForeground.asStateFlow()
|
||||||
|
|
||||||
|
private val session =
|
||||||
|
BridgeSession(
|
||||||
|
scope = scope,
|
||||||
|
onConnected = { name, remote ->
|
||||||
|
_statusText.value = "Connected"
|
||||||
|
_serverName.value = name
|
||||||
|
_remoteAddress.value = remote
|
||||||
|
_isConnected.value = true
|
||||||
|
scope.launch { refreshWakeWordsFromGateway() }
|
||||||
|
},
|
||||||
|
onDisconnected = { message ->
|
||||||
|
_statusText.value = message
|
||||||
|
_serverName.value = null
|
||||||
|
_remoteAddress.value = null
|
||||||
|
_isConnected.value = false
|
||||||
|
},
|
||||||
|
onEvent = { event, payloadJson ->
|
||||||
|
handleBridgeEvent(event, payloadJson)
|
||||||
|
},
|
||||||
|
onInvoke = { req ->
|
||||||
|
handleInvoke(req.command, req.paramsJson)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
val instanceId: StateFlow<String> = prefs.instanceId
|
||||||
|
val displayName: StateFlow<String> = prefs.displayName
|
||||||
|
val cameraEnabled: StateFlow<Boolean> = prefs.cameraEnabled
|
||||||
|
val wakeWords: StateFlow<List<String>> = prefs.wakeWords
|
||||||
|
val manualEnabled: StateFlow<Boolean> = prefs.manualEnabled
|
||||||
|
val manualHost: StateFlow<String> = prefs.manualHost
|
||||||
|
val manualPort: StateFlow<Int> = prefs.manualPort
|
||||||
|
val lastDiscoveredStableId: StateFlow<String> = prefs.lastDiscoveredStableId
|
||||||
|
|
||||||
|
private var didAutoConnect = false
|
||||||
|
private var suppressWakeWordsSync = false
|
||||||
|
private var wakeWordsSyncJob: Job? = null
|
||||||
|
|
||||||
|
data class ChatMessage(val id: String, val role: String, val text: String, val timestampMs: Long?)
|
||||||
|
|
||||||
|
private val _chatMessages = MutableStateFlow<List<ChatMessage>>(emptyList())
|
||||||
|
val chatMessages: StateFlow<List<ChatMessage>> = _chatMessages.asStateFlow()
|
||||||
|
|
||||||
|
private val _chatError = MutableStateFlow<String?>(null)
|
||||||
|
val chatError: StateFlow<String?> = _chatError.asStateFlow()
|
||||||
|
|
||||||
|
private val pendingRuns = mutableSetOf<String>()
|
||||||
|
private val _pendingRunCount = MutableStateFlow(0)
|
||||||
|
val pendingRunCount: StateFlow<Int> = _pendingRunCount.asStateFlow()
|
||||||
|
|
||||||
|
init {
|
||||||
|
scope.launch(Dispatchers.Default) {
|
||||||
|
bridges.collect { list ->
|
||||||
|
if (list.isNotEmpty()) {
|
||||||
|
// Persist the last discovered bridge (best-effort UX parity with iOS).
|
||||||
|
prefs.setLastDiscoveredStableId(list.last().stableId)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (didAutoConnect) return@collect
|
||||||
|
if (_isConnected.value) return@collect
|
||||||
|
|
||||||
|
val token = prefs.loadBridgeToken()
|
||||||
|
if (token.isNullOrBlank()) return@collect
|
||||||
|
|
||||||
|
if (manualEnabled.value) {
|
||||||
|
val host = manualHost.value.trim()
|
||||||
|
val port = manualPort.value
|
||||||
|
if (host.isNotEmpty() && port in 1..65535) {
|
||||||
|
didAutoConnect = true
|
||||||
|
connect(BridgeEndpoint.manual(host = host, port = port))
|
||||||
|
}
|
||||||
|
return@collect
|
||||||
|
}
|
||||||
|
|
||||||
|
val targetStableId = lastDiscoveredStableId.value.trim()
|
||||||
|
if (targetStableId.isEmpty()) return@collect
|
||||||
|
val target = list.firstOrNull { it.stableId == targetStableId } ?: return@collect
|
||||||
|
didAutoConnect = true
|
||||||
|
connect(target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setForeground(value: Boolean) {
|
||||||
|
_isForeground.value = value
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setDisplayName(value: String) {
|
||||||
|
prefs.setDisplayName(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setCameraEnabled(value: Boolean) {
|
||||||
|
prefs.setCameraEnabled(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualEnabled(value: Boolean) {
|
||||||
|
prefs.setManualEnabled(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualHost(value: String) {
|
||||||
|
prefs.setManualHost(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualPort(value: Int) {
|
||||||
|
prefs.setManualPort(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setWakeWords(words: List<String>) {
|
||||||
|
prefs.setWakeWords(words)
|
||||||
|
scheduleWakeWordsSyncIfNeeded()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun resetWakeWordsDefaults() {
|
||||||
|
setWakeWords(SecurePrefs.defaultWakeWords)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connect(endpoint: BridgeEndpoint) {
|
||||||
|
scope.launch {
|
||||||
|
_statusText.value = "Connecting…"
|
||||||
|
val storedToken = prefs.loadBridgeToken()
|
||||||
|
val resolved =
|
||||||
|
if (storedToken.isNullOrBlank()) {
|
||||||
|
_statusText.value = "Pairing…"
|
||||||
|
BridgePairingClient().pairAndHello(
|
||||||
|
endpoint = endpoint,
|
||||||
|
hello =
|
||||||
|
BridgePairingClient.Hello(
|
||||||
|
nodeId = instanceId.value,
|
||||||
|
displayName = displayName.value,
|
||||||
|
token = null,
|
||||||
|
platform = "Android",
|
||||||
|
version = "dev",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
BridgePairingClient.PairResult(ok = true, token = storedToken.trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!resolved.ok || resolved.token.isNullOrBlank()) {
|
||||||
|
_statusText.value = "Failed: pairing required"
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
|
||||||
|
val authToken = requireNotNull(resolved.token).trim()
|
||||||
|
prefs.saveBridgeToken(authToken)
|
||||||
|
session.connect(
|
||||||
|
endpoint = endpoint,
|
||||||
|
hello =
|
||||||
|
BridgeSession.Hello(
|
||||||
|
nodeId = instanceId.value,
|
||||||
|
displayName = displayName.value,
|
||||||
|
token = authToken,
|
||||||
|
platform = "Android",
|
||||||
|
version = "dev",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun connectManual() {
|
||||||
|
val host = manualHost.value.trim()
|
||||||
|
val port = manualPort.value
|
||||||
|
if (host.isEmpty() || port <= 0 || port > 65535) {
|
||||||
|
_statusText.value = "Failed: invalid manual host/port"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
connect(BridgeEndpoint.manual(host = host, port = port))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun disconnect() {
|
||||||
|
session.disconnect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadChat(sessionKey: String = "main") {
|
||||||
|
scope.launch {
|
||||||
|
_chatError.value = null
|
||||||
|
try {
|
||||||
|
// Best-effort; push events are optional, but improve latency.
|
||||||
|
session.sendEvent("chat.subscribe", """{"sessionKey":"$sessionKey"}""")
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
val res = session.request("chat.history", """{"sessionKey":"$sessionKey"}""")
|
||||||
|
_chatMessages.value = parseHistory(res)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_chatError.value = e.message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendChat(sessionKey: String = "main", message: String, thinking: String = "off") {
|
||||||
|
val trimmed = message.trim()
|
||||||
|
if (trimmed.isEmpty()) return
|
||||||
|
scope.launch {
|
||||||
|
_chatError.value = null
|
||||||
|
val idem = java.util.UUID.randomUUID().toString()
|
||||||
|
|
||||||
|
_chatMessages.value =
|
||||||
|
_chatMessages.value +
|
||||||
|
ChatMessage(
|
||||||
|
id = java.util.UUID.randomUUID().toString(),
|
||||||
|
role = "user",
|
||||||
|
text = trimmed,
|
||||||
|
timestampMs = System.currentTimeMillis(),
|
||||||
|
)
|
||||||
|
|
||||||
|
try {
|
||||||
|
val params =
|
||||||
|
"""{"sessionKey":"$sessionKey","message":${trimmed.toJsonString()},"thinking":"$thinking","timeoutMs":30000,"idempotencyKey":"$idem"}"""
|
||||||
|
val res = session.request("chat.send", params)
|
||||||
|
val runId = parseRunId(res) ?: idem
|
||||||
|
pendingRuns.add(runId)
|
||||||
|
_pendingRunCount.value = pendingRuns.size
|
||||||
|
} catch (e: Exception) {
|
||||||
|
_chatError.value = e.message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleBridgeEvent(event: String, payloadJson: String?) {
|
||||||
|
if (payloadJson.isNullOrBlank()) return
|
||||||
|
|
||||||
|
if (event == "voicewake.changed") {
|
||||||
|
try {
|
||||||
|
val payload = json.parseToJsonElement(payloadJson).asObjectOrNull() ?: return
|
||||||
|
val array = payload["triggers"] as? JsonArray ?: return
|
||||||
|
val triggers = array.mapNotNull { it.asStringOrNull() }
|
||||||
|
applyWakeWordsFromGateway(triggers)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event != "chat") return
|
||||||
|
|
||||||
|
try {
|
||||||
|
val payload = json.parseToJsonElement(payloadJson).asObjectOrNull() ?: return
|
||||||
|
val state = payload["state"].asStringOrNull()
|
||||||
|
val runId = payload["runId"].asStringOrNull()
|
||||||
|
if (!runId.isNullOrBlank()) {
|
||||||
|
pendingRuns.remove(runId)
|
||||||
|
_pendingRunCount.value = pendingRuns.size
|
||||||
|
}
|
||||||
|
|
||||||
|
when (state) {
|
||||||
|
"final" -> {
|
||||||
|
val msgObj = payload["message"].asObjectOrNull()
|
||||||
|
val role = msgObj?.get("role").asStringOrNull() ?: "assistant"
|
||||||
|
val text = extractTextFromMessage(msgObj)
|
||||||
|
if (!text.isNullOrBlank()) {
|
||||||
|
_chatMessages.value =
|
||||||
|
_chatMessages.value +
|
||||||
|
ChatMessage(
|
||||||
|
id = java.util.UUID.randomUUID().toString(),
|
||||||
|
role = role,
|
||||||
|
text = text,
|
||||||
|
timestampMs = System.currentTimeMillis(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"error" -> {
|
||||||
|
_chatError.value = payload["errorMessage"].asStringOrNull() ?: "Chat failed"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyWakeWordsFromGateway(words: List<String>) {
|
||||||
|
suppressWakeWordsSync = true
|
||||||
|
prefs.setWakeWords(words)
|
||||||
|
suppressWakeWordsSync = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scheduleWakeWordsSyncIfNeeded() {
|
||||||
|
if (suppressWakeWordsSync) return
|
||||||
|
if (!_isConnected.value) return
|
||||||
|
|
||||||
|
val snapshot = prefs.wakeWords.value
|
||||||
|
wakeWordsSyncJob?.cancel()
|
||||||
|
wakeWordsSyncJob =
|
||||||
|
scope.launch {
|
||||||
|
delay(650)
|
||||||
|
val jsonList = snapshot.joinToString(separator = ",") { it.toJsonString() }
|
||||||
|
val params = """{"triggers":[$jsonList]}"""
|
||||||
|
try {
|
||||||
|
session.request("voicewake.set", params)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun refreshWakeWordsFromGateway() {
|
||||||
|
if (!_isConnected.value) return
|
||||||
|
try {
|
||||||
|
val res = session.request("voicewake.get", "{}")
|
||||||
|
val payload = json.parseToJsonElement(res).asObjectOrNull() ?: return
|
||||||
|
val array = payload["triggers"] as? JsonArray ?: return
|
||||||
|
val triggers = array.mapNotNull { it.asStringOrNull() }
|
||||||
|
applyWakeWordsFromGateway(triggers)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseHistory(historyJson: String): List<ChatMessage> {
|
||||||
|
val root = json.parseToJsonElement(historyJson).asObjectOrNull() ?: return emptyList()
|
||||||
|
val raw = root["messages"] ?: return emptyList()
|
||||||
|
val array = raw as? JsonArray ?: return emptyList()
|
||||||
|
return array.mapNotNull { item ->
|
||||||
|
val obj = item as? JsonObject ?: return@mapNotNull null
|
||||||
|
val role = obj["role"].asStringOrNull() ?: return@mapNotNull null
|
||||||
|
val text = extractTextFromMessage(obj) ?: return@mapNotNull null
|
||||||
|
ChatMessage(
|
||||||
|
id = java.util.UUID.randomUUID().toString(),
|
||||||
|
role = role,
|
||||||
|
text = text,
|
||||||
|
timestampMs = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractTextFromMessage(msgObj: JsonObject?): String? {
|
||||||
|
if (msgObj == null) return null
|
||||||
|
val content = msgObj["content"] ?: return null
|
||||||
|
return when (content) {
|
||||||
|
is JsonPrimitive -> content.asStringOrNull()
|
||||||
|
else -> {
|
||||||
|
val arr = (content as? JsonArray) ?: return null
|
||||||
|
arr.mapNotNull { part ->
|
||||||
|
val p = part as? JsonObject ?: return@mapNotNull null
|
||||||
|
p["text"].asStringOrNull()
|
||||||
|
}.joinToString("\n").trim().ifBlank { null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseRunId(resJson: String): String? {
|
||||||
|
return try {
|
||||||
|
json.parseToJsonElement(resJson).asObjectOrNull()?.get("runId").asStringOrNull()
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun handleInvoke(command: String, paramsJson: String?): BridgeSession.InvokeResult {
|
||||||
|
if (command.startsWith("screen.") || command.startsWith("camera.")) {
|
||||||
|
if (!isForeground.value) {
|
||||||
|
return BridgeSession.InvokeResult.error(
|
||||||
|
code = "NODE_BACKGROUND_UNAVAILABLE",
|
||||||
|
message = "NODE_BACKGROUND_UNAVAILABLE: screen/camera commands require foreground",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (command.startsWith("camera.") && !cameraEnabled.value) {
|
||||||
|
return BridgeSession.InvokeResult.error(
|
||||||
|
code = "CAMERA_DISABLED",
|
||||||
|
message = "CAMERA_DISABLED: enable Camera in Settings",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return when (command) {
|
||||||
|
"screen.show" -> BridgeSession.InvokeResult.ok(null)
|
||||||
|
"screen.hide" -> BridgeSession.InvokeResult.ok(null)
|
||||||
|
"screen.setMode" -> {
|
||||||
|
val mode = CanvasController.parseMode(paramsJson)
|
||||||
|
canvas.setMode(mode)
|
||||||
|
BridgeSession.InvokeResult.ok(null)
|
||||||
|
}
|
||||||
|
"screen.navigate" -> {
|
||||||
|
val url = CanvasController.parseNavigateUrl(paramsJson)
|
||||||
|
if (url != null) canvas.navigate(url)
|
||||||
|
BridgeSession.InvokeResult.ok(null)
|
||||||
|
}
|
||||||
|
"screen.eval" -> {
|
||||||
|
val js =
|
||||||
|
CanvasController.parseEvalJs(paramsJson)
|
||||||
|
?: return BridgeSession.InvokeResult.error(
|
||||||
|
code = "INVALID_REQUEST",
|
||||||
|
message = "INVALID_REQUEST: javaScript required",
|
||||||
|
)
|
||||||
|
val result =
|
||||||
|
try {
|
||||||
|
canvas.eval(js)
|
||||||
|
} catch (err: Throwable) {
|
||||||
|
return BridgeSession.InvokeResult.error(
|
||||||
|
code = "NODE_BACKGROUND_UNAVAILABLE",
|
||||||
|
message = "NODE_BACKGROUND_UNAVAILABLE: canvas unavailable",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
BridgeSession.InvokeResult.ok("""{"result":${result.toJsonString()}}""")
|
||||||
|
}
|
||||||
|
"screen.snapshot" -> {
|
||||||
|
val maxWidth = CanvasController.parseSnapshotMaxWidth(paramsJson)
|
||||||
|
val base64 =
|
||||||
|
try {
|
||||||
|
canvas.snapshotPngBase64(maxWidth = maxWidth)
|
||||||
|
} catch (err: Throwable) {
|
||||||
|
return BridgeSession.InvokeResult.error(
|
||||||
|
code = "NODE_BACKGROUND_UNAVAILABLE",
|
||||||
|
message = "NODE_BACKGROUND_UNAVAILABLE: canvas unavailable",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
BridgeSession.InvokeResult.ok("""{"format":"png","base64":"$base64"}""")
|
||||||
|
}
|
||||||
|
"camera.snap" -> {
|
||||||
|
val res = camera.snap(paramsJson)
|
||||||
|
BridgeSession.InvokeResult.ok(res.payloadJson)
|
||||||
|
}
|
||||||
|
"camera.clip" -> {
|
||||||
|
val res = camera.clip(paramsJson)
|
||||||
|
BridgeSession.InvokeResult.ok(res.payloadJson)
|
||||||
|
}
|
||||||
|
else ->
|
||||||
|
BridgeSession.InvokeResult.error(
|
||||||
|
code = "INVALID_REQUEST",
|
||||||
|
message = "INVALID_REQUEST: unknown command",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun String.toJsonString(): String {
|
||||||
|
val escaped =
|
||||||
|
this.replace("\\", "\\\\")
|
||||||
|
.replace("\"", "\\\"")
|
||||||
|
.replace("\n", "\\n")
|
||||||
|
.replace("\r", "\\r")
|
||||||
|
return "\"$escaped\""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JsonElement?.asObjectOrNull(): JsonObject? = this as? JsonObject
|
||||||
|
|
||||||
|
private fun JsonElement?.asStringOrNull(): String? =
|
||||||
|
when (this) {
|
||||||
|
is JsonNull -> null
|
||||||
|
is JsonPrimitive -> content
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package com.steipete.clawdis.node
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.security.crypto.EncryptedSharedPreferences
|
||||||
|
import androidx.security.crypto.MasterKey
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.JsonArray
|
||||||
|
import kotlinx.serialization.json.JsonNull
|
||||||
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
class SecurePrefs(context: Context) {
|
||||||
|
companion object {
|
||||||
|
val defaultWakeWords: List<String> = listOf("clawd", "claude")
|
||||||
|
}
|
||||||
|
|
||||||
|
private val json = Json { ignoreUnknownKeys = true }
|
||||||
|
|
||||||
|
private val masterKey =
|
||||||
|
MasterKey.Builder(context)
|
||||||
|
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
private val prefs =
|
||||||
|
EncryptedSharedPreferences.create(
|
||||||
|
context,
|
||||||
|
"clawdis.node.secure",
|
||||||
|
masterKey,
|
||||||
|
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
|
||||||
|
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
|
||||||
|
)
|
||||||
|
|
||||||
|
private val _instanceId = MutableStateFlow(loadOrCreateInstanceId())
|
||||||
|
val instanceId: StateFlow<String> = _instanceId
|
||||||
|
|
||||||
|
private val _displayName = MutableStateFlow(prefs.getString("node.displayName", "Android Node")!!)
|
||||||
|
val displayName: StateFlow<String> = _displayName
|
||||||
|
|
||||||
|
private val _cameraEnabled = MutableStateFlow(prefs.getBoolean("camera.enabled", true))
|
||||||
|
val cameraEnabled: StateFlow<Boolean> = _cameraEnabled
|
||||||
|
|
||||||
|
private val _manualEnabled = MutableStateFlow(prefs.getBoolean("bridge.manual.enabled", false))
|
||||||
|
val manualEnabled: StateFlow<Boolean> = _manualEnabled
|
||||||
|
|
||||||
|
private val _manualHost = MutableStateFlow(prefs.getString("bridge.manual.host", "")!!)
|
||||||
|
val manualHost: StateFlow<String> = _manualHost
|
||||||
|
|
||||||
|
private val _manualPort = MutableStateFlow(prefs.getInt("bridge.manual.port", 18790))
|
||||||
|
val manualPort: StateFlow<Int> = _manualPort
|
||||||
|
|
||||||
|
private val _lastDiscoveredStableId =
|
||||||
|
MutableStateFlow(prefs.getString("bridge.lastDiscoveredStableId", "")!!)
|
||||||
|
val lastDiscoveredStableId: StateFlow<String> = _lastDiscoveredStableId
|
||||||
|
|
||||||
|
private val _wakeWords = MutableStateFlow(loadWakeWords())
|
||||||
|
val wakeWords: StateFlow<List<String>> = _wakeWords
|
||||||
|
|
||||||
|
fun setLastDiscoveredStableId(value: String) {
|
||||||
|
val trimmed = value.trim()
|
||||||
|
prefs.edit().putString("bridge.lastDiscoveredStableId", trimmed).apply()
|
||||||
|
_lastDiscoveredStableId.value = trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setDisplayName(value: String) {
|
||||||
|
val trimmed = value.trim()
|
||||||
|
prefs.edit().putString("node.displayName", trimmed).apply()
|
||||||
|
_displayName.value = trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setCameraEnabled(value: Boolean) {
|
||||||
|
prefs.edit().putBoolean("camera.enabled", value).apply()
|
||||||
|
_cameraEnabled.value = value
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualEnabled(value: Boolean) {
|
||||||
|
prefs.edit().putBoolean("bridge.manual.enabled", value).apply()
|
||||||
|
_manualEnabled.value = value
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualHost(value: String) {
|
||||||
|
val trimmed = value.trim()
|
||||||
|
prefs.edit().putString("bridge.manual.host", trimmed).apply()
|
||||||
|
_manualHost.value = trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setManualPort(value: Int) {
|
||||||
|
prefs.edit().putInt("bridge.manual.port", value).apply()
|
||||||
|
_manualPort.value = value
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadBridgeToken(): String? {
|
||||||
|
val key = "bridge.token.${_instanceId.value}"
|
||||||
|
return prefs.getString(key, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveBridgeToken(token: String) {
|
||||||
|
val key = "bridge.token.${_instanceId.value}"
|
||||||
|
prefs.edit().putString(key, token.trim()).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadOrCreateInstanceId(): String {
|
||||||
|
val existing = prefs.getString("node.instanceId", null)?.trim()
|
||||||
|
if (!existing.isNullOrBlank()) return existing
|
||||||
|
val fresh = UUID.randomUUID().toString()
|
||||||
|
prefs.edit().putString("node.instanceId", fresh).apply()
|
||||||
|
return fresh
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setWakeWords(words: List<String>) {
|
||||||
|
val sanitized = WakeWords.sanitize(words, defaultWakeWords)
|
||||||
|
val encoded =
|
||||||
|
JsonArray(sanitized.map { JsonPrimitive(it) }).toString()
|
||||||
|
prefs.edit().putString("voiceWake.triggerWords", encoded).apply()
|
||||||
|
_wakeWords.value = sanitized
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadWakeWords(): List<String> {
|
||||||
|
val raw = prefs.getString("voiceWake.triggerWords", null)?.trim()
|
||||||
|
if (raw.isNullOrEmpty()) return defaultWakeWords
|
||||||
|
return try {
|
||||||
|
val element = json.parseToJsonElement(raw)
|
||||||
|
val array = element as? JsonArray ?: return defaultWakeWords
|
||||||
|
val decoded =
|
||||||
|
array.mapNotNull { item ->
|
||||||
|
when (item) {
|
||||||
|
is JsonNull -> null
|
||||||
|
is JsonPrimitive -> item.content.trim().takeIf { it.isNotEmpty() }
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WakeWords.sanitize(decoded, defaultWakeWords)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
defaultWakeWords
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.steipete.clawdis.node
|
||||||
|
|
||||||
|
object WakeWords {
|
||||||
|
const val maxWords: Int = 32
|
||||||
|
const val maxWordLength: Int = 64
|
||||||
|
|
||||||
|
fun parseCommaSeparated(input: String): List<String> {
|
||||||
|
return input.split(",").map { it.trim() }.filter { it.isNotEmpty() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sanitize(words: List<String>, defaults: List<String>): List<String> {
|
||||||
|
val cleaned =
|
||||||
|
words.map { it.trim() }.filter { it.isNotEmpty() }.take(maxWords).map { it.take(maxWordLength) }
|
||||||
|
return cleaned.ifEmpty { defaults }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.steipete.clawdis.node.bridge
|
||||||
|
|
||||||
|
object BonjourEscapes {
|
||||||
|
fun decode(input: String): String {
|
||||||
|
if (input.isEmpty()) return input
|
||||||
|
|
||||||
|
val out = StringBuilder(input.length)
|
||||||
|
var i = 0
|
||||||
|
while (i < input.length) {
|
||||||
|
if (input[i] == '\\' && i + 3 < input.length) {
|
||||||
|
val d0 = input[i + 1]
|
||||||
|
val d1 = input[i + 2]
|
||||||
|
val d2 = input[i + 3]
|
||||||
|
if (d0.isDigit() && d1.isDigit() && d2.isDigit()) {
|
||||||
|
val value =
|
||||||
|
((d0.code - '0'.code) * 100) + ((d1.code - '0'.code) * 10) + (d2.code - '0'.code)
|
||||||
|
if (value in 0..0x10FFFF) {
|
||||||
|
out.appendCodePoint(value)
|
||||||
|
i += 4
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
out.append(input[i])
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
return out.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
package com.steipete.clawdis.node.bridge
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.nsd.NsdManager
|
||||||
|
import android.net.nsd.NsdServiceInfo
|
||||||
|
import android.os.Build
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.time.Duration
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import org.xbill.DNS.ExtendedResolver
|
||||||
|
import org.xbill.DNS.Lookup
|
||||||
|
import org.xbill.DNS.PTRRecord
|
||||||
|
import org.xbill.DNS.SRVRecord
|
||||||
|
import org.xbill.DNS.TXTRecord
|
||||||
|
import org.xbill.DNS.Type
|
||||||
|
|
||||||
|
class BridgeDiscovery(
|
||||||
|
context: Context,
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
) {
|
||||||
|
private val nsd = context.getSystemService(NsdManager::class.java)
|
||||||
|
private val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||||
|
private val serviceType = "_clawdis-bridge._tcp."
|
||||||
|
private val wideAreaDomain = "clawdis.internal."
|
||||||
|
|
||||||
|
private val localById = ConcurrentHashMap<String, BridgeEndpoint>()
|
||||||
|
private val unicastById = ConcurrentHashMap<String, BridgeEndpoint>()
|
||||||
|
private val _bridges = MutableStateFlow<List<BridgeEndpoint>>(emptyList())
|
||||||
|
val bridges: StateFlow<List<BridgeEndpoint>> = _bridges.asStateFlow()
|
||||||
|
|
||||||
|
private var unicastJob: Job? = null
|
||||||
|
|
||||||
|
private val discoveryListener =
|
||||||
|
object : NsdManager.DiscoveryListener {
|
||||||
|
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {}
|
||||||
|
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {}
|
||||||
|
override fun onDiscoveryStarted(serviceType: String) {}
|
||||||
|
override fun onDiscoveryStopped(serviceType: String) {}
|
||||||
|
|
||||||
|
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
|
||||||
|
if (serviceInfo.serviceType != this@BridgeDiscovery.serviceType) return
|
||||||
|
resolve(serviceInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onServiceLost(serviceInfo: NsdServiceInfo) {
|
||||||
|
val id = stableId(serviceInfo.serviceName, "local.")
|
||||||
|
localById.remove(id)
|
||||||
|
publish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
init {
|
||||||
|
startLocalDiscovery()
|
||||||
|
startUnicastDiscovery(wideAreaDomain)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startLocalDiscovery() {
|
||||||
|
try {
|
||||||
|
nsd.discoverServices(serviceType, NsdManager.PROTOCOL_DNS_SD, discoveryListener)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore (best-effort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stopLocalDiscovery() {
|
||||||
|
try {
|
||||||
|
nsd.stopServiceDiscovery(discoveryListener)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore (best-effort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startUnicastDiscovery(domain: String) {
|
||||||
|
unicastJob =
|
||||||
|
scope.launch(Dispatchers.IO) {
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
refreshUnicast(domain)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore (best-effort)
|
||||||
|
}
|
||||||
|
delay(5000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolve(serviceInfo: NsdServiceInfo) {
|
||||||
|
nsd.resolveService(
|
||||||
|
serviceInfo,
|
||||||
|
object : NsdManager.ResolveListener {
|
||||||
|
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {}
|
||||||
|
|
||||||
|
override fun onServiceResolved(resolved: NsdServiceInfo) {
|
||||||
|
val host = resolved.host?.hostAddress ?: return
|
||||||
|
val port = resolved.port
|
||||||
|
if (port <= 0) return
|
||||||
|
|
||||||
|
val rawServiceName = resolved.serviceName
|
||||||
|
val serviceName = BonjourEscapes.decode(rawServiceName)
|
||||||
|
val displayName = BonjourEscapes.decode(txt(resolved, "displayName") ?: serviceName)
|
||||||
|
val id = stableId(serviceName, "local.")
|
||||||
|
localById[id] = BridgeEndpoint(stableId = id, name = displayName, host = host, port = port)
|
||||||
|
publish()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun publish() {
|
||||||
|
_bridges.value =
|
||||||
|
(localById.values + unicastById.values).sortedBy { it.name.lowercase() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stableId(serviceName: String, domain: String): String {
|
||||||
|
return "${serviceType}|${domain}|${normalizeName(serviceName)}"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun normalizeName(raw: String): String {
|
||||||
|
return raw.trim().split(Regex("\\s+")).joinToString(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun txt(info: NsdServiceInfo, key: String): String? {
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null
|
||||||
|
val bytes = info.attributes[key] ?: return null
|
||||||
|
return try {
|
||||||
|
String(bytes, Charsets.UTF_8).trim().ifEmpty { null }
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun refreshUnicast(domain: String) {
|
||||||
|
val resolver = createUnicastResolver()
|
||||||
|
val ptrName = "${serviceType}${domain}"
|
||||||
|
val ptrRecords = lookup(ptrName, Type.PTR, resolver).mapNotNull { it as? PTRRecord }
|
||||||
|
|
||||||
|
val next = LinkedHashMap<String, BridgeEndpoint>()
|
||||||
|
for (ptr in ptrRecords) {
|
||||||
|
val instanceFqdn = ptr.target.toString()
|
||||||
|
val srv =
|
||||||
|
lookup(instanceFqdn, Type.SRV, resolver).firstOrNull { it is SRVRecord } as? SRVRecord ?: continue
|
||||||
|
val port = srv.port
|
||||||
|
if (port <= 0) continue
|
||||||
|
|
||||||
|
val targetName = stripTrailingDot(srv.target.toString())
|
||||||
|
val host =
|
||||||
|
try {
|
||||||
|
val addrs = InetAddress.getAllByName(targetName).mapNotNull { it.hostAddress }
|
||||||
|
addrs.firstOrNull { !it.contains(":") } ?: addrs.firstOrNull()
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
null
|
||||||
|
} ?: continue
|
||||||
|
|
||||||
|
val txt = lookup(instanceFqdn, Type.TXT, resolver).mapNotNull { it as? TXTRecord }
|
||||||
|
val instanceName = BonjourEscapes.decode(decodeInstanceName(instanceFqdn, domain))
|
||||||
|
val displayName = BonjourEscapes.decode(txtValue(txt, "displayName") ?: instanceName)
|
||||||
|
val id = stableId(instanceName, domain)
|
||||||
|
next[id] = BridgeEndpoint(stableId = id, name = displayName, host = host, port = port)
|
||||||
|
}
|
||||||
|
|
||||||
|
unicastById.clear()
|
||||||
|
unicastById.putAll(next)
|
||||||
|
publish()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeInstanceName(instanceFqdn: String, domain: String): String {
|
||||||
|
val suffix = "${serviceType}${domain}"
|
||||||
|
val withoutSuffix =
|
||||||
|
if (instanceFqdn.endsWith(suffix)) {
|
||||||
|
instanceFqdn.removeSuffix(suffix)
|
||||||
|
} else {
|
||||||
|
instanceFqdn.substringBefore(serviceType)
|
||||||
|
}
|
||||||
|
return normalizeName(stripTrailingDot(withoutSuffix))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stripTrailingDot(raw: String): String {
|
||||||
|
return raw.removeSuffix(".")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lookup(name: String, type: Int, resolver: org.xbill.DNS.Resolver?): List<org.xbill.DNS.Record> {
|
||||||
|
return try {
|
||||||
|
val lookup = Lookup(name, type)
|
||||||
|
if (resolver != null) {
|
||||||
|
lookup.setResolver(resolver)
|
||||||
|
lookup.setCache(null)
|
||||||
|
}
|
||||||
|
val out = lookup.run() ?: return emptyList()
|
||||||
|
out.toList()
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createUnicastResolver(): org.xbill.DNS.Resolver? {
|
||||||
|
val cm = connectivity ?: return null
|
||||||
|
val net = cm.activeNetwork ?: return null
|
||||||
|
val dnsServers = cm.getLinkProperties(net)?.dnsServers ?: return null
|
||||||
|
val addrs =
|
||||||
|
dnsServers
|
||||||
|
.mapNotNull { it.hostAddress }
|
||||||
|
.map { it.trim() }
|
||||||
|
.filter { it.isNotEmpty() }
|
||||||
|
.distinct()
|
||||||
|
if (addrs.isEmpty()) return null
|
||||||
|
|
||||||
|
return try {
|
||||||
|
ExtendedResolver(addrs.toTypedArray()).apply {
|
||||||
|
setTimeout(Duration.ofMillis(1500))
|
||||||
|
}
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun txtValue(records: List<TXTRecord>, key: String): String? {
|
||||||
|
val prefix = "$key="
|
||||||
|
for (r in records) {
|
||||||
|
val strings: List<String> =
|
||||||
|
try {
|
||||||
|
r.strings.mapNotNull { it as? String }
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
for (s in strings) {
|
||||||
|
val trimmed = s.trim()
|
||||||
|
if (trimmed.startsWith(prefix)) {
|
||||||
|
return trimmed.removePrefix(prefix).trim().ifEmpty { null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.steipete.clawdis.node.bridge
|
||||||
|
|
||||||
|
data class BridgeEndpoint(
|
||||||
|
val stableId: String,
|
||||||
|
val name: String,
|
||||||
|
val host: String,
|
||||||
|
val port: Int,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
fun manual(host: String, port: Int): BridgeEndpoint =
|
||||||
|
BridgeEndpoint(
|
||||||
|
stableId = "manual|$host|$port",
|
||||||
|
name = "$host:$port",
|
||||||
|
host = host,
|
||||||
|
port = port,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package com.steipete.clawdis.node.bridge
|
||||||
|
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.JsonObject
|
||||||
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
|
import kotlinx.serialization.json.JsonNull
|
||||||
|
import kotlinx.serialization.json.JsonElement
|
||||||
|
import kotlinx.serialization.json.buildJsonObject
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.Socket
|
||||||
|
|
||||||
|
class BridgePairingClient {
|
||||||
|
private val json = Json { ignoreUnknownKeys = true }
|
||||||
|
|
||||||
|
data class Hello(
|
||||||
|
val nodeId: String,
|
||||||
|
val displayName: String?,
|
||||||
|
val token: String?,
|
||||||
|
val platform: String?,
|
||||||
|
val version: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class PairResult(val ok: Boolean, val token: String?, val error: String? = null)
|
||||||
|
|
||||||
|
suspend fun pairAndHello(endpoint: BridgeEndpoint, hello: Hello): PairResult =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
val socket = Socket()
|
||||||
|
socket.tcpNoDelay = true
|
||||||
|
socket.connect(InetSocketAddress(endpoint.host, endpoint.port), 8_000)
|
||||||
|
socket.soTimeout = 60_000
|
||||||
|
|
||||||
|
val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8))
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8))
|
||||||
|
|
||||||
|
fun send(line: String) {
|
||||||
|
writer.write(line)
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendJson(obj: JsonObject) = send(obj.toString())
|
||||||
|
|
||||||
|
try {
|
||||||
|
sendJson(
|
||||||
|
buildJsonObject {
|
||||||
|
put("type", JsonPrimitive("hello"))
|
||||||
|
put("nodeId", JsonPrimitive(hello.nodeId))
|
||||||
|
hello.displayName?.let { put("displayName", JsonPrimitive(it)) }
|
||||||
|
hello.token?.let { put("token", JsonPrimitive(it)) }
|
||||||
|
hello.platform?.let { put("platform", JsonPrimitive(it)) }
|
||||||
|
hello.version?.let { put("version", JsonPrimitive(it)) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
val firstObj = json.parseToJsonElement(reader.readLine()).asObjectOrNull()
|
||||||
|
?: return@withContext PairResult(ok = false, token = null, error = "unexpected bridge response")
|
||||||
|
when (firstObj["type"].asStringOrNull()) {
|
||||||
|
"hello-ok" -> PairResult(ok = true, token = hello.token)
|
||||||
|
"error" -> {
|
||||||
|
val code = firstObj["code"].asStringOrNull() ?: "UNAVAILABLE"
|
||||||
|
val message = firstObj["message"].asStringOrNull() ?: "pairing required"
|
||||||
|
if (code != "NOT_PAIRED" && code != "UNAUTHORIZED") {
|
||||||
|
return@withContext PairResult(ok = false, token = null, error = "$code: $message")
|
||||||
|
}
|
||||||
|
|
||||||
|
sendJson(
|
||||||
|
buildJsonObject {
|
||||||
|
put("type", JsonPrimitive("pair-request"))
|
||||||
|
put("nodeId", JsonPrimitive(hello.nodeId))
|
||||||
|
hello.displayName?.let { put("displayName", JsonPrimitive(it)) }
|
||||||
|
hello.platform?.let { put("platform", JsonPrimitive(it)) }
|
||||||
|
hello.version?.let { put("version", JsonPrimitive(it)) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
val nextLine = reader.readLine() ?: break
|
||||||
|
val next = json.parseToJsonElement(nextLine).asObjectOrNull() ?: continue
|
||||||
|
when (next["type"].asStringOrNull()) {
|
||||||
|
"pair-ok" -> {
|
||||||
|
val token = next["token"].asStringOrNull()
|
||||||
|
return@withContext PairResult(ok = !token.isNullOrBlank(), token = token)
|
||||||
|
}
|
||||||
|
"error" -> {
|
||||||
|
val c = next["code"].asStringOrNull() ?: "UNAVAILABLE"
|
||||||
|
val m = next["message"].asStringOrNull() ?: "pairing failed"
|
||||||
|
return@withContext PairResult(ok = false, token = null, error = "$c: $m")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PairResult(ok = false, token = null, error = "pairing failed")
|
||||||
|
}
|
||||||
|
else -> PairResult(ok = false, token = null, error = "unexpected bridge response")
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
socket.close()
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JsonElement?.asObjectOrNull(): JsonObject? = this as? JsonObject
|
||||||
|
|
||||||
|
private fun JsonElement?.asStringOrNull(): String? =
|
||||||
|
when (this) {
|
||||||
|
is JsonNull -> null
|
||||||
|
is JsonPrimitive -> content
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
package com.steipete.clawdis.node.bridge
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.cancelAndJoin
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.isActive
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.JsonObject
|
||||||
|
import kotlinx.serialization.json.JsonNull
|
||||||
|
import kotlinx.serialization.json.JsonElement
|
||||||
|
import kotlinx.serialization.json.JsonPrimitive
|
||||||
|
import kotlinx.serialization.json.buildJsonObject
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.net.Socket
|
||||||
|
import java.util.UUID
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
|
class BridgeSession(
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
private val onConnected: (serverName: String, remoteAddress: String?) -> Unit,
|
||||||
|
private val onDisconnected: (message: String) -> Unit,
|
||||||
|
private val onEvent: (event: String, payloadJson: String?) -> Unit,
|
||||||
|
private val onInvoke: suspend (InvokeRequest) -> InvokeResult,
|
||||||
|
) {
|
||||||
|
data class Hello(
|
||||||
|
val nodeId: String,
|
||||||
|
val displayName: String?,
|
||||||
|
val token: String?,
|
||||||
|
val platform: String?,
|
||||||
|
val version: String?,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class InvokeRequest(val id: String, val command: String, val paramsJson: String?)
|
||||||
|
|
||||||
|
data class InvokeResult(val ok: Boolean, val payloadJson: String?, val error: ErrorShape?) {
|
||||||
|
companion object {
|
||||||
|
fun ok(payloadJson: String?) = InvokeResult(ok = true, payloadJson = payloadJson, error = null)
|
||||||
|
fun error(code: String, message: String) =
|
||||||
|
InvokeResult(ok = false, payloadJson = null, error = ErrorShape(code = code, message = message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class ErrorShape(val code: String, val message: String)
|
||||||
|
|
||||||
|
private val json = Json { ignoreUnknownKeys = true }
|
||||||
|
private val writeLock = Mutex()
|
||||||
|
private val pending = ConcurrentHashMap<String, CompletableDeferred<RpcResponse>>()
|
||||||
|
|
||||||
|
private var desired: Pair<BridgeEndpoint, Hello>? = null
|
||||||
|
private var job: Job? = null
|
||||||
|
|
||||||
|
fun connect(endpoint: BridgeEndpoint, hello: Hello) {
|
||||||
|
desired = endpoint to hello
|
||||||
|
if (job == null) {
|
||||||
|
job = scope.launch(Dispatchers.IO) { runLoop() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun disconnect() {
|
||||||
|
desired = null
|
||||||
|
scope.launch(Dispatchers.IO) {
|
||||||
|
job?.cancelAndJoin()
|
||||||
|
job = null
|
||||||
|
onDisconnected("Disconnected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun sendEvent(event: String, payloadJson: String?) {
|
||||||
|
val conn = currentConnection ?: return
|
||||||
|
conn.sendJson(
|
||||||
|
buildJsonObject {
|
||||||
|
put("type", JsonPrimitive("event"))
|
||||||
|
put("event", JsonPrimitive(event))
|
||||||
|
if (payloadJson != null) put("payloadJSON", JsonPrimitive(payloadJson)) else put("payloadJSON", JsonNull)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun request(method: String, paramsJson: String?): String {
|
||||||
|
val conn = currentConnection ?: throw IllegalStateException("not connected")
|
||||||
|
val id = UUID.randomUUID().toString()
|
||||||
|
val deferred = CompletableDeferred<RpcResponse>()
|
||||||
|
pending[id] = deferred
|
||||||
|
conn.sendJson(
|
||||||
|
buildJsonObject {
|
||||||
|
put("type", JsonPrimitive("req"))
|
||||||
|
put("id", JsonPrimitive(id))
|
||||||
|
put("method", JsonPrimitive(method))
|
||||||
|
if (paramsJson != null) put("paramsJSON", JsonPrimitive(paramsJson)) else put("paramsJSON", JsonNull)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
val res = deferred.await()
|
||||||
|
if (res.ok) return res.payloadJson ?: ""
|
||||||
|
val err = res.error
|
||||||
|
throw IllegalStateException("${err?.code ?: "UNAVAILABLE"}: ${err?.message ?: "request failed"}")
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class RpcResponse(val id: String, val ok: Boolean, val payloadJson: String?, val error: ErrorShape?)
|
||||||
|
|
||||||
|
private class Connection(private val socket: Socket, private val reader: BufferedReader, private val writer: BufferedWriter, private val writeLock: Mutex) {
|
||||||
|
val remoteAddress: String? =
|
||||||
|
socket.inetAddress?.hostAddress?.takeIf { it.isNotBlank() }?.let { "${it}:${socket.port}" }
|
||||||
|
|
||||||
|
suspend fun sendJson(obj: JsonObject) {
|
||||||
|
writeLock.withLock {
|
||||||
|
writer.write(obj.toString())
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun closeQuietly() {
|
||||||
|
try {
|
||||||
|
socket.close()
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile private var currentConnection: Connection? = null
|
||||||
|
|
||||||
|
private suspend fun runLoop() {
|
||||||
|
var attempt = 0
|
||||||
|
while (scope.isActive) {
|
||||||
|
val target = desired
|
||||||
|
if (target == null) {
|
||||||
|
currentConnection?.closeQuietly()
|
||||||
|
currentConnection = null
|
||||||
|
delay(250)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
val (endpoint, hello) = target
|
||||||
|
try {
|
||||||
|
onDisconnected(if (attempt == 0) "Connecting…" else "Reconnecting…")
|
||||||
|
connectOnce(endpoint, hello)
|
||||||
|
attempt = 0
|
||||||
|
} catch (err: Throwable) {
|
||||||
|
attempt += 1
|
||||||
|
onDisconnected("Bridge error: ${err.message ?: err::class.java.simpleName}")
|
||||||
|
val sleepMs = minOf(8_000L, (350.0 * Math.pow(1.7, attempt.toDouble())).toLong())
|
||||||
|
delay(sleepMs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun invokeErrorFromThrowable(err: Throwable): InvokeResult {
|
||||||
|
val msg = err.message?.trim().takeIf { !it.isNullOrEmpty() } ?: err::class.java.simpleName
|
||||||
|
val parts = msg.split(":", limit = 2)
|
||||||
|
if (parts.size == 2) {
|
||||||
|
val code = parts[0].trim()
|
||||||
|
val rest = parts[1].trim()
|
||||||
|
if (code.isNotEmpty() && code.all { it.isUpperCase() || it == '_' }) {
|
||||||
|
return InvokeResult.error(code = code, message = rest.ifEmpty { msg })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return InvokeResult.error(code = "UNAVAILABLE", message = msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun connectOnce(endpoint: BridgeEndpoint, hello: Hello) =
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
val socket = Socket()
|
||||||
|
socket.tcpNoDelay = true
|
||||||
|
socket.connect(InetSocketAddress(endpoint.host, endpoint.port), 8_000)
|
||||||
|
socket.soTimeout = 0
|
||||||
|
|
||||||
|
val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.UTF_8))
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8))
|
||||||
|
|
||||||
|
val conn = Connection(socket, reader, writer, writeLock)
|
||||||
|
currentConnection = conn
|
||||||
|
|
||||||
|
try {
|
||||||
|
conn.sendJson(
|
||||||
|
buildJsonObject {
|
||||||
|
put("type", JsonPrimitive("hello"))
|
||||||
|
put("nodeId", JsonPrimitive(hello.nodeId))
|
||||||
|
hello.displayName?.let { put("displayName", JsonPrimitive(it)) }
|
||||||
|
hello.token?.let { put("token", JsonPrimitive(it)) }
|
||||||
|
hello.platform?.let { put("platform", JsonPrimitive(it)) }
|
||||||
|
hello.version?.let { put("version", JsonPrimitive(it)) }
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
val firstLine = reader.readLine() ?: throw IllegalStateException("bridge closed connection")
|
||||||
|
val first = json.parseToJsonElement(firstLine).asObjectOrNull()
|
||||||
|
?: throw IllegalStateException("unexpected bridge response")
|
||||||
|
when (first["type"].asStringOrNull()) {
|
||||||
|
"hello-ok" -> {
|
||||||
|
val name = first["serverName"].asStringOrNull() ?: "Bridge"
|
||||||
|
onConnected(name, conn.remoteAddress)
|
||||||
|
}
|
||||||
|
"error" -> {
|
||||||
|
val code = first["code"].asStringOrNull() ?: "UNAVAILABLE"
|
||||||
|
val msg = first["message"].asStringOrNull() ?: "connect failed"
|
||||||
|
throw IllegalStateException("$code: $msg")
|
||||||
|
}
|
||||||
|
else -> throw IllegalStateException("unexpected bridge response")
|
||||||
|
}
|
||||||
|
|
||||||
|
while (scope.isActive) {
|
||||||
|
val line = reader.readLine() ?: break
|
||||||
|
val frame = json.parseToJsonElement(line).asObjectOrNull() ?: continue
|
||||||
|
when (frame["type"].asStringOrNull()) {
|
||||||
|
"event" -> {
|
||||||
|
val event = frame["event"].asStringOrNull() ?: return@withContext
|
||||||
|
val payload = frame["payloadJSON"].asStringOrNull()
|
||||||
|
onEvent(event, payload)
|
||||||
|
}
|
||||||
|
"ping" -> {
|
||||||
|
val id = frame["id"].asStringOrNull() ?: ""
|
||||||
|
conn.sendJson(buildJsonObject { put("type", JsonPrimitive("pong")); put("id", JsonPrimitive(id)) })
|
||||||
|
}
|
||||||
|
"res" -> {
|
||||||
|
val id = frame["id"].asStringOrNull() ?: continue
|
||||||
|
val ok = frame["ok"].asBooleanOrNull() ?: false
|
||||||
|
val payloadJson = frame["payloadJSON"].asStringOrNull()
|
||||||
|
val error =
|
||||||
|
frame["error"]?.let {
|
||||||
|
val obj = it.asObjectOrNull() ?: return@let null
|
||||||
|
val code = obj["code"].asStringOrNull() ?: "UNAVAILABLE"
|
||||||
|
val msg = obj["message"].asStringOrNull() ?: "request failed"
|
||||||
|
ErrorShape(code, msg)
|
||||||
|
}
|
||||||
|
pending.remove(id)?.complete(RpcResponse(id, ok, payloadJson, error))
|
||||||
|
}
|
||||||
|
"invoke" -> {
|
||||||
|
val id = frame["id"].asStringOrNull() ?: continue
|
||||||
|
val command = frame["command"].asStringOrNull() ?: ""
|
||||||
|
val params = frame["paramsJSON"].asStringOrNull()
|
||||||
|
val result =
|
||||||
|
try {
|
||||||
|
onInvoke(InvokeRequest(id, command, params))
|
||||||
|
} catch (err: Throwable) {
|
||||||
|
invokeErrorFromThrowable(err)
|
||||||
|
}
|
||||||
|
conn.sendJson(
|
||||||
|
buildJsonObject {
|
||||||
|
put("type", JsonPrimitive("invoke-res"))
|
||||||
|
put("id", JsonPrimitive(id))
|
||||||
|
put("ok", JsonPrimitive(result.ok))
|
||||||
|
if (result.payloadJson != null) put("payloadJSON", JsonPrimitive(result.payloadJson))
|
||||||
|
if (result.error != null) {
|
||||||
|
put(
|
||||||
|
"error",
|
||||||
|
buildJsonObject {
|
||||||
|
put("code", JsonPrimitive(result.error.code))
|
||||||
|
put("message", JsonPrimitive(result.error.message))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
"invoke-res" -> {
|
||||||
|
// gateway->node only (ignore)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
currentConnection = null
|
||||||
|
for ((_, waiter) in pending) {
|
||||||
|
waiter.cancel()
|
||||||
|
}
|
||||||
|
pending.clear()
|
||||||
|
conn.closeQuietly()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JsonElement?.asObjectOrNull(): JsonObject? = this as? JsonObject
|
||||||
|
|
||||||
|
private fun JsonElement?.asStringOrNull(): String? =
|
||||||
|
when (this) {
|
||||||
|
is JsonNull -> null
|
||||||
|
is JsonPrimitive -> content
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JsonElement?.asBooleanOrNull(): Boolean? =
|
||||||
|
when (this) {
|
||||||
|
is JsonPrimitive -> {
|
||||||
|
val c = content.trim()
|
||||||
|
when {
|
||||||
|
c.equals("true", ignoreCase = true) -> true
|
||||||
|
c.equals("false", ignoreCase = true) -> false
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
package com.steipete.clawdis.node.node
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.util.Base64
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import androidx.lifecycle.LifecycleOwner
|
||||||
|
import androidx.camera.core.CameraSelector
|
||||||
|
import androidx.camera.core.ImageCapture
|
||||||
|
import androidx.camera.core.ImageCaptureException
|
||||||
|
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||||
|
import androidx.camera.video.FileOutputOptions
|
||||||
|
import androidx.camera.video.Recorder
|
||||||
|
import androidx.camera.video.Recording
|
||||||
|
import androidx.camera.video.VideoCapture
|
||||||
|
import androidx.camera.video.VideoRecordEvent
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import androidx.core.content.ContextCompat.checkSelfPermission
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.Executor
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
import kotlin.coroutines.resumeWithException
|
||||||
|
|
||||||
|
class CameraCaptureManager(private val context: Context) {
|
||||||
|
data class Payload(val payloadJson: String)
|
||||||
|
|
||||||
|
@Volatile private var lifecycleOwner: LifecycleOwner? = null
|
||||||
|
|
||||||
|
fun attachLifecycleOwner(owner: LifecycleOwner) {
|
||||||
|
lifecycleOwner = owner
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun requireCameraPermission() {
|
||||||
|
val granted = checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
|
||||||
|
if (!granted) throw IllegalStateException("CAMERA_PERMISSION_REQUIRED: grant Camera permission")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun requireMicPermission() {
|
||||||
|
val granted = checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||||
|
if (!granted) throw IllegalStateException("MIC_PERMISSION_REQUIRED: grant Microphone permission")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun snap(paramsJson: String?): Payload =
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
requireCameraPermission()
|
||||||
|
val owner = lifecycleOwner ?: throw IllegalStateException("UNAVAILABLE: camera not ready")
|
||||||
|
val facing = parseFacing(paramsJson) ?: "front"
|
||||||
|
val quality = (parseQuality(paramsJson) ?: 0.9).coerceIn(0.1, 1.0)
|
||||||
|
val maxWidth = parseMaxWidth(paramsJson)
|
||||||
|
|
||||||
|
val provider = context.cameraProvider()
|
||||||
|
val capture = ImageCapture.Builder().build()
|
||||||
|
val selector =
|
||||||
|
if (facing == "front") CameraSelector.DEFAULT_FRONT_CAMERA else CameraSelector.DEFAULT_BACK_CAMERA
|
||||||
|
|
||||||
|
provider.unbindAll()
|
||||||
|
provider.bindToLifecycle(owner, selector, capture)
|
||||||
|
|
||||||
|
val bytes = capture.takeJpegBytes(context.mainExecutor())
|
||||||
|
val decoded = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||||
|
?: throw IllegalStateException("UNAVAILABLE: failed to decode captured image")
|
||||||
|
val scaled =
|
||||||
|
if (maxWidth != null && maxWidth > 0 && decoded.width > maxWidth) {
|
||||||
|
val h =
|
||||||
|
(decoded.height.toDouble() * (maxWidth.toDouble() / decoded.width.toDouble()))
|
||||||
|
.toInt()
|
||||||
|
.coerceAtLeast(1)
|
||||||
|
Bitmap.createScaledBitmap(decoded, maxWidth, h, true)
|
||||||
|
} else {
|
||||||
|
decoded
|
||||||
|
}
|
||||||
|
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
val jpegQuality = (quality * 100.0).toInt().coerceIn(10, 100)
|
||||||
|
if (!scaled.compress(Bitmap.CompressFormat.JPEG, jpegQuality, out)) {
|
||||||
|
throw IllegalStateException("UNAVAILABLE: failed to encode JPEG")
|
||||||
|
}
|
||||||
|
val base64 = Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP)
|
||||||
|
Payload(
|
||||||
|
"""{"format":"jpg","base64":"$base64","width":${scaled.width},"height":${scaled.height}}""",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun clip(paramsJson: String?): Payload =
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
requireCameraPermission()
|
||||||
|
val owner = lifecycleOwner ?: throw IllegalStateException("UNAVAILABLE: camera not ready")
|
||||||
|
val facing = parseFacing(paramsJson) ?: "front"
|
||||||
|
val durationMs = (parseDurationMs(paramsJson) ?: 3_000).coerceIn(200, 45_000)
|
||||||
|
val includeAudio = parseIncludeAudio(paramsJson) ?: true
|
||||||
|
if (includeAudio) requireMicPermission()
|
||||||
|
|
||||||
|
val provider = context.cameraProvider()
|
||||||
|
val recorder = Recorder.Builder().build()
|
||||||
|
val videoCapture = VideoCapture.withOutput(recorder)
|
||||||
|
val selector =
|
||||||
|
if (facing == "front") CameraSelector.DEFAULT_FRONT_CAMERA else CameraSelector.DEFAULT_BACK_CAMERA
|
||||||
|
|
||||||
|
provider.unbindAll()
|
||||||
|
provider.bindToLifecycle(owner, selector, videoCapture)
|
||||||
|
|
||||||
|
val file = File.createTempFile("clawdis-clip-", ".mp4")
|
||||||
|
val outputOptions = FileOutputOptions.Builder(file).build()
|
||||||
|
|
||||||
|
val finalized = kotlinx.coroutines.CompletableDeferred<VideoRecordEvent.Finalize>()
|
||||||
|
val recording: Recording =
|
||||||
|
videoCapture.output
|
||||||
|
.prepareRecording(context, outputOptions)
|
||||||
|
.apply {
|
||||||
|
if (includeAudio) withAudioEnabled()
|
||||||
|
}
|
||||||
|
.start(context.mainExecutor()) { event ->
|
||||||
|
if (event is VideoRecordEvent.Finalize) {
|
||||||
|
finalized.complete(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
kotlinx.coroutines.delay(durationMs.toLong())
|
||||||
|
} finally {
|
||||||
|
recording.stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
val finalizeEvent =
|
||||||
|
try {
|
||||||
|
withTimeout(10_000) { finalized.await() }
|
||||||
|
} catch (err: Throwable) {
|
||||||
|
file.delete()
|
||||||
|
throw IllegalStateException("UNAVAILABLE: camera clip finalize timed out")
|
||||||
|
}
|
||||||
|
if (finalizeEvent.hasError()) {
|
||||||
|
file.delete()
|
||||||
|
throw IllegalStateException("UNAVAILABLE: camera clip failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
val bytes = file.readBytes()
|
||||||
|
file.delete()
|
||||||
|
val base64 = Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||||
|
Payload(
|
||||||
|
"""{"format":"mp4","base64":"$base64","durationMs":$durationMs,"hasAudio":${includeAudio}}""",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseFacing(paramsJson: String?): String? =
|
||||||
|
when {
|
||||||
|
paramsJson?.contains("\"front\"") == true -> "front"
|
||||||
|
paramsJson?.contains("\"back\"") == true -> "back"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseQuality(paramsJson: String?): Double? =
|
||||||
|
parseNumber(paramsJson, key = "quality")?.toDoubleOrNull()
|
||||||
|
|
||||||
|
private fun parseMaxWidth(paramsJson: String?): Int? =
|
||||||
|
parseNumber(paramsJson, key = "maxWidth")?.toIntOrNull()
|
||||||
|
|
||||||
|
private fun parseDurationMs(paramsJson: String?): Int? =
|
||||||
|
parseNumber(paramsJson, key = "durationMs")?.toIntOrNull()
|
||||||
|
|
||||||
|
private fun parseIncludeAudio(paramsJson: String?): Boolean? {
|
||||||
|
val raw = paramsJson ?: return null
|
||||||
|
val key = "\"includeAudio\""
|
||||||
|
val idx = raw.indexOf(key)
|
||||||
|
if (idx < 0) return null
|
||||||
|
val colon = raw.indexOf(':', idx + key.length)
|
||||||
|
if (colon < 0) return null
|
||||||
|
val tail = raw.substring(colon + 1).trimStart()
|
||||||
|
return when {
|
||||||
|
tail.startsWith("true") -> true
|
||||||
|
tail.startsWith("false") -> false
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseNumber(paramsJson: String?, key: String): String? {
|
||||||
|
val raw = paramsJson ?: return null
|
||||||
|
val needle = "\"$key\""
|
||||||
|
val idx = raw.indexOf(needle)
|
||||||
|
if (idx < 0) return null
|
||||||
|
val colon = raw.indexOf(':', idx + needle.length)
|
||||||
|
if (colon < 0) return null
|
||||||
|
val tail = raw.substring(colon + 1).trimStart()
|
||||||
|
return tail.takeWhile { it.isDigit() || it == '.' }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Context.mainExecutor(): Executor = ContextCompat.getMainExecutor(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun Context.cameraProvider(): ProcessCameraProvider =
|
||||||
|
suspendCancellableCoroutine { cont ->
|
||||||
|
val future = ProcessCameraProvider.getInstance(this)
|
||||||
|
future.addListener(
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
cont.resume(future.get())
|
||||||
|
} catch (e: Exception) {
|
||||||
|
cont.resumeWithException(e)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ContextCompat.getMainExecutor(this),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun ImageCapture.takeJpegBytes(executor: Executor): ByteArray =
|
||||||
|
suspendCancellableCoroutine { cont ->
|
||||||
|
val file = File.createTempFile("clawdis-snap-", ".jpg")
|
||||||
|
val options = ImageCapture.OutputFileOptions.Builder(file).build()
|
||||||
|
takePicture(
|
||||||
|
options,
|
||||||
|
executor,
|
||||||
|
object : ImageCapture.OnImageSavedCallback {
|
||||||
|
override fun onError(exception: ImageCaptureException) {
|
||||||
|
cont.resumeWithException(exception)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
|
||||||
|
try {
|
||||||
|
val bytes = file.readBytes()
|
||||||
|
cont.resume(bytes)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
cont.resumeWithException(e)
|
||||||
|
} finally {
|
||||||
|
file.delete()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
package com.steipete.clawdis.node.node
|
||||||
|
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.os.Build
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.webkit.WebView
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import android.util.Base64
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
class CanvasController {
|
||||||
|
enum class Mode { CANVAS, WEB }
|
||||||
|
|
||||||
|
@Volatile private var webView: WebView? = null
|
||||||
|
@Volatile private var mode: Mode = Mode.CANVAS
|
||||||
|
@Volatile private var url: String = ""
|
||||||
|
|
||||||
|
fun attach(webView: WebView) {
|
||||||
|
this.webView = webView
|
||||||
|
reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setMode(mode: Mode) {
|
||||||
|
this.mode = mode
|
||||||
|
reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun navigate(url: String) {
|
||||||
|
this.url = url
|
||||||
|
reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun reload() {
|
||||||
|
val wv = webView ?: return
|
||||||
|
when (mode) {
|
||||||
|
Mode.WEB -> wv.loadUrl(url.trim())
|
||||||
|
Mode.CANVAS -> wv.loadDataWithBaseURL(null, canvasHtml, "text/html", "utf-8", null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun eval(javaScript: String): String =
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
val wv = webView ?: throw IllegalStateException("no webview")
|
||||||
|
suspendCancellableCoroutine { cont ->
|
||||||
|
wv.evaluateJavascript(javaScript) { result ->
|
||||||
|
cont.resume(result ?: "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun snapshotPngBase64(maxWidth: Int?): String =
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
val wv = webView ?: throw IllegalStateException("no webview")
|
||||||
|
val bmp = wv.captureBitmap()
|
||||||
|
val scaled =
|
||||||
|
if (maxWidth != null && maxWidth > 0 && bmp.width > maxWidth) {
|
||||||
|
val h = (bmp.height.toDouble() * (maxWidth.toDouble() / bmp.width.toDouble())).toInt().coerceAtLeast(1)
|
||||||
|
Bitmap.createScaledBitmap(bmp, maxWidth, h, true)
|
||||||
|
} else {
|
||||||
|
bmp
|
||||||
|
}
|
||||||
|
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
scaled.compress(Bitmap.CompressFormat.PNG, 100, out)
|
||||||
|
Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun WebView.captureBitmap(): Bitmap =
|
||||||
|
suspendCancellableCoroutine { cont ->
|
||||||
|
val width = width.coerceAtLeast(1)
|
||||||
|
val height = height.coerceAtLeast(1)
|
||||||
|
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||||
|
|
||||||
|
// WebView isn't supported by PixelCopy.request(...) directly; draw() is the most reliable
|
||||||
|
// cross-version snapshot for this lightweight "canvas" use-case.
|
||||||
|
draw(Canvas(bitmap))
|
||||||
|
cont.resume(bitmap)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun parseMode(paramsJson: String?): Mode {
|
||||||
|
val raw = paramsJson ?: return Mode.CANVAS
|
||||||
|
return if (raw.contains("\"web\"")) Mode.WEB else Mode.CANVAS
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parseNavigateUrl(paramsJson: String?): String? {
|
||||||
|
val raw = paramsJson ?: return null
|
||||||
|
val key = "\"url\""
|
||||||
|
val idx = raw.indexOf(key)
|
||||||
|
if (idx < 0) return null
|
||||||
|
val start = raw.indexOf('"', idx + key.length)
|
||||||
|
if (start < 0) return null
|
||||||
|
val end = raw.indexOf('"', start + 1)
|
||||||
|
if (end < 0) return null
|
||||||
|
return raw.substring(start + 1, end)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parseEvalJs(paramsJson: String?): String? {
|
||||||
|
val raw = paramsJson ?: return null
|
||||||
|
val key = "\"javaScript\""
|
||||||
|
val idx = raw.indexOf(key)
|
||||||
|
if (idx < 0) return null
|
||||||
|
val start = raw.indexOf('"', idx + key.length)
|
||||||
|
if (start < 0) return null
|
||||||
|
val end = raw.lastIndexOf('"')
|
||||||
|
if (end <= start) return null
|
||||||
|
return raw.substring(start + 1, end)
|
||||||
|
.replace("\\n", "\n")
|
||||||
|
.replace("\\\"", "\"")
|
||||||
|
.replace("\\\\", "\\")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parseSnapshotMaxWidth(paramsJson: String?): Int? {
|
||||||
|
val raw = paramsJson ?: return null
|
||||||
|
val key = "\"maxWidth\""
|
||||||
|
val idx = raw.indexOf(key)
|
||||||
|
if (idx < 0) return null
|
||||||
|
val colon = raw.indexOf(':', idx + key.length)
|
||||||
|
if (colon < 0) return null
|
||||||
|
val tail = raw.substring(colon + 1).trimStart()
|
||||||
|
val num = tail.takeWhile { it.isDigit() }
|
||||||
|
return num.toIntOrNull()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val canvasHtml =
|
||||||
|
"""
|
||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
|
<title>Canvas</title>
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: dark; }
|
||||||
|
html,body { height:100%; margin:0; }
|
||||||
|
body {
|
||||||
|
background: radial-gradient(1200px 900px at 15% 20%, rgba(42, 113, 255, 0.18), rgba(0,0,0,0) 55%),
|
||||||
|
radial-gradient(900px 700px at 85% 30%, rgba(255, 0, 138, 0.14), rgba(0,0,0,0) 60%),
|
||||||
|
radial-gradient(1000px 900px at 60% 90%, rgba(0, 209, 255, 0.10), rgba(0,0,0,0) 60%),
|
||||||
|
#000;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
body::before {
|
||||||
|
content:"";
|
||||||
|
position: fixed;
|
||||||
|
inset: -20%;
|
||||||
|
background:
|
||||||
|
repeating-linear-gradient(0deg, rgba(255,255,255,0.02) 0, rgba(255,255,255,0.02) 1px,
|
||||||
|
transparent 1px, transparent 48px),
|
||||||
|
repeating-linear-gradient(90deg, rgba(255,255,255,0.02) 0, rgba(255,255,255,0.02) 1px,
|
||||||
|
transparent 1px, transparent 48px);
|
||||||
|
transform: rotate(-7deg);
|
||||||
|
opacity: 0.55;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
canvas {
|
||||||
|
display:block;
|
||||||
|
width:100vw;
|
||||||
|
height:100vh;
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
#clawdis-status {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
#clawdis-status .card {
|
||||||
|
text-align: center;
|
||||||
|
padding: 16px 18px;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: rgba(18, 18, 22, 0.42);
|
||||||
|
border: 1px solid rgba(255,255,255,0.08);
|
||||||
|
box-shadow: 0 18px 60px rgba(0,0,0,0.55);
|
||||||
|
backdrop-filter: blur(14px);
|
||||||
|
}
|
||||||
|
#clawdis-status .title {
|
||||||
|
font: 600 20px system-ui, sans-serif;
|
||||||
|
letter-spacing: 0.2px;
|
||||||
|
color: rgba(255,255,255,0.92);
|
||||||
|
text-shadow: 0 0 22px rgba(42, 113, 255, 0.35);
|
||||||
|
}
|
||||||
|
#clawdis-status .subtitle {
|
||||||
|
margin-top: 6px;
|
||||||
|
font: 500 12px system-ui, sans-serif;
|
||||||
|
color: rgba(255,255,255,0.58);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<canvas id="clawdis-canvas"></canvas>
|
||||||
|
<div id="clawdis-status">
|
||||||
|
<div class="card">
|
||||||
|
<div class="title" id="clawdis-status-title">Ready</div>
|
||||||
|
<div class="subtitle" id="clawdis-status-subtitle">Waiting for agent</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
(() => {
|
||||||
|
const canvas = document.getElementById('clawdis-canvas');
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
const statusEl = document.getElementById('clawdis-status');
|
||||||
|
const titleEl = document.getElementById('clawdis-status-title');
|
||||||
|
const subtitleEl = document.getElementById('clawdis-status-subtitle');
|
||||||
|
|
||||||
|
function resize() {
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
const w = Math.max(1, Math.floor(window.innerWidth * dpr));
|
||||||
|
const h = Math.max(1, Math.floor(window.innerHeight * dpr));
|
||||||
|
canvas.width = w;
|
||||||
|
canvas.height = h;
|
||||||
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('resize', resize);
|
||||||
|
resize();
|
||||||
|
|
||||||
|
window.__clawdis = {
|
||||||
|
canvas,
|
||||||
|
ctx,
|
||||||
|
setStatus: (title, subtitle) => {
|
||||||
|
if (!statusEl) return;
|
||||||
|
if (!title && !subtitle) {
|
||||||
|
statusEl.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
statusEl.style.display = 'grid';
|
||||||
|
if (titleEl && typeof title === 'string') titleEl.textContent = title;
|
||||||
|
if (subtitleEl && typeof subtitle === 'string') subtitleEl.textContent = subtitle;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
""".trimIndent()
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package com.steipete.clawdis.node.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import com.steipete.clawdis.node.MainViewModel
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ChatSheet(viewModel: MainViewModel) {
|
||||||
|
val messages by viewModel.chatMessages.collectAsState()
|
||||||
|
val error by viewModel.chatError.collectAsState()
|
||||||
|
val pendingRunCount by viewModel.pendingRunCount.collectAsState()
|
||||||
|
var input by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
viewModel.loadChat("main")
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(modifier = Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
Text("Clawd Chat · session main")
|
||||||
|
|
||||||
|
if (!error.isNullOrBlank()) {
|
||||||
|
Text("Error: $error")
|
||||||
|
}
|
||||||
|
|
||||||
|
LazyColumn(modifier = Modifier.fillMaxWidth().weight(1f, fill = true)) {
|
||||||
|
items(messages) { msg ->
|
||||||
|
Text("${msg.role}: ${msg.text}")
|
||||||
|
}
|
||||||
|
if (pendingRunCount > 0) {
|
||||||
|
item { Text("assistant: …") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = input,
|
||||||
|
onValueChange = { input = it },
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
label = { Text("Message") },
|
||||||
|
)
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
val text = input
|
||||||
|
input = ""
|
||||||
|
viewModel.sendChat("main", text)
|
||||||
|
},
|
||||||
|
enabled = input.trim().isNotEmpty(),
|
||||||
|
) {
|
||||||
|
Text("Send")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package com.steipete.clawdis.node.ui
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.webkit.WebView
|
||||||
|
import android.webkit.WebViewClient
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.WindowInsets
|
||||||
|
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.only
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.safeDrawing
|
||||||
|
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||||
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.rememberModalBottomSheetState
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
|
import androidx.compose.ui.window.Popup
|
||||||
|
import androidx.compose.ui.window.PopupProperties
|
||||||
|
import com.steipete.clawdis.node.MainViewModel
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun RootScreen(viewModel: MainViewModel) {
|
||||||
|
var sheet by remember { mutableStateOf<Sheet?>(null) }
|
||||||
|
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||||
|
val safeButtonInsets = WindowInsets.safeDrawing.only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal)
|
||||||
|
|
||||||
|
Box(modifier = Modifier.fillMaxSize()) {
|
||||||
|
CanvasView(viewModel = viewModel, modifier = Modifier.fillMaxSize())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the overlay buttons above the WebView canvas (AndroidView), otherwise they may not receive touches.
|
||||||
|
Popup(alignment = Alignment.TopCenter, properties = PopupProperties(focusable = false)) {
|
||||||
|
Row(
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.windowInsetsPadding(safeButtonInsets)
|
||||||
|
.padding(12.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Button(onClick = { sheet = Sheet.Chat }) { Text("Chat") }
|
||||||
|
Button(onClick = { sheet = Sheet.Settings }) { Text("Settings") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val currentSheet = sheet
|
||||||
|
if (currentSheet != null) {
|
||||||
|
ModalBottomSheet(
|
||||||
|
onDismissRequest = { sheet = null },
|
||||||
|
sheetState = sheetState,
|
||||||
|
) {
|
||||||
|
when (currentSheet) {
|
||||||
|
Sheet.Chat -> ChatSheet(viewModel = viewModel)
|
||||||
|
Sheet.Settings -> SettingsSheet(viewModel = viewModel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum class Sheet {
|
||||||
|
Chat,
|
||||||
|
Settings,
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressLint("SetJavaScriptEnabled")
|
||||||
|
@Composable
|
||||||
|
private fun CanvasView(viewModel: MainViewModel, modifier: Modifier = Modifier) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
AndroidView(
|
||||||
|
modifier = modifier,
|
||||||
|
factory = {
|
||||||
|
WebView(context).apply {
|
||||||
|
settings.javaScriptEnabled = true
|
||||||
|
settings.domStorageEnabled = false
|
||||||
|
webViewClient = WebViewClient()
|
||||||
|
setBackgroundColor(0x00000000)
|
||||||
|
viewModel.canvas.attach(this)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
package com.steipete.clawdis.node.ui
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.PaddingValues
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.Spacer
|
||||||
|
import androidx.compose.foundation.layout.WindowInsets
|
||||||
|
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.fillMaxHeight
|
||||||
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.imePadding
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.layout.safeDrawing
|
||||||
|
import androidx.compose.foundation.layout.only
|
||||||
|
import androidx.compose.foundation.layout.windowInsetsPadding
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.OutlinedTextField
|
||||||
|
import androidx.compose.material3.Switch
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.collectAsState
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.steipete.clawdis.node.MainViewModel
|
||||||
|
import com.steipete.clawdis.node.NodeForegroundService
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun SettingsSheet(viewModel: MainViewModel) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val instanceId by viewModel.instanceId.collectAsState()
|
||||||
|
val displayName by viewModel.displayName.collectAsState()
|
||||||
|
val cameraEnabled by viewModel.cameraEnabled.collectAsState()
|
||||||
|
val wakeWords by viewModel.wakeWords.collectAsState()
|
||||||
|
val isConnected by viewModel.isConnected.collectAsState()
|
||||||
|
val manualEnabled by viewModel.manualEnabled.collectAsState()
|
||||||
|
val manualHost by viewModel.manualHost.collectAsState()
|
||||||
|
val manualPort by viewModel.manualPort.collectAsState()
|
||||||
|
val statusText by viewModel.statusText.collectAsState()
|
||||||
|
val serverName by viewModel.serverName.collectAsState()
|
||||||
|
val remoteAddress by viewModel.remoteAddress.collectAsState()
|
||||||
|
val bridges by viewModel.bridges.collectAsState()
|
||||||
|
val listState = rememberLazyListState()
|
||||||
|
|
||||||
|
val (wakeWordsText, setWakeWordsText) = remember { mutableStateOf("") }
|
||||||
|
LaunchedEffect(wakeWords) { setWakeWordsText(wakeWords.joinToString(", ")) }
|
||||||
|
|
||||||
|
val permissionLauncher =
|
||||||
|
rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { perms ->
|
||||||
|
val cameraOk = perms[Manifest.permission.CAMERA] == true
|
||||||
|
viewModel.setCameraEnabled(cameraOk)
|
||||||
|
}
|
||||||
|
|
||||||
|
LazyColumn(
|
||||||
|
state = listState,
|
||||||
|
modifier =
|
||||||
|
Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.fillMaxHeight()
|
||||||
|
.imePadding()
|
||||||
|
.windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Bottom)),
|
||||||
|
contentPadding = PaddingValues(16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||||
|
) {
|
||||||
|
item { Text("Node") }
|
||||||
|
item {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = displayName,
|
||||||
|
onValueChange = viewModel::setDisplayName,
|
||||||
|
label = { Text("Name") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
item { Text("Instance ID: $instanceId") }
|
||||||
|
|
||||||
|
item { HorizontalDivider() }
|
||||||
|
|
||||||
|
item { Text("Wake Words") }
|
||||||
|
item {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = wakeWordsText,
|
||||||
|
onValueChange = setWakeWordsText,
|
||||||
|
label = { Text("Comma-separated (global)") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
val parsed = com.steipete.clawdis.node.WakeWords.parseCommaSeparated(wakeWordsText)
|
||||||
|
viewModel.setWakeWords(parsed)
|
||||||
|
},
|
||||||
|
enabled = isConnected,
|
||||||
|
) {
|
||||||
|
Text("Save + Sync")
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(onClick = viewModel::resetWakeWordsDefaults) { Text("Reset defaults") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Text(
|
||||||
|
if (isConnected) {
|
||||||
|
"Any node can edit wake words. Changes sync via the gateway bridge."
|
||||||
|
} else {
|
||||||
|
"Connect to a gateway to sync wake words globally."
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
item { HorizontalDivider() }
|
||||||
|
|
||||||
|
item { Text("Camera") }
|
||||||
|
item {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Switch(
|
||||||
|
checked = cameraEnabled,
|
||||||
|
onCheckedChange = { enabled ->
|
||||||
|
if (!enabled) {
|
||||||
|
viewModel.setCameraEnabled(false)
|
||||||
|
return@Switch
|
||||||
|
}
|
||||||
|
|
||||||
|
val cameraOk =
|
||||||
|
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
|
||||||
|
PackageManager.PERMISSION_GRANTED
|
||||||
|
if (cameraOk) {
|
||||||
|
viewModel.setCameraEnabled(true)
|
||||||
|
} else {
|
||||||
|
permissionLauncher.launch(arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
Text(if (cameraEnabled) "Allow Camera" else "Camera Disabled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item { Text("Tip: grant Microphone permission for video clips with audio.") }
|
||||||
|
|
||||||
|
item { HorizontalDivider() }
|
||||||
|
|
||||||
|
item { Text("Bridge") }
|
||||||
|
item { Text("Status: $statusText") }
|
||||||
|
item { if (serverName != null) Text("Server: $serverName") }
|
||||||
|
item { if (remoteAddress != null) Text("Address: $remoteAddress") }
|
||||||
|
item {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
viewModel.disconnect()
|
||||||
|
NodeForegroundService.stop(context)
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Text("Disconnect")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item { HorizontalDivider() }
|
||||||
|
|
||||||
|
item { Text("Advanced") }
|
||||||
|
item {
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Switch(checked = manualEnabled, onCheckedChange = viewModel::setManualEnabled)
|
||||||
|
Text(if (manualEnabled) "Manual Bridge Enabled" else "Manual Bridge Disabled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = manualHost,
|
||||||
|
onValueChange = viewModel::setManualHost,
|
||||||
|
label = { Text("Host") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
enabled = manualEnabled,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = manualPort.toString(),
|
||||||
|
onValueChange = { v -> viewModel.setManualPort(v.toIntOrNull() ?: 0) },
|
||||||
|
label = { Text("Port") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
enabled = manualEnabled,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
NodeForegroundService.start(context)
|
||||||
|
viewModel.connectManual()
|
||||||
|
},
|
||||||
|
enabled = manualEnabled,
|
||||||
|
) {
|
||||||
|
Text("Connect (Manual)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item { HorizontalDivider() }
|
||||||
|
|
||||||
|
item { Text("Discovered Bridges") }
|
||||||
|
if (bridges.isEmpty()) {
|
||||||
|
item { Text("No bridges found yet.") }
|
||||||
|
} else {
|
||||||
|
items(items = bridges, key = { it.stableId }) { bridge ->
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(bridge.name)
|
||||||
|
Text("${bridge.host}:${bridge.port}")
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.padding(4.dp))
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
NodeForegroundService.start(context)
|
||||||
|
viewModel.connect(bridge)
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Text("Connect")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
HorizontalDivider()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
item { Spacer(modifier = Modifier.height(20.dp)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@color/ic_launcher_background" />
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@color/ic_launcher_background" />
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground" />
|
||||||
|
</adaptive-icon>
|
||||||
|
|
||||||
|
After Width: | Height: | Size: 9.4 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 4.6 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 148 KiB |
|
After Width: | Height: | Size: 54 KiB |
|
After Width: | Height: | Size: 267 KiB |
@@ -0,0 +1,4 @@
|
|||||||
|
<resources>
|
||||||
|
<color name="ic_launcher_background">#0A0A0A</color>
|
||||||
|
</resources>
|
||||||
|
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<resources>
|
||||||
|
<string name="app_name">Clawdis Node</string>
|
||||||
|
</resources>
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
<style name="Theme.ClawdisNode" parent="Theme.Material3.DayNight.NoActionBar">
|
||||||
|
<item name="android:statusBarColor">@android:color/transparent</item>
|
||||||
|
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||||
|
<item name="android:windowLightStatusBar" tools:targetApi="m">false</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
|
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package com.steipete.clawdis.node
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class WakeWordsTest {
|
||||||
|
@Test
|
||||||
|
fun parseCommaSeparatedTrimsAndDropsEmpty() {
|
||||||
|
assertEquals(listOf("clawd", "claude"), WakeWords.parseCommaSeparated(" clawd , claude, , "))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sanitizeTrimsCapsAndFallsBack() {
|
||||||
|
val defaults = listOf("clawd", "claude")
|
||||||
|
val long = "x".repeat(WakeWords.maxWordLength + 10)
|
||||||
|
val words = listOf(" ", " hello ", long)
|
||||||
|
|
||||||
|
val sanitized = WakeWords.sanitize(words, defaults)
|
||||||
|
assertEquals(2, sanitized.size)
|
||||||
|
assertEquals("hello", sanitized[0])
|
||||||
|
assertEquals("x".repeat(WakeWords.maxWordLength), sanitized[1])
|
||||||
|
|
||||||
|
assertEquals(defaults, WakeWords.sanitize(listOf(" ", ""), defaults))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sanitizeLimitsWordCount() {
|
||||||
|
val defaults = listOf("clawd")
|
||||||
|
val words = (1..(WakeWords.maxWords + 5)).map { "w$it" }
|
||||||
|
val sanitized = WakeWords.sanitize(words, defaults)
|
||||||
|
assertEquals(WakeWords.maxWords, sanitized.size)
|
||||||
|
assertEquals("w1", sanitized.first())
|
||||||
|
assertEquals("w${WakeWords.maxWords}", sanitized.last())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.steipete.clawdis.node.bridge
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class BonjourEscapesTest {
|
||||||
|
@Test
|
||||||
|
fun decodeNoop() {
|
||||||
|
assertEquals("", BonjourEscapes.decode(""))
|
||||||
|
assertEquals("hello", BonjourEscapes.decode("hello"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun decodeDecodesDecimalEscapes() {
|
||||||
|
assertEquals("Clawdis Gateway", BonjourEscapes.decode("Clawdis\\032Gateway"))
|
||||||
|
assertEquals("A B", BonjourEscapes.decode("A\\032B"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package com.steipete.clawdis.node.bridge
|
||||||
|
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.ServerSocket
|
||||||
|
|
||||||
|
class BridgePairingClientTest {
|
||||||
|
@Test
|
||||||
|
fun helloOkReturnsExistingToken() = runBlocking {
|
||||||
|
val serverSocket = ServerSocket(0)
|
||||||
|
val port = serverSocket.localPort
|
||||||
|
|
||||||
|
val server =
|
||||||
|
async(Dispatchers.IO) {
|
||||||
|
serverSocket.use { ss ->
|
||||||
|
val sock = ss.accept()
|
||||||
|
sock.use { s ->
|
||||||
|
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||||
|
|
||||||
|
val hello = reader.readLine()
|
||||||
|
assertTrue(hello.contains("\"type\":\"hello\""))
|
||||||
|
writer.write("""{"type":"hello-ok","serverName":"Test Bridge"}""")
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val client = BridgePairingClient()
|
||||||
|
val res =
|
||||||
|
client.pairAndHello(
|
||||||
|
endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port),
|
||||||
|
hello =
|
||||||
|
BridgePairingClient.Hello(
|
||||||
|
nodeId = "node-1",
|
||||||
|
displayName = "Android Node",
|
||||||
|
token = "token-123",
|
||||||
|
platform = "Android",
|
||||||
|
version = "test",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertTrue(res.ok)
|
||||||
|
assertEquals("token-123", res.token)
|
||||||
|
server.await()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun notPairedTriggersPairRequestAndReturnsToken() = runBlocking {
|
||||||
|
val serverSocket = ServerSocket(0)
|
||||||
|
val port = serverSocket.localPort
|
||||||
|
|
||||||
|
val server =
|
||||||
|
async(Dispatchers.IO) {
|
||||||
|
serverSocket.use { ss ->
|
||||||
|
val sock = ss.accept()
|
||||||
|
sock.use { s ->
|
||||||
|
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||||
|
|
||||||
|
reader.readLine() // hello
|
||||||
|
writer.write("""{"type":"error","code":"NOT_PAIRED","message":"not paired"}""")
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
|
||||||
|
val pairReq = reader.readLine()
|
||||||
|
assertTrue(pairReq.contains("\"type\":\"pair-request\""))
|
||||||
|
writer.write("""{"type":"pair-ok","token":"new-token"}""")
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val client = BridgePairingClient()
|
||||||
|
val res =
|
||||||
|
client.pairAndHello(
|
||||||
|
endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port),
|
||||||
|
hello =
|
||||||
|
BridgePairingClient.Hello(
|
||||||
|
nodeId = "node-1",
|
||||||
|
displayName = "Android Node",
|
||||||
|
token = null,
|
||||||
|
platform = "Android",
|
||||||
|
version = "test",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
assertTrue(res.ok)
|
||||||
|
assertEquals("new-token", res.token)
|
||||||
|
server.await()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
package com.steipete.clawdis.node.bridge
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.net.ServerSocket
|
||||||
|
|
||||||
|
class BridgeSessionTest {
|
||||||
|
@Test
|
||||||
|
fun requestReturnsPayloadJson() = runBlocking {
|
||||||
|
val serverSocket = ServerSocket(0)
|
||||||
|
val port = serverSocket.localPort
|
||||||
|
|
||||||
|
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
val connected = CompletableDeferred<Unit>()
|
||||||
|
|
||||||
|
val session =
|
||||||
|
BridgeSession(
|
||||||
|
scope = scope,
|
||||||
|
onConnected = { _, _ -> connected.complete(Unit) },
|
||||||
|
onDisconnected = { /* ignore */ },
|
||||||
|
onEvent = { _, _ -> /* ignore */ },
|
||||||
|
onInvoke = { BridgeSession.InvokeResult.ok(null) },
|
||||||
|
)
|
||||||
|
|
||||||
|
val server =
|
||||||
|
async(Dispatchers.IO) {
|
||||||
|
serverSocket.use { ss ->
|
||||||
|
val sock = ss.accept()
|
||||||
|
sock.use { s ->
|
||||||
|
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||||
|
|
||||||
|
val hello = reader.readLine()
|
||||||
|
assertTrue(hello.contains("\"type\":\"hello\""))
|
||||||
|
writer.write("""{"type":"hello-ok","serverName":"Test Bridge"}""")
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
|
||||||
|
val req = reader.readLine()
|
||||||
|
assertTrue(req.contains("\"type\":\"req\""))
|
||||||
|
val id = extractJsonString(req, "id")
|
||||||
|
writer.write("""{"type":"res","id":"$id","ok":true,"payloadJSON":"{\"value\":123}"}""")
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
session.connect(
|
||||||
|
endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port),
|
||||||
|
hello =
|
||||||
|
BridgeSession.Hello(
|
||||||
|
nodeId = "node-1",
|
||||||
|
displayName = "Android Node",
|
||||||
|
token = null,
|
||||||
|
platform = "Android",
|
||||||
|
version = "test",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
connected.await()
|
||||||
|
val payload = session.request(method = "health", paramsJson = null)
|
||||||
|
assertEquals("""{"value":123}""", payload)
|
||||||
|
server.await()
|
||||||
|
|
||||||
|
session.disconnect()
|
||||||
|
scope.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun requestThrowsOnErrorResponse() = runBlocking {
|
||||||
|
val serverSocket = ServerSocket(0)
|
||||||
|
val port = serverSocket.localPort
|
||||||
|
|
||||||
|
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
val connected = CompletableDeferred<Unit>()
|
||||||
|
|
||||||
|
val session =
|
||||||
|
BridgeSession(
|
||||||
|
scope = scope,
|
||||||
|
onConnected = { _, _ -> connected.complete(Unit) },
|
||||||
|
onDisconnected = { /* ignore */ },
|
||||||
|
onEvent = { _, _ -> /* ignore */ },
|
||||||
|
onInvoke = { BridgeSession.InvokeResult.ok(null) },
|
||||||
|
)
|
||||||
|
|
||||||
|
val server =
|
||||||
|
async(Dispatchers.IO) {
|
||||||
|
serverSocket.use { ss ->
|
||||||
|
val sock = ss.accept()
|
||||||
|
sock.use { s ->
|
||||||
|
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||||
|
|
||||||
|
reader.readLine() // hello
|
||||||
|
writer.write("""{"type":"hello-ok","serverName":"Test Bridge"}""")
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
|
||||||
|
val req = reader.readLine()
|
||||||
|
val id = extractJsonString(req, "id")
|
||||||
|
writer.write(
|
||||||
|
"""{"type":"res","id":"$id","ok":false,"error":{"code":"FORBIDDEN","message":"nope"}}""",
|
||||||
|
)
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
session.connect(
|
||||||
|
endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port),
|
||||||
|
hello =
|
||||||
|
BridgeSession.Hello(
|
||||||
|
nodeId = "node-1",
|
||||||
|
displayName = "Android Node",
|
||||||
|
token = null,
|
||||||
|
platform = "Android",
|
||||||
|
version = "test",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
connected.await()
|
||||||
|
|
||||||
|
try {
|
||||||
|
session.request(method = "chat.history", paramsJson = """{"sessionKey":"main"}""")
|
||||||
|
throw AssertionError("expected request() to throw")
|
||||||
|
} catch (e: IllegalStateException) {
|
||||||
|
assertTrue(e.message?.contains("FORBIDDEN: nope") == true)
|
||||||
|
}
|
||||||
|
server.await()
|
||||||
|
|
||||||
|
session.disconnect()
|
||||||
|
scope.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun invokeResReturnsErrorWhenHandlerThrows() = runBlocking {
|
||||||
|
val serverSocket = ServerSocket(0)
|
||||||
|
val port = serverSocket.localPort
|
||||||
|
|
||||||
|
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
val connected = CompletableDeferred<Unit>()
|
||||||
|
|
||||||
|
val session =
|
||||||
|
BridgeSession(
|
||||||
|
scope = scope,
|
||||||
|
onConnected = { _, _ -> connected.complete(Unit) },
|
||||||
|
onDisconnected = { /* ignore */ },
|
||||||
|
onEvent = { _, _ -> /* ignore */ },
|
||||||
|
onInvoke = { throw IllegalStateException("FOO_BAR: boom") },
|
||||||
|
)
|
||||||
|
|
||||||
|
val invokeResLine = CompletableDeferred<String>()
|
||||||
|
val server =
|
||||||
|
async(Dispatchers.IO) {
|
||||||
|
serverSocket.use { ss ->
|
||||||
|
val sock = ss.accept()
|
||||||
|
sock.use { s ->
|
||||||
|
val reader = BufferedReader(InputStreamReader(s.getInputStream(), Charsets.UTF_8))
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(s.getOutputStream(), Charsets.UTF_8))
|
||||||
|
|
||||||
|
reader.readLine() // hello
|
||||||
|
writer.write("""{"type":"hello-ok","serverName":"Test Bridge"}""")
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
|
||||||
|
// Ask the node to invoke something; handler will throw.
|
||||||
|
writer.write("""{"type":"invoke","id":"i1","command":"screen.snapshot","paramsJSON":null}""")
|
||||||
|
writer.write("\n")
|
||||||
|
writer.flush()
|
||||||
|
|
||||||
|
val res = reader.readLine()
|
||||||
|
invokeResLine.complete(res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
session.connect(
|
||||||
|
endpoint = BridgeEndpoint.manual(host = "127.0.0.1", port = port),
|
||||||
|
hello =
|
||||||
|
BridgeSession.Hello(
|
||||||
|
nodeId = "node-1",
|
||||||
|
displayName = "Android Node",
|
||||||
|
token = null,
|
||||||
|
platform = "Android",
|
||||||
|
version = "test",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
connected.await()
|
||||||
|
|
||||||
|
// Give the reader loop time to process.
|
||||||
|
val line = invokeResLine.await()
|
||||||
|
assertTrue(line.contains("\"type\":\"invoke-res\""))
|
||||||
|
assertTrue(line.contains("\"ok\":false"))
|
||||||
|
assertTrue(line.contains("\"code\":\"FOO_BAR\""))
|
||||||
|
assertTrue(line.contains("\"message\":\"boom\""))
|
||||||
|
server.await()
|
||||||
|
|
||||||
|
session.disconnect()
|
||||||
|
scope.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractJsonString(raw: String, key: String): String {
|
||||||
|
val needle = "\"$key\":\""
|
||||||
|
val start = raw.indexOf(needle)
|
||||||
|
if (start < 0) throw IllegalArgumentException("missing key $key in $raw")
|
||||||
|
val from = start + needle.length
|
||||||
|
val end = raw.indexOf('"', from)
|
||||||
|
if (end < 0) throw IllegalArgumentException("unterminated string for $key in $raw")
|
||||||
|
return raw.substring(from, end)
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application") version "8.13.2" apply false
|
||||||
|
id("org.jetbrains.kotlin.android") version "2.2.21" apply false
|
||||||
|
id("org.jetbrains.kotlin.plugin.compose") version "2.2.21" apply false
|
||||||
|
id("org.jetbrains.kotlin.plugin.serialization") version "2.2.21" apply false
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
|
||||||
|
android.useAndroidX=true
|
||||||
|
android.nonTransitiveRClass=true
|
||||||
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
org.gradle.wrapper.GradleWrapperMain \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = "ClawdisNodeAndroid"
|
||||||
|
include(":app")
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# ClawdisNode (iOS)
|
# Clawdis (iOS)
|
||||||
|
|
||||||
Internal-only SwiftUI app scaffold.
|
Internal-only SwiftUI app scaffold.
|
||||||
|
|
||||||
@@ -11,8 +11,18 @@ brew install swiftformat swiftlint
|
|||||||
```bash
|
```bash
|
||||||
cd apps/ios
|
cd apps/ios
|
||||||
xcodegen generate
|
xcodegen generate
|
||||||
open ClawdisNode.xcodeproj
|
open Clawdis.xcodeproj
|
||||||
```
|
```
|
||||||
|
|
||||||
## Shared packages
|
## Shared packages
|
||||||
- `../shared/ClawdisKit` — shared types/constants used by iOS (and later macOS bridge + gateway routing).
|
- `../shared/ClawdisKit` — shared types/constants used by iOS (and later macOS bridge + gateway routing).
|
||||||
|
|
||||||
|
## fastlane
|
||||||
|
```bash
|
||||||
|
brew install fastlane
|
||||||
|
|
||||||
|
cd apps/ios
|
||||||
|
fastlane lanes
|
||||||
|
```
|
||||||
|
|
||||||
|
See `apps/ios/fastlane/SETUP.md` for App Store Connect auth + upload lanes.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"images" : [
|
||||||
|
{ "filename" : "icon-20@1x.png", "idiom" : "ipad", "scale" : "1x", "size" : "20x20" },
|
||||||
|
{ "filename" : "icon-20@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "20x20" },
|
||||||
|
{ "filename" : "icon-20@2x.png", "idiom" : "iphone","scale" : "2x", "size" : "20x20" },
|
||||||
|
{ "filename" : "icon-20@3x.png", "idiom" : "iphone","scale" : "3x", "size" : "20x20" },
|
||||||
|
|
||||||
|
{ "filename" : "icon-29@1x.png", "idiom" : "ipad", "scale" : "1x", "size" : "29x29" },
|
||||||
|
{ "filename" : "icon-29@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "29x29" },
|
||||||
|
{ "filename" : "icon-29@2x.png", "idiom" : "iphone","scale" : "2x", "size" : "29x29" },
|
||||||
|
{ "filename" : "icon-29@3x.png", "idiom" : "iphone","scale" : "3x", "size" : "29x29" },
|
||||||
|
|
||||||
|
{ "filename" : "icon-40@1x.png", "idiom" : "ipad", "scale" : "1x", "size" : "40x40" },
|
||||||
|
{ "filename" : "icon-40@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "40x40" },
|
||||||
|
{ "filename" : "icon-40@2x.png", "idiom" : "iphone","scale" : "2x", "size" : "40x40" },
|
||||||
|
{ "filename" : "icon-40@3x.png", "idiom" : "iphone","scale" : "3x", "size" : "40x40" },
|
||||||
|
|
||||||
|
{ "filename" : "icon-60@2x.png", "idiom" : "iphone","scale" : "2x", "size" : "60x60" },
|
||||||
|
{ "filename" : "icon-60@3x.png", "idiom" : "iphone","scale" : "3x", "size" : "60x60" },
|
||||||
|
|
||||||
|
{ "filename" : "icon-76@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "76x76" },
|
||||||
|
|
||||||
|
{ "filename" : "icon-83.5@2x.png", "idiom" : "ipad", "scale" : "2x", "size" : "83.5x83.5" },
|
||||||
|
|
||||||
|
{ "filename" : "icon-1024.png", "idiom" : "ios-marketing", "scale" : "1x", "size" : "1024x1024" }
|
||||||
|
],
|
||||||
|
"info" : {
|
||||||
|
"author" : "xcode",
|
||||||
|
"version" : 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 1.4 MiB |
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 38 KiB |
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"info" : {
|
||||||
|
"author" : "xcode",
|
||||||
|
"version" : 1
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,76 +5,84 @@ import Network
|
|||||||
actor BridgeClient {
|
actor BridgeClient {
|
||||||
private let encoder = JSONEncoder()
|
private let encoder = JSONEncoder()
|
||||||
private let decoder = JSONDecoder()
|
private let decoder = JSONDecoder()
|
||||||
|
private var lineBuffer = Data()
|
||||||
|
|
||||||
func pairAndHello(
|
func pairAndHello(
|
||||||
endpoint: NWEndpoint,
|
endpoint: NWEndpoint,
|
||||||
nodeId: String,
|
hello: BridgeHello,
|
||||||
displayName: String?,
|
onStatus: (@Sendable (String) -> Void)? = nil) async throws -> String
|
||||||
platform: String,
|
|
||||||
version: String,
|
|
||||||
existingToken: String?) async throws -> String
|
|
||||||
{
|
{
|
||||||
|
self.lineBuffer = Data()
|
||||||
let connection = NWConnection(to: endpoint, using: .tcp)
|
let connection = NWConnection(to: endpoint, using: .tcp)
|
||||||
let queue = DispatchQueue(label: "com.steipete.clawdis.ios.bridge-client")
|
let queue = DispatchQueue(label: "com.steipete.clawdis.ios.bridge-client")
|
||||||
connection.start(queue: queue)
|
defer { connection.cancel() }
|
||||||
|
try await self.withTimeout(seconds: 8, purpose: "connect") {
|
||||||
|
try await self.startAndWaitForReady(connection, queue: queue)
|
||||||
|
}
|
||||||
|
|
||||||
let token = existingToken
|
onStatus?("Authenticating…")
|
||||||
try await self.send(
|
try await self.send(hello, over: connection)
|
||||||
BridgeHello(
|
|
||||||
nodeId: nodeId,
|
|
||||||
displayName: displayName,
|
|
||||||
token: token,
|
|
||||||
platform: platform,
|
|
||||||
version: version),
|
|
||||||
over: connection)
|
|
||||||
|
|
||||||
if let line = try await self.receiveLine(over: connection),
|
let first = try await self.withTimeout(seconds: 10, purpose: "hello") { () -> ReceivedFrame in
|
||||||
let data = line.data(using: .utf8),
|
guard let frame = try await self.receiveFrame(over: connection) else {
|
||||||
let base = try? self.decoder.decode(BridgeBaseFrame.self, from: data)
|
throw NSError(domain: "Bridge", code: 0, userInfo: [
|
||||||
{
|
NSLocalizedDescriptionKey: "Bridge closed connection during hello",
|
||||||
if base.type == "hello-ok" {
|
])
|
||||||
connection.cancel()
|
|
||||||
return existingToken ?? ""
|
|
||||||
}
|
}
|
||||||
if base.type == "error" {
|
return frame
|
||||||
let err = try self.decoder.decode(BridgeErrorFrame.self, from: data)
|
}
|
||||||
if err.code == "NOT_PAIRED" || err.code == "UNAUTHORIZED" {
|
|
||||||
try await self.send(
|
|
||||||
BridgePairRequest(
|
|
||||||
nodeId: nodeId,
|
|
||||||
displayName: displayName,
|
|
||||||
platform: platform,
|
|
||||||
version: version),
|
|
||||||
over: connection)
|
|
||||||
|
|
||||||
while let next = try await self.receiveLine(over: connection) {
|
switch first.base.type {
|
||||||
guard let nextData = next.data(using: .utf8) else { continue }
|
case "hello-ok":
|
||||||
let nextBase = try self.decoder.decode(BridgeBaseFrame.self, from: nextData)
|
// We only return a token if we have one; callers should treat empty as "no token yet".
|
||||||
if nextBase.type == "pair-ok" {
|
return hello.token ?? ""
|
||||||
let ok = try self.decoder.decode(BridgePairOk.self, from: nextData)
|
|
||||||
connection.cancel()
|
case "error":
|
||||||
return ok.token
|
let err = try self.decoder.decode(BridgeErrorFrame.self, from: first.data)
|
||||||
}
|
if err.code != "NOT_PAIRED", err.code != "UNAUTHORIZED" {
|
||||||
if nextBase.type == "error" {
|
|
||||||
let e = try self.decoder.decode(BridgeErrorFrame.self, from: nextData)
|
|
||||||
connection.cancel()
|
|
||||||
throw NSError(domain: "Bridge", code: 2, userInfo: [
|
|
||||||
NSLocalizedDescriptionKey: "\(e.code): \(e.message)",
|
|
||||||
])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
connection.cancel()
|
|
||||||
throw NSError(domain: "Bridge", code: 1, userInfo: [
|
throw NSError(domain: "Bridge", code: 1, userInfo: [
|
||||||
NSLocalizedDescriptionKey: "\(err.code): \(err.message)",
|
NSLocalizedDescriptionKey: "\(err.code): \(err.message)",
|
||||||
])
|
])
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
connection.cancel()
|
onStatus?("Requesting approval…")
|
||||||
throw NSError(domain: "Bridge", code: 0, userInfo: [
|
try await self.send(
|
||||||
NSLocalizedDescriptionKey: "Unexpected bridge response",
|
BridgePairRequest(
|
||||||
])
|
nodeId: hello.nodeId,
|
||||||
|
displayName: hello.displayName,
|
||||||
|
platform: hello.platform,
|
||||||
|
version: hello.version,
|
||||||
|
deviceFamily: hello.deviceFamily,
|
||||||
|
modelIdentifier: hello.modelIdentifier),
|
||||||
|
over: connection)
|
||||||
|
|
||||||
|
onStatus?("Waiting for approval…")
|
||||||
|
let ok = try await self.withTimeout(seconds: 60, purpose: "pairing approval") {
|
||||||
|
while let next = try await self.receiveFrame(over: connection) {
|
||||||
|
switch next.base.type {
|
||||||
|
case "pair-ok":
|
||||||
|
return try self.decoder.decode(BridgePairOk.self, from: next.data)
|
||||||
|
case "error":
|
||||||
|
let e = try self.decoder.decode(BridgeErrorFrame.self, from: next.data)
|
||||||
|
throw NSError(domain: "Bridge", code: 2, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "\(e.code): \(e.message)",
|
||||||
|
])
|
||||||
|
default:
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw NSError(domain: "Bridge", code: 3, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "Pairing failed: bridge closed connection",
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
return ok.token
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw NSError(domain: "Bridge", code: 0, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "Unexpected bridge response",
|
||||||
|
])
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func send(_ obj: some Encodable, over connection: NWConnection) async throws {
|
private func send(_ obj: some Encodable, over connection: NWConnection) async throws {
|
||||||
@@ -89,18 +97,17 @@ actor BridgeClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func receiveLine(over connection: NWConnection) async throws -> String? {
|
private struct ReceivedFrame {
|
||||||
var buffer = Data()
|
var base: BridgeBaseFrame
|
||||||
while true {
|
var data: Data
|
||||||
if let idx = buffer.firstIndex(of: 0x0A) {
|
}
|
||||||
let lineData = buffer.prefix(upTo: idx)
|
|
||||||
return String(data: lineData, encoding: .utf8)
|
|
||||||
}
|
|
||||||
|
|
||||||
let chunk = try await self.receiveChunk(over: connection)
|
private func receiveFrame(over connection: NWConnection) async throws -> ReceivedFrame? {
|
||||||
if chunk.isEmpty { return nil }
|
guard let lineData = try await self.receiveLineData(over: connection) else {
|
||||||
buffer.append(chunk)
|
return nil
|
||||||
}
|
}
|
||||||
|
let base = try self.decoder.decode(BridgeBaseFrame.self, from: lineData)
|
||||||
|
return ReceivedFrame(base: base, data: lineData)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func receiveChunk(over connection: NWConnection) async throws -> Data {
|
private func receiveChunk(over connection: NWConnection) async throws -> Data {
|
||||||
@@ -118,4 +125,88 @@ actor BridgeClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func receiveLineData(over connection: NWConnection) async throws -> Data? {
|
||||||
|
while true {
|
||||||
|
if let idx = self.lineBuffer.firstIndex(of: 0x0A) {
|
||||||
|
let line = self.lineBuffer.prefix(upTo: idx)
|
||||||
|
self.lineBuffer.removeSubrange(...idx)
|
||||||
|
return Data(line)
|
||||||
|
}
|
||||||
|
|
||||||
|
let chunk = try await self.receiveChunk(over: connection)
|
||||||
|
if chunk.isEmpty { return nil }
|
||||||
|
self.lineBuffer.append(chunk)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct TimeoutError: LocalizedError, Sendable {
|
||||||
|
var purpose: String
|
||||||
|
var seconds: Int
|
||||||
|
|
||||||
|
var errorDescription: String? {
|
||||||
|
if self.purpose == "pairing approval" {
|
||||||
|
return
|
||||||
|
"Timed out waiting for approval (\(self.seconds)s). " +
|
||||||
|
"Approve the node on your gateway and try again."
|
||||||
|
}
|
||||||
|
return "Timed out during \(self.purpose) (\(self.seconds)s)."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func withTimeout<T: Sendable>(
|
||||||
|
seconds: Int,
|
||||||
|
purpose: String,
|
||||||
|
_ op: @escaping @Sendable () async throws -> T) async throws -> T
|
||||||
|
{
|
||||||
|
try await withThrowingTaskGroup(of: T.self) { group in
|
||||||
|
group.addTask {
|
||||||
|
try await op()
|
||||||
|
}
|
||||||
|
group.addTask {
|
||||||
|
try await Task.sleep(nanoseconds: UInt64(seconds) * 1_000_000_000)
|
||||||
|
throw TimeoutError(purpose: purpose, seconds: seconds)
|
||||||
|
}
|
||||||
|
let result = try await group.next()!
|
||||||
|
group.cancelAll()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startAndWaitForReady(_ connection: NWConnection, queue: DispatchQueue) async throws {
|
||||||
|
try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation<Void, Error>) in
|
||||||
|
final class ResumeFlag: @unchecked Sendable {
|
||||||
|
private let lock = NSLock()
|
||||||
|
private var value = false
|
||||||
|
|
||||||
|
func trySet() -> Bool {
|
||||||
|
self.lock.lock()
|
||||||
|
defer { self.lock.unlock() }
|
||||||
|
if self.value { return false }
|
||||||
|
self.value = true
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let didResume = ResumeFlag()
|
||||||
|
connection.stateUpdateHandler = { state in
|
||||||
|
switch state {
|
||||||
|
case .ready:
|
||||||
|
if didResume.trySet() { cont.resume(returning: ()) }
|
||||||
|
case let .failed(err):
|
||||||
|
if didResume.trySet() { cont.resume(throwing: err) }
|
||||||
|
case let .waiting(err):
|
||||||
|
if didResume.trySet() { cont.resume(throwing: err) }
|
||||||
|
case .cancelled:
|
||||||
|
if didResume.trySet() {
|
||||||
|
cont.resume(throwing: NSError(domain: "Bridge", code: 50, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "Connection cancelled",
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
connection.start(queue: queue)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import ClawdisKit
|
||||||
|
import Foundation
|
||||||
|
import Network
|
||||||
|
import Observation
|
||||||
|
import SwiftUI
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Observable
|
||||||
|
final class BridgeConnectionController {
|
||||||
|
private(set) var bridges: [BridgeDiscoveryModel.DiscoveredBridge] = []
|
||||||
|
private(set) var discoveryStatusText: String = "Idle"
|
||||||
|
private(set) var discoveryDebugLog: [BridgeDiscoveryModel.DebugLogEntry] = []
|
||||||
|
|
||||||
|
private let discovery = BridgeDiscoveryModel()
|
||||||
|
private weak var appModel: NodeAppModel?
|
||||||
|
private var didAutoConnect = false
|
||||||
|
private var seenStableIDs = Set<String>()
|
||||||
|
|
||||||
|
init(appModel: NodeAppModel, startDiscovery: Bool = true) {
|
||||||
|
self.appModel = appModel
|
||||||
|
|
||||||
|
BridgeSettingsStore.bootstrapPersistence()
|
||||||
|
let defaults = UserDefaults.standard
|
||||||
|
self.discovery.setDebugLoggingEnabled(defaults.bool(forKey: "bridge.discovery.debugLogs"))
|
||||||
|
|
||||||
|
self.updateFromDiscovery()
|
||||||
|
self.observeDiscovery()
|
||||||
|
|
||||||
|
if startDiscovery {
|
||||||
|
self.discovery.start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setDiscoveryDebugLoggingEnabled(_ enabled: Bool) {
|
||||||
|
self.discovery.setDebugLoggingEnabled(enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
func setScenePhase(_ phase: ScenePhase) {
|
||||||
|
switch phase {
|
||||||
|
case .background:
|
||||||
|
self.discovery.stop()
|
||||||
|
case .active, .inactive:
|
||||||
|
self.discovery.start()
|
||||||
|
@unknown default:
|
||||||
|
self.discovery.start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func updateFromDiscovery() {
|
||||||
|
let newBridges = self.discovery.bridges
|
||||||
|
self.bridges = newBridges
|
||||||
|
self.discoveryStatusText = self.discovery.statusText
|
||||||
|
self.discoveryDebugLog = self.discovery.debugLog
|
||||||
|
self.updateLastDiscoveredBridge(from: newBridges)
|
||||||
|
self.maybeAutoConnect()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func observeDiscovery() {
|
||||||
|
withObservationTracking {
|
||||||
|
_ = self.discovery.bridges
|
||||||
|
_ = self.discovery.statusText
|
||||||
|
_ = self.discovery.debugLog
|
||||||
|
} onChange: { [weak self] in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard let self else { return }
|
||||||
|
self.updateFromDiscovery()
|
||||||
|
self.observeDiscovery()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func maybeAutoConnect() {
|
||||||
|
guard !self.didAutoConnect else { return }
|
||||||
|
guard let appModel = self.appModel else { return }
|
||||||
|
guard appModel.bridgeServerName == nil else { return }
|
||||||
|
|
||||||
|
let defaults = UserDefaults.standard
|
||||||
|
let manualEnabled = defaults.bool(forKey: "bridge.manual.enabled")
|
||||||
|
|
||||||
|
let instanceId = defaults.string(forKey: "node.instanceId")?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||||
|
guard !instanceId.isEmpty else { return }
|
||||||
|
|
||||||
|
let token = KeychainStore.loadString(
|
||||||
|
service: "com.steipete.clawdis.bridge",
|
||||||
|
account: "bridge-token.\(instanceId)")?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||||
|
guard !token.isEmpty else { return }
|
||||||
|
|
||||||
|
if manualEnabled {
|
||||||
|
let manualHost = defaults.string(forKey: "bridge.manual.host")?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||||
|
guard !manualHost.isEmpty else { return }
|
||||||
|
|
||||||
|
let manualPort = defaults.integer(forKey: "bridge.manual.port")
|
||||||
|
let resolvedPort = manualPort > 0 ? manualPort : 18790
|
||||||
|
guard let port = NWEndpoint.Port(rawValue: UInt16(resolvedPort)) else { return }
|
||||||
|
|
||||||
|
self.didAutoConnect = true
|
||||||
|
appModel.connectToBridge(
|
||||||
|
endpoint: .hostPort(host: NWEndpoint.Host(manualHost), port: port),
|
||||||
|
hello: self.makeHello(token: token))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let targetStableID = defaults.string(forKey: "bridge.lastDiscoveredStableID")?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||||
|
guard !targetStableID.isEmpty else { return }
|
||||||
|
|
||||||
|
guard let target = self.bridges.first(where: { $0.stableID == targetStableID }) else { return }
|
||||||
|
|
||||||
|
self.didAutoConnect = true
|
||||||
|
appModel.connectToBridge(endpoint: target.endpoint, hello: self.makeHello(token: token))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func updateLastDiscoveredBridge(from bridges: [BridgeDiscoveryModel.DiscoveredBridge]) {
|
||||||
|
let newlyDiscovered = bridges.filter { self.seenStableIDs.insert($0.stableID).inserted }
|
||||||
|
guard let last = newlyDiscovered.last else { return }
|
||||||
|
|
||||||
|
UserDefaults.standard.set(last.stableID, forKey: "bridge.lastDiscoveredStableID")
|
||||||
|
BridgeSettingsStore.saveLastDiscoveredBridgeStableID(last.stableID)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeHello(token: String) -> BridgeHello {
|
||||||
|
let defaults = UserDefaults.standard
|
||||||
|
let nodeId = defaults.string(forKey: "node.instanceId") ?? "ios-node"
|
||||||
|
let displayName = defaults.string(forKey: "node.displayName") ?? "iOS Node"
|
||||||
|
|
||||||
|
return BridgeHello(
|
||||||
|
nodeId: nodeId,
|
||||||
|
displayName: displayName,
|
||||||
|
token: token,
|
||||||
|
platform: self.platformString(),
|
||||||
|
version: self.appVersion(),
|
||||||
|
deviceFamily: self.deviceFamily(),
|
||||||
|
modelIdentifier: self.modelIdentifier())
|
||||||
|
}
|
||||||
|
|
||||||
|
private func platformString() -> String {
|
||||||
|
let v = ProcessInfo.processInfo.operatingSystemVersion
|
||||||
|
let name: String
|
||||||
|
switch UIDevice.current.userInterfaceIdiom {
|
||||||
|
case .pad:
|
||||||
|
name = "iPadOS"
|
||||||
|
case .phone:
|
||||||
|
name = "iOS"
|
||||||
|
default:
|
||||||
|
name = "iOS"
|
||||||
|
}
|
||||||
|
return "\(name) \(v.majorVersion).\(v.minorVersion).\(v.patchVersion)"
|
||||||
|
}
|
||||||
|
|
||||||
|
private func deviceFamily() -> String {
|
||||||
|
switch UIDevice.current.userInterfaceIdiom {
|
||||||
|
case .pad:
|
||||||
|
return "iPad"
|
||||||
|
case .phone:
|
||||||
|
return "iPhone"
|
||||||
|
default:
|
||||||
|
return "iOS"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func modelIdentifier() -> String {
|
||||||
|
var systemInfo = utsname()
|
||||||
|
uname(&systemInfo)
|
||||||
|
let machine = withUnsafeBytes(of: &systemInfo.machine) { ptr in
|
||||||
|
String(decoding: ptr.prefix { $0 != 0 }, as: UTF8.self)
|
||||||
|
}
|
||||||
|
return machine.isEmpty ? "unknown" : machine
|
||||||
|
}
|
||||||
|
|
||||||
|
private func appVersion() -> String {
|
||||||
|
Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "dev"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import SwiftUI
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
struct BridgeDiscoveryDebugLogView: View {
|
||||||
|
@Environment(BridgeConnectionController.self) private var bridgeController
|
||||||
|
@AppStorage("bridge.discovery.debugLogs") private var debugLogsEnabled: Bool = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
List {
|
||||||
|
if !self.debugLogsEnabled {
|
||||||
|
Text("Enable “Discovery Debug Logs” to start collecting events.")
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.bridgeController.discoveryDebugLog.isEmpty {
|
||||||
|
Text("No log entries yet.")
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
} else {
|
||||||
|
ForEach(self.bridgeController.discoveryDebugLog) { entry in
|
||||||
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
|
Text(Self.formatTime(entry.ts))
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
Text(entry.message)
|
||||||
|
.font(.callout)
|
||||||
|
.textSelection(.enabled)
|
||||||
|
}
|
||||||
|
.padding(.vertical, 4)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.navigationTitle("Discovery Logs")
|
||||||
|
.toolbar {
|
||||||
|
ToolbarItem(placement: .topBarTrailing) {
|
||||||
|
Button("Copy") {
|
||||||
|
UIPasteboard.general.string = self.formattedLog()
|
||||||
|
}
|
||||||
|
.disabled(self.bridgeController.discoveryDebugLog.isEmpty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func formattedLog() -> String {
|
||||||
|
self.bridgeController.discoveryDebugLog
|
||||||
|
.map { "\(Self.formatISO($0.ts)) \($0.message)" }
|
||||||
|
.joined(separator: "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
private static let timeFormatter: DateFormatter = {
|
||||||
|
let formatter = DateFormatter()
|
||||||
|
formatter.dateFormat = "HH:mm:ss"
|
||||||
|
return formatter
|
||||||
|
}()
|
||||||
|
|
||||||
|
private static let isoFormatter: ISO8601DateFormatter = {
|
||||||
|
let formatter = ISO8601DateFormatter()
|
||||||
|
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
||||||
|
return formatter
|
||||||
|
}()
|
||||||
|
|
||||||
|
private static func formatTime(_ date: Date) -> String {
|
||||||
|
self.timeFormatter.string(from: date)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func formatISO(_ date: Date) -> String {
|
||||||
|
self.isoFormatter.string(from: date)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,108 +1,194 @@
|
|||||||
import ClawdisKit
|
import ClawdisKit
|
||||||
import Foundation
|
import Foundation
|
||||||
import Network
|
import Network
|
||||||
|
import Observation
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
final class BridgeDiscoveryModel: ObservableObject {
|
@Observable
|
||||||
|
final class BridgeDiscoveryModel {
|
||||||
|
struct DebugLogEntry: Identifiable, Equatable {
|
||||||
|
var id = UUID()
|
||||||
|
var ts: Date
|
||||||
|
var message: String
|
||||||
|
}
|
||||||
|
|
||||||
struct DiscoveredBridge: Identifiable, Equatable {
|
struct DiscoveredBridge: Identifiable, Equatable {
|
||||||
var id: String { self.debugID }
|
var id: String { self.stableID }
|
||||||
var name: String
|
var name: String
|
||||||
var endpoint: NWEndpoint
|
var endpoint: NWEndpoint
|
||||||
|
var stableID: String
|
||||||
var debugID: String
|
var debugID: String
|
||||||
}
|
}
|
||||||
|
|
||||||
@Published var bridges: [DiscoveredBridge] = []
|
var bridges: [DiscoveredBridge] = []
|
||||||
@Published var statusText: String = "Idle"
|
var statusText: String = "Idle"
|
||||||
|
private(set) var debugLog: [DebugLogEntry] = []
|
||||||
|
|
||||||
private var browser: NWBrowser?
|
private var browsers: [String: NWBrowser] = [:]
|
||||||
|
private var bridgesByDomain: [String: [DiscoveredBridge]] = [:]
|
||||||
|
private var statesByDomain: [String: NWBrowser.State] = [:]
|
||||||
|
private var debugLoggingEnabled = false
|
||||||
|
private var lastStableIDs = Set<String>()
|
||||||
|
|
||||||
|
func setDebugLoggingEnabled(_ enabled: Bool) {
|
||||||
|
let wasEnabled = self.debugLoggingEnabled
|
||||||
|
self.debugLoggingEnabled = enabled
|
||||||
|
if !enabled {
|
||||||
|
self.debugLog = []
|
||||||
|
} else if !wasEnabled {
|
||||||
|
self.appendDebugLog("debug logging enabled")
|
||||||
|
self.appendDebugLog("snapshot: status=\(self.statusText) bridges=\(self.bridges.count)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func start() {
|
func start() {
|
||||||
if self.browser != nil { return }
|
if !self.browsers.isEmpty { return }
|
||||||
let params = NWParameters.tcp
|
self.appendDebugLog("start()")
|
||||||
params.includePeerToPeer = true
|
|
||||||
let browser = NWBrowser(
|
|
||||||
for: .bonjour(type: ClawdisBonjour.bridgeServiceType, domain: ClawdisBonjour.bridgeServiceDomain),
|
|
||||||
using: params)
|
|
||||||
|
|
||||||
browser.stateUpdateHandler = { [weak self] state in
|
for domain in ClawdisBonjour.bridgeServiceDomains {
|
||||||
Task { @MainActor in
|
let params = NWParameters.tcp
|
||||||
guard let self else { return }
|
params.includePeerToPeer = true
|
||||||
switch state {
|
let browser = NWBrowser(
|
||||||
case .setup:
|
for: .bonjour(type: ClawdisBonjour.bridgeServiceType, domain: domain),
|
||||||
self.statusText = "Setup"
|
using: params)
|
||||||
case .ready:
|
|
||||||
self.statusText = "Searching…"
|
browser.stateUpdateHandler = { [weak self] state in
|
||||||
case let .failed(err):
|
Task { @MainActor in
|
||||||
self.statusText = "Failed: \(err)"
|
guard let self else { return }
|
||||||
case .cancelled:
|
self.statesByDomain[domain] = state
|
||||||
self.statusText = "Stopped"
|
self.updateStatusText()
|
||||||
case let .waiting(err):
|
self.appendDebugLog("state[\(domain)]: \(Self.prettyState(state))")
|
||||||
self.statusText = "Waiting: \(err)"
|
|
||||||
@unknown default:
|
|
||||||
self.statusText = "Unknown"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
browser.browseResultsChangedHandler = { [weak self] results, _ in
|
browser.browseResultsChangedHandler = { [weak self] results, _ in
|
||||||
Task { @MainActor in
|
Task { @MainActor in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
self.bridges = results.compactMap { result -> DiscoveredBridge? in
|
self.bridgesByDomain[domain] = results.compactMap { result -> DiscoveredBridge? in
|
||||||
switch result.endpoint {
|
switch result.endpoint {
|
||||||
case let .service(name, _, _, _):
|
case let .service(name, _, _, _):
|
||||||
return DiscoveredBridge(
|
let decodedName = BonjourEscapes.decode(name)
|
||||||
name: name,
|
let advertisedName = result.endpoint.txtRecord?.dictionary["displayName"]
|
||||||
endpoint: result.endpoint,
|
let prettyAdvertised = advertisedName
|
||||||
debugID: Self.prettyEndpointDebugID(result.endpoint))
|
.map(Self.prettifyInstanceName)
|
||||||
default:
|
.flatMap { $0.isEmpty ? nil : $0 }
|
||||||
return nil
|
let prettyName = prettyAdvertised ?? Self.prettifyInstanceName(decodedName)
|
||||||
|
return DiscoveredBridge(
|
||||||
|
name: prettyName,
|
||||||
|
endpoint: result.endpoint,
|
||||||
|
stableID: BridgeEndpointID.stableID(result.endpoint),
|
||||||
|
debugID: BridgeEndpointID.prettyDescription(result.endpoint))
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
|
||||||
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.browser = browser
|
self.recomputeBridges()
|
||||||
browser.start(queue: DispatchQueue(label: "com.steipete.clawdis.ios.bridge-discovery"))
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.browsers[domain] = browser
|
||||||
|
browser.start(queue: DispatchQueue(label: "com.steipete.clawdis.ios.bridge-discovery.\(domain)"))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func stop() {
|
func stop() {
|
||||||
self.browser?.cancel()
|
self.appendDebugLog("stop()")
|
||||||
self.browser = nil
|
for browser in self.browsers.values {
|
||||||
|
browser.cancel()
|
||||||
|
}
|
||||||
|
self.browsers = [:]
|
||||||
|
self.bridgesByDomain = [:]
|
||||||
|
self.statesByDomain = [:]
|
||||||
self.bridges = []
|
self.bridges = []
|
||||||
self.statusText = "Stopped"
|
self.statusText = "Stopped"
|
||||||
}
|
}
|
||||||
|
|
||||||
private static func prettyEndpointDebugID(_ endpoint: NWEndpoint) -> String {
|
private func recomputeBridges() {
|
||||||
self.decodeBonjourEscapes(String(describing: endpoint))
|
let next = self.bridgesByDomain.values
|
||||||
|
.flatMap(\.self)
|
||||||
|
.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
|
||||||
|
|
||||||
|
let nextIDs = Set(next.map(\.stableID))
|
||||||
|
let added = nextIDs.subtracting(self.lastStableIDs)
|
||||||
|
let removed = self.lastStableIDs.subtracting(nextIDs)
|
||||||
|
if !added.isEmpty || !removed.isEmpty {
|
||||||
|
self.appendDebugLog("results: total=\(next.count) added=\(added.count) removed=\(removed.count)")
|
||||||
|
}
|
||||||
|
self.lastStableIDs = nextIDs
|
||||||
|
self.bridges = next
|
||||||
}
|
}
|
||||||
|
|
||||||
private static func decodeBonjourEscapes(_ input: String) -> String {
|
private func updateStatusText() {
|
||||||
// mDNS / DNS-SD commonly escapes spaces as `\\032` (decimal byte value 32). Make this human-friendly for UI.
|
let states = Array(self.statesByDomain.values)
|
||||||
var out = ""
|
if states.isEmpty {
|
||||||
var i = input.startIndex
|
self.statusText = self.browsers.isEmpty ? "Idle" : "Setup"
|
||||||
while i < input.endIndex {
|
return
|
||||||
if input[i] == "\\",
|
|
||||||
let d0 = input.index(i, offsetBy: 1, limitedBy: input.index(before: input.endIndex)),
|
|
||||||
let d1 = input.index(i, offsetBy: 2, limitedBy: input.index(before: input.endIndex)),
|
|
||||||
let d2 = input.index(i, offsetBy: 3, limitedBy: input.index(before: input.endIndex)),
|
|
||||||
input[d0].isNumber,
|
|
||||||
input[d1].isNumber,
|
|
||||||
input[d2].isNumber
|
|
||||||
{
|
|
||||||
let digits = String(input[d0...d2])
|
|
||||||
if let value = Int(digits),
|
|
||||||
let scalar = UnicodeScalar(value)
|
|
||||||
{
|
|
||||||
out.append(Character(scalar))
|
|
||||||
i = input.index(i, offsetBy: 4)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
out.append(input[i])
|
|
||||||
i = input.index(after: i)
|
|
||||||
}
|
}
|
||||||
return out
|
|
||||||
|
if let failed = states.first(where: { state in
|
||||||
|
if case .failed = state { return true }
|
||||||
|
return false
|
||||||
|
}) {
|
||||||
|
if case let .failed(err) = failed {
|
||||||
|
self.statusText = "Failed: \(err)"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let waiting = states.first(where: { state in
|
||||||
|
if case .waiting = state { return true }
|
||||||
|
return false
|
||||||
|
}) {
|
||||||
|
if case let .waiting(err) = waiting {
|
||||||
|
self.statusText = "Waiting: \(err)"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if states.contains(where: { if case .ready = $0 { true } else { false } }) {
|
||||||
|
self.statusText = "Searching…"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if states.contains(where: { if case .setup = $0 { true } else { false } }) {
|
||||||
|
self.statusText = "Setup"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
self.statusText = "Searching…"
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func prettyState(_ state: NWBrowser.State) -> String {
|
||||||
|
switch state {
|
||||||
|
case .setup:
|
||||||
|
"setup"
|
||||||
|
case .ready:
|
||||||
|
"ready"
|
||||||
|
case let .failed(err):
|
||||||
|
"failed (\(err))"
|
||||||
|
case .cancelled:
|
||||||
|
"cancelled"
|
||||||
|
case let .waiting(err):
|
||||||
|
"waiting (\(err))"
|
||||||
|
@unknown default:
|
||||||
|
"unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func appendDebugLog(_ message: String) {
|
||||||
|
guard self.debugLoggingEnabled else { return }
|
||||||
|
self.debugLog.append(DebugLogEntry(ts: Date(), message: message))
|
||||||
|
if self.debugLog.count > 200 {
|
||||||
|
self.debugLog.removeFirst(self.debugLog.count - 200)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func prettifyInstanceName(_ decodedName: String) -> String {
|
||||||
|
let normalized = decodedName.split(whereSeparator: \.isWhitespace).joined(separator: " ")
|
||||||
|
let stripped = normalized.replacingOccurrences(of: " (Clawdis)", with: "")
|
||||||
|
.replacingOccurrences(of: #"\s+\(\d+\)$"#, with: "", options: .regularExpression)
|
||||||
|
return stripped.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import ClawdisKit
|
||||||
|
import Foundation
|
||||||
|
import Network
|
||||||
|
|
||||||
|
enum BridgeEndpointID {
|
||||||
|
static func stableID(_ endpoint: NWEndpoint) -> String {
|
||||||
|
switch endpoint {
|
||||||
|
case let .service(name, type, domain, _):
|
||||||
|
// Keep this stable across encode/decode differences (e.g. `\032` for spaces).
|
||||||
|
let normalizedName = Self.normalizeServiceNameForID(name)
|
||||||
|
return "\(type)|\(domain)|\(normalizedName)"
|
||||||
|
default:
|
||||||
|
return String(describing: endpoint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static func prettyDescription(_ endpoint: NWEndpoint) -> String {
|
||||||
|
BonjourEscapes.decode(String(describing: endpoint))
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func normalizeServiceNameForID(_ rawName: String) -> String {
|
||||||
|
let decoded = BonjourEscapes.decode(rawName)
|
||||||
|
let normalized = decoded.split(whereSeparator: \.isWhitespace).joined(separator: " ")
|
||||||
|
return normalized.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,11 @@ import Foundation
|
|||||||
import Network
|
import Network
|
||||||
|
|
||||||
actor BridgeSession {
|
actor BridgeSession {
|
||||||
|
private struct TimeoutError: LocalizedError {
|
||||||
|
var message: String
|
||||||
|
var errorDescription: String? { self.message }
|
||||||
|
}
|
||||||
|
|
||||||
enum State: Sendable, Equatable {
|
enum State: Sendable, Equatable {
|
||||||
case idle
|
case idle
|
||||||
case connecting
|
case connecting
|
||||||
@@ -16,9 +21,45 @@ actor BridgeSession {
|
|||||||
private var connection: NWConnection?
|
private var connection: NWConnection?
|
||||||
private var queue: DispatchQueue?
|
private var queue: DispatchQueue?
|
||||||
private var buffer = Data()
|
private var buffer = Data()
|
||||||
|
private var pendingRPC: [String: CheckedContinuation<BridgeRPCResponse, Error>] = [:]
|
||||||
|
private var serverEventSubscribers: [UUID: AsyncStream<BridgeEventFrame>.Continuation] = [:]
|
||||||
|
|
||||||
private(set) var state: State = .idle
|
private(set) var state: State = .idle
|
||||||
|
|
||||||
|
func currentRemoteAddress() -> String? {
|
||||||
|
guard let endpoint = self.connection?.currentPath?.remoteEndpoint else { return nil }
|
||||||
|
return Self.prettyRemoteEndpoint(endpoint)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func prettyRemoteEndpoint(_ endpoint: NWEndpoint) -> String? {
|
||||||
|
switch endpoint {
|
||||||
|
case let .hostPort(host, port):
|
||||||
|
let hostString = Self.prettyHostString(host)
|
||||||
|
if hostString.contains(":") {
|
||||||
|
return "[\(hostString)]:\(port)"
|
||||||
|
}
|
||||||
|
return "\(hostString):\(port)"
|
||||||
|
default:
|
||||||
|
return String(describing: endpoint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func prettyHostString(_ host: NWEndpoint.Host) -> String {
|
||||||
|
var hostString = String(describing: host)
|
||||||
|
hostString = hostString.replacingOccurrences(of: "::ffff:", with: "")
|
||||||
|
|
||||||
|
guard let percentIndex = hostString.firstIndex(of: "%") else { return hostString }
|
||||||
|
|
||||||
|
let prefix = hostString[..<percentIndex]
|
||||||
|
let allowed = CharacterSet(charactersIn: "0123456789abcdefABCDEF:.")
|
||||||
|
let isIPAddressPrefix = prefix.unicodeScalars.allSatisfy { allowed.contains($0) }
|
||||||
|
if isIPAddressPrefix {
|
||||||
|
return String(prefix)
|
||||||
|
}
|
||||||
|
|
||||||
|
return hostString
|
||||||
|
}
|
||||||
|
|
||||||
func connect(
|
func connect(
|
||||||
endpoint: NWEndpoint,
|
endpoint: NWEndpoint,
|
||||||
hello: BridgeHello,
|
hello: BridgeHello,
|
||||||
@@ -29,17 +70,27 @@ actor BridgeSession {
|
|||||||
await self.disconnect()
|
await self.disconnect()
|
||||||
self.state = .connecting
|
self.state = .connecting
|
||||||
|
|
||||||
let connection = NWConnection(to: endpoint, using: .tcp)
|
let params = NWParameters.tcp
|
||||||
|
params.includePeerToPeer = true
|
||||||
|
let connection = NWConnection(to: endpoint, using: params)
|
||||||
let queue = DispatchQueue(label: "com.steipete.clawdis.ios.bridge-session")
|
let queue = DispatchQueue(label: "com.steipete.clawdis.ios.bridge-session")
|
||||||
self.connection = connection
|
self.connection = connection
|
||||||
self.queue = queue
|
self.queue = queue
|
||||||
|
|
||||||
|
let stateStream = Self.makeStateStream(for: connection)
|
||||||
connection.start(queue: queue)
|
connection.start(queue: queue)
|
||||||
|
|
||||||
try await self.send(hello)
|
try await Self.waitForReady(stateStream, timeoutSeconds: 6)
|
||||||
|
|
||||||
guard let line = try await self.receiveLine(),
|
try await Self.withTimeout(seconds: 6) {
|
||||||
let data = line.data(using: .utf8),
|
try await self.send(hello)
|
||||||
let base = try? self.decoder.decode(BridgeBaseFrame.self, from: data)
|
}
|
||||||
|
|
||||||
|
guard let line = try await Self.withTimeout(seconds: 6, operation: {
|
||||||
|
try await self.receiveLine()
|
||||||
|
}),
|
||||||
|
let data = line.data(using: .utf8),
|
||||||
|
let base = try? self.decoder.decode(BridgeBaseFrame.self, from: data)
|
||||||
else {
|
else {
|
||||||
await self.disconnect()
|
await self.disconnect()
|
||||||
throw NSError(domain: "Bridge", code: 1, userInfo: [
|
throw NSError(domain: "Bridge", code: 1, userInfo: [
|
||||||
@@ -72,6 +123,16 @@ actor BridgeSession {
|
|||||||
guard let nextBase = try? self.decoder.decode(BridgeBaseFrame.self, from: nextData) else { continue }
|
guard let nextBase = try? self.decoder.decode(BridgeBaseFrame.self, from: nextData) else { continue }
|
||||||
|
|
||||||
switch nextBase.type {
|
switch nextBase.type {
|
||||||
|
case "res":
|
||||||
|
let res = try self.decoder.decode(BridgeRPCResponse.self, from: nextData)
|
||||||
|
if let cont = self.pendingRPC.removeValue(forKey: res.id) {
|
||||||
|
cont.resume(returning: res)
|
||||||
|
}
|
||||||
|
|
||||||
|
case "event":
|
||||||
|
let evt = try self.decoder.decode(BridgeEventFrame.self, from: nextData)
|
||||||
|
self.broadcastServerEvent(evt)
|
||||||
|
|
||||||
case "ping":
|
case "ping":
|
||||||
let ping = try self.decoder.decode(BridgePing.self, from: nextData)
|
let ping = try self.decoder.decode(BridgePing.self, from: nextData)
|
||||||
try await self.send(BridgePong(type: "pong", id: ping.id))
|
try await self.send(BridgePong(type: "pong", id: ping.id))
|
||||||
@@ -93,14 +154,114 @@ actor BridgeSession {
|
|||||||
try await self.send(BridgeEventFrame(type: "event", event: event, payloadJSON: payloadJSON))
|
try await self.send(BridgeEventFrame(type: "event", event: event, payloadJSON: payloadJSON))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func request(method: String, paramsJSON: String?, timeoutSeconds: Int = 15) async throws -> Data {
|
||||||
|
guard self.connection != nil else {
|
||||||
|
throw NSError(domain: "Bridge", code: 11, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "not connected",
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = UUID().uuidString
|
||||||
|
let req = BridgeRPCRequest(type: "req", id: id, method: method, paramsJSON: paramsJSON)
|
||||||
|
|
||||||
|
let timeoutTask = Task {
|
||||||
|
try await Task.sleep(nanoseconds: UInt64(timeoutSeconds) * 1_000_000_000)
|
||||||
|
await self.timeoutRPC(id: id)
|
||||||
|
}
|
||||||
|
defer { timeoutTask.cancel() }
|
||||||
|
|
||||||
|
let res: BridgeRPCResponse = try await withCheckedThrowingContinuation { cont in
|
||||||
|
Task { [weak self] in
|
||||||
|
guard let self else { return }
|
||||||
|
await self.beginRPC(id: id, request: req, continuation: cont)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if res.ok {
|
||||||
|
let payload = res.payloadJSON ?? ""
|
||||||
|
guard let data = payload.data(using: .utf8) else {
|
||||||
|
throw NSError(domain: "Bridge", code: 12, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "Bridge response not UTF-8",
|
||||||
|
])
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
let code = res.error?.code ?? "UNAVAILABLE"
|
||||||
|
let message = res.error?.message ?? "request failed"
|
||||||
|
throw NSError(domain: "Bridge", code: 13, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "\(code): \(message)",
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
func subscribeServerEvents(bufferingNewest: Int = 200) -> AsyncStream<BridgeEventFrame> {
|
||||||
|
let id = UUID()
|
||||||
|
let session = self
|
||||||
|
return AsyncStream(bufferingPolicy: .bufferingNewest(bufferingNewest)) { continuation in
|
||||||
|
self.serverEventSubscribers[id] = continuation
|
||||||
|
continuation.onTermination = { @Sendable _ in
|
||||||
|
Task { await session.removeServerEventSubscriber(id) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func disconnect() async {
|
func disconnect() async {
|
||||||
self.connection?.cancel()
|
self.connection?.cancel()
|
||||||
self.connection = nil
|
self.connection = nil
|
||||||
self.queue = nil
|
self.queue = nil
|
||||||
self.buffer = Data()
|
self.buffer = Data()
|
||||||
|
|
||||||
|
let pending = self.pendingRPC.values
|
||||||
|
self.pendingRPC.removeAll()
|
||||||
|
for cont in pending {
|
||||||
|
cont.resume(throwing: NSError(domain: "Bridge", code: 14, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "UNAVAILABLE: connection closed",
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
for (_, cont) in self.serverEventSubscribers {
|
||||||
|
cont.finish()
|
||||||
|
}
|
||||||
|
self.serverEventSubscribers.removeAll()
|
||||||
|
|
||||||
self.state = .idle
|
self.state = .idle
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func beginRPC(
|
||||||
|
id: String,
|
||||||
|
request: BridgeRPCRequest,
|
||||||
|
continuation: CheckedContinuation<BridgeRPCResponse, Error>) async
|
||||||
|
{
|
||||||
|
self.pendingRPC[id] = continuation
|
||||||
|
do {
|
||||||
|
try await self.send(request)
|
||||||
|
} catch {
|
||||||
|
await self.failRPC(id: id, error: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func timeoutRPC(id: String) async {
|
||||||
|
guard let cont = self.pendingRPC.removeValue(forKey: id) else { return }
|
||||||
|
cont.resume(throwing: NSError(domain: "Bridge", code: 15, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "UNAVAILABLE: request timeout",
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func failRPC(id: String, error: Error) async {
|
||||||
|
guard let cont = self.pendingRPC.removeValue(forKey: id) else { return }
|
||||||
|
cont.resume(throwing: error)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func broadcastServerEvent(_ evt: BridgeEventFrame) {
|
||||||
|
for (_, cont) in self.serverEventSubscribers {
|
||||||
|
cont.yield(evt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func removeServerEventSubscriber(_ id: UUID) {
|
||||||
|
self.serverEventSubscribers[id] = nil
|
||||||
|
}
|
||||||
|
|
||||||
private func send(_ obj: some Encodable) async throws {
|
private func send(_ obj: some Encodable) async throws {
|
||||||
guard let connection = self.connection else {
|
guard let connection = self.connection else {
|
||||||
throw NSError(domain: "Bridge", code: 10, userInfo: [
|
throw NSError(domain: "Bridge", code: 10, userInfo: [
|
||||||
@@ -148,4 +309,70 @@ actor BridgeSession {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static func withTimeout<T: Sendable>(
|
||||||
|
seconds: Double,
|
||||||
|
operation: @escaping @Sendable () async throws -> T) async throws -> T
|
||||||
|
{
|
||||||
|
try await withThrowingTaskGroup(of: T.self) { group in
|
||||||
|
group.addTask { try await operation() }
|
||||||
|
group.addTask {
|
||||||
|
try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
|
||||||
|
throw TimeoutError(message: "UNAVAILABLE: connection timeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let first = try await group.next() else {
|
||||||
|
throw TimeoutError(message: "UNAVAILABLE: connection timeout")
|
||||||
|
}
|
||||||
|
|
||||||
|
group.cancelAll()
|
||||||
|
return first
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func makeStateStream(for connection: NWConnection) -> AsyncStream<NWConnection.State> {
|
||||||
|
AsyncStream { continuation in
|
||||||
|
continuation.onTermination = { @Sendable _ in
|
||||||
|
connection.stateUpdateHandler = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
connection.stateUpdateHandler = { state in
|
||||||
|
continuation.yield(state)
|
||||||
|
switch state {
|
||||||
|
case .ready, .cancelled, .failed, .waiting:
|
||||||
|
continuation.finish()
|
||||||
|
case .setup, .preparing:
|
||||||
|
break
|
||||||
|
@unknown default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func waitForReady(
|
||||||
|
_ stateStream: AsyncStream<NWConnection.State>,
|
||||||
|
timeoutSeconds: Double) async throws
|
||||||
|
{
|
||||||
|
try await self.withTimeout(seconds: timeoutSeconds) {
|
||||||
|
for await state in stateStream {
|
||||||
|
switch state {
|
||||||
|
case .ready:
|
||||||
|
return
|
||||||
|
case let .failed(error):
|
||||||
|
throw error
|
||||||
|
case let .waiting(error):
|
||||||
|
throw error
|
||||||
|
case .cancelled:
|
||||||
|
throw TimeoutError(message: "UNAVAILABLE: connection cancelled")
|
||||||
|
case .setup, .preparing:
|
||||||
|
break
|
||||||
|
@unknown default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw TimeoutError(message: "UNAVAILABLE: connection ended")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
enum BridgeSettingsStore {
|
||||||
|
private static let bridgeService = "com.steipete.clawdis.bridge"
|
||||||
|
private static let nodeService = "com.steipete.clawdis.node"
|
||||||
|
|
||||||
|
private static let instanceIdDefaultsKey = "node.instanceId"
|
||||||
|
private static let preferredBridgeStableIDDefaultsKey = "bridge.preferredStableID"
|
||||||
|
private static let lastDiscoveredBridgeStableIDDefaultsKey = "bridge.lastDiscoveredStableID"
|
||||||
|
|
||||||
|
private static let instanceIdAccount = "instanceId"
|
||||||
|
private static let preferredBridgeStableIDAccount = "preferredStableID"
|
||||||
|
private static let lastDiscoveredBridgeStableIDAccount = "lastDiscoveredStableID"
|
||||||
|
|
||||||
|
static func bootstrapPersistence() {
|
||||||
|
self.ensureStableInstanceID()
|
||||||
|
self.ensurePreferredBridgeStableID()
|
||||||
|
self.ensureLastDiscoveredBridgeStableID()
|
||||||
|
}
|
||||||
|
|
||||||
|
static func loadStableInstanceID() -> String? {
|
||||||
|
KeychainStore.loadString(service: self.nodeService, account: self.instanceIdAccount)?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func saveStableInstanceID(_ instanceId: String) {
|
||||||
|
_ = KeychainStore.saveString(instanceId, service: self.nodeService, account: self.instanceIdAccount)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func loadPreferredBridgeStableID() -> String? {
|
||||||
|
KeychainStore.loadString(service: self.bridgeService, account: self.preferredBridgeStableIDAccount)?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func savePreferredBridgeStableID(_ stableID: String) {
|
||||||
|
_ = KeychainStore.saveString(
|
||||||
|
stableID,
|
||||||
|
service: self.bridgeService,
|
||||||
|
account: self.preferredBridgeStableIDAccount)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func loadLastDiscoveredBridgeStableID() -> String? {
|
||||||
|
KeychainStore.loadString(service: self.bridgeService, account: self.lastDiscoveredBridgeStableIDAccount)?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func saveLastDiscoveredBridgeStableID(_ stableID: String) {
|
||||||
|
_ = KeychainStore.saveString(
|
||||||
|
stableID,
|
||||||
|
service: self.bridgeService,
|
||||||
|
account: self.lastDiscoveredBridgeStableIDAccount)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func ensureStableInstanceID() {
|
||||||
|
let defaults = UserDefaults.standard
|
||||||
|
|
||||||
|
if let existing = defaults.string(forKey: self.instanceIdDefaultsKey)?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||||
|
!existing.isEmpty
|
||||||
|
{
|
||||||
|
if self.loadStableInstanceID() == nil {
|
||||||
|
self.saveStableInstanceID(existing)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if let stored = self.loadStableInstanceID(), !stored.isEmpty {
|
||||||
|
defaults.set(stored, forKey: self.instanceIdDefaultsKey)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let fresh = UUID().uuidString
|
||||||
|
self.saveStableInstanceID(fresh)
|
||||||
|
defaults.set(fresh, forKey: self.instanceIdDefaultsKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func ensurePreferredBridgeStableID() {
|
||||||
|
let defaults = UserDefaults.standard
|
||||||
|
|
||||||
|
if let existing = defaults.string(forKey: self.preferredBridgeStableIDDefaultsKey)?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||||
|
!existing.isEmpty
|
||||||
|
{
|
||||||
|
if self.loadPreferredBridgeStableID() == nil {
|
||||||
|
self.savePreferredBridgeStableID(existing)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if let stored = self.loadPreferredBridgeStableID(), !stored.isEmpty {
|
||||||
|
defaults.set(stored, forKey: self.preferredBridgeStableIDDefaultsKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func ensureLastDiscoveredBridgeStableID() {
|
||||||
|
let defaults = UserDefaults.standard
|
||||||
|
|
||||||
|
if let existing = defaults.string(forKey: self.lastDiscoveredBridgeStableIDDefaultsKey)?
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines),
|
||||||
|
!existing.isEmpty
|
||||||
|
{
|
||||||
|
if self.loadLastDiscoveredBridgeStableID() == nil {
|
||||||
|
self.saveLastDiscoveredBridgeStableID(existing)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if let stored = self.loadLastDiscoveredBridgeStableID(), !stored.isEmpty {
|
||||||
|
defaults.set(stored, forKey: self.lastDiscoveredBridgeStableIDDefaultsKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,14 +3,13 @@ import Security
|
|||||||
|
|
||||||
enum KeychainStore {
|
enum KeychainStore {
|
||||||
static func loadString(service: String, account: String) -> String? {
|
static func loadString(service: String, account: String) -> String? {
|
||||||
var query: [String: Any] = [
|
let query: [String: Any] = [
|
||||||
kSecClass as String: kSecClassGenericPassword,
|
kSecClass as String: kSecClassGenericPassword,
|
||||||
kSecAttrService as String: service,
|
kSecAttrService as String: service,
|
||||||
kSecAttrAccount as String: account,
|
kSecAttrAccount as String: account,
|
||||||
kSecReturnData as String: true,
|
kSecReturnData as String: true,
|
||||||
kSecMatchLimit as String: kSecMatchLimitOne,
|
kSecMatchLimit as String: kSecMatchLimitOne,
|
||||||
]
|
]
|
||||||
query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
|
||||||
|
|
||||||
var item: CFTypeRef?
|
var item: CFTypeRef?
|
||||||
let status = SecItemCopyMatching(query as CFDictionary, &item)
|
let status = SecItemCopyMatching(query as CFDictionary, &item)
|
||||||
@@ -20,20 +19,20 @@ enum KeychainStore {
|
|||||||
|
|
||||||
static func saveString(_ value: String, service: String, account: String) -> Bool {
|
static func saveString(_ value: String, service: String, account: String) -> Bool {
|
||||||
let data = Data(value.utf8)
|
let data = Data(value.utf8)
|
||||||
let base: [String: Any] = [
|
let query: [String: Any] = [
|
||||||
kSecClass as String: kSecClassGenericPassword,
|
kSecClass as String: kSecClassGenericPassword,
|
||||||
kSecAttrService as String: service,
|
kSecAttrService as String: service,
|
||||||
kSecAttrAccount as String: account,
|
kSecAttrAccount as String: account,
|
||||||
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
|
|
||||||
]
|
]
|
||||||
|
|
||||||
let update: [String: Any] = [kSecValueData as String: data]
|
let update: [String: Any] = [kSecValueData as String: data]
|
||||||
let status = SecItemUpdate(base as CFDictionary, update as CFDictionary)
|
let status = SecItemUpdate(query as CFDictionary, update as CFDictionary)
|
||||||
if status == errSecSuccess { return true }
|
if status == errSecSuccess { return true }
|
||||||
if status != errSecItemNotFound { return false }
|
if status != errSecItemNotFound { return false }
|
||||||
|
|
||||||
var insert = base
|
var insert = query
|
||||||
insert[kSecValueData as String] = data
|
insert[kSecValueData as String] = data
|
||||||
|
insert[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
||||||
return SecItemAdd(insert as CFDictionary, nil) == errSecSuccess
|
return SecItemAdd(insert as CFDictionary, nil) == errSecSuccess
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,342 @@
|
|||||||
|
import AVFoundation
|
||||||
|
import ClawdisKit
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
actor CameraController {
|
||||||
|
enum CameraError: LocalizedError, Sendable {
|
||||||
|
case cameraUnavailable
|
||||||
|
case microphoneUnavailable
|
||||||
|
case permissionDenied(kind: String)
|
||||||
|
case invalidParams(String)
|
||||||
|
case captureFailed(String)
|
||||||
|
case exportFailed(String)
|
||||||
|
|
||||||
|
var errorDescription: String? {
|
||||||
|
switch self {
|
||||||
|
case .cameraUnavailable:
|
||||||
|
"Camera unavailable"
|
||||||
|
case .microphoneUnavailable:
|
||||||
|
"Microphone unavailable"
|
||||||
|
case let .permissionDenied(kind):
|
||||||
|
"\(kind) permission denied"
|
||||||
|
case let .invalidParams(msg):
|
||||||
|
msg
|
||||||
|
case let .captureFailed(msg):
|
||||||
|
msg
|
||||||
|
case let .exportFailed(msg):
|
||||||
|
msg
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func snap(params: ClawdisCameraSnapParams) async throws -> (
|
||||||
|
format: String,
|
||||||
|
base64: String,
|
||||||
|
width: Int,
|
||||||
|
height: Int)
|
||||||
|
{
|
||||||
|
let facing = params.facing ?? .front
|
||||||
|
let format = params.format ?? .jpg
|
||||||
|
// Default to a reasonable max width to keep bridge payload sizes manageable.
|
||||||
|
// If you need the full-res photo, explicitly request a larger maxWidth.
|
||||||
|
let maxWidth = params.maxWidth.flatMap { $0 > 0 ? $0 : nil } ?? 1600
|
||||||
|
let quality = Self.clampQuality(params.quality)
|
||||||
|
|
||||||
|
try await self.ensureAccess(for: .video)
|
||||||
|
|
||||||
|
let session = AVCaptureSession()
|
||||||
|
session.sessionPreset = .photo
|
||||||
|
|
||||||
|
guard let device = Self.pickCamera(facing: facing) else {
|
||||||
|
throw CameraError.cameraUnavailable
|
||||||
|
}
|
||||||
|
|
||||||
|
let input = try AVCaptureDeviceInput(device: device)
|
||||||
|
guard session.canAddInput(input) else {
|
||||||
|
throw CameraError.captureFailed("Failed to add camera input")
|
||||||
|
}
|
||||||
|
session.addInput(input)
|
||||||
|
|
||||||
|
let output = AVCapturePhotoOutput()
|
||||||
|
guard session.canAddOutput(output) else {
|
||||||
|
throw CameraError.captureFailed("Failed to add photo output")
|
||||||
|
}
|
||||||
|
session.addOutput(output)
|
||||||
|
output.maxPhotoQualityPrioritization = .quality
|
||||||
|
|
||||||
|
session.startRunning()
|
||||||
|
defer { session.stopRunning() }
|
||||||
|
await Self.warmUpCaptureSession()
|
||||||
|
|
||||||
|
let settings: AVCapturePhotoSettings = {
|
||||||
|
if output.availablePhotoCodecTypes.contains(.jpeg) {
|
||||||
|
return AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
|
||||||
|
}
|
||||||
|
return AVCapturePhotoSettings()
|
||||||
|
}()
|
||||||
|
settings.photoQualityPrioritization = .quality
|
||||||
|
|
||||||
|
var delegate: PhotoCaptureDelegate?
|
||||||
|
let rawData: Data = try await withCheckedThrowingContinuation { cont in
|
||||||
|
let d = PhotoCaptureDelegate(cont)
|
||||||
|
delegate = d
|
||||||
|
output.capturePhoto(with: settings, delegate: d)
|
||||||
|
}
|
||||||
|
withExtendedLifetime(delegate) {}
|
||||||
|
|
||||||
|
let res = try JPEGTranscoder.transcodeToJPEG(
|
||||||
|
imageData: rawData,
|
||||||
|
maxWidthPx: maxWidth,
|
||||||
|
quality: quality)
|
||||||
|
|
||||||
|
return (
|
||||||
|
format: format.rawValue,
|
||||||
|
base64: res.data.base64EncodedString(),
|
||||||
|
width: res.widthPx,
|
||||||
|
height: res.heightPx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func clip(params: ClawdisCameraClipParams) async throws -> (
|
||||||
|
format: String,
|
||||||
|
base64: String,
|
||||||
|
durationMs: Int,
|
||||||
|
hasAudio: Bool)
|
||||||
|
{
|
||||||
|
let facing = params.facing ?? .front
|
||||||
|
let durationMs = Self.clampDurationMs(params.durationMs)
|
||||||
|
let includeAudio = params.includeAudio ?? true
|
||||||
|
let format = params.format ?? .mp4
|
||||||
|
|
||||||
|
try await self.ensureAccess(for: .video)
|
||||||
|
if includeAudio {
|
||||||
|
try await self.ensureAccess(for: .audio)
|
||||||
|
}
|
||||||
|
|
||||||
|
let session = AVCaptureSession()
|
||||||
|
session.sessionPreset = .high
|
||||||
|
|
||||||
|
guard let camera = Self.pickCamera(facing: facing) else {
|
||||||
|
throw CameraError.cameraUnavailable
|
||||||
|
}
|
||||||
|
let cameraInput = try AVCaptureDeviceInput(device: camera)
|
||||||
|
guard session.canAddInput(cameraInput) else {
|
||||||
|
throw CameraError.captureFailed("Failed to add camera input")
|
||||||
|
}
|
||||||
|
session.addInput(cameraInput)
|
||||||
|
|
||||||
|
if includeAudio {
|
||||||
|
guard let mic = AVCaptureDevice.default(for: .audio) else {
|
||||||
|
throw CameraError.microphoneUnavailable
|
||||||
|
}
|
||||||
|
let micInput = try AVCaptureDeviceInput(device: mic)
|
||||||
|
if session.canAddInput(micInput) {
|
||||||
|
session.addInput(micInput)
|
||||||
|
} else {
|
||||||
|
throw CameraError.captureFailed("Failed to add microphone input")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let output = AVCaptureMovieFileOutput()
|
||||||
|
guard session.canAddOutput(output) else {
|
||||||
|
throw CameraError.captureFailed("Failed to add movie output")
|
||||||
|
}
|
||||||
|
session.addOutput(output)
|
||||||
|
output.maxRecordedDuration = CMTime(value: Int64(durationMs), timescale: 1000)
|
||||||
|
|
||||||
|
session.startRunning()
|
||||||
|
defer { session.stopRunning() }
|
||||||
|
await Self.warmUpCaptureSession()
|
||||||
|
|
||||||
|
let movURL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("clawdis-camera-\(UUID().uuidString).mov")
|
||||||
|
let mp4URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent("clawdis-camera-\(UUID().uuidString).mp4")
|
||||||
|
|
||||||
|
defer {
|
||||||
|
try? FileManager.default.removeItem(at: movURL)
|
||||||
|
try? FileManager.default.removeItem(at: mp4URL)
|
||||||
|
}
|
||||||
|
|
||||||
|
var delegate: MovieFileDelegate?
|
||||||
|
let recordedURL: URL = try await withCheckedThrowingContinuation { cont in
|
||||||
|
let d = MovieFileDelegate(cont)
|
||||||
|
delegate = d
|
||||||
|
output.startRecording(to: movURL, recordingDelegate: d)
|
||||||
|
}
|
||||||
|
withExtendedLifetime(delegate) {}
|
||||||
|
|
||||||
|
// Transcode .mov -> .mp4 for easier downstream handling.
|
||||||
|
try await Self.exportToMP4(inputURL: recordedURL, outputURL: mp4URL)
|
||||||
|
|
||||||
|
let data = try Data(contentsOf: mp4URL)
|
||||||
|
return (
|
||||||
|
format: format.rawValue,
|
||||||
|
base64: data.base64EncodedString(),
|
||||||
|
durationMs: durationMs,
|
||||||
|
hasAudio: includeAudio)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func ensureAccess(for mediaType: AVMediaType) async throws {
|
||||||
|
let status = AVCaptureDevice.authorizationStatus(for: mediaType)
|
||||||
|
switch status {
|
||||||
|
case .authorized:
|
||||||
|
return
|
||||||
|
case .notDetermined:
|
||||||
|
let ok = await withCheckedContinuation(isolation: nil) { cont in
|
||||||
|
AVCaptureDevice.requestAccess(for: mediaType) { granted in
|
||||||
|
cont.resume(returning: granted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
throw CameraError.permissionDenied(kind: mediaType == .video ? "Camera" : "Microphone")
|
||||||
|
}
|
||||||
|
case .denied, .restricted:
|
||||||
|
throw CameraError.permissionDenied(kind: mediaType == .video ? "Camera" : "Microphone")
|
||||||
|
@unknown default:
|
||||||
|
throw CameraError.permissionDenied(kind: mediaType == .video ? "Camera" : "Microphone")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private nonisolated static func pickCamera(facing: ClawdisCameraFacing) -> AVCaptureDevice? {
|
||||||
|
let position: AVCaptureDevice.Position = (facing == .front) ? .front : .back
|
||||||
|
if let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position) {
|
||||||
|
return device
|
||||||
|
}
|
||||||
|
// Fall back to any default camera (e.g. simulator / unusual device configurations).
|
||||||
|
return AVCaptureDevice.default(for: .video)
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated static func clampQuality(_ quality: Double?) -> Double {
|
||||||
|
let q = quality ?? 0.9
|
||||||
|
return min(1.0, max(0.05, q))
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated static func clampDurationMs(_ ms: Int?) -> Int {
|
||||||
|
let v = ms ?? 3000
|
||||||
|
// Keep clips short by default; avoid huge base64 payloads on the bridge.
|
||||||
|
return min(15000, max(250, v))
|
||||||
|
}
|
||||||
|
|
||||||
|
private nonisolated static func exportToMP4(inputURL: URL, outputURL: URL) async throws {
|
||||||
|
let asset = AVURLAsset(url: inputURL)
|
||||||
|
guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality) else {
|
||||||
|
throw CameraError.exportFailed("Failed to create export session")
|
||||||
|
}
|
||||||
|
exporter.shouldOptimizeForNetworkUse = true
|
||||||
|
|
||||||
|
if #available(iOS 18.0, tvOS 18.0, visionOS 2.0, *) {
|
||||||
|
do {
|
||||||
|
try await exporter.export(to: outputURL, as: .mp4)
|
||||||
|
return
|
||||||
|
} catch {
|
||||||
|
throw CameraError.exportFailed(error.localizedDescription)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
exporter.outputURL = outputURL
|
||||||
|
exporter.outputFileType = .mp4
|
||||||
|
|
||||||
|
try await withCheckedThrowingContinuation(isolation: nil) { (cont: CheckedContinuation<Void, Error>) in
|
||||||
|
exporter.exportAsynchronously {
|
||||||
|
cont.resume(returning: ())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch exporter.status {
|
||||||
|
case .completed:
|
||||||
|
return
|
||||||
|
case .failed:
|
||||||
|
throw CameraError.exportFailed(exporter.error?.localizedDescription ?? "export failed")
|
||||||
|
case .cancelled:
|
||||||
|
throw CameraError.exportFailed("export cancelled")
|
||||||
|
default:
|
||||||
|
throw CameraError.exportFailed("export did not complete")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private nonisolated static func warmUpCaptureSession() async {
|
||||||
|
// A short delay after `startRunning()` significantly reduces "blank first frame" captures on some devices.
|
||||||
|
try? await Task.sleep(nanoseconds: 150_000_000) // 150ms
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class PhotoCaptureDelegate: NSObject, AVCapturePhotoCaptureDelegate {
|
||||||
|
private let continuation: CheckedContinuation<Data, Error>
|
||||||
|
private var didResume = false
|
||||||
|
|
||||||
|
init(_ continuation: CheckedContinuation<Data, Error>) {
|
||||||
|
self.continuation = continuation
|
||||||
|
}
|
||||||
|
|
||||||
|
func photoOutput(
|
||||||
|
_ output: AVCapturePhotoOutput,
|
||||||
|
didFinishProcessingPhoto photo: AVCapturePhoto,
|
||||||
|
error: Error?)
|
||||||
|
{
|
||||||
|
guard !self.didResume else { return }
|
||||||
|
self.didResume = true
|
||||||
|
|
||||||
|
if let error {
|
||||||
|
self.continuation.resume(throwing: error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard let data = photo.fileDataRepresentation() else {
|
||||||
|
self.continuation.resume(
|
||||||
|
throwing: NSError(domain: "Camera", code: 1, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "photo data missing",
|
||||||
|
]))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if data.isEmpty {
|
||||||
|
self.continuation.resume(
|
||||||
|
throwing: NSError(domain: "Camera", code: 2, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "photo data empty",
|
||||||
|
]))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
self.continuation.resume(returning: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func photoOutput(
|
||||||
|
_ output: AVCapturePhotoOutput,
|
||||||
|
didFinishCaptureFor resolvedSettings: AVCaptureResolvedPhotoSettings,
|
||||||
|
error: Error?)
|
||||||
|
{
|
||||||
|
guard let error else { return }
|
||||||
|
guard !self.didResume else { return }
|
||||||
|
self.didResume = true
|
||||||
|
self.continuation.resume(throwing: error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class MovieFileDelegate: NSObject, AVCaptureFileOutputRecordingDelegate {
|
||||||
|
private let continuation: CheckedContinuation<URL, Error>
|
||||||
|
private var didResume = false
|
||||||
|
|
||||||
|
init(_ continuation: CheckedContinuation<URL, Error>) {
|
||||||
|
self.continuation = continuation
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileOutput(
|
||||||
|
_ output: AVCaptureFileOutput,
|
||||||
|
didFinishRecordingTo outputFileURL: URL,
|
||||||
|
from connections: [AVCaptureConnection],
|
||||||
|
error: Error?)
|
||||||
|
{
|
||||||
|
guard !self.didResume else { return }
|
||||||
|
self.didResume = true
|
||||||
|
|
||||||
|
if let error {
|
||||||
|
let ns = error as NSError
|
||||||
|
if ns.domain == AVFoundationErrorDomain,
|
||||||
|
ns.code == AVError.maximumDurationReached.rawValue
|
||||||
|
{
|
||||||
|
self.continuation.resume(returning: outputFileURL)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
self.continuation.resume(throwing: error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
self.continuation.resume(returning: outputFileURL)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import ClawdisChatUI
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct ChatSheet: View {
|
||||||
|
@Environment(\.dismiss) private var dismiss
|
||||||
|
@State private var viewModel: ClawdisChatViewModel
|
||||||
|
|
||||||
|
init(bridge: BridgeSession, sessionKey: String = "main") {
|
||||||
|
let transport = IOSBridgeChatTransport(bridge: bridge)
|
||||||
|
self._viewModel = State(
|
||||||
|
initialValue: ClawdisChatViewModel(
|
||||||
|
sessionKey: sessionKey,
|
||||||
|
transport: transport))
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
NavigationStack {
|
||||||
|
ClawdisChatView(viewModel: self.viewModel)
|
||||||
|
.navigationTitle("Chat")
|
||||||
|
.navigationBarTitleDisplayMode(.inline)
|
||||||
|
.toolbar {
|
||||||
|
ToolbarItem(placement: .topBarTrailing) {
|
||||||
|
Button {
|
||||||
|
self.dismiss()
|
||||||
|
} label: {
|
||||||
|
Image(systemName: "xmark")
|
||||||
|
}
|
||||||
|
.accessibilityLabel("Close")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import ClawdisChatUI
|
||||||
|
import ClawdisKit
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
struct IOSBridgeChatTransport: ClawdisChatTransport, Sendable {
|
||||||
|
private let bridge: BridgeSession
|
||||||
|
|
||||||
|
init(bridge: BridgeSession) {
|
||||||
|
self.bridge = bridge
|
||||||
|
}
|
||||||
|
|
||||||
|
func setActiveSessionKey(_ sessionKey: String) async throws {
|
||||||
|
struct Subscribe: Codable { var sessionKey: String }
|
||||||
|
let data = try JSONEncoder().encode(Subscribe(sessionKey: sessionKey))
|
||||||
|
let json = String(data: data, encoding: .utf8)
|
||||||
|
try await self.bridge.sendEvent(event: "chat.subscribe", payloadJSON: json)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestHistory(sessionKey: String) async throws -> ClawdisChatHistoryPayload {
|
||||||
|
struct Params: Codable { var sessionKey: String }
|
||||||
|
let data = try JSONEncoder().encode(Params(sessionKey: sessionKey))
|
||||||
|
let json = String(data: data, encoding: .utf8)
|
||||||
|
let res = try await self.bridge.request(method: "chat.history", paramsJSON: json, timeoutSeconds: 15)
|
||||||
|
return try JSONDecoder().decode(ClawdisChatHistoryPayload.self, from: res)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendMessage(
|
||||||
|
sessionKey: String,
|
||||||
|
message: String,
|
||||||
|
thinking: String,
|
||||||
|
idempotencyKey: String,
|
||||||
|
attachments: [ClawdisChatAttachmentPayload]) async throws -> ClawdisChatSendResponse
|
||||||
|
{
|
||||||
|
struct Params: Codable {
|
||||||
|
var sessionKey: String
|
||||||
|
var message: String
|
||||||
|
var thinking: String
|
||||||
|
var attachments: [ClawdisChatAttachmentPayload]?
|
||||||
|
var timeoutMs: Int
|
||||||
|
var idempotencyKey: String
|
||||||
|
}
|
||||||
|
|
||||||
|
let params = Params(
|
||||||
|
sessionKey: sessionKey,
|
||||||
|
message: message,
|
||||||
|
thinking: thinking,
|
||||||
|
attachments: attachments.isEmpty ? nil : attachments,
|
||||||
|
timeoutMs: 30000,
|
||||||
|
idempotencyKey: idempotencyKey)
|
||||||
|
let data = try JSONEncoder().encode(params)
|
||||||
|
let json = String(data: data, encoding: .utf8)
|
||||||
|
let res = try await self.bridge.request(method: "chat.send", paramsJSON: json, timeoutSeconds: 35)
|
||||||
|
return try JSONDecoder().decode(ClawdisChatSendResponse.self, from: res)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestHealth(timeoutMs: Int) async throws -> Bool {
|
||||||
|
let seconds = max(1, Int(ceil(Double(timeoutMs) / 1000.0)))
|
||||||
|
let res = try await self.bridge.request(method: "health", paramsJSON: nil, timeoutSeconds: seconds)
|
||||||
|
return (try? JSONDecoder().decode(ClawdisGatewayHealthOK.self, from: res))?.ok ?? true
|
||||||
|
}
|
||||||
|
|
||||||
|
func events() -> AsyncStream<ClawdisChatTransportEvent> {
|
||||||
|
AsyncStream { continuation in
|
||||||
|
let task = Task {
|
||||||
|
let stream = await self.bridge.subscribeServerEvents()
|
||||||
|
for await evt in stream {
|
||||||
|
if Task.isCancelled { return }
|
||||||
|
switch evt.event {
|
||||||
|
case "tick":
|
||||||
|
continuation.yield(.tick)
|
||||||
|
case "seqGap":
|
||||||
|
continuation.yield(.seqGap)
|
||||||
|
case "health":
|
||||||
|
guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { break }
|
||||||
|
let ok = (try? JSONDecoder().decode(ClawdisGatewayHealthOK.self, from: data))?.ok ?? true
|
||||||
|
continuation.yield(.health(ok: ok))
|
||||||
|
case "chat":
|
||||||
|
guard let json = evt.payloadJSON, let data = json.data(using: .utf8) else { break }
|
||||||
|
if let payload = try? JSONDecoder().decode(ClawdisChatEventPayload.self, from: data) {
|
||||||
|
continuation.yield(.chat(payload))
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
continuation.onTermination = { @Sendable _ in
|
||||||
|
task.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
@main
|
||||||
|
struct ClawdisApp: App {
|
||||||
|
@State private var appModel: NodeAppModel
|
||||||
|
@State private var bridgeController: BridgeConnectionController
|
||||||
|
@Environment(\.scenePhase) private var scenePhase
|
||||||
|
|
||||||
|
init() {
|
||||||
|
BridgeSettingsStore.bootstrapPersistence()
|
||||||
|
let appModel = NodeAppModel()
|
||||||
|
_appModel = State(initialValue: appModel)
|
||||||
|
_bridgeController = State(initialValue: BridgeConnectionController(appModel: appModel))
|
||||||
|
}
|
||||||
|
|
||||||
|
var body: some Scene {
|
||||||
|
WindowGroup {
|
||||||
|
RootCanvas()
|
||||||
|
.environment(self.appModel)
|
||||||
|
.environment(self.appModel.voiceWake)
|
||||||
|
.environment(self.bridgeController)
|
||||||
|
.onOpenURL { url in
|
||||||
|
Task { await self.appModel.handleDeepLink(url: url) }
|
||||||
|
}
|
||||||
|
.onChange(of: self.scenePhase) { _, newValue in
|
||||||
|
self.appModel.setScenePhase(newValue)
|
||||||
|
self.bridgeController.setScenePhase(newValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import SwiftUI
|
|
||||||
|
|
||||||
@main
|
|
||||||
struct ClawdisNodeApp: App {
|
|
||||||
@StateObject private var appModel = NodeAppModel()
|
|
||||||
@Environment(\.scenePhase) private var scenePhase
|
|
||||||
|
|
||||||
var body: some Scene {
|
|
||||||
WindowGroup {
|
|
||||||
RootCanvas()
|
|
||||||
.environmentObject(self.appModel)
|
|
||||||
.environmentObject(self.appModel.voiceWake)
|
|
||||||
.onOpenURL { url in
|
|
||||||
Task { await self.appModel.handleDeepLink(url: url) }
|
|
||||||
}
|
|
||||||
.onChange(of: self.scenePhase) { _, newValue in
|
|
||||||
self.appModel.setScenePhase(newValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,9 +5,11 @@
|
|||||||
<key>CFBundleDevelopmentRegion</key>
|
<key>CFBundleDevelopmentRegion</key>
|
||||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||||
<key>CFBundleDisplayName</key>
|
<key>CFBundleDisplayName</key>
|
||||||
<string>Clawdis Node</string>
|
<string>Clawdis</string>
|
||||||
<key>CFBundleExecutable</key>
|
<key>CFBundleExecutable</key>
|
||||||
<string>$(EXECUTABLE_NAME)</string>
|
<string>$(EXECUTABLE_NAME)</string>
|
||||||
|
<key>CFBundleIconName</key>
|
||||||
|
<string>AppIcon</string>
|
||||||
<key>CFBundleIdentifier</key>
|
<key>CFBundleIdentifier</key>
|
||||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||||
<key>CFBundleInfoDictionaryVersion</key>
|
<key>CFBundleInfoDictionaryVersion</key>
|
||||||
@@ -24,12 +26,14 @@
|
|||||||
<array>
|
<array>
|
||||||
<string>_clawdis-bridge._tcp</string>
|
<string>_clawdis-bridge._tcp</string>
|
||||||
</array>
|
</array>
|
||||||
|
<key>NSCameraUsageDescription</key>
|
||||||
|
<string>Clawdis can capture photos or short video clips when requested via the bridge.</string>
|
||||||
<key>NSLocalNetworkUsageDescription</key>
|
<key>NSLocalNetworkUsageDescription</key>
|
||||||
<string>Clawdis Node discovers and connects to your Clawdis bridge on the local network.</string>
|
<string>Clawdis discovers and connects to your Clawdis bridge on the local network.</string>
|
||||||
<key>NSMicrophoneUsageDescription</key>
|
<key>NSMicrophoneUsageDescription</key>
|
||||||
<string>Clawdis Node needs microphone access for voice wake.</string>
|
<string>Clawdis needs microphone access for voice wake.</string>
|
||||||
<key>NSSpeechRecognitionUsageDescription</key>
|
<key>NSSpeechRecognitionUsageDescription</key>
|
||||||
<string>Clawdis Node uses on-device speech recognition for voice wake.</string>
|
<string>Clawdis uses on-device speech recognition for voice wake.</string>
|
||||||
<key>UIApplicationSceneManifest</key>
|
<key>UIApplicationSceneManifest</key>
|
||||||
<dict>
|
<dict>
|
||||||
<key>UIApplicationSupportsMultipleScenes</key>
|
<key>UIApplicationSupportsMultipleScenes</key>
|
||||||
|
|||||||
@@ -1,18 +1,26 @@
|
|||||||
import ClawdisKit
|
import ClawdisKit
|
||||||
import Network
|
import Network
|
||||||
|
import Observation
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
final class NodeAppModel: ObservableObject {
|
@Observable
|
||||||
@Published var isBackgrounded: Bool = false
|
final class NodeAppModel {
|
||||||
|
var isBackgrounded: Bool = false
|
||||||
let screen = ScreenController()
|
let screen = ScreenController()
|
||||||
@Published var bridgeStatusText: String = "Not connected"
|
let camera = CameraController()
|
||||||
@Published var bridgeServerName: String?
|
var bridgeStatusText: String = "Not connected"
|
||||||
|
var bridgeServerName: String?
|
||||||
|
var bridgeRemoteAddress: String?
|
||||||
|
var connectedBridgeID: String?
|
||||||
|
|
||||||
private let bridge = BridgeSession()
|
private let bridge = BridgeSession()
|
||||||
private var bridgeTask: Task<Void, Never>?
|
private var bridgeTask: Task<Void, Never>?
|
||||||
|
private var voiceWakeSyncTask: Task<Void, Never>?
|
||||||
let voiceWake = VoiceWakeManager()
|
let voiceWake = VoiceWakeManager()
|
||||||
|
|
||||||
|
var bridgeSession: BridgeSession { self.bridge }
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
self.voiceWake.configure { [weak self] cmd in
|
self.voiceWake.configure { [weak self] cmd in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
@@ -27,6 +35,14 @@ final class NodeAppModel: ObservableObject {
|
|||||||
|
|
||||||
let enabled = UserDefaults.standard.bool(forKey: "voiceWake.enabled")
|
let enabled = UserDefaults.standard.bool(forKey: "voiceWake.enabled")
|
||||||
self.voiceWake.setEnabled(enabled)
|
self.voiceWake.setEnabled(enabled)
|
||||||
|
|
||||||
|
// Wire up deep links from canvas taps
|
||||||
|
self.screen.onDeepLink = { [weak self] url in
|
||||||
|
guard let self else { return }
|
||||||
|
Task { @MainActor in
|
||||||
|
await self.handleDeepLink(url: url)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func setScenePhase(_ phase: ScenePhase) {
|
func setScenePhase(_ phase: ScenePhase) {
|
||||||
@@ -46,61 +62,137 @@ final class NodeAppModel: ObservableObject {
|
|||||||
|
|
||||||
func connectToBridge(
|
func connectToBridge(
|
||||||
endpoint: NWEndpoint,
|
endpoint: NWEndpoint,
|
||||||
token: String,
|
hello: BridgeHello)
|
||||||
nodeId: String,
|
|
||||||
displayName: String?,
|
|
||||||
platform: String,
|
|
||||||
version: String)
|
|
||||||
{
|
{
|
||||||
self.bridgeTask?.cancel()
|
self.bridgeTask?.cancel()
|
||||||
self.bridgeStatusText = "Connecting…"
|
|
||||||
self.bridgeServerName = nil
|
self.bridgeServerName = nil
|
||||||
|
self.bridgeRemoteAddress = nil
|
||||||
|
self.connectedBridgeID = BridgeEndpointID.stableID(endpoint)
|
||||||
|
self.voiceWakeSyncTask?.cancel()
|
||||||
|
self.voiceWakeSyncTask = nil
|
||||||
|
|
||||||
self.bridgeTask = Task {
|
self.bridgeTask = Task {
|
||||||
do {
|
var attempt = 0
|
||||||
try await self.bridge.connect(
|
while !Task.isCancelled {
|
||||||
endpoint: endpoint,
|
await MainActor.run {
|
||||||
hello: BridgeHello(
|
if attempt == 0 {
|
||||||
nodeId: nodeId,
|
self.bridgeStatusText = "Connecting…"
|
||||||
displayName: displayName,
|
} else {
|
||||||
token: token,
|
self.bridgeStatusText = "Reconnecting…"
|
||||||
platform: platform,
|
}
|
||||||
version: version),
|
self.bridgeServerName = nil
|
||||||
onConnected: { [weak self] serverName in
|
self.bridgeRemoteAddress = nil
|
||||||
await MainActor.run {
|
}
|
||||||
self?.bridgeStatusText = "Connected"
|
|
||||||
self?.bridgeServerName = serverName
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onInvoke: { [weak self] req in
|
|
||||||
guard let self else {
|
|
||||||
return BridgeInvokeResponse(
|
|
||||||
id: req.id,
|
|
||||||
ok: false,
|
|
||||||
error: ClawdisNodeError(code: .unavailable, message: "UNAVAILABLE: node not ready"))
|
|
||||||
}
|
|
||||||
return await self.handleInvoke(req)
|
|
||||||
})
|
|
||||||
|
|
||||||
await MainActor.run {
|
do {
|
||||||
self.bridgeStatusText = "Disconnected"
|
try await self.bridge.connect(
|
||||||
self.bridgeServerName = nil
|
endpoint: endpoint,
|
||||||
}
|
hello: hello,
|
||||||
} catch {
|
onConnected: { [weak self] serverName in
|
||||||
await MainActor.run {
|
guard let self else { return }
|
||||||
self.bridgeStatusText = "Bridge error: \(error.localizedDescription)"
|
await MainActor.run {
|
||||||
self.bridgeServerName = nil
|
self.bridgeStatusText = "Connected"
|
||||||
|
self.bridgeServerName = serverName
|
||||||
|
}
|
||||||
|
if let addr = await self.bridge.currentRemoteAddress() {
|
||||||
|
await MainActor.run {
|
||||||
|
self.bridgeRemoteAddress = addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await self.startVoiceWakeSync()
|
||||||
|
},
|
||||||
|
onInvoke: { [weak self] req in
|
||||||
|
guard let self else {
|
||||||
|
return BridgeInvokeResponse(
|
||||||
|
id: req.id,
|
||||||
|
ok: false,
|
||||||
|
error: ClawdisNodeError(code: .unavailable, message: "UNAVAILABLE: node not ready"))
|
||||||
|
}
|
||||||
|
return await self.handleInvoke(req)
|
||||||
|
})
|
||||||
|
|
||||||
|
if Task.isCancelled { break }
|
||||||
|
attempt += 1
|
||||||
|
let sleepSeconds = min(6.0, 0.35 * pow(1.7, Double(attempt)))
|
||||||
|
try? await Task.sleep(nanoseconds: UInt64(sleepSeconds * 1_000_000_000))
|
||||||
|
} catch {
|
||||||
|
if Task.isCancelled { break }
|
||||||
|
attempt += 1
|
||||||
|
await MainActor.run {
|
||||||
|
self.bridgeStatusText = "Bridge error: \(error.localizedDescription)"
|
||||||
|
self.bridgeServerName = nil
|
||||||
|
self.bridgeRemoteAddress = nil
|
||||||
|
}
|
||||||
|
let sleepSeconds = min(8.0, 0.5 * pow(1.7, Double(attempt)))
|
||||||
|
try? await Task.sleep(nanoseconds: UInt64(sleepSeconds * 1_000_000_000))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await MainActor.run {
|
||||||
|
self.bridgeStatusText = "Disconnected"
|
||||||
|
self.bridgeServerName = nil
|
||||||
|
self.bridgeRemoteAddress = nil
|
||||||
|
self.connectedBridgeID = nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func disconnectBridge() {
|
func disconnectBridge() {
|
||||||
self.bridgeTask?.cancel()
|
self.bridgeTask?.cancel()
|
||||||
self.bridgeTask = nil
|
self.bridgeTask = nil
|
||||||
|
self.voiceWakeSyncTask?.cancel()
|
||||||
|
self.voiceWakeSyncTask = nil
|
||||||
Task { await self.bridge.disconnect() }
|
Task { await self.bridge.disconnect() }
|
||||||
self.bridgeStatusText = "Disconnected"
|
self.bridgeStatusText = "Disconnected"
|
||||||
self.bridgeServerName = nil
|
self.bridgeServerName = nil
|
||||||
|
self.bridgeRemoteAddress = nil
|
||||||
|
self.connectedBridgeID = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func setGlobalWakeWords(_ words: [String]) async {
|
||||||
|
let sanitized = VoiceWakePreferences.sanitizeTriggerWords(words)
|
||||||
|
|
||||||
|
struct Payload: Codable {
|
||||||
|
var triggers: [String]
|
||||||
|
}
|
||||||
|
let payload = Payload(triggers: sanitized)
|
||||||
|
guard let data = try? JSONEncoder().encode(payload),
|
||||||
|
let json = String(data: data, encoding: .utf8)
|
||||||
|
else { return }
|
||||||
|
|
||||||
|
do {
|
||||||
|
_ = try await self.bridge.request(method: "voicewake.set", paramsJSON: json, timeoutSeconds: 12)
|
||||||
|
} catch {
|
||||||
|
// Best-effort only.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startVoiceWakeSync() async {
|
||||||
|
self.voiceWakeSyncTask?.cancel()
|
||||||
|
self.voiceWakeSyncTask = Task { [weak self] in
|
||||||
|
guard let self else { return }
|
||||||
|
|
||||||
|
await self.refreshWakeWordsFromGateway()
|
||||||
|
|
||||||
|
let stream = await self.bridge.subscribeServerEvents(bufferingNewest: 200)
|
||||||
|
for await evt in stream {
|
||||||
|
if Task.isCancelled { return }
|
||||||
|
guard evt.event == "voicewake.changed" else { continue }
|
||||||
|
guard let payloadJSON = evt.payloadJSON else { continue }
|
||||||
|
guard let triggers = VoiceWakePreferences.decodeGatewayTriggers(from: payloadJSON) else { continue }
|
||||||
|
VoiceWakePreferences.saveTriggerWords(triggers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func refreshWakeWordsFromGateway() async {
|
||||||
|
do {
|
||||||
|
let data = try await self.bridge.request(method: "voicewake.get", paramsJSON: "{}", timeoutSeconds: 8)
|
||||||
|
guard let triggers = VoiceWakePreferences.decodeGatewayTriggers(from: data) else { return }
|
||||||
|
VoiceWakePreferences.saveTriggerWords(triggers)
|
||||||
|
} catch {
|
||||||
|
// Best-effort only.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func sendVoiceTranscript(text: String, sessionKey: String?) async throws {
|
func sendVoiceTranscript(text: String, sessionKey: String?) async throws {
|
||||||
@@ -110,7 +202,11 @@ final class NodeAppModel: ObservableObject {
|
|||||||
}
|
}
|
||||||
let payload = Payload(text: text, sessionKey: sessionKey)
|
let payload = Payload(text: text, sessionKey: sessionKey)
|
||||||
let data = try JSONEncoder().encode(payload)
|
let data = try JSONEncoder().encode(payload)
|
||||||
let json = String(decoding: data, as: UTF8.self)
|
guard let json = String(bytes: data, encoding: .utf8) else {
|
||||||
|
throw NSError(domain: "NodeAppModel", code: 1, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "Failed to encode voice transcript payload as UTF-8",
|
||||||
|
])
|
||||||
|
}
|
||||||
try await self.bridge.sendEvent(event: "voice.transcript", payloadJSON: json)
|
try await self.bridge.sendEvent(event: "voice.transcript", payloadJSON: json)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -155,7 +251,11 @@ final class NodeAppModel: ObservableObject {
|
|||||||
// iOS bridge forwards to the gateway; no local auth prompts here.
|
// iOS bridge forwards to the gateway; no local auth prompts here.
|
||||||
// (Key-based unattended auth is handled on macOS for clawdis:// links.)
|
// (Key-based unattended auth is handled on macOS for clawdis:// links.)
|
||||||
let data = try JSONEncoder().encode(link)
|
let data = try JSONEncoder().encode(link)
|
||||||
let json = String(decoding: data, as: UTF8.self)
|
guard let json = String(bytes: data, encoding: .utf8) else {
|
||||||
|
throw NSError(domain: "NodeAppModel", code: 2, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "Failed to encode agent request payload as UTF-8",
|
||||||
|
])
|
||||||
|
}
|
||||||
try await self.bridge.sendEvent(event: "agent.request", payloadJSON: json)
|
try await self.bridge.sendEvent(event: "agent.request", payloadJSON: json)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,13 +265,22 @@ final class NodeAppModel: ObservableObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func handleInvoke(_ req: BridgeInvokeRequest) async -> BridgeInvokeResponse {
|
private func handleInvoke(_ req: BridgeInvokeRequest) async -> BridgeInvokeResponse {
|
||||||
if req.command.hasPrefix("screen."), self.isBackgrounded {
|
if req.command.hasPrefix("screen.") || req.command.hasPrefix("camera."), self.isBackgrounded {
|
||||||
return BridgeInvokeResponse(
|
return BridgeInvokeResponse(
|
||||||
id: req.id,
|
id: req.id,
|
||||||
ok: false,
|
ok: false,
|
||||||
error: ClawdisNodeError(
|
error: ClawdisNodeError(
|
||||||
code: .backgroundUnavailable,
|
code: .backgroundUnavailable,
|
||||||
message: "NODE_BACKGROUND_UNAVAILABLE: screen commands require foreground"))
|
message: "NODE_BACKGROUND_UNAVAILABLE: screen/camera commands require foreground"))
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.command.hasPrefix("camera."), !self.isCameraEnabled() {
|
||||||
|
return BridgeInvokeResponse(
|
||||||
|
id: req.id,
|
||||||
|
ok: false,
|
||||||
|
error: ClawdisNodeError(
|
||||||
|
code: .unavailable,
|
||||||
|
message: "CAMERA_DISABLED: enable Camera in iOS Settings → Camera → Allow Camera"))
|
||||||
}
|
}
|
||||||
|
|
||||||
do {
|
do {
|
||||||
@@ -205,6 +314,46 @@ final class NodeAppModel: ObservableObject {
|
|||||||
let payload = try Self.encodePayload(["format": "png", "base64": base64])
|
let payload = try Self.encodePayload(["format": "png", "base64": base64])
|
||||||
return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload)
|
return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload)
|
||||||
|
|
||||||
|
case ClawdisCameraCommand.snap.rawValue:
|
||||||
|
let params = (try? Self.decodeParams(ClawdisCameraSnapParams.self, from: req.paramsJSON)) ??
|
||||||
|
ClawdisCameraSnapParams()
|
||||||
|
let res = try await self.camera.snap(params: params)
|
||||||
|
|
||||||
|
struct Payload: Codable {
|
||||||
|
var format: String
|
||||||
|
var base64: String
|
||||||
|
var width: Int
|
||||||
|
var height: Int
|
||||||
|
}
|
||||||
|
let payload = try Self.encodePayload(Payload(
|
||||||
|
format: res.format,
|
||||||
|
base64: res.base64,
|
||||||
|
width: res.width,
|
||||||
|
height: res.height))
|
||||||
|
return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload)
|
||||||
|
|
||||||
|
case ClawdisCameraCommand.clip.rawValue:
|
||||||
|
let params = (try? Self.decodeParams(ClawdisCameraClipParams.self, from: req.paramsJSON)) ??
|
||||||
|
ClawdisCameraClipParams()
|
||||||
|
|
||||||
|
let suspended = (params.includeAudio ?? true) ? self.voiceWake.suspendForExternalAudioCapture() : false
|
||||||
|
defer { self.voiceWake.resumeAfterExternalAudioCapture(wasSuspended: suspended) }
|
||||||
|
|
||||||
|
let res = try await self.camera.clip(params: params)
|
||||||
|
|
||||||
|
struct Payload: Codable {
|
||||||
|
var format: String
|
||||||
|
var base64: String
|
||||||
|
var durationMs: Int
|
||||||
|
var hasAudio: Bool
|
||||||
|
}
|
||||||
|
let payload = try Self.encodePayload(Payload(
|
||||||
|
format: res.format,
|
||||||
|
base64: res.base64,
|
||||||
|
durationMs: res.durationMs,
|
||||||
|
hasAudio: res.hasAudio))
|
||||||
|
return BridgeInvokeResponse(id: req.id, ok: true, payloadJSON: payload)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return BridgeInvokeResponse(
|
return BridgeInvokeResponse(
|
||||||
id: req.id,
|
id: req.id,
|
||||||
@@ -230,6 +379,17 @@ final class NodeAppModel: ObservableObject {
|
|||||||
|
|
||||||
private static func encodePayload(_ obj: some Encodable) throws -> String {
|
private static func encodePayload(_ obj: some Encodable) throws -> String {
|
||||||
let data = try JSONEncoder().encode(obj)
|
let data = try JSONEncoder().encode(obj)
|
||||||
return String(decoding: data, as: UTF8.self)
|
guard let json = String(bytes: data, encoding: .utf8) else {
|
||||||
|
throw NSError(domain: "NodeAppModel", code: 21, userInfo: [
|
||||||
|
NSLocalizedDescriptionKey: "Failed to encode payload as UTF-8",
|
||||||
|
])
|
||||||
|
}
|
||||||
|
return json
|
||||||
|
}
|
||||||
|
|
||||||
|
private func isCameraEnabled() -> Bool {
|
||||||
|
// Default-on: if the key doesn't exist yet, treat it as enabled.
|
||||||
|
if UserDefaults.standard.object(forKey: "camera.enabled") == nil { return true }
|
||||||
|
return UserDefaults.standard.bool(forKey: "camera.enabled")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,49 +1,144 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
struct RootCanvas: View {
|
struct RootCanvas: View {
|
||||||
@State private var isShowingSettings = false
|
@Environment(NodeAppModel.self) private var appModel
|
||||||
|
@Environment(VoiceWakeManager.self) private var voiceWake
|
||||||
|
@AppStorage(VoiceWakePreferences.enabledKey) private var voiceWakeEnabled: Bool = false
|
||||||
|
@State private var presentedSheet: PresentedSheet?
|
||||||
|
@State private var voiceWakeToastText: String?
|
||||||
|
@State private var toastDismissTask: Task<Void, Never>?
|
||||||
|
|
||||||
|
private enum PresentedSheet: Identifiable {
|
||||||
|
case settings
|
||||||
|
case chat
|
||||||
|
|
||||||
|
var id: Int {
|
||||||
|
switch self {
|
||||||
|
case .settings: 0
|
||||||
|
case .chat: 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
ZStack(alignment: .topTrailing) {
|
ZStack(alignment: .topTrailing) {
|
||||||
ScreenTab()
|
ScreenTab()
|
||||||
|
|
||||||
Button {
|
VStack(spacing: 10) {
|
||||||
self.isShowingSettings = true
|
OverlayButton(systemImage: "text.bubble.fill") {
|
||||||
} label: {
|
self.presentedSheet = .chat
|
||||||
Image(systemName: "gearshape.fill")
|
}
|
||||||
.font(.system(size: 16, weight: .semibold))
|
.accessibilityLabel("Chat")
|
||||||
.foregroundStyle(.primary)
|
|
||||||
.padding(10)
|
OverlayButton(systemImage: "gearshape.fill") {
|
||||||
.background {
|
self.presentedSheet = .settings
|
||||||
RoundedRectangle(cornerRadius: 12, style: .continuous)
|
}
|
||||||
.fill(.ultraThinMaterial)
|
.accessibilityLabel("Settings")
|
||||||
.overlay {
|
|
||||||
RoundedRectangle(cornerRadius: 12, style: .continuous)
|
|
||||||
.fill(
|
|
||||||
LinearGradient(
|
|
||||||
colors: [
|
|
||||||
.white.opacity(0.18),
|
|
||||||
.white.opacity(0.04),
|
|
||||||
.clear,
|
|
||||||
],
|
|
||||||
startPoint: .topLeading,
|
|
||||||
endPoint: .bottomTrailing))
|
|
||||||
.blendMode(.overlay)
|
|
||||||
}
|
|
||||||
.overlay {
|
|
||||||
RoundedRectangle(cornerRadius: 12, style: .continuous)
|
|
||||||
.strokeBorder(.white.opacity(0.18), lineWidth: 0.5)
|
|
||||||
}
|
|
||||||
.shadow(color: .black.opacity(0.35), radius: 12, y: 6)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
.buttonStyle(.plain)
|
|
||||||
.padding(.top, 10)
|
.padding(.top, 10)
|
||||||
.padding(.trailing, 10)
|
.padding(.trailing, 10)
|
||||||
.accessibilityLabel("Settings")
|
|
||||||
}
|
}
|
||||||
.sheet(isPresented: self.$isShowingSettings) {
|
.overlay(alignment: .topLeading) {
|
||||||
SettingsTab()
|
StatusPill(
|
||||||
|
bridge: self.bridgeStatus,
|
||||||
|
voiceWakeEnabled: self.voiceWakeEnabled,
|
||||||
|
onTap: { self.presentedSheet = .settings })
|
||||||
|
.padding(.leading, 10)
|
||||||
|
.safeAreaPadding(.top, 10)
|
||||||
|
}
|
||||||
|
.overlay(alignment: .topLeading) {
|
||||||
|
if let voiceWakeToastText, !voiceWakeToastText.isEmpty {
|
||||||
|
VoiceWakeToast(command: voiceWakeToastText)
|
||||||
|
.padding(.leading, 10)
|
||||||
|
.safeAreaPadding(.top, 58)
|
||||||
|
.transition(.move(edge: .top).combined(with: .opacity))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.sheet(item: self.$presentedSheet) { sheet in
|
||||||
|
switch sheet {
|
||||||
|
case .settings:
|
||||||
|
SettingsTab()
|
||||||
|
case .chat:
|
||||||
|
ChatSheet(bridge: self.appModel.bridgeSession)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.preferredColorScheme(.dark)
|
||||||
|
.onChange(of: self.voiceWake.lastTriggeredCommand) { _, newValue in
|
||||||
|
guard let newValue else { return }
|
||||||
|
let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !trimmed.isEmpty else { return }
|
||||||
|
|
||||||
|
self.toastDismissTask?.cancel()
|
||||||
|
withAnimation(.spring(response: 0.25, dampingFraction: 0.85)) {
|
||||||
|
self.voiceWakeToastText = trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
self.toastDismissTask = Task {
|
||||||
|
try? await Task.sleep(nanoseconds: 2_300_000_000)
|
||||||
|
await MainActor.run {
|
||||||
|
withAnimation(.easeOut(duration: 0.25)) {
|
||||||
|
self.voiceWakeToastText = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onDisappear {
|
||||||
|
self.toastDismissTask?.cancel()
|
||||||
|
self.toastDismissTask = nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var bridgeStatus: StatusPill.BridgeState {
|
||||||
|
if self.appModel.bridgeServerName != nil { return .connected }
|
||||||
|
|
||||||
|
let text = self.appModel.bridgeStatusText.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if text.localizedCaseInsensitiveContains("connecting") ||
|
||||||
|
text.localizedCaseInsensitiveContains("reconnecting")
|
||||||
|
{
|
||||||
|
return .connecting
|
||||||
|
}
|
||||||
|
|
||||||
|
if text.localizedCaseInsensitiveContains("error") {
|
||||||
|
return .error
|
||||||
|
}
|
||||||
|
|
||||||
|
return .disconnected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct OverlayButton: View {
|
||||||
|
let systemImage: String
|
||||||
|
let action: () -> Void
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button(action: self.action) {
|
||||||
|
Image(systemName: self.systemImage)
|
||||||
|
.font(.system(size: 16, weight: .semibold))
|
||||||
|
.foregroundStyle(.primary)
|
||||||
|
.padding(10)
|
||||||
|
.background {
|
||||||
|
RoundedRectangle(cornerRadius: 12, style: .continuous)
|
||||||
|
.fill(.ultraThinMaterial)
|
||||||
|
.overlay {
|
||||||
|
RoundedRectangle(cornerRadius: 12, style: .continuous)
|
||||||
|
.fill(
|
||||||
|
LinearGradient(
|
||||||
|
colors: [
|
||||||
|
.white.opacity(0.18),
|
||||||
|
.white.opacity(0.04),
|
||||||
|
.clear,
|
||||||
|
],
|
||||||
|
startPoint: .topLeading,
|
||||||
|
endPoint: .bottomTrailing))
|
||||||
|
.blendMode(.overlay)
|
||||||
|
}
|
||||||
|
.overlay {
|
||||||
|
RoundedRectangle(cornerRadius: 12, style: .continuous)
|
||||||
|
.strokeBorder(.white.opacity(0.18), lineWidth: 0.5)
|
||||||
|
}
|
||||||
|
.shadow(color: .black.opacity(0.35), radius: 12, y: 6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,82 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
struct RootTabs: View {
|
struct RootTabs: View {
|
||||||
|
@Environment(NodeAppModel.self) private var appModel
|
||||||
|
@Environment(VoiceWakeManager.self) private var voiceWake
|
||||||
|
@AppStorage(VoiceWakePreferences.enabledKey) private var voiceWakeEnabled: Bool = false
|
||||||
|
@State private var selectedTab: Int = 0
|
||||||
|
@State private var voiceWakeToastText: String?
|
||||||
|
@State private var toastDismissTask: Task<Void, Never>?
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
TabView {
|
TabView(selection: self.$selectedTab) {
|
||||||
ScreenTab()
|
ScreenTab()
|
||||||
.tabItem { Label("Screen", systemImage: "rectangle.and.hand.point.up.left") }
|
.tabItem { Label("Screen", systemImage: "rectangle.and.hand.point.up.left") }
|
||||||
|
.tag(0)
|
||||||
|
|
||||||
VoiceTab()
|
VoiceTab()
|
||||||
.tabItem { Label("Voice", systemImage: "mic") }
|
.tabItem { Label("Voice", systemImage: "mic") }
|
||||||
|
.tag(1)
|
||||||
|
|
||||||
SettingsTab()
|
SettingsTab()
|
||||||
.tabItem { Label("Settings", systemImage: "gearshape") }
|
.tabItem { Label("Settings", systemImage: "gearshape") }
|
||||||
|
.tag(2)
|
||||||
|
}
|
||||||
|
.overlay(alignment: .topLeading) {
|
||||||
|
StatusPill(
|
||||||
|
bridge: self.bridgeStatus,
|
||||||
|
voiceWakeEnabled: self.voiceWakeEnabled,
|
||||||
|
onTap: { self.selectedTab = 2 })
|
||||||
|
.padding(.leading, 10)
|
||||||
|
.safeAreaPadding(.top, 10)
|
||||||
|
}
|
||||||
|
.overlay(alignment: .topLeading) {
|
||||||
|
if let voiceWakeToastText, !voiceWakeToastText.isEmpty {
|
||||||
|
VoiceWakeToast(command: voiceWakeToastText)
|
||||||
|
.padding(.leading, 10)
|
||||||
|
.safeAreaPadding(.top, 58)
|
||||||
|
.transition(.move(edge: .top).combined(with: .opacity))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onChange(of: self.voiceWake.lastTriggeredCommand) { _, newValue in
|
||||||
|
guard let newValue else { return }
|
||||||
|
let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !trimmed.isEmpty else { return }
|
||||||
|
|
||||||
|
self.toastDismissTask?.cancel()
|
||||||
|
withAnimation(.spring(response: 0.25, dampingFraction: 0.85)) {
|
||||||
|
self.voiceWakeToastText = trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
self.toastDismissTask = Task {
|
||||||
|
try? await Task.sleep(nanoseconds: 2_300_000_000)
|
||||||
|
await MainActor.run {
|
||||||
|
withAnimation(.easeOut(duration: 0.25)) {
|
||||||
|
self.voiceWakeToastText = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onDisappear {
|
||||||
|
self.toastDismissTask?.cancel()
|
||||||
|
self.toastDismissTask = nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private var bridgeStatus: StatusPill.BridgeState {
|
||||||
|
if self.appModel.bridgeServerName != nil { return .connected }
|
||||||
|
|
||||||
|
let text = self.appModel.bridgeStatusText.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
if text.localizedCaseInsensitiveContains("connecting") ||
|
||||||
|
text.localizedCaseInsensitiveContains("reconnecting")
|
||||||
|
{
|
||||||
|
return .connecting
|
||||||
|
}
|
||||||
|
|
||||||
|
if text.localizedCaseInsensitiveContains("error") {
|
||||||
|
return .error
|
||||||
|
}
|
||||||
|
|
||||||
|
return .disconnected
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,23 +1,38 @@
|
|||||||
import ClawdisKit
|
import ClawdisKit
|
||||||
|
import Observation
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
import WebKit
|
import WebKit
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
final class ScreenController: ObservableObject {
|
@Observable
|
||||||
|
final class ScreenController {
|
||||||
let webView: WKWebView
|
let webView: WKWebView
|
||||||
|
private let navigationDelegate: ScreenNavigationDelegate
|
||||||
|
|
||||||
@Published var mode: ClawdisScreenMode = .canvas
|
var mode: ClawdisScreenMode = .canvas
|
||||||
@Published var urlString: String = ""
|
var urlString: String = ""
|
||||||
@Published var errorText: String?
|
var errorText: String?
|
||||||
|
|
||||||
|
/// Callback invoked when a clawdis:// deep link is tapped in the canvas
|
||||||
|
var onDeepLink: ((URL) -> Void)?
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
let config = WKWebViewConfiguration()
|
let config = WKWebViewConfiguration()
|
||||||
config.websiteDataStore = .nonPersistent()
|
config.websiteDataStore = .nonPersistent()
|
||||||
|
self.navigationDelegate = ScreenNavigationDelegate()
|
||||||
self.webView = WKWebView(frame: .zero, configuration: config)
|
self.webView = WKWebView(frame: .zero, configuration: config)
|
||||||
|
self.webView.isOpaque = false
|
||||||
|
self.webView.backgroundColor = .clear
|
||||||
|
self.webView.scrollView.backgroundColor = .clear
|
||||||
self.webView.scrollView.contentInsetAdjustmentBehavior = .never
|
self.webView.scrollView.contentInsetAdjustmentBehavior = .never
|
||||||
self.webView.scrollView.contentInset = .zero
|
self.webView.scrollView.contentInset = .zero
|
||||||
self.webView.scrollView.scrollIndicatorInsets = .zero
|
self.webView.scrollView.scrollIndicatorInsets = .zero
|
||||||
self.webView.scrollView.automaticallyAdjustsScrollIndicatorInsets = false
|
self.webView.scrollView.automaticallyAdjustsScrollIndicatorInsets = false
|
||||||
|
// Disable scroll to allow touch events to pass through to canvas
|
||||||
|
self.webView.scrollView.isScrollEnabled = false
|
||||||
|
self.webView.scrollView.bounces = false
|
||||||
|
self.webView.navigationDelegate = self.navigationDelegate
|
||||||
|
self.navigationDelegate.controller = self
|
||||||
self.reload()
|
self.reload()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,6 +109,9 @@ final class ScreenController: ObservableObject {
|
|||||||
<title>Canvas</title>
|
<title>Canvas</title>
|
||||||
<style>
|
<style>
|
||||||
:root { color-scheme: dark; }
|
:root { color-scheme: dark; }
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
body::before, body::after { animation: none !important; }
|
||||||
|
}
|
||||||
html,body { height:100%; margin:0; }
|
html,body { height:100%; margin:0; }
|
||||||
body {
|
body {
|
||||||
background: radial-gradient(1200px 900px at 15% 20%, rgba(42, 113, 255, 0.18), rgba(0,0,0,0) 55%),
|
background: radial-gradient(1200px 900px at 15% 20%, rgba(42, 113, 255, 0.18), rgba(0,0,0,0) 55%),
|
||||||
@@ -107,11 +125,38 @@ final class ScreenController: ObservableObject {
|
|||||||
position: fixed;
|
position: fixed;
|
||||||
inset: -20%;
|
inset: -20%;
|
||||||
background:
|
background:
|
||||||
repeating-linear-gradient(0deg, rgba(255,255,255,0.02) 0, rgba(255,255,255,0.02) 1px, transparent 1px, transparent 48px),
|
repeating-linear-gradient(0deg, rgba(255,255,255,0.02) 0, rgba(255,255,255,0.02) 1px,
|
||||||
repeating-linear-gradient(90deg, rgba(255,255,255,0.02) 0, rgba(255,255,255,0.02) 1px, transparent 1px, transparent 48px);
|
transparent 1px, transparent 48px),
|
||||||
|
repeating-linear-gradient(90deg, rgba(255,255,255,0.02) 0, rgba(255,255,255,0.02) 1px,
|
||||||
|
transparent 1px, transparent 48px);
|
||||||
transform: rotate(-7deg);
|
transform: rotate(-7deg);
|
||||||
opacity: 0.55;
|
opacity: 0.55;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
|
animation: clawdis-grid-drift 22s linear infinite;
|
||||||
|
}
|
||||||
|
body::after {
|
||||||
|
content:"";
|
||||||
|
position: fixed;
|
||||||
|
inset: -35%;
|
||||||
|
background:
|
||||||
|
radial-gradient(900px 700px at 30% 30%, rgba(42,113,255,0.16), rgba(0,0,0,0) 60%),
|
||||||
|
radial-gradient(800px 650px at 70% 35%, rgba(255,0,138,0.12), rgba(0,0,0,0) 62%),
|
||||||
|
radial-gradient(900px 800px at 55% 75%, rgba(0,209,255,0.10), rgba(0,0,0,0) 62%);
|
||||||
|
filter: blur(28px);
|
||||||
|
opacity: 0.55;
|
||||||
|
mix-blend-mode: screen;
|
||||||
|
pointer-events: none;
|
||||||
|
animation: clawdis-glow-drift 18s ease-in-out infinite alternate;
|
||||||
|
}
|
||||||
|
@keyframes clawdis-grid-drift {
|
||||||
|
0% { transform: translate3d(-18px, 12px, 0) rotate(-7deg); opacity: 0.50; }
|
||||||
|
50% { transform: translate3d( 14px,-10px, 0) rotate(-6.2deg); opacity: 0.62; }
|
||||||
|
100% { transform: translate3d(-10px, 8px, 0) rotate(-7.4deg); opacity: 0.52; }
|
||||||
|
}
|
||||||
|
@keyframes clawdis-glow-drift {
|
||||||
|
0% { transform: translate3d(-26px, 18px, 0) scale(1.02); opacity: 0.42; }
|
||||||
|
50% { transform: translate3d( 20px,-14px, 0) scale(1.05); opacity: 0.55; }
|
||||||
|
100% { transform: translate3d(-12px, 10px, 0) scale(1.03); opacity: 0.46; }
|
||||||
}
|
}
|
||||||
canvas {
|
canvas {
|
||||||
display:block;
|
display:block;
|
||||||
@@ -188,6 +233,11 @@ final class ScreenController: ObservableObject {
|
|||||||
statusEl.style.display = 'grid';
|
statusEl.style.display = 'grid';
|
||||||
if (titleEl && typeof title === 'string') titleEl.textContent = title;
|
if (titleEl && typeof title === 'string') titleEl.textContent = title;
|
||||||
if (subtitleEl && typeof subtitle === 'string') subtitleEl.textContent = subtitle;
|
if (subtitleEl && typeof subtitle === 'string') subtitleEl.textContent = subtitle;
|
||||||
|
// Auto-hide after 3 seconds
|
||||||
|
clearTimeout(window.__statusTimeout);
|
||||||
|
window.__statusTimeout = setTimeout(() => {
|
||||||
|
statusEl.style.display = 'none';
|
||||||
|
}, 3000);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
})();
|
})();
|
||||||
@@ -196,3 +246,32 @@ final class ScreenController: ObservableObject {
|
|||||||
</html>
|
</html>
|
||||||
"""
|
"""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Navigation Delegate
|
||||||
|
|
||||||
|
/// Handles navigation policy to intercept clawdis:// deep links from canvas
|
||||||
|
private final class ScreenNavigationDelegate: NSObject, WKNavigationDelegate {
|
||||||
|
weak var controller: ScreenController?
|
||||||
|
|
||||||
|
func webView(
|
||||||
|
_ webView: WKWebView,
|
||||||
|
decidePolicyFor navigationAction: WKNavigationAction,
|
||||||
|
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
|
||||||
|
{
|
||||||
|
guard let url = navigationAction.request.url else {
|
||||||
|
decisionHandler(.allow)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Intercept clawdis:// deep links
|
||||||
|
if url.scheme == "clawdis" {
|
||||||
|
decisionHandler(.cancel)
|
||||||
|
Task { @MainActor in
|
||||||
|
self.controller?.onDeepLink?(url)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
decisionHandler(.allow)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ import ClawdisKit
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
struct ScreenTab: View {
|
struct ScreenTab: View {
|
||||||
@EnvironmentObject private var appModel: NodeAppModel
|
@Environment(NodeAppModel.self) private var appModel
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
ZStack(alignment: .top) {
|
ZStack(alignment: .top) {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import SwiftUI
|
|||||||
import WebKit
|
import WebKit
|
||||||
|
|
||||||
struct ScreenWebView: UIViewRepresentable {
|
struct ScreenWebView: UIViewRepresentable {
|
||||||
@ObservedObject var controller: ScreenController
|
var controller: ScreenController
|
||||||
|
|
||||||
func makeUIView(context: Context) -> WKWebView {
|
func makeUIView(context: Context) -> WKWebView {
|
||||||
self.controller.webView
|
self.controller.webView
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
struct SettingsHostPort: Equatable {
|
||||||
|
var host: String
|
||||||
|
var port: Int
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SettingsNetworkingHelpers {
|
||||||
|
static func parseHostPort(from address: String) -> SettingsHostPort? {
|
||||||
|
let trimmed = address.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !trimmed.isEmpty else { return nil }
|
||||||
|
|
||||||
|
if trimmed.hasPrefix("["),
|
||||||
|
let close = trimmed.firstIndex(of: "]"),
|
||||||
|
close < trimmed.endIndex
|
||||||
|
{
|
||||||
|
let host = String(trimmed[trimmed.index(after: trimmed.startIndex)..<close])
|
||||||
|
let portStart = trimmed.index(after: close)
|
||||||
|
guard portStart < trimmed.endIndex, trimmed[portStart] == ":" else { return nil }
|
||||||
|
let portString = String(trimmed[trimmed.index(after: portStart)...])
|
||||||
|
guard let port = Int(portString) else { return nil }
|
||||||
|
return SettingsHostPort(host: host, port: port)
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let colon = trimmed.lastIndex(of: ":") else { return nil }
|
||||||
|
let host = String(trimmed[..<colon])
|
||||||
|
let portString = String(trimmed[trimmed.index(after: colon)...])
|
||||||
|
guard !host.isEmpty, let port = Int(portString) else { return nil }
|
||||||
|
return SettingsHostPort(host: host, port: port)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func httpURLString(host: String?, port: Int?, fallback: String) -> String {
|
||||||
|
if let host, let port {
|
||||||
|
let needsBrackets = host.contains(":") && !host.hasPrefix("[") && !host.hasSuffix("]")
|
||||||
|
let hostPart = needsBrackets ? "[\(host)]" : host
|
||||||
|
return "http://\(hostPart):\(port)"
|
||||||
|
}
|
||||||
|
return "http://\(fallback)"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +1,35 @@
|
|||||||
|
import ClawdisKit
|
||||||
|
import Network
|
||||||
|
import Observation
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import UIKit
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Observable
|
||||||
|
private final class ConnectStatusStore {
|
||||||
|
var text: String?
|
||||||
|
}
|
||||||
|
|
||||||
|
extension ConnectStatusStore: @unchecked Sendable {}
|
||||||
|
|
||||||
struct SettingsTab: View {
|
struct SettingsTab: View {
|
||||||
@EnvironmentObject private var appModel: NodeAppModel
|
@Environment(NodeAppModel.self) private var appModel: NodeAppModel
|
||||||
|
@Environment(VoiceWakeManager.self) private var voiceWake: VoiceWakeManager
|
||||||
|
@Environment(BridgeConnectionController.self) private var bridgeController: BridgeConnectionController
|
||||||
@Environment(\.dismiss) private var dismiss
|
@Environment(\.dismiss) private var dismiss
|
||||||
@AppStorage("node.displayName") private var displayName: String = "iOS Node"
|
@AppStorage("node.displayName") private var displayName: String = "iOS Node"
|
||||||
@AppStorage("node.instanceId") private var instanceId: String = UUID().uuidString
|
@AppStorage("node.instanceId") private var instanceId: String = UUID().uuidString
|
||||||
@AppStorage("voiceWake.enabled") private var voiceWakeEnabled: Bool = false
|
@AppStorage("voiceWake.enabled") private var voiceWakeEnabled: Bool = false
|
||||||
@StateObject private var discovery = BridgeDiscoveryModel()
|
@AppStorage("camera.enabled") private var cameraEnabled: Bool = true
|
||||||
@State private var connectStatus: String?
|
@AppStorage("bridge.preferredStableID") private var preferredBridgeStableID: String = ""
|
||||||
@State private var isConnecting = false
|
@AppStorage("bridge.lastDiscoveredStableID") private var lastDiscoveredBridgeStableID: String = ""
|
||||||
@State private var didAutoConnect = false
|
@AppStorage("bridge.manual.enabled") private var manualBridgeEnabled: Bool = false
|
||||||
@State private var isShowingBridgeList = false
|
@AppStorage("bridge.manual.host") private var manualBridgeHost: String = ""
|
||||||
|
@AppStorage("bridge.manual.port") private var manualBridgePort: Int = 18790
|
||||||
|
@AppStorage("bridge.discovery.debugLogs") private var discoveryDebugLogsEnabled: Bool = false
|
||||||
|
@State private var connectStatus = ConnectStatusStore()
|
||||||
|
@State private var connectingBridgeID: String?
|
||||||
|
@State private var localIPAddress: String?
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
NavigationStack {
|
NavigationStack {
|
||||||
@@ -20,6 +39,16 @@ struct SettingsTab: View {
|
|||||||
Text(self.instanceId)
|
Text(self.instanceId)
|
||||||
.font(.footnote)
|
.font(.footnote)
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
|
LabeledContent("IP", value: self.localIPAddress ?? "—")
|
||||||
|
.contextMenu {
|
||||||
|
if let ip = self.localIPAddress {
|
||||||
|
Button {
|
||||||
|
UIPasteboard.general.string = ip
|
||||||
|
} label: {
|
||||||
|
Label("Copy", systemImage: "doc.on.doc")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Section("Voice") {
|
Section("Voice") {
|
||||||
@@ -27,30 +56,114 @@ struct SettingsTab: View {
|
|||||||
.onChange(of: self.voiceWakeEnabled) { _, newValue in
|
.onChange(of: self.voiceWakeEnabled) { _, newValue in
|
||||||
self.appModel.setVoiceWakeEnabled(newValue)
|
self.appModel.setVoiceWakeEnabled(newValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
NavigationLink {
|
||||||
|
VoiceWakeWordsSettingsView()
|
||||||
|
} label: {
|
||||||
|
LabeledContent(
|
||||||
|
"Wake Words",
|
||||||
|
value: VoiceWakePreferences.displayString(for: self.voiceWake.triggerWords))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Section("Camera") {
|
||||||
|
Toggle("Allow Camera", isOn: self.$cameraEnabled)
|
||||||
|
Text("Allows the bridge to request photos or short video clips (foreground only).")
|
||||||
|
.font(.footnote)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
}
|
}
|
||||||
|
|
||||||
Section("Bridge") {
|
Section("Bridge") {
|
||||||
LabeledContent("Discovery", value: self.discovery.statusText)
|
LabeledContent("Discovery", value: self.bridgeController.discoveryStatusText)
|
||||||
LabeledContent("Status", value: self.appModel.bridgeStatusText)
|
LabeledContent("Status", value: self.appModel.bridgeStatusText)
|
||||||
if let serverName = self.appModel.bridgeServerName {
|
if let serverName = self.appModel.bridgeServerName {
|
||||||
LabeledContent("Server", value: serverName)
|
LabeledContent("Server", value: serverName)
|
||||||
|
if let addr = self.appModel.bridgeRemoteAddress {
|
||||||
|
let parts = Self.parseHostPort(from: addr)
|
||||||
|
let urlString = Self.httpURLString(host: parts?.host, port: parts?.port, fallback: addr)
|
||||||
|
LabeledContent("Address") {
|
||||||
|
Text(urlString)
|
||||||
|
}
|
||||||
|
.contextMenu {
|
||||||
|
Button {
|
||||||
|
UIPasteboard.general.string = urlString
|
||||||
|
} label: {
|
||||||
|
Label("Copy URL", systemImage: "doc.on.doc")
|
||||||
|
}
|
||||||
|
|
||||||
|
if let parts {
|
||||||
|
Button {
|
||||||
|
UIPasteboard.general.string = parts.host
|
||||||
|
} label: {
|
||||||
|
Label("Copy Host", systemImage: "doc.on.doc")
|
||||||
|
}
|
||||||
|
|
||||||
|
Button {
|
||||||
|
UIPasteboard.general.string = "\(parts.port)"
|
||||||
|
} label: {
|
||||||
|
Label("Copy Port", systemImage: "doc.on.doc")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Button("Disconnect", role: .destructive) {
|
Button("Disconnect", role: .destructive) {
|
||||||
self.appModel.disconnectBridge()
|
self.appModel.disconnectBridge()
|
||||||
}
|
}
|
||||||
|
|
||||||
DisclosureGroup("Switch bridge", isExpanded: self.$isShowingBridgeList) {
|
self.bridgeList(showing: .availableOnly)
|
||||||
self.bridgeList(showConnectedRow: true)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
self.bridgeList(showConnectedRow: false)
|
self.bridgeList(showing: .all)
|
||||||
}
|
}
|
||||||
|
|
||||||
if let connectStatus {
|
if let text = self.connectStatus.text {
|
||||||
Text(connectStatus)
|
Text(text)
|
||||||
.font(.footnote)
|
.font(.footnote)
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
DisclosureGroup("Advanced") {
|
||||||
|
Toggle("Use Manual Bridge", isOn: self.$manualBridgeEnabled)
|
||||||
|
|
||||||
|
TextField("Host", text: self.$manualBridgeHost)
|
||||||
|
.textInputAutocapitalization(.never)
|
||||||
|
.autocorrectionDisabled()
|
||||||
|
|
||||||
|
TextField("Port", value: self.$manualBridgePort, format: .number)
|
||||||
|
.keyboardType(.numberPad)
|
||||||
|
|
||||||
|
Button {
|
||||||
|
Task { await self.connectManual() }
|
||||||
|
} label: {
|
||||||
|
if self.connectingBridgeID == "manual" {
|
||||||
|
HStack(spacing: 8) {
|
||||||
|
ProgressView()
|
||||||
|
.progressViewStyle(.circular)
|
||||||
|
Text("Connecting…")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Text("Connect (Manual)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.disabled(self.connectingBridgeID != nil || self.manualBridgeHost
|
||||||
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
.isEmpty || self.manualBridgePort <= 0 || self.manualBridgePort > 65535)
|
||||||
|
|
||||||
|
Text(
|
||||||
|
"Use this when mDNS/Bonjour discovery is blocked. "
|
||||||
|
+ "The bridge runs on the gateway (default port 18790).")
|
||||||
|
.font(.footnote)
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
|
||||||
|
Toggle("Discovery Debug Logs", isOn: self.$discoveryDebugLogsEnabled)
|
||||||
|
.onChange(of: self.discoveryDebugLogsEnabled) { _, newValue in
|
||||||
|
self.bridgeController.setDiscoveryDebugLoggingEnabled(newValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
NavigationLink("Discovery Logs") {
|
||||||
|
BridgeDiscoveryDebugLogView()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.navigationTitle("Settings")
|
.navigationTitle("Settings")
|
||||||
@@ -64,79 +177,68 @@ struct SettingsTab: View {
|
|||||||
.accessibilityLabel("Close")
|
.accessibilityLabel("Close")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.onAppear { self.discovery.start() }
|
.onAppear {
|
||||||
.onDisappear { self.discovery.stop() }
|
self.localIPAddress = Self.primaryIPv4Address()
|
||||||
.onChange(of: self.discovery.bridges) { _, newValue in
|
}
|
||||||
if self.didAutoConnect { return }
|
.onChange(of: self.preferredBridgeStableID) { _, newValue in
|
||||||
if self.appModel.bridgeServerName != nil { return }
|
let trimmed = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !trimmed.isEmpty else { return }
|
||||||
let existing = KeychainStore.loadString(
|
BridgeSettingsStore.savePreferredBridgeStableID(trimmed)
|
||||||
service: "com.steipete.clawdis.bridge",
|
|
||||||
account: self.keychainAccount())
|
|
||||||
guard let existing, !existing.isEmpty else { return }
|
|
||||||
guard let first = newValue.first else { return }
|
|
||||||
|
|
||||||
self.didAutoConnect = true
|
|
||||||
self.appModel.connectToBridge(
|
|
||||||
endpoint: first.endpoint,
|
|
||||||
token: existing,
|
|
||||||
nodeId: self.instanceId,
|
|
||||||
displayName: self.displayName,
|
|
||||||
platform: self.platformString(),
|
|
||||||
version: self.appVersion())
|
|
||||||
self.connectStatus = nil
|
|
||||||
}
|
}
|
||||||
.onChange(of: self.appModel.bridgeServerName) { _, _ in
|
.onChange(of: self.appModel.bridgeServerName) { _, _ in
|
||||||
self.connectStatus = nil
|
self.connectStatus.text = nil
|
||||||
self.isShowingBridgeList = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ViewBuilder
|
@ViewBuilder
|
||||||
private func bridgeList(showConnectedRow: Bool) -> some View {
|
private func bridgeList(showing: BridgeListMode) -> some View {
|
||||||
if self.discovery.bridges.isEmpty {
|
if self.bridgeController.bridges.isEmpty {
|
||||||
Text("No bridges found yet.")
|
Text("No bridges found yet.")
|
||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
} else {
|
} else {
|
||||||
ForEach(self.discovery.bridges) { bridge in
|
let connectedID = self.appModel.connectedBridgeID
|
||||||
let isConnected = self.isConnectedBridge(bridge)
|
let rows = self.bridgeController.bridges.filter { bridge in
|
||||||
if isConnected, !showConnectedRow {
|
let isConnected = bridge.stableID == connectedID
|
||||||
EmptyView()
|
switch showing {
|
||||||
} else {
|
case .all:
|
||||||
|
return true
|
||||||
|
case .availableOnly:
|
||||||
|
return !isConnected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if rows.isEmpty, showing == .availableOnly {
|
||||||
|
Text("No other bridges found.")
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
} else {
|
||||||
|
ForEach(rows) { bridge in
|
||||||
HStack {
|
HStack {
|
||||||
VStack(alignment: .leading, spacing: 2) {
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
Text(bridge.name)
|
Text(bridge.name)
|
||||||
Text(bridge.debugID)
|
|
||||||
.font(.caption2)
|
|
||||||
.foregroundStyle(.secondary)
|
|
||||||
.lineLimit(1)
|
|
||||||
}
|
}
|
||||||
Spacer()
|
Spacer()
|
||||||
|
|
||||||
if isConnected {
|
Button {
|
||||||
Image(systemName: "checkmark.circle.fill")
|
Task { await self.connect(bridge) }
|
||||||
.foregroundStyle(.green)
|
} label: {
|
||||||
.accessibilityLabel("Connected")
|
if self.connectingBridgeID == bridge.id {
|
||||||
} else {
|
ProgressView()
|
||||||
Button(self.isConnecting ? "…" : "Connect") {
|
.progressViewStyle(.circular)
|
||||||
Task { await self.connect(bridge) }
|
} else {
|
||||||
|
Text("Connect")
|
||||||
}
|
}
|
||||||
.disabled(self.isConnecting)
|
|
||||||
}
|
}
|
||||||
|
.disabled(self.connectingBridgeID != nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func isConnectedBridge(_ bridge: BridgeDiscoveryModel.DiscoveredBridge) -> Bool {
|
private enum BridgeListMode: Equatable {
|
||||||
guard let serverName = self.appModel.bridgeServerName?.trimmingCharacters(in: .whitespacesAndNewlines),
|
case all
|
||||||
!serverName.isEmpty
|
case availableOnly
|
||||||
else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return bridge.name.localizedCaseInsensitiveContains(serverName)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func keychainAccount() -> String {
|
private func keychainAccount() -> String {
|
||||||
@@ -153,44 +255,168 @@ struct SettingsTab: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func connect(_ bridge: BridgeDiscoveryModel.DiscoveredBridge) async {
|
private func connect(_ bridge: BridgeDiscoveryModel.DiscoveredBridge) async {
|
||||||
self.isConnecting = true
|
self.connectingBridgeID = bridge.id
|
||||||
defer { self.isConnecting = false }
|
self.manualBridgeEnabled = false
|
||||||
|
self.preferredBridgeStableID = bridge.stableID
|
||||||
|
BridgeSettingsStore.savePreferredBridgeStableID(bridge.stableID)
|
||||||
|
self.lastDiscoveredBridgeStableID = bridge.stableID
|
||||||
|
BridgeSettingsStore.saveLastDiscoveredBridgeStableID(bridge.stableID)
|
||||||
|
defer { self.connectingBridgeID = nil }
|
||||||
|
|
||||||
let existing = KeychainStore.loadString(service: "com.steipete.clawdis.bridge", account: self.keychainAccount())
|
|
||||||
do {
|
do {
|
||||||
let token: String
|
let statusStore = self.connectStatus
|
||||||
if let existing, !existing.isEmpty {
|
let existing = KeychainStore.loadString(
|
||||||
token = existing
|
service: "com.steipete.clawdis.bridge",
|
||||||
} else {
|
account: self.keychainAccount())
|
||||||
let newToken = try await BridgeClient().pairAndHello(
|
let existingToken = (existing?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false) ?
|
||||||
endpoint: bridge.endpoint,
|
existing :
|
||||||
nodeId: self.instanceId,
|
nil
|
||||||
displayName: self.displayName,
|
|
||||||
platform: self.platformString(),
|
let hello = BridgeHello(
|
||||||
version: self.appVersion(),
|
nodeId: self.instanceId,
|
||||||
existingToken: nil)
|
displayName: self.displayName,
|
||||||
guard !newToken.isEmpty else {
|
token: existingToken,
|
||||||
self.connectStatus = "Pairing failed: empty token"
|
platform: self.platformString(),
|
||||||
return
|
version: self.appVersion())
|
||||||
}
|
let token = try await BridgeClient().pairAndHello(
|
||||||
|
endpoint: bridge.endpoint,
|
||||||
|
hello: hello,
|
||||||
|
onStatus: { status in
|
||||||
|
Task { @MainActor in
|
||||||
|
statusStore.text = status
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if !token.isEmpty, token != existingToken {
|
||||||
_ = KeychainStore.saveString(
|
_ = KeychainStore.saveString(
|
||||||
newToken,
|
token,
|
||||||
service: "com.steipete.clawdis.bridge",
|
service: "com.steipete.clawdis.bridge",
|
||||||
account: self.keychainAccount())
|
account: self.keychainAccount())
|
||||||
token = newToken
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.appModel.connectToBridge(
|
self.appModel.connectToBridge(
|
||||||
endpoint: bridge.endpoint,
|
endpoint: bridge.endpoint,
|
||||||
token: token,
|
hello: BridgeHello(
|
||||||
nodeId: self.instanceId,
|
nodeId: self.instanceId,
|
||||||
displayName: self.displayName,
|
displayName: self.displayName,
|
||||||
platform: self.platformString(),
|
token: token,
|
||||||
version: self.appVersion())
|
platform: self.platformString(),
|
||||||
|
version: self.appVersion()))
|
||||||
|
|
||||||
self.connectStatus = "Connected"
|
|
||||||
} catch {
|
} catch {
|
||||||
self.connectStatus = "Failed: \(error.localizedDescription)"
|
self.connectStatus.text = "Failed: \(error.localizedDescription)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func connectManual() async {
|
||||||
|
let host = self.manualBridgeHost.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !host.isEmpty else {
|
||||||
|
self.connectStatus.text = "Failed: host required"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard self.manualBridgePort > 0, self.manualBridgePort <= 65535 else {
|
||||||
|
self.connectStatus.text = "Failed: invalid port"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard let port = NWEndpoint.Port(rawValue: UInt16(self.manualBridgePort)) else {
|
||||||
|
self.connectStatus.text = "Failed: invalid port"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
self.connectingBridgeID = "manual"
|
||||||
|
self.manualBridgeEnabled = true
|
||||||
|
defer { self.connectingBridgeID = nil }
|
||||||
|
|
||||||
|
let endpoint: NWEndpoint = .hostPort(host: NWEndpoint.Host(host), port: port)
|
||||||
|
|
||||||
|
do {
|
||||||
|
let statusStore = self.connectStatus
|
||||||
|
let existing = KeychainStore.loadString(
|
||||||
|
service: "com.steipete.clawdis.bridge",
|
||||||
|
account: self.keychainAccount())
|
||||||
|
let existingToken = (existing?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false) ?
|
||||||
|
existing :
|
||||||
|
nil
|
||||||
|
|
||||||
|
let hello = BridgeHello(
|
||||||
|
nodeId: self.instanceId,
|
||||||
|
displayName: self.displayName,
|
||||||
|
token: existingToken,
|
||||||
|
platform: self.platformString(),
|
||||||
|
version: self.appVersion())
|
||||||
|
let token = try await BridgeClient().pairAndHello(
|
||||||
|
endpoint: endpoint,
|
||||||
|
hello: hello,
|
||||||
|
onStatus: { status in
|
||||||
|
Task { @MainActor in
|
||||||
|
statusStore.text = status
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if !token.isEmpty, token != existingToken {
|
||||||
|
_ = KeychainStore.saveString(
|
||||||
|
token,
|
||||||
|
service: "com.steipete.clawdis.bridge",
|
||||||
|
account: self.keychainAccount())
|
||||||
|
}
|
||||||
|
|
||||||
|
self.appModel.connectToBridge(
|
||||||
|
endpoint: endpoint,
|
||||||
|
hello: BridgeHello(
|
||||||
|
nodeId: self.instanceId,
|
||||||
|
displayName: self.displayName,
|
||||||
|
token: token,
|
||||||
|
platform: self.platformString(),
|
||||||
|
version: self.appVersion()))
|
||||||
|
|
||||||
|
} catch {
|
||||||
|
self.connectStatus.text = "Failed: \(error.localizedDescription)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func primaryIPv4Address() -> String? {
|
||||||
|
var addrList: UnsafeMutablePointer<ifaddrs>?
|
||||||
|
guard getifaddrs(&addrList) == 0, let first = addrList else { return nil }
|
||||||
|
defer { freeifaddrs(addrList) }
|
||||||
|
|
||||||
|
var fallback: String?
|
||||||
|
var en0: String?
|
||||||
|
|
||||||
|
for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
|
||||||
|
let flags = Int32(ptr.pointee.ifa_flags)
|
||||||
|
let isUp = (flags & IFF_UP) != 0
|
||||||
|
let isLoopback = (flags & IFF_LOOPBACK) != 0
|
||||||
|
let name = String(cString: ptr.pointee.ifa_name)
|
||||||
|
let family = ptr.pointee.ifa_addr.pointee.sa_family
|
||||||
|
if !isUp || isLoopback || family != UInt8(AF_INET) { continue }
|
||||||
|
|
||||||
|
var addr = ptr.pointee.ifa_addr.pointee
|
||||||
|
var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
|
||||||
|
let result = getnameinfo(
|
||||||
|
&addr,
|
||||||
|
socklen_t(ptr.pointee.ifa_addr.pointee.sa_len),
|
||||||
|
&buffer,
|
||||||
|
socklen_t(buffer.count),
|
||||||
|
nil,
|
||||||
|
0,
|
||||||
|
NI_NUMERICHOST)
|
||||||
|
guard result == 0 else { continue }
|
||||||
|
let len = buffer.prefix { $0 != 0 }
|
||||||
|
let bytes = len.map { UInt8(bitPattern: $0) }
|
||||||
|
guard let ip = String(bytes: bytes, encoding: .utf8) else { continue }
|
||||||
|
|
||||||
|
if name == "en0" { en0 = ip; break }
|
||||||
|
if fallback == nil { fallback = ip }
|
||||||
|
}
|
||||||
|
|
||||||
|
return en0 ?? fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func parseHostPort(from address: String) -> SettingsHostPort? {
|
||||||
|
SettingsNetworkingHelpers.parseHostPort(from: address)
|
||||||
|
}
|
||||||
|
|
||||||
|
private static func httpURLString(host: String?, port: Int?, fallback: String) -> String {
|
||||||
|
SettingsNetworkingHelpers.httpURLString(host: host, port: port, fallback: fallback)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct VoiceWakeWordsSettingsView: View {
|
||||||
|
@Environment(NodeAppModel.self) private var appModel
|
||||||
|
@State private var triggerWords: [String] = VoiceWakePreferences.loadTriggerWords()
|
||||||
|
@State private var syncTask: Task<Void, Never>?
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Form {
|
||||||
|
Section {
|
||||||
|
ForEach(self.triggerWords.indices, id: \.self) { index in
|
||||||
|
TextField("Wake word", text: self.binding(for: index))
|
||||||
|
.textInputAutocapitalization(.never)
|
||||||
|
.autocorrectionDisabled()
|
||||||
|
}
|
||||||
|
.onDelete(perform: self.removeWords)
|
||||||
|
|
||||||
|
Button {
|
||||||
|
self.addWord()
|
||||||
|
} label: {
|
||||||
|
Label("Add word", systemImage: "plus")
|
||||||
|
}
|
||||||
|
.disabled(self.triggerWords
|
||||||
|
.contains(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }))
|
||||||
|
|
||||||
|
Button("Reset defaults") {
|
||||||
|
self.triggerWords = VoiceWakePreferences.defaultTriggerWords
|
||||||
|
}
|
||||||
|
} header: {
|
||||||
|
Text("Wake Words")
|
||||||
|
} footer: {
|
||||||
|
Text(
|
||||||
|
"Clawdis reacts when any trigger appears in a transcription. "
|
||||||
|
+ "Keep them short to avoid false positives.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.navigationTitle("Wake Words")
|
||||||
|
.toolbar { EditButton() }
|
||||||
|
.onAppear {
|
||||||
|
if self.triggerWords.isEmpty {
|
||||||
|
self.triggerWords = VoiceWakePreferences.defaultTriggerWords
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onChange(of: self.triggerWords) { _, newValue in
|
||||||
|
// Keep local voice wake responsive even if bridge isn't connected yet.
|
||||||
|
VoiceWakePreferences.saveTriggerWords(newValue)
|
||||||
|
|
||||||
|
let snapshot = VoiceWakePreferences.sanitizeTriggerWords(newValue)
|
||||||
|
self.syncTask?.cancel()
|
||||||
|
self.syncTask = Task { [snapshot, weak appModel = self.appModel] in
|
||||||
|
try? await Task.sleep(nanoseconds: 650_000_000)
|
||||||
|
await appModel?.setGlobalWakeWords(snapshot)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func addWord() {
|
||||||
|
self.triggerWords.append("")
|
||||||
|
}
|
||||||
|
|
||||||
|
private func removeWords(at offsets: IndexSet) {
|
||||||
|
self.triggerWords.remove(atOffsets: offsets)
|
||||||
|
if self.triggerWords.isEmpty {
|
||||||
|
self.triggerWords = VoiceWakePreferences.defaultTriggerWords
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func binding(for index: Int) -> Binding<String> {
|
||||||
|
Binding(
|
||||||
|
get: {
|
||||||
|
guard self.triggerWords.indices.contains(index) else { return "" }
|
||||||
|
return self.triggerWords[index]
|
||||||
|
},
|
||||||
|
set: { newValue in
|
||||||
|
guard self.triggerWords.indices.contains(index) else { return }
|
||||||
|
self.triggerWords[index] = newValue
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct StatusPill: View {
|
||||||
|
enum BridgeState: Equatable {
|
||||||
|
case connected
|
||||||
|
case connecting
|
||||||
|
case error
|
||||||
|
case disconnected
|
||||||
|
|
||||||
|
var title: String {
|
||||||
|
switch self {
|
||||||
|
case .connected: "Connected"
|
||||||
|
case .connecting: "Connecting…"
|
||||||
|
case .error: "Error"
|
||||||
|
case .disconnected: "Offline"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var color: Color {
|
||||||
|
switch self {
|
||||||
|
case .connected: .green
|
||||||
|
case .connecting: .yellow
|
||||||
|
case .error: .red
|
||||||
|
case .disconnected: .gray
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var bridge: BridgeState
|
||||||
|
var voiceWakeEnabled: Bool
|
||||||
|
var onTap: () -> Void
|
||||||
|
|
||||||
|
@State private var pulse: Bool = false
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
Button(action: self.onTap) {
|
||||||
|
HStack(spacing: 10) {
|
||||||
|
HStack(spacing: 8) {
|
||||||
|
Circle()
|
||||||
|
.fill(self.bridge.color)
|
||||||
|
.frame(width: 9, height: 9)
|
||||||
|
.scaleEffect(self.bridge == .connecting ? (self.pulse ? 1.15 : 0.85) : 1.0)
|
||||||
|
.opacity(self.bridge == .connecting ? (self.pulse ? 1.0 : 0.6) : 1.0)
|
||||||
|
|
||||||
|
Text(self.bridge.title)
|
||||||
|
.font(.system(size: 13, weight: .semibold))
|
||||||
|
.foregroundStyle(.primary)
|
||||||
|
}
|
||||||
|
|
||||||
|
Divider()
|
||||||
|
.frame(height: 14)
|
||||||
|
.opacity(0.35)
|
||||||
|
|
||||||
|
Image(systemName: self.voiceWakeEnabled ? "mic.fill" : "mic.slash")
|
||||||
|
.font(.system(size: 13, weight: .semibold))
|
||||||
|
.foregroundStyle(self.voiceWakeEnabled ? .primary : .secondary)
|
||||||
|
.accessibilityLabel(self.voiceWakeEnabled ? "Voice Wake enabled" : "Voice Wake disabled")
|
||||||
|
}
|
||||||
|
.padding(.vertical, 8)
|
||||||
|
.padding(.horizontal, 12)
|
||||||
|
.background {
|
||||||
|
RoundedRectangle(cornerRadius: 14, style: .continuous)
|
||||||
|
.fill(.ultraThinMaterial)
|
||||||
|
.overlay {
|
||||||
|
RoundedRectangle(cornerRadius: 14, style: .continuous)
|
||||||
|
.strokeBorder(.white.opacity(0.18), lineWidth: 0.5)
|
||||||
|
}
|
||||||
|
.shadow(color: .black.opacity(0.25), radius: 12, y: 6)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.buttonStyle(.plain)
|
||||||
|
.accessibilityLabel("Status")
|
||||||
|
.accessibilityValue("\(self.bridge.title), Voice Wake \(self.voiceWakeEnabled ? "enabled" : "disabled")")
|
||||||
|
.onAppear { self.updatePulse(for: self.bridge) }
|
||||||
|
.onChange(of: self.bridge) { _, newValue in
|
||||||
|
self.updatePulse(for: newValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func updatePulse(for bridge: BridgeState) {
|
||||||
|
guard bridge == .connecting else {
|
||||||
|
withAnimation(.easeOut(duration: 0.2)) { self.pulse = false }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
guard !self.pulse else { return }
|
||||||
|
withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) {
|
||||||
|
self.pulse = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct VoiceWakeToast: View {
|
||||||
|
var command: String
|
||||||
|
|
||||||
|
var body: some View {
|
||||||
|
HStack(spacing: 10) {
|
||||||
|
Image(systemName: "mic.fill")
|
||||||
|
.font(.system(size: 14, weight: .semibold))
|
||||||
|
.foregroundStyle(.primary)
|
||||||
|
|
||||||
|
Text(self.command)
|
||||||
|
.font(.system(size: 14, weight: .semibold))
|
||||||
|
.foregroundStyle(.primary)
|
||||||
|
.lineLimit(1)
|
||||||
|
.truncationMode(.tail)
|
||||||
|
}
|
||||||
|
.padding(.vertical, 10)
|
||||||
|
.padding(.horizontal, 12)
|
||||||
|
.background {
|
||||||
|
RoundedRectangle(cornerRadius: 14, style: .continuous)
|
||||||
|
.fill(.ultraThinMaterial)
|
||||||
|
.overlay {
|
||||||
|
RoundedRectangle(cornerRadius: 14, style: .continuous)
|
||||||
|
.strokeBorder(.white.opacity(0.18), lineWidth: 0.5)
|
||||||
|
}
|
||||||
|
.shadow(color: .black.opacity(0.25), radius: 12, y: 6)
|
||||||
|
}
|
||||||
|
.accessibilityLabel("Voice Wake")
|
||||||
|
.accessibilityValue(self.command)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
|
||||||
struct VoiceTab: View {
|
struct VoiceTab: View {
|
||||||
@EnvironmentObject private var appModel: NodeAppModel
|
@Environment(NodeAppModel.self) private var appModel
|
||||||
@EnvironmentObject private var voiceWake: VoiceWakeManager
|
@Environment(VoiceWakeManager.self) private var voiceWake
|
||||||
@AppStorage("voiceWake.enabled") private var voiceWakeEnabled: Bool = false
|
@AppStorage("voiceWake.enabled") private var voiceWakeEnabled: Bool = false
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -17,8 +17,19 @@ struct VoiceTab: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Section("Notes") {
|
Section("Notes") {
|
||||||
Text("Say “clawdis …” to trigger.")
|
let triggers = self.voiceWake.activeTriggerWords
|
||||||
.foregroundStyle(.secondary)
|
Group {
|
||||||
|
if triggers.isEmpty {
|
||||||
|
Text("Add wake words in Settings.")
|
||||||
|
} else if triggers.count == 1 {
|
||||||
|
Text("Say “\(triggers[0]) …” to trigger.")
|
||||||
|
} else if triggers.count == 2 {
|
||||||
|
Text("Say “\(triggers[0]) …” or “\(triggers[1]) …” to trigger.")
|
||||||
|
} else {
|
||||||
|
Text("Say “\(triggers.joined(separator: " …”, “")) …” to trigger.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.navigationTitle("Voice")
|
.navigationTitle("Voice")
|
||||||
|
|||||||
@@ -1,40 +1,131 @@
|
|||||||
import AVFAudio
|
import AVFAudio
|
||||||
import Foundation
|
import Foundation
|
||||||
|
import Observation
|
||||||
import Speech
|
import Speech
|
||||||
|
|
||||||
enum SpeechAudioTapFactory {
|
private func makeAudioTapEnqueueCallback(queue: AudioBufferQueue) -> @Sendable (AVAudioPCMBuffer, AVAudioTime) -> Void {
|
||||||
static func makeAppendTap(requestBox: SpeechRequestBox) -> @Sendable (AVAudioPCMBuffer, AVAudioTime) -> Void {
|
{ buffer, _ in
|
||||||
{ buffer, _ in
|
// This callback is invoked on a realtime audio thread/queue. Keep it tiny and nonisolated.
|
||||||
requestBox.append(buffer)
|
queue.enqueueCopy(of: buffer)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
final class SpeechRequestBox: @unchecked Sendable {
|
private final class AudioBufferQueue: @unchecked Sendable {
|
||||||
let request: SFSpeechAudioBufferRecognitionRequest
|
private let lock = NSLock()
|
||||||
|
private var buffers: [AVAudioPCMBuffer] = []
|
||||||
|
|
||||||
init(request: SFSpeechAudioBufferRecognitionRequest) {
|
func enqueueCopy(of buffer: AVAudioPCMBuffer) {
|
||||||
self.request = request
|
guard let copy = buffer.deepCopy() else { return }
|
||||||
|
self.lock.lock()
|
||||||
|
self.buffers.append(copy)
|
||||||
|
self.lock.unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
func append(_ buffer: AVAudioPCMBuffer) {
|
func drain() -> [AVAudioPCMBuffer] {
|
||||||
self.request.append(buffer)
|
self.lock.lock()
|
||||||
|
let drained = self.buffers
|
||||||
|
self.buffers.removeAll(keepingCapacity: true)
|
||||||
|
self.lock.unlock()
|
||||||
|
return drained
|
||||||
|
}
|
||||||
|
|
||||||
|
func clear() {
|
||||||
|
self.lock.lock()
|
||||||
|
self.buffers.removeAll(keepingCapacity: false)
|
||||||
|
self.lock.unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension AVAudioPCMBuffer {
|
||||||
|
fileprivate func deepCopy() -> AVAudioPCMBuffer? {
|
||||||
|
let format = self.format
|
||||||
|
let frameLength = self.frameLength
|
||||||
|
guard let copy = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameLength) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
copy.frameLength = frameLength
|
||||||
|
|
||||||
|
if let src = self.floatChannelData, let dst = copy.floatChannelData {
|
||||||
|
let channels = Int(format.channelCount)
|
||||||
|
let frames = Int(frameLength)
|
||||||
|
for ch in 0..<channels {
|
||||||
|
dst[ch].update(from: src[ch], count: frames)
|
||||||
|
}
|
||||||
|
return copy
|
||||||
|
}
|
||||||
|
|
||||||
|
if let src = self.int16ChannelData, let dst = copy.int16ChannelData {
|
||||||
|
let channels = Int(format.channelCount)
|
||||||
|
let frames = Int(frameLength)
|
||||||
|
for ch in 0..<channels {
|
||||||
|
dst[ch].update(from: src[ch], count: frames)
|
||||||
|
}
|
||||||
|
return copy
|
||||||
|
}
|
||||||
|
|
||||||
|
if let src = self.int32ChannelData, let dst = copy.int32ChannelData {
|
||||||
|
let channels = Int(format.channelCount)
|
||||||
|
let frames = Int(frameLength)
|
||||||
|
for ch in 0..<channels {
|
||||||
|
dst[ch].update(from: src[ch], count: frames)
|
||||||
|
}
|
||||||
|
return copy
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@MainActor
|
@MainActor
|
||||||
final class VoiceWakeManager: NSObject, ObservableObject {
|
@Observable
|
||||||
@Published var isEnabled: Bool = false
|
final class VoiceWakeManager: NSObject {
|
||||||
@Published var isListening: Bool = false
|
var isEnabled: Bool = false
|
||||||
@Published var statusText: String = "Off"
|
var isListening: Bool = false
|
||||||
|
var statusText: String = "Off"
|
||||||
|
var triggerWords: [String] = VoiceWakePreferences.loadTriggerWords()
|
||||||
|
var lastTriggeredCommand: String?
|
||||||
|
|
||||||
private let audioEngine = AVAudioEngine()
|
private let audioEngine = AVAudioEngine()
|
||||||
private var speechRecognizer: SFSpeechRecognizer?
|
private var speechRecognizer: SFSpeechRecognizer?
|
||||||
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
|
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
|
||||||
private var recognitionTask: SFSpeechRecognitionTask?
|
private var recognitionTask: SFSpeechRecognitionTask?
|
||||||
|
private var tapQueue: AudioBufferQueue?
|
||||||
|
private var tapDrainTask: Task<Void, Never>?
|
||||||
|
|
||||||
private var lastDispatched: String?
|
private var lastDispatched: String?
|
||||||
private var onCommand: (@Sendable (String) async -> Void)?
|
private var onCommand: (@Sendable (String) async -> Void)?
|
||||||
|
private nonisolated(unsafe) var userDefaultsObserver: NSObjectProtocol?
|
||||||
|
|
||||||
|
override init() {
|
||||||
|
super.init()
|
||||||
|
self.triggerWords = VoiceWakePreferences.loadTriggerWords()
|
||||||
|
self.userDefaultsObserver = NotificationCenter.default.addObserver(
|
||||||
|
forName: UserDefaults.didChangeNotification,
|
||||||
|
object: UserDefaults.standard,
|
||||||
|
queue: .main,
|
||||||
|
using: { [weak self] _ in
|
||||||
|
Task { @MainActor in
|
||||||
|
self?.handleUserDefaultsDidChange()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
deinit {
|
||||||
|
if let userDefaultsObserver = self.userDefaultsObserver {
|
||||||
|
NotificationCenter.default.removeObserver(userDefaultsObserver)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var activeTriggerWords: [String] {
|
||||||
|
VoiceWakePreferences.sanitizeTriggerWords(self.triggerWords)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handleUserDefaultsDidChange() {
|
||||||
|
let updated = VoiceWakePreferences.loadTriggerWords()
|
||||||
|
if updated != self.triggerWords {
|
||||||
|
self.triggerWords = updated
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func configure(onCommand: @escaping @Sendable (String) async -> Void) {
|
func configure(onCommand: @escaping @Sendable (String) async -> Void) {
|
||||||
self.onCommand = onCommand
|
self.onCommand = onCommand
|
||||||
@@ -53,6 +144,16 @@ final class VoiceWakeManager: NSObject, ObservableObject {
|
|||||||
guard self.isEnabled else { return }
|
guard self.isEnabled else { return }
|
||||||
if self.isListening { return }
|
if self.isListening { return }
|
||||||
|
|
||||||
|
if ProcessInfo.processInfo.environment["SIMULATOR_DEVICE_NAME"] != nil ||
|
||||||
|
ProcessInfo.processInfo.environment["SIMULATOR_UDID"] != nil
|
||||||
|
{
|
||||||
|
// The iOS Simulator’s audio stack is unreliable for long-running microphone capture.
|
||||||
|
// (We’ve observed CoreAudio deadlocks after TCC permission prompts.)
|
||||||
|
self.isListening = false
|
||||||
|
self.statusText = "Voice Wake isn’t supported on Simulator"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
self.statusText = "Requesting permissions…"
|
self.statusText = "Requesting permissions…"
|
||||||
|
|
||||||
let micOk = await Self.requestMicrophonePermission()
|
let micOk = await Self.requestMicrophonePermission()
|
||||||
@@ -92,6 +193,11 @@ final class VoiceWakeManager: NSObject, ObservableObject {
|
|||||||
self.isListening = false
|
self.isListening = false
|
||||||
self.statusText = "Off"
|
self.statusText = "Off"
|
||||||
|
|
||||||
|
self.tapDrainTask?.cancel()
|
||||||
|
self.tapDrainTask = nil
|
||||||
|
self.tapQueue?.clear()
|
||||||
|
self.tapQueue = nil
|
||||||
|
|
||||||
self.recognitionTask?.cancel()
|
self.recognitionTask?.cancel()
|
||||||
self.recognitionTask = nil
|
self.recognitionTask = nil
|
||||||
self.recognitionRequest = nil
|
self.recognitionRequest = nil
|
||||||
@@ -104,9 +210,44 @@ final class VoiceWakeManager: NSObject, ObservableObject {
|
|||||||
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
|
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Temporarily releases the microphone so other subsystems (e.g. camera video capture) can record audio.
|
||||||
|
/// Returns `true` when listening was active and was suspended.
|
||||||
|
func suspendForExternalAudioCapture() -> Bool {
|
||||||
|
guard self.isEnabled, self.isListening else { return false }
|
||||||
|
|
||||||
|
self.isListening = false
|
||||||
|
self.statusText = "Paused"
|
||||||
|
|
||||||
|
self.tapDrainTask?.cancel()
|
||||||
|
self.tapDrainTask = nil
|
||||||
|
self.tapQueue?.clear()
|
||||||
|
self.tapQueue = nil
|
||||||
|
|
||||||
|
self.recognitionTask?.cancel()
|
||||||
|
self.recognitionTask = nil
|
||||||
|
self.recognitionRequest = nil
|
||||||
|
|
||||||
|
if self.audioEngine.isRunning {
|
||||||
|
self.audioEngine.stop()
|
||||||
|
self.audioEngine.inputNode.removeTap(onBus: 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func resumeAfterExternalAudioCapture(wasSuspended: Bool) {
|
||||||
|
guard wasSuspended else { return }
|
||||||
|
Task { await self.start() }
|
||||||
|
}
|
||||||
|
|
||||||
private func startRecognition() throws {
|
private func startRecognition() throws {
|
||||||
self.recognitionTask?.cancel()
|
self.recognitionTask?.cancel()
|
||||||
self.recognitionTask = nil
|
self.recognitionTask = nil
|
||||||
|
self.tapDrainTask?.cancel()
|
||||||
|
self.tapDrainTask = nil
|
||||||
|
self.tapQueue?.clear()
|
||||||
|
self.tapQueue = nil
|
||||||
|
|
||||||
let request = SFSpeechAudioBufferRecognitionRequest()
|
let request = SFSpeechAudioBufferRecognitionRequest()
|
||||||
request.shouldReportPartialResults = true
|
request.shouldReportPartialResults = true
|
||||||
@@ -115,16 +256,34 @@ final class VoiceWakeManager: NSObject, ObservableObject {
|
|||||||
let inputNode = self.audioEngine.inputNode
|
let inputNode = self.audioEngine.inputNode
|
||||||
inputNode.removeTap(onBus: 0)
|
inputNode.removeTap(onBus: 0)
|
||||||
|
|
||||||
let requestBox = SpeechRequestBox(request: request)
|
|
||||||
let recordingFormat = inputNode.outputFormat(forBus: 0)
|
let recordingFormat = inputNode.outputFormat(forBus: 0)
|
||||||
let tap = SpeechAudioTapFactory.makeAppendTap(requestBox: requestBox)
|
|
||||||
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat, block: tap)
|
let queue = AudioBufferQueue()
|
||||||
|
self.tapQueue = queue
|
||||||
|
let tapBlock: @Sendable (AVAudioPCMBuffer, AVAudioTime) -> Void = makeAudioTapEnqueueCallback(queue: queue)
|
||||||
|
inputNode.installTap(
|
||||||
|
onBus: 0,
|
||||||
|
bufferSize: 1024,
|
||||||
|
format: recordingFormat,
|
||||||
|
block: tapBlock)
|
||||||
|
|
||||||
self.audioEngine.prepare()
|
self.audioEngine.prepare()
|
||||||
try self.audioEngine.start()
|
try self.audioEngine.start()
|
||||||
|
|
||||||
let handler = self.makeRecognitionResultHandler()
|
let handler = self.makeRecognitionResultHandler()
|
||||||
self.recognitionTask = self.speechRecognizer?.recognitionTask(with: request, resultHandler: handler)
|
self.recognitionTask = self.speechRecognizer?.recognitionTask(with: request, resultHandler: handler)
|
||||||
|
|
||||||
|
self.tapDrainTask = Task { [weak self] in
|
||||||
|
guard let self, let queue = self.tapQueue else { return }
|
||||||
|
while !Task.isCancelled {
|
||||||
|
try? await Task.sleep(nanoseconds: 40_000_000)
|
||||||
|
let drained = queue.drain()
|
||||||
|
if drained.isEmpty { continue }
|
||||||
|
for buf in drained {
|
||||||
|
request.append(buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private nonisolated func makeRecognitionResultHandler() -> @Sendable (SFSpeechRecognitionResult?, Error?) -> Void {
|
private nonisolated func makeRecognitionResultHandler() -> @Sendable (SFSpeechRecognitionResult?, Error?) -> Void {
|
||||||
@@ -158,6 +317,7 @@ final class VoiceWakeManager: NSObject, ObservableObject {
|
|||||||
|
|
||||||
if cmd == self.lastDispatched { return }
|
if cmd == self.lastDispatched { return }
|
||||||
self.lastDispatched = cmd
|
self.lastDispatched = cmd
|
||||||
|
self.lastTriggeredCommand = cmd
|
||||||
self.statusText = "Triggered"
|
self.statusText = "Triggered"
|
||||||
|
|
||||||
Task { [weak self] in
|
Task { [weak self] in
|
||||||
@@ -175,12 +335,29 @@ final class VoiceWakeManager: NSObject, ObservableObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func extractCommand(from transcript: String) -> String? {
|
private func extractCommand(from transcript: String) -> String? {
|
||||||
let lower = transcript.lowercased()
|
Self.extractCommand(from: transcript, triggers: self.activeTriggerWords)
|
||||||
guard let range = lower.range(of: "clawdis", options: .backwards) else { return nil }
|
}
|
||||||
let after = lower[range.upperBound...]
|
|
||||||
|
nonisolated static func extractCommand(from transcript: String, triggers: [String]) -> String? {
|
||||||
|
var bestRange: Range<String.Index>?
|
||||||
|
for trigger in triggers {
|
||||||
|
let token = trigger.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !token.isEmpty else { continue }
|
||||||
|
guard let range = transcript.range(of: token, options: [.caseInsensitive, .backwards]) else { continue }
|
||||||
|
if let currentBest = bestRange {
|
||||||
|
if range.lowerBound > currentBest.lowerBound {
|
||||||
|
bestRange = range
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
bestRange = range
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let bestRange else { return nil }
|
||||||
|
let after = transcript[bestRange.upperBound...]
|
||||||
let trimmed = after.trimmingCharacters(in: .whitespacesAndNewlines)
|
let trimmed = after.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
if trimmed.isEmpty { return nil }
|
guard !trimmed.isEmpty else { return nil }
|
||||||
return trimmed
|
return String(trimmed)
|
||||||
}
|
}
|
||||||
|
|
||||||
private static func configureAudioSession() throws {
|
private static func configureAudioSession() throws {
|
||||||
@@ -195,21 +372,17 @@ final class VoiceWakeManager: NSObject, ObservableObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private nonisolated static func requestMicrophonePermission() async -> Bool {
|
private nonisolated static func requestMicrophonePermission() async -> Bool {
|
||||||
await withCheckedContinuation { cont in
|
await withCheckedContinuation(isolation: nil) { cont in
|
||||||
AVAudioApplication.requestRecordPermission { ok in
|
AVAudioApplication.requestRecordPermission { ok in
|
||||||
Task { @MainActor in
|
cont.resume(returning: ok)
|
||||||
cont.resume(returning: ok)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private nonisolated static func requestSpeechPermission() async -> Bool {
|
private nonisolated static func requestSpeechPermission() async -> Bool {
|
||||||
await withCheckedContinuation { cont in
|
await withCheckedContinuation(isolation: nil) { cont in
|
||||||
SFSpeechRecognizer.requestAuthorization { status in
|
SFSpeechRecognizer.requestAuthorization { status in
|
||||||
Task { @MainActor in
|
cont.resume(returning: status == .authorized)
|
||||||
cont.resume(returning: status == .authorized)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
enum VoiceWakePreferences {
|
||||||
|
static let enabledKey = "voiceWake.enabled"
|
||||||
|
static let triggerWordsKey = "voiceWake.triggerWords"
|
||||||
|
|
||||||
|
// Keep defaults aligned with the mac app.
|
||||||
|
static let defaultTriggerWords: [String] = ["clawd", "claude"]
|
||||||
|
|
||||||
|
static func decodeGatewayTriggers(from payloadJSON: String) -> [String]? {
|
||||||
|
guard let data = payloadJSON.data(using: .utf8) else { return nil }
|
||||||
|
return self.decodeGatewayTriggers(from: data)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func decodeGatewayTriggers(from data: Data) -> [String]? {
|
||||||
|
struct Payload: Decodable { var triggers: [String] }
|
||||||
|
guard let decoded = try? JSONDecoder().decode(Payload.self, from: data) else { return nil }
|
||||||
|
return self.sanitizeTriggerWords(decoded.triggers)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func loadTriggerWords(defaults: UserDefaults = .standard) -> [String] {
|
||||||
|
defaults.stringArray(forKey: self.triggerWordsKey) ?? self.defaultTriggerWords
|
||||||
|
}
|
||||||
|
|
||||||
|
static func saveTriggerWords(_ words: [String], defaults: UserDefaults = .standard) {
|
||||||
|
defaults.set(words, forKey: self.triggerWordsKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
static func sanitizeTriggerWords(_ words: [String]) -> [String] {
|
||||||
|
let cleaned = words
|
||||||
|
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
||||||
|
.filter { !$0.isEmpty }
|
||||||
|
return cleaned.isEmpty ? Self.defaultTriggerWords : cleaned
|
||||||
|
}
|
||||||
|
|
||||||
|
static func displayString(for words: [String]) -> String {
|
||||||
|
let sanitized = self.sanitizeTriggerWords(words)
|
||||||
|
return sanitized.joined(separator: ", ")
|
||||||
|
}
|
||||||
|
}
|
||||||