Compare commits

...
14 Commits
Author SHA1 Message Date
MasterControl b4b4f12b0c chore: sync main with upstream 25cb255b 2026-11-19 21:49:09 +00:00
James Babcock 25cb255be2 Merge pull request #68 from mwlaboratories/calendar-event-end
Calendar: include the end of each event, and list ongoing multi-day events under today
2026-11-18 20:53:00 -08:00
James Babcock 2ecb8b64b1 Grouping of glanceboard settings 2026-11-18 16:13:24 -08:00
James Babcock d8a15c5251 Expand the resource cache from 192kb to 320kb 2026-11-18 12:29:29 -08:00
James Babcock 2922f07c2f Merge branch 'ssh-client' 2026-11-17 17:39:13 -08:00
James Babcock d1e424b7e1 Fix an issue where iOS couldn't reconnect to a G2 arm because it already had an ANCS connection open to it 2026-11-17 17:38:11 -08:00
mwlaboratoriesandClaude Opus 5.5 e94b373431 Calendar app: list an ongoing multi-day event under today, with its span
A three-day all-day event showed only under its first day, so on day three
the app had nothing under Today. An event that began on an earlier day and is
still going is now listed under today, and an event covering more than one
day shows its span ("Mon 16 – Wed 18 Nov").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 00:26:36 +01:00
mwlaboratoriesandClaude Opus 5.5 2e7ca866a8 calendar.list_events: include the end of each event
A multi-day all-day event that started yesterday read as yesterday's
("Mon Nov 16 (all day)"), so the assistant left it out of today's plans;
timed events had no end time. Format the span: the last day of an all-day
event (ends are exclusive) and the end time of a timed one.

The date formatting moves into a pure app/assistant/date-format.ts with
unit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:50:00 +01:00
James Babcock 2b75a9d66e Add an ssh client to Terminal, as an alternative to (or tunnel for) g2mirror 2026-11-16 01:41:12 -08:00
James Babcock ab692741f7 Add support for a BLE mouse (ie, the touchpad/mouse buttons in a handheld mouse/keyboard combo like the Rii K28) 2026-11-15 23:57:33 -08:00
Blendman974 15d7e9482d Merge pull request 'chore: synchroniser main avec upstream c162c8e6' (#20) from MasterControl/faceclaw:sync/upstream-main-20261114 into main
Reviewed-on: Blendman974/faceclaw#20
2026-11-14 23:11:11 +00:00
MasterControl d8fa4822ef chore: sync upstream main c162c8e6 preserving mirror history 2026-11-14 23:07:09 +00:00
Blendman974 6efc67f226 revert 3eb9b09e3d
revert Hide phone UI action in EvenAnchor menu
2026-11-14 19:55:55 +00:00
Blendman974 b4a2b2931b Merge pull request 'chore: synchroniser main avec jimrandomh/faceclaw' (#13) from MasterControl/faceclaw:sync/upstream-main into main
Reviewed-on: Blendman974/faceclaw#13
2026-11-09 06:13:40 +00:00
74 changed files with 6181 additions and 287 deletions

No files matched your search

+2
View File
@@ -58,6 +58,8 @@ native/kotlin/.kotlin/
native/kotlin/build/
native/kotlin/shared/build/
native/kotlin/local.properties
# Go SSH transport build outputs (scripts/go-ssh-build.cjs)
native/ssh/build/
native/kotlin/plugin/platforms/android/*.aar
native/kotlin/plugin/platforms/ios/
!native/kotlin/plugin/platforms/
@@ -0,0 +1,212 @@
package com.faceclaw.app
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.security.keystore.StrongBoxUnavailableException
import android.util.Base64
import android.util.Log
import com.faceclaw.ssh.faceclawssh.Channel
import com.faceclaw.ssh.faceclawssh.Faceclawssh
import com.faceclaw.ssh.faceclawssh.Listener
import com.faceclaw.ssh.faceclawssh.Signer
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.PrivateKey
import java.security.Signature
import java.security.spec.ECGenParameterSpec
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/**
* One SSH channel for the TypeScript side (app/native/ssh.ts), backed by the
* gomobile-bound Go transport in native/ssh. `spec` is the Go openSpec JSON.
* Events arrive from Go goroutines and are posted to the Looper of the
* thread that constructed this object (a JS isolate's own thread), like
* FaceclawWebSocket.
*/
class FaceclawSshChannel(spec: String, useKey: Boolean, listener: FaceclawSshListener) {
private val handler = Handler(Looper.myLooper() ?: Looper.getMainLooper())
private val channel: Channel
init {
val signer = if (useKey) FaceclawSshKeys.signer() else null
channel = Faceclawssh.open(spec, signer, object : Listener {
override fun onEvent(kind: String?, payload: String?) {
handler.post {
try {
listener.onEvent(kind, payload)
} catch (t: Throwable) {
Log.w(TAG, "listener onEvent($kind) failed", t)
}
}
}
})
}
fun send(text: String): Boolean = channel.send(text)
fun close() = channel.close()
private companion object {
const val TAG = "FaceclawSsh"
}
}
/**
* The device's SSH client key and the Terminal app's saved SSH passwords.
*
* The client key is an ECDSA P-256 key generated inside Android Keystore
* (StrongBox when the device has one) and never exportable: only its public
* half leaves the keystore, as an authorized_keys line. Passwords are
* encrypted with an AES-GCM key that also lives in Keystore, and stored in a
* private SharedPreferences file kept apart from the settings store (which is
* exported by the settings port).
*/
object FaceclawSshKeys {
private const val TAG = "FaceclawSsh"
private const val CLIENT_KEY_ALIAS = "faceclaw-ssh-client"
private const val SECRET_KEY_ALIAS = "faceclaw-ssh-secrets"
private const val SECRETS_PREFS = "faceclaw_ssh_secrets"
private const val GCM_TAG_BITS = 128
private fun keyStore(): KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
@JvmStatic
@Synchronized
fun hasClientKey(): Boolean = keyStore().containsAlias(CLIENT_KEY_ALIAS)
/** Generate the client key if it doesn't exist yet. */
@JvmStatic
@Synchronized
fun ensureClientKey() {
if (keyStore().containsAlias(CLIENT_KEY_ALIAS)) return
fun spec(strongBox: Boolean): KeyGenParameterSpec {
val builder = KeyGenParameterSpec.Builder(CLIENT_KEY_ALIAS, KeyProperties.PURPOSE_SIGN)
.setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
.setDigests(KeyProperties.DIGEST_SHA256)
if (strongBox && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) builder.setIsStrongBoxBacked(true)
return builder.build()
}
val generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore")
try {
generator.initialize(spec(strongBox = true))
generator.generateKeyPair()
} catch (e: Exception) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && e is StrongBoxUnavailableException) {
Log.i(TAG, "StrongBox unavailable; generating the SSH key in the TEE")
} else {
Log.w(TAG, "StrongBox key generation failed; retrying in the TEE", e)
}
generator.initialize(spec(strongBox = false))
generator.generateKeyPair()
}
Log.i(TAG, "generated SSH client key")
}
/** X.509 SubjectPublicKeyInfo DER of the client key, or null if none. */
@JvmStatic
fun publicKey(): ByteArray? = keyStore().getCertificate(CLIENT_KEY_ALIAS)?.publicKey?.encoded
/** The client key's authorized_keys line (generating the key if needed). */
@JvmStatic
fun authorizedKey(comment: String): String {
ensureClientKey()
return Faceclawssh.authorizedKey(publicKey(), comment)
}
/** The client key's SHA256 fingerprint (generating the key if needed). */
@JvmStatic
fun fingerprint(): String {
ensureClientKey()
return Faceclawssh.fingerprint(publicKey())
}
/** A Go Signer over the client key, generating the key if needed. */
@JvmStatic
fun signer(): Signer? = try {
ensureClientKey()
val publicKey = publicKey() ?: throw IllegalStateException("client key has no certificate")
object : Signer {
override fun publicKey(): ByteArray = publicKey
override fun sign(data: ByteArray?): ByteArray {
val privateKey = keyStore().getKey(CLIENT_KEY_ALIAS, null) as PrivateKey
return Signature.getInstance("SHA256withECDSA").run {
initSign(privateKey)
update(data ?: ByteArray(0))
sign()
}
}
}
} catch (t: Throwable) {
Log.w(TAG, "SSH client key unavailable", t)
null
}
private fun secretKey(): SecretKey {
val store = keyStore()
(store.getKey(SECRET_KEY_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init(
KeyGenParameterSpec.Builder(SECRET_KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build()
)
return generator.generateKey()
}
private fun prefs(context: Context) =
context.applicationContext.getSharedPreferences(SECRETS_PREFS, Context.MODE_PRIVATE)
@JvmStatic
@Synchronized
fun setSecret(context: Context, id: String, value: String) {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, secretKey())
val sealed = cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8))
prefs(context).edit().putString(id, Base64.encodeToString(sealed, Base64.NO_WRAP)).apply()
}
/** The saved secret, or "" if none (or it can no longer be decrypted). */
@JvmStatic
@Synchronized
fun getSecret(context: Context, id: String): String {
val encoded = prefs(context).getString(id, null) ?: return ""
return try {
val sealed = Base64.decode(encoded, Base64.NO_WRAP)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val ivLength = 12
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, sealed, 0, ivLength))
String(cipher.doFinal(sealed, ivLength, sealed.size - ivLength), Charsets.UTF_8)
} catch (t: Throwable) {
Log.w(TAG, "saved SSH secret unreadable; dropping it", t)
prefs(context).edit().remove(id).apply()
""
}
}
@JvmStatic
@Synchronized
fun removeSecret(context: Context, id: String) {
prefs(context).edit().remove(id).apply()
}
/** Put text on the phone's clipboard (from any thread). */
@JvmStatic
fun copyToClipboard(context: Context, label: String, text: String) {
val appContext = context.applicationContext
Handler(Looper.getMainLooper()).post {
val clipboard = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(ClipData.newPlainText(label, text))
}
}
}
+31
View File
@@ -0,0 +1,31 @@
#import <Foundation/Foundation.h>
/**
* One SSH channel for the TypeScript side (app/native/ssh.ios.ts), backed by
* the gomobile-bound Go transport in native/ssh. `spec` is the Go openSpec
* JSON. Events arrive on Go threads and queue here; the owning JS isolate
* drains them with takeEvents (a JSON array of {kind, payload}).
*/
@interface FaceclawSshChannel : NSObject
- (instancetype)initWithSpec:(NSString *)spec useKey:(BOOL)useKey;
- (NSString *)takeEvents;
- (BOOL)send:(NSString *)text;
- (void)close;
@end
/**
* The device's SSH client key (a non-exportable Secure Enclave P-256 key; a
* plain keychain key on the simulator, which has no Secure Enclave) and the
* Terminal app's saved SSH passwords (keychain generic passwords).
*/
@interface FaceclawSshKeys : NSObject
/** "ecdsa-sha2-nistp256 AAAA... comment"; generates the key if needed. nil on failure. */
+ (NSString *)authorizedKeyWithComment:(NSString *)comment;
/** "SHA256:..." fingerprint; generates the key if needed. nil on failure. */
+ (NSString *)fingerprint;
+ (void)setSecret:(NSString *)value forId:(NSString *)secretId;
/** The saved secret, or "" if none. */
+ (NSString *)secretForId:(NSString *)secretId;
+ (void)removeSecretForId:(NSString *)secretId;
+ (void)copyToClipboard:(NSString *)text;
@end
+234
View File
@@ -0,0 +1,234 @@
#import "FaceclawSsh.h"
#import <Faceclawssh/Faceclawssh.h>
#import <Security/Security.h>
#import <UIKit/UIKit.h>
static NSString *const kClientKeyTag = @"com.faceclaw.ssh.client";
static NSString *const kSecretService = @"com.faceclaw.ssh.secret";
#pragma mark - Client key
static NSData *ClientKeyTagData(void) {
return [kClientKeyTag dataUsingEncoding:NSUTF8StringEncoding];
}
static SecKeyRef CopyClientKey(void) {
NSDictionary *query = @{
(id)kSecClass: (id)kSecClassKey,
(id)kSecAttrApplicationTag: ClientKeyTagData(),
(id)kSecAttrKeyType: (id)kSecAttrKeyTypeECSECPrimeRandom,
(id)kSecReturnRef: @YES,
};
CFTypeRef key = NULL;
if (SecItemCopyMatching((__bridge CFDictionaryRef)query, &key) != errSecSuccess) return NULL;
return (SecKeyRef)key;
}
static SecKeyRef CreateClientKey(BOOL secureEnclave) {
SecAccessControlRef access = SecAccessControlCreateWithFlags(
kCFAllocatorDefault, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
secureEnclave ? kSecAccessControlPrivateKeyUsage : 0, NULL);
if (!access) return NULL;
NSMutableDictionary *attributes = [@{
(id)kSecAttrKeyType: (id)kSecAttrKeyTypeECSECPrimeRandom,
(id)kSecAttrKeySizeInBits: @256,
(id)kSecPrivateKeyAttrs: @{
(id)kSecAttrIsPermanent: @YES,
(id)kSecAttrApplicationTag: ClientKeyTagData(),
(id)kSecAttrAccessControl: (__bridge id)access,
},
} mutableCopy];
if (secureEnclave) attributes[(id)kSecAttrTokenID] = (id)kSecAttrTokenIDSecureEnclave;
CFErrorRef error = NULL;
SecKeyRef key = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes, &error);
CFRelease(access);
if (!key && error) {
NSLog(@"FaceclawSsh: key generation failed (secure enclave %d): %@", secureEnclave, (__bridge NSError *)error);
CFRelease(error);
}
return key;
}
/** The client key, generating it on first use. Caller releases. */
static SecKeyRef CopyOrCreateClientKey(void) {
@synchronized([FaceclawSshKeys class]) {
SecKeyRef key = CopyClientKey();
if (key) return key;
key = CreateClientKey(YES);
#if TARGET_OS_SIMULATOR
if (!key) key = CreateClientKey(NO);
#endif
return key;
}
}
/** Uncompressed X9.62 public point (0x04 || X || Y). */
static NSData *PublicKeyData(SecKeyRef key) {
SecKeyRef publicKey = SecKeyCopyPublicKey(key);
if (!publicKey) return nil;
NSData *data = (__bridge_transfer NSData *)SecKeyCopyExternalRepresentation(publicKey, NULL);
CFRelease(publicKey);
return data;
}
@interface FaceclawSshSigner : NSObject <FaceclawsshSigner>
@end
@implementation FaceclawSshSigner {
SecKeyRef _key;
NSData *_publicKey;
}
- (instancetype)initWithKey:(SecKeyRef)key {
if ((self = [super init])) {
_key = (SecKeyRef)CFRetain(key);
_publicKey = PublicKeyData(key);
}
return self;
}
- (void)dealloc {
if (_key) CFRelease(_key);
}
- (NSData *)publicKey {
return _publicKey;
}
- (NSData *)sign:(NSData *)data error:(NSError **)error {
CFErrorRef cfError = NULL;
NSData *signature = (__bridge_transfer NSData *)SecKeyCreateSignature(
_key, kSecKeyAlgorithmECDSASignatureMessageX962SHA256, (__bridge CFDataRef)(data ?: [NSData data]), &cfError);
if (!signature) {
if (error) *error = (__bridge_transfer NSError *)cfError;
else if (cfError) CFRelease(cfError);
}
return signature;
}
@end
#pragma mark - Channel
@interface FaceclawSshEventQueue : NSObject <FaceclawsshListener>
@property(nonatomic, strong) NSMutableArray *events;
@property(nonatomic) BOOL ended;
@end
@implementation FaceclawSshEventQueue
- (instancetype)init {
if ((self = [super init])) _events = [NSMutableArray array];
return self;
}
- (void)onEvent:(NSString *)kind payload:(NSString *)payload {
@synchronized(self) {
if (_ended) return;
[_events addObject:@{@"kind": kind ?: @"", @"payload": payload ?: @""}];
}
}
@end
@implementation FaceclawSshChannel {
FaceclawsshChannel *_channel;
FaceclawSshEventQueue *_queue;
}
- (instancetype)initWithSpec:(NSString *)spec useKey:(BOOL)useKey {
if ((self = [super init])) {
_queue = [FaceclawSshEventQueue new];
FaceclawSshSigner *signer = nil;
if (useKey) {
SecKeyRef key = CopyOrCreateClientKey();
if (key) {
signer = [[FaceclawSshSigner alloc] initWithKey:key];
CFRelease(key);
}
}
_channel = FaceclawsshOpen(spec, signer, _queue);
}
return self;
}
- (NSString *)takeEvents {
NSArray *events;
@synchronized(_queue) {
if (_queue.events.count == 0) return @"[]";
events = [_queue.events copy];
[_queue.events removeAllObjects];
}
NSData *data = [NSJSONSerialization dataWithJSONObject:events options:0 error:nil];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"[]";
}
- (BOOL)send:(NSString *)text {
return [_channel send:text];
}
- (void)close {
@synchronized(_queue) {
_queue.ended = YES;
[_queue.events removeAllObjects];
}
[_channel close];
}
@end
#pragma mark - Keys and secrets
@implementation FaceclawSshKeys
+ (NSString *)authorizedKeyWithComment:(NSString *)comment {
SecKeyRef key = CopyOrCreateClientKey();
if (!key) return nil;
NSData *publicKey = PublicKeyData(key);
CFRelease(key);
NSError *error = nil;
NSString *line = FaceclawsshAuthorizedKey(publicKey, comment ?: @"", &error);
if (error) NSLog(@"FaceclawSsh: authorizedKey failed: %@", error);
return line;
}
+ (NSString *)fingerprint {
SecKeyRef key = CopyOrCreateClientKey();
if (!key) return nil;
NSData *publicKey = PublicKeyData(key);
CFRelease(key);
NSError *error = nil;
NSString *fingerprint = FaceclawsshFingerprint(publicKey, &error);
if (error) NSLog(@"FaceclawSsh: fingerprint failed: %@", error);
return fingerprint;
}
+ (NSDictionary *)secretQuery:(NSString *)secretId {
return @{
(id)kSecClass: (id)kSecClassGenericPassword,
(id)kSecAttrService: kSecretService,
(id)kSecAttrAccount: secretId ?: @"",
};
}
+ (void)setSecret:(NSString *)value forId:(NSString *)secretId {
NSDictionary *query = [self secretQuery:secretId];
SecItemDelete((__bridge CFDictionaryRef)query);
NSMutableDictionary *item = [query mutableCopy];
item[(id)kSecValueData] = [(value ?: @"") dataUsingEncoding:NSUTF8StringEncoding];
item[(id)kSecAttrAccessible] = (id)kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)item, NULL);
if (status != errSecSuccess) NSLog(@"FaceclawSsh: saving secret failed: %d", (int)status);
}
+ (NSString *)secretForId:(NSString *)secretId {
NSMutableDictionary *query = [[self secretQuery:secretId] mutableCopy];
query[(id)kSecReturnData] = @YES;
query[(id)kSecMatchLimit] = (id)kSecMatchLimitOne;
CFTypeRef result = NULL;
if (SecItemCopyMatching((__bridge CFDictionaryRef)query, &result) != errSecSuccess) return @"";
NSData *data = (__bridge_transfer NSData *)result;
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ?: @"";
}
+ (void)removeSecretForId:(NSString *)secretId {
SecItemDelete((__bridge CFDictionaryRef)[self secretQuery:secretId]);
}
+ (void)copyToClipboard:(NSString *)text {
dispatch_async(dispatch_get_main_queue(), ^{
UIPasteboard.generalPasteboard.string = text ?: @"";
});
}
@end
+1
View File
@@ -2,6 +2,7 @@ module FaceclawGraphics {
header "FaceclawGraphics.h"
header "FaceclawFontRenderer.h"
header "FaceclawSocket.h"
header "FaceclawSsh.h"
header "FaceclawLc3Decoder.h"
header "FaceclawSpeech.h"
header "FaceclawLocation.h"
+4 -2
View File
@@ -80,8 +80,10 @@ import it into the new version (see [config transfer](scripts/config-transfer.md
* **Integration with Android notifications**: shows the same notification
icons your phone does, and popups when notifications arrive.
* **Terminal mirroring.** Mirror terminal apps such as Claude Code or Codex
CLI with [g2mirror](https://github.com/jimrandomh/g2mirror), view them on
the glasses, and send them inputs with the voice assistant.
CLI with [g2mirror](https://github.com/jimrandomh/g2mirror), or attach to
tmux sessions over SSH (no server-side setup beyond tmux 3.2+), view them
on the glasses, and send them inputs with the voice assistant. g2mirror
can also be tunnelled over SSH instead of a VPN.
* **Media player controls** including playlist and media library navigation,
compatible with most Android media players.
* **Turn-by-turn directions** (requires a Mapbox API token).
+9 -2
View File
@@ -9,6 +9,7 @@ import { hasCalendarPermission } from "../../native/calendar-permissions";
import { type Layer, type LayerContext } from "../../ui/layers";
import { lineStep } from "../../ui/metrics";
import type { Viewport } from "../../ui/viewport";
import { listingDayMs, spanLabel, spansDays } from "./event-days";
/** How far a row's text sits inside its selection box; the title lines up with it. */
const ROW_TEXT_INSET = 10;
@@ -143,14 +144,20 @@ export class CalendarLayer implements Layer {
function buildEventRows(font: UiFont, events: CalendarEvent[]): EventRow[] {
const rows: EventRow[] = [];
let previousDayKey = "";
const nowMs = Date.now();
for (const event of events) {
const dayKey = dayKeyOf(event.startMs);
const dayHeader = dayKey === previousDayKey ? null : dayHeaderLabel(event.startMs);
// An event still going since an earlier day is listed under today, not its first day.
const listedMs = listingDayMs(event, nowMs);
const dayKey = dayKeyOf(listedMs);
const dayHeader = dayKey === previousDayKey ? null : dayHeaderLabel(listedMs);
previousDayKey = dayKey;
const lines: string[] = [];
const timeLabel = event.allDay ? "All day" : formatEventTime(event.startMs);
lines.push(`${timeLabel} ${event.title || "(untitled)"}`);
if (spansDays(event)) {
lines.push(spanLabel(event));
}
if (event.location) {
lines.push(event.location);
}
+43
View File
@@ -0,0 +1,43 @@
/**
* Which day an event is listed under, and how a multi-day span reads. Pure (no
* native or UI imports) so it can be unit-tested.
*/
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
export type DayEvent = { startMs: number; endMs: number; allDay: boolean };
function midnight(timestampMs: number): number {
const date = new Date(timestampMs);
return new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
}
/** The last moment the event covers: all-day ends are exclusive (the midnight after its last day). */
function lastMomentMs(event: DayEvent): number {
return event.allDay ? Math.max(event.startMs, event.endMs - 1) : Math.max(event.startMs, event.endMs);
}
/**
* The day to list an event under: its start, or today for one that began on an
* earlier day and is still going. Without this, the third day of a three-day
* event shows under its first day and never under today.
*/
export function listingDayMs(event: DayEvent, nowMs: number): number {
return Math.max(midnight(event.startMs), Math.min(midnight(nowMs), midnight(lastMomentMs(event))));
}
/** Whether the event covers more than one calendar day. */
export function spansDays(event: DayEvent): boolean {
return midnight(lastMomentMs(event)) > midnight(event.startMs);
}
/** "Mon 16 – Wed 18 Nov", or with both months when they differ ("Mon 30 Nov – Tue 1 Dec"). */
export function spanLabel(event: DayEvent): string {
const start = new Date(event.startMs);
const last = new Date(lastMomentMs(event));
const day = (date: Date) => `${WEEKDAYS[date.getDay()]} ${date.getDate()}`;
return start.getMonth() === last.getMonth() && start.getFullYear() === last.getFullYear()
? `${day(start)} – ${day(last)} ${MONTHS[last.getMonth()]}`
: `${day(start)} ${MONTHS[start.getMonth()]} – ${day(last)} ${MONTHS[last.getMonth()]}`;
}
+8
View File
@@ -6,6 +6,7 @@ import { BuzzerDemoLayer } from "./buzzer-demo";
import { AccelerometerDemoLayer } from "./accelerometer-demo";
import { BandwidthBenchmarkLayer } from "./bandwidth-benchmark";
import { LightSensorDemoLayer } from "./light-sensor-demo";
import { MouseTestLayer } from "./mouse-test";
import { MicrophonesMonitorLayer } from "./microphones-monitor";
import { ResourceUsageLayer } from "./resource-usage";
import { RingStatusLayer } from "./ring-status";
@@ -70,6 +71,13 @@ function debugTestsMenu(openInputEvents: OpenPage, openMicrophones: OpenPage): M
label: "Microphones",
onSelect: openMicrophones,
},
{
// The touchpad or mouse of a keyboard paired through the glasses.
label: "Mouse cursor",
onSelect: (ctx) => {
ctx.stack.push(new MouseTestLayer(DEVELOPER_WINDOW_ID, ctx.actions.requestRender));
},
},
{
label: "BLE bandwidth",
onSelect: (ctx) => {
+206
View File
@@ -0,0 +1,206 @@
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
import { GrayImage } from "../../graphics/image";
import type { HidPointerSample } from "../../g2/keyboard/hid";
import { keyboardService } from "../../g2/keyboard/service";
import { type InputEvent } from "../../ui/gestures";
import { Layer, type LayerContext } from "../../ui/layers";
import { shell } from "../../ui/shell/shell";
import { clamp } from "../../util/numeric-util";
// How often to reconcile holding the pointer with window visibility.
const RECONCILE_INTERVAL_MS = 400;
/** A touchpad reports a hundred times a second; the page repaints at most this often. */
const RENDER_INTERVAL_MS = 33;
/** Cursor pixels per count the touchpad reports. */
const POINTER_GAIN = 1;
/** Left-click marks kept on the page. */
const MAX_MARKS = 12;
/** The arrow, tip at its top left: '#' is the outline, '.' the fill. */
const CURSOR = [
"#",
"##",
"#.#",
"#..#",
"#...#",
"#....#",
"#.....#",
"#......#",
"#.......#",
"#........#",
"#.....#####",
"#..#..#",
"#.# #..#",
"## #..#",
"# #..#",
" #..#",
" ##",
];
/**
* Mouse cursor test: moves an arrow with the touchpad or mouse of the
* keyboard paired through the glasses (app/g2/keyboard/), and shows its
* buttons and wheel. The main UI has no cursor; this is where one is tried
* out.
*
* While the page is visible it takes the pointer, so the buttons and wheel
* show here instead of acting as select, back and scroll. A left click
* leaves a mark where the arrow is and a right click clears them. Leave
* with Esc, or a double tap on the ring or a temple.
*/
export class MouseTestLayer implements Layer {
private x = -1;
private y = -1;
private size = { width: 0, height: 0 };
private buttons = 0;
private wheel = 0;
private marks: Array<{ x: number; y: number }> = [];
private samples = 0;
private rate = 0;
private rateWindowStart = Date.now();
private removed = false;
private release: (() => void) | null = null;
private reconcileTimer: ReturnType<typeof setInterval> | null = null;
private renderTimer: ReturnType<typeof setTimeout> | null = null;
constructor(
private readonly windowId: string,
private readonly requestRender: () => void,
) {
this.reconcileTimer = setInterval(() => this.reconcile(), RECONCILE_INTERVAL_MS);
this.reconcile();
}
/** Hold the pointer only while the page can be seen; elsewhere its buttons go back to being keys. */
private reconcile(): void {
if (this.removed) return;
const visible = shell.isWindowVisible(this.windowId);
if (visible && !this.release) {
this.release = keyboardService.takePointer((sample) => this.onSample(sample));
} else if (!visible && this.release) {
this.release();
this.release = null;
this.buttons = 0;
}
// The rate reads zero once the pointer has been still for a second.
const now = Date.now();
if (now - this.rateWindowStart >= 1000) {
const rate = this.samples;
this.samples = 0;
this.rateWindowStart = now;
if (rate !== this.rate) {
this.rate = rate;
this.scheduleRender();
}
}
}
private onSample(sample: HidPointerSample): void {
if (this.removed) return;
this.samples++;
const { width, height } = this.size;
if (width > 0 && height > 0) {
if (this.x < 0) {
this.x = width / 2;
this.y = height / 2;
}
this.x = clamp(this.x + sample.dx * POINTER_GAIN, 0, width - 1);
this.y = clamp(this.y + sample.dy * POINTER_GAIN, 0, height - 1);
}
const pressed = sample.buttons & ~this.buttons;
this.buttons = sample.buttons;
this.wheel += sample.wheel;
if (pressed & 1 && this.x >= 0) {
this.marks.push({ x: Math.round(this.x), y: Math.round(this.y) });
if (this.marks.length > MAX_MARKS) this.marks.shift();
}
if (pressed & 2) this.marks = [];
this.scheduleRender();
}
private scheduleRender(): void {
if (this.renderTimer !== null || this.removed) return;
this.renderTimer = setTimeout(() => {
this.renderTimer = null;
if (!this.removed) this.requestRender();
}, RENDER_INTERVAL_MS);
}
onRemoved(): void {
this.removed = true;
if (this.reconcileTimer !== null) clearInterval(this.reconcileTimer);
this.reconcileTimer = null;
if (this.renderTimer !== null) clearTimeout(this.renderTimer);
this.renderTimer = null;
this.release?.();
this.release = null;
}
paint(ctx: LayerContext): GrayImage {
const font = getDefaultSmallFont();
const { width, height, padding } = ctx.stack.getBaseSize();
this.size = { width, height };
const image = new GrayImage(width, height, 0);
const left = padding.left;
const right = width - padding.right;
const top = padding.top;
const line = font.lineHeight + 4;
image.drawText(font, left, top, "Mouse cursor", 220);
const snapshot = keyboardService.snapshot();
const problem = snapshot.state !== "connected"
? "No keyboard is connected."
: !snapshot.pointer ? "This keyboard has no touchpad or mouse buttons." : null;
if (problem) {
image.drawText(font, left, top + 2 * line, problem, 190);
image.drawText(font, left, top + 3 * line, "Pair one under Settings > Keyboard.", 120);
return image;
}
const position = this.x < 0 ? "move the pointer" : `${Math.round(this.x)}, ${Math.round(this.y)}`;
image.drawText(font, right - font.measureText(position), top, position, 150);
// Buttons: a box each, filled while held.
let x = left;
const boxY = top + line;
for (const [index, label] of ["L", "M", "R"].entries()) {
// HID numbers them left, right, middle; they sit left, middle, right.
const held = !!(this.buttons & [1, 4, 2][index]!);
const boxW = font.measureText(label) + 10;
if (held) image.fillRect(x, boxY, boxW, font.lineHeight + 2, 200);
else image.drawRect(x, boxY, boxW, font.lineHeight + 2, 90);
image.drawText(font, x + 5, boxY + 1, label, held ? 1 : 170);
x += boxW + 4;
}
image.drawText(font, x + 8, boxY + 1, `wheel ${this.wheel}`, 150);
const rate = `${this.rate}/s`;
image.drawText(font, right - font.measureText(rate), boxY + 1, rate, 110);
const hint = "Left click marks, right click clears. Esc or double tap: back";
image.drawText(font, left, height - padding.bottom - font.lineHeight, hint, 90);
for (const mark of this.marks) {
image.drawLine(mark.x - 4, mark.y, mark.x + 4, mark.y, 140);
image.drawLine(mark.x, mark.y - 4, mark.x, mark.y + 4, 140);
}
if (this.x >= 0) drawCursor(image, Math.round(this.x), Math.round(this.y));
return image;
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
if (event.type === "double-click") {
ctx.stack.pop();
}
}
}
function drawCursor(image: GrayImage, x: number, y: number): void {
for (const [row, pixels] of CURSOR.entries()) {
for (let col = 0; col < pixels.length; col++) {
const pixel = pixels[col];
if (pixel === " ") continue;
const px = x + col;
const py = y + row;
if (px < 0 || py < 0 || px >= image.width || py >= image.height) continue;
image.setPixel(px, py, pixel === "#" ? 255 : 70);
}
}
}
+38 -27
View File
@@ -5,7 +5,7 @@ import { enumSettingMenuItem, onAnySettingChanged, toggleSettingMenuItem } from
import { uiFontOverridePickerMenuItem } from "../../ui/font-picker";
import { type InputEvent } from "../../ui/gestures";
import { type Layer, type LayerContext } from "../../ui/layers";
import { drawSelectionHighlight, isMenuItemDisabled, MenuLayer, openModalMenu, submenuItem, type MenuItem } from "../../ui/menu";
import { drawSelectionHighlight, isMenuItemDisabled, menuHeadingItem, MenuLayer, openModalMenu, submenuItem, type MenuItem } from "../../ui/menu";
import { liveHeadPitchFooter } from "../../g2/head-angle";
import { headUpControlsAvailable } from "../../native/glasses-controls";
import { Menu } from "../../ui/menu-core";
@@ -323,34 +323,45 @@ function openSlotPicker(ctx: LayerContext, slotIndex: number): void {
}
/**
* Settings: layout, sleep gestures, duration, slot lines, widget font, and
* stereo depth, then a row per widget on the board for its own settings.
* Settings, in four sections: Layout (the slot grid), Trigger (the sleep
* gestures that show the board, and for how long), Display (slot lines,
* widget font, stereo depth) and Cards (a row per widget on the board, for
* its own settings; left out while the board is empty).
*/
function openGlanceSettings(ctx: LayerContext): void {
const items = (): MenuItem[] => [
// The layout decides which slots (and so which widgets) are on the board.
enumSettingMenuItem(glanceLayoutSetting, { onChange: () => layer.setItems(items()) }),
enumSettingMenuItem(glanceTapDurationSetting),
toggleSettingMenuItem(glanceShowOnLongPressSetting),
toggleSettingMenuItem(glanceShowOnHeadTiltSetting),
enumSettingMenuItem(glanceTiltTimeoutSetting),
// Only Android can change the glasses' head-up setting (glasses-controls.ts).
// The controller's settings listener sends a new angle to the glasses; the
// picker shows the head's current angle to choose by.
...(headUpControlsAvailable()
? [enumSettingMenuItem(glanceAngleSetting, {
pickerFooter: liveHeadPitchFooter(() => shell.isWindowVisible(GLANCEBOARD_WINDOW_ID)),
})]
: []),
toggleSettingMenuItem(glanceShowLinesSetting),
uiFontOverridePickerMenuItem(glanceFont, {
title: "Glanceboard font",
description:
"Typeface for the Glanceboard's widgets. Same as UI font follows the Font setting in Settings > Customization.",
}),
enumSettingMenuItem(glanceDepthSetting),
...widgetSettingsMenuItems(),
];
const items = (): MenuItem[] => {
const cards = widgetSettingsMenuItems();
return [
menuHeadingItem("Layout"),
// The layout decides which slots (and so which widgets) are on the board.
enumSettingMenuItem(glanceLayoutSetting, { onChange: () => layer.setItems(items()) }),
menuHeadingItem("Trigger"),
enumSettingMenuItem(glanceTapDurationSetting),
toggleSettingMenuItem(glanceShowOnLongPressSetting),
toggleSettingMenuItem(glanceShowOnHeadTiltSetting),
enumSettingMenuItem(glanceTiltTimeoutSetting),
// Only Android can change the glasses' head-up setting (glasses-controls.ts).
// The controller's settings listener sends a new angle to the glasses; the
// picker shows the head's current angle to choose by.
...(headUpControlsAvailable()
? [enumSettingMenuItem(glanceAngleSetting, {
pickerFooter: liveHeadPitchFooter(() => shell.isWindowVisible(GLANCEBOARD_WINDOW_ID)),
})]
: []),
menuHeadingItem("Display"),
toggleSettingMenuItem(glanceShowLinesSetting),
uiFontOverridePickerMenuItem(glanceFont, {
title: "Glanceboard font",
description:
"Typeface for the Glanceboard's widgets. Same as UI font follows the Font setting in Settings > Customization.",
}),
enumSettingMenuItem(glanceDepthSetting),
...(cards.length ? [menuHeadingItem("Cards"), ...cards] : []),
];
};
const layer = new MenuLayer("Glanceboard settings", items(), PAGE_MENU_LAYOUT);
ctx.stack.push(layer);
}
+15 -5
View File
@@ -50,16 +50,26 @@ export const musicShowAlbumArtSetting = new ConfigSettingBoolean({
"Show the album art beside the track details. When off, the title, artist, album and progress bar use the full width of the card.",
});
export const musicShowIdleNoteSetting = new ConfigSettingBoolean({
id: "glanceboard-music-show-idle-note",
label: "Show note when idle",
storageKey: "glanceboard.music.showIdleNote",
defaultValue: true,
description: "Show a dim music note on the card while nothing is playing. When off, the card is left blank.",
});
/** The music card's submenu in Glanceboard > Settings. */
export function musicSettingsMenuItems(): MenuItem[] {
return [toggleSettingMenuItem(musicShowAlbumArtSetting)];
return [toggleSettingMenuItem(musicShowAlbumArtSetting), toggleSettingMenuItem(musicShowIdleNoteSetting)];
}
/**
* Now playing: album art (unless turned off), title/artist/album and a
* progress bar for the active media session (Apple Music on iOS), the Music
* app's header at card size. The media bridge runs for the whole session; the
* widget subscribes and ticks once a second only while something is playing.
* app's header at card size. With nothing playing the card holds a dim note,
* or nothing with that turned off. The media bridge runs for the whole
* session; the widget subscribes and ticks once a second only while
* something is playing.
*/
export class MusicWidget implements GlanceWidget {
private media: MediaControllerState = mediaControllerBridge.snapshot();
@@ -108,8 +118,8 @@ export class MusicWidget implements GlanceWidget {
image.drawText(small, PAD, PAD + small.lineHeight + 6, mediaControllerBridge.accessLabel, 140);
return;
}
// Nothing playing: a dim note, centred, and nothing else.
const note = idleNoteImage();
// Nothing playing: a dim note, centred, and nothing else; or a blank card.
const note = musicShowIdleNoteSetting.get() ? idleNoteImage() : null;
if (note) image.drawImage(note, ((image.width - note.width) / 2) | 0, ((image.height - note.height) / 2) | 0);
return;
}
+89 -7
View File
@@ -1,13 +1,21 @@
import { getStringSetting, setStringSetting } from "../../native/settings-store";
/**
* Terminal-app connection registry: the g2mirror hosts the app knows about,
* stored as JSON under one settings key so every isolate sees the same list
* and change notifications ride the ordinary settings-store channel.
* Terminal-app connection registry: the hosts the app knows about, stored as
* JSON under one settings key so every isolate sees the same list and change
* notifications ride the ordinary settings-store channel.
*
* A connection is entered as a g2mirror:// connection string (the same form
* g2mirror-view accepts): g2mirror://<token>@<host>[:port] for plain
* websockets (default port 8737), g2mirrors://... for TLS (default 443).
* A connection is entered as a connection string:
* - g2mirror://<token>@<host>[:port]: a g2mirror server reached directly
* (the same form g2mirror-view accepts) over a plain websocket (default
* port 8737); g2mirrors://... for TLS (default 443).
* - ssh://<user>@<host>[:port]: tmux on an SSH host (default port 22).
* - ssh://<user>@<host>[:port]?g2mirror=<token>[@<host>[:port]]: a g2mirror
* server tunnelled over SSH; the address after the token is where the
* server listens as seen from the SSH host (default 127.0.0.1:8737).
* SSH connections pin the host's key (hostKeys, trusted on first connection
* after the user checks its fingerprint); their passwords live in the
* platform keystore (app/native/ssh), not here.
*/
export const TERMINAL_CONNECTIONS_KEY = "terminal.connections";
@@ -25,6 +33,8 @@ export type TerminalConnection = {
serverName: string | null;
/** Auto-connect while the Terminal app is open. Toggled by Connect/Disconnect. */
enabled: boolean;
/** SSH connections: trusted host keys (SSH wire format, base64). */
hostKeys: string[];
};
export type ParsedConnectionString = {
@@ -54,8 +64,79 @@ export function parseConnectionString(url: string): ParsedConnectionString | nul
return { secure, host, port, authToken };
}
/** The host[:port] part of a connection string; "" if it doesn't parse. */
export type ParsedSshConnection = {
user: string;
host: string;
port: number;
} & (
| { mode: "tmux" }
| {
mode: "g2mirror";
authToken: string;
/** Where g2mirror-server listens, from the SSH host's point of view. */
targetHost: string;
targetPort: number;
}
);
function decodeComponent(text: string): string {
try {
return decodeURIComponent(text);
} catch {
return text;
}
}
/** Parse an ssh://user@host[:port][?g2mirror=token[@host[:port]]] string; null if malformed. */
export function parseSshConnectionString(url: string): ParsedSshConnection | null {
const match = /^ssh:\/\/([^@\s/?]+)@(\[[^\]\s]+\]|[^:/@\s?]+)(?::(\d+))?\/?(?:\?(.*))?$/.exec(url.trim());
if (!match) return null;
const user = decodeComponent(match[1]!);
const host = match[2]!.replace(/^\[(.*)\]$/, "$1");
const port = match[3] ? parseInt(match[3], 10) : 22;
if (!user || !(port >= 1 && port <= 65535)) return null;
const params = new Map<string, string>();
for (const part of (match[4] ?? "").split("&").filter(Boolean)) {
const equals = part.indexOf("=");
if (equals < 0) return null;
params.set(part.slice(0, equals), decodeComponent(part.slice(equals + 1)));
}
for (const key of params.keys()) {
if (key !== "g2mirror") return null;
}
const g2mirror = params.get("g2mirror");
if (g2mirror === undefined) return { user, host, port, mode: "tmux" };
// token[@host[:port]], split at the last "@" so the token may contain one.
const at = g2mirror.lastIndexOf("@");
const authToken = at < 0 ? g2mirror : g2mirror.slice(0, at);
const target = at < 0 ? "" : g2mirror.slice(at + 1);
const targetMatch = /^(\[[^\]\s]+\]|[^:\s]*)(?::(\d+))?$/.exec(target);
if (!authToken || !targetMatch) return null;
const targetHost = targetMatch[1] || "127.0.0.1";
const targetPort = targetMatch[2] ? parseInt(targetMatch[2], 10) : 8737;
if (!(targetPort >= 1 && targetPort <= 65535)) return null;
return { user, host, port, mode: "g2mirror", authToken, targetHost, targetPort };
}
export type ParsedAnyConnection =
| ({ kind: "g2mirror" } & ParsedConnectionString)
| ({ kind: "ssh" } & ParsedSshConnection);
/** Parse any supported connection string; null if it's none of them. */
export function parseAnyConnectionString(url: string): ParsedAnyConnection | null {
const direct = parseConnectionString(url);
if (direct) return { kind: "g2mirror", ...direct };
const ssh = parseSshConnectionString(url);
return ssh ? { kind: "ssh", ...ssh } : null;
}
/** The [user@]host[:port] part of a connection string (never a token); "" if it doesn't parse. */
export function connectionStringHostLabel(url: string): string {
const ssh = parseSshConnectionString(url);
if (ssh) {
const host = ssh.host.includes(":") ? `[${ssh.host}]` : ssh.host;
return `${ssh.user}@${host}${ssh.port === 22 ? "" : `:${ssh.port}`}`;
}
const parsed = parseConnectionString(url);
if (!parsed) return "";
const defaultPort = parsed.secure ? 443 : 8737;
@@ -79,6 +160,7 @@ export function loadConnections(): TerminalConnection[] {
url: String(item?.url ?? ""),
serverName: typeof item?.serverName === "string" && item.serverName ? item.serverName : null,
enabled: item?.enabled !== false,
hostKeys: Array.isArray(item?.hostKeys) ? item.hostKeys.filter((key: unknown) => typeof key === "string") : [],
}))
.filter((connection) => connection.id.length > 0 && connection.url.length > 0);
} catch {
+461 -36
View File
@@ -16,11 +16,17 @@
* Each view has its own websocket connection (the protocol allows one attached
* session per connection) and its own xterm emulator.
*
* Connections are g2mirror://<token>@<host>[:port] strings (g2mirrors:// for
* TLS), stored as JSON in the settings store (see connections.ts). Each
* enabled connection gets a control websocket that backs the session list and
* carries unsolicited bell/title notifications; control connections live as
* long as the worker so bells keep flowing even if the hub window is closed.
* Connections are connection strings stored as JSON in the settings store
* (see connections.ts): g2mirror://<token>@<host>[:port] for a g2mirror
* server (g2mirrors:// for TLS), ssh://<user>@<host> for tmux over SSH
* (TmuxClient), or ssh://<user>@<host>?g2mirror=<token> for a g2mirror server
* tunnelled over SSH. Each enabled connection gets a control client that
* backs the session list and carries bell/title/activity notifications;
* control connections live as long as the worker so bells keep flowing even
* if the hub window is closed. SSH connections that need the user (an
* unverified or changed host key, a password, an unauthorized key) record
* the failure on the control (sshIssue) and offer a page that resolves it
* instead of retrying.
* The host's server_name (from the init reply) is cached per connection and
* used as its display name, falling back to the connection string's
* host[:port] before the first successful handshake.
@@ -57,7 +63,22 @@ import { getActiveDisplay } from "../../native/active-display";
import { GESTURE_DOUBLE_CLICK, type InputEvent } from "../../ui/gestures";
import type { KeyEvent } from "../../g2/keyboard/keys";
import { encodeTerminalKey, terminalScrollbackKey } from "./terminal-keys";
import { G2MirrorClient, type G2MirrorClientOptions, type G2MirrorSession, type G2MirrorState } from "../../native/g2mirror-client";
import { G2MirrorClient, type G2MirrorSession, type G2MirrorState } from "../../native/g2mirror-client";
import type { TerminalClient } from "./terminal-client";
import { TmuxClient, type OpenLineChannel } from "./tmux-client";
import {
copyToPhoneClipboard,
describeSshFailure,
getSshSecret,
openSshChannel,
removeSshSecret,
setSshSecret,
sshClientKey,
type SshEndpoint,
type SshFailure,
type SshHostKey,
} from "../../native/ssh";
import { wrapText } from "../../graphics/textwrap";
import { onSettingsStoreChanged } from "../../native/settings-store";
import { clamp } from "../../util/numeric-util";
import {
@@ -66,12 +87,22 @@ import {
terminalDisplayLayoutSetting,
terminalLaunchPresetsSetting,
terminalNewConnectionSetting,
terminalSshPasswordSetting,
terminalWakeOnBellSetting,
textSettingMenuItem,
toggleSettingMenuItem,
} from "../../ui/dashboard-settings";
import { terminalFontPickerMenuItem } from "../../ui/font-picker";
import { connectionDisplayName, loadConnections, parseConnectionString, saveConnections, TERMINAL_CONNECTIONS_KEY, updateConnection, type TerminalConnection } from "./connections";
import {
connectionDisplayName,
connectionStringHostLabel,
loadConnections,
parseAnyConnectionString,
saveConnections,
TERMINAL_CONNECTIONS_KEY,
updateConnection,
type TerminalConnection,
} from "./connections";
import { TerminalEmulator } from "./terminal-emulator";
import { drawSubmenuIndicator, submenuItem, type MenuItem } from "../../ui/menu";
import { Menu, type MenuDrawArgs } from "../../ui/menu-core";
@@ -114,6 +145,10 @@ const RECONNECT_MAX_DELAY_MS = 60_000;
const NEW_CONNECTION_DRAFT_KEY = "terminal.newConnectionDraft";
// Storage key of terminalLaunchPresetsSetting, edited from the window menu.
const LAUNCH_PRESETS_KEY = "terminal.launchPresets";
// Storage key of terminalSshPasswordSetting (the password page's draft).
const SSH_PASSWORD_DRAFT_KEY = "terminal.sshPasswordDraft";
// Comment on this device's SSH public key in authorized_keys.
const SSH_KEY_COMMENT = "faceclaw";
type BaseWindow = {
windowId: string;
@@ -150,10 +185,24 @@ type BaseWindow = {
/**
* What the hub window is showing: the session list, the Manage Connections
* section, or the Add-connection screen (type the g2mirror:// string on the
* phone, click to save).
* section, the Add-connection screen (type the connection string on the
* phone, click to save), or a page of text with a click action (verify a
* host key, enter a password, show this device's SSH key).
*/
type HubMode = "sessions" | "connections" | "add";
type HubMode = "sessions" | "connections" | "add" | "page";
type HubPage = {
title: string;
/** Body text, wrapped to the window; re-read on every paint. */
body: () => string;
/** Bottom hint line. */
hint: string;
onClick?: () => void;
/** Double-click. */
onBack: () => void;
/** Runs whenever the page goes away (back, click, window closed). */
onLeave?: () => void;
};
type HubWindow = BaseWindow & {
kind: "hub";
@@ -170,6 +219,8 @@ type HubWindow = BaseWindow & {
sessionOrder: string[];
/** Parse-failure message shown on the Add-connection screen. */
addError: string;
/** The page shown in mode "page". */
page: HubPage | null;
};
type ViewWindow = BaseWindow & {
@@ -188,7 +239,7 @@ type ViewWindow = BaseWindow & {
label: string;
/** Sidebar-icon character (">3"); "" if every glyph was taken at open time. */
glyph: string;
client: G2MirrorClient;
client: TerminalClient;
emulator: TerminalEmulator;
receivedData: boolean;
attachRequested: boolean;
@@ -222,8 +273,8 @@ type PendingView = {
socket: string;
label: string;
glyph: string;
/** Client options captured when the view was requested from a live control. */
options: G2MirrorClientOptions;
/** How to make the view's client, captured when it was requested from a live control. */
options: ClientRecipe;
};
const windows = new Map<string, TerminalWindow>();
@@ -304,7 +355,13 @@ let screenOn = true;
*/
type ControlConnection = {
config: TerminalConnection;
client: G2MirrorClient | null;
client: TerminalClient | null;
/**
* An SSH failure only the user can fix (host key to verify, password or
* key needed). Shown on the host's heading with a row that opens the fix;
* reconnects wait for it. Cleared on a successful connection.
*/
sshIssue: SshFailure | null;
state: G2MirrorState | null;
unsubscribers: Array<() => void>;
reconnectTimer: ReturnType<typeof setTimeout> | null;
@@ -513,7 +570,8 @@ onSettingsStoreChanged((key) => {
reportIdle();
return;
case NEW_CONNECTION_DRAFT_KEY:
// Live keystrokes from the phone editor; repaint the add screen.
case SSH_PASSWORD_DRAFT_KEY:
// Live keystrokes from the phone editor; repaint the add/password screen.
renderHubWindows();
return;
case "terminal.autoReconnect":
@@ -587,6 +645,7 @@ function openWindow(windowId: string, surfaceId: string, title: string, viewport
list: null,
sessionOrder: [],
addError: "",
page: null,
});
// The hub carries the app's assistant tools; declare them once it exists.
post({ type: "set-tools", windowId, tools: TERMINAL_TOOLS });
@@ -619,6 +678,10 @@ function closeWindow(windowId: string): void {
// Window closed mid-add: shut the phone editor down.
endAddConnection(window);
}
if (window.kind === "hub" && window.mode === "page") {
// Likewise for a page's phone editor (the password draft).
closeHubPage(window, "sessions");
}
// Likewise for a setting being edited from the window menu.
window.menu?.close();
windows.delete(windowId);
@@ -636,17 +699,120 @@ function closeWindow(windowId: string): void {
}
}
/** Client options for a connection string; null if the string doesn't parse. */
function clientOptionsFor(connection: TerminalConnection): G2MirrorClientOptions | null {
const parsed = parseConnectionString(connection.url);
/**
* How to make clients for a connection: "g2mirror" dials a g2mirror server
* directly, "ssh-g2mirror" reaches one through an SSH tunnel, "tmux" runs
* tmux control mode over SSH.
*/
type ClientRecipe = {
kind: "g2mirror" | "ssh-g2mirror" | "tmux";
/**
* `role` "control" watches bells (tmux keeps the bell bookkeeping for that
* client only). `onSshFailure` hears why an SSH channel failed.
*/
create(cols: number, rows: number, role: "control" | "view", onSshFailure?: (failure: SshFailure) => void): TerminalClient;
};
/** Client recipe for a connection string; null if the string doesn't parse. */
function clientOptionsFor(connection: TerminalConnection): ClientRecipe | null {
const parsed = parseAnyConnectionString(connection.url);
if (!parsed) return null;
if (parsed.kind === "g2mirror") {
const { secure, host, port, authToken } = parsed;
return {
kind: "g2mirror",
create: (cols, rows) => new G2MirrorClient({ secure, host, port, authToken, deviceName: DEVICE_NAME, cols, rows }),
};
}
const connectionId = connection.id;
const label = connectionStringHostLabel(connection.url);
// Read at every channel open, so a newly trusted key or saved password
// applies to the next (re)connect, views included.
const endpoint = (): SshEndpoint => ({
host: parsed.host,
port: parsed.port,
user: parsed.user,
hostKeys: loadConnections().find((candidate) => candidate.id === connectionId)?.hostKeys ?? [],
password: getSshSecret(sshPasswordSecretId(connectionId)),
useKey: true,
});
if (parsed.mode === "g2mirror") {
const { authToken, targetHost, targetPort } = parsed;
const urlHost = targetHost.includes(":") && !targetHost.startsWith("[") ? `[${targetHost}]` : targetHost;
const url = `ws://${urlHost}:${targetPort}/`;
return {
kind: "ssh-g2mirror",
create: (cols, rows, _role, onSshFailure) =>
new G2MirrorClient({
secure: false,
host: targetHost,
port: targetPort,
authToken,
deviceName: DEVICE_NAME,
cols,
rows,
transport: {
label: `${label} over SSH`,
open: (listener) => {
const channel = openSshChannel(endpoint(), { type: "websocket", url }, {
onOpen: () => listener.onOpen(),
onText: (text) => listener.onTextMessage(text),
onClosed: (info) => listener.onClosed(info.code ?? 1000, info.reason ?? ""),
onFailure: (failure) => {
onSshFailure?.(failure);
listener.onFailure(describeSshFailure(failure));
},
});
return { sendText: (text) => channel.send(text), sendBinary: () => false, close: () => channel.close() };
},
},
}),
};
}
return {
...parsed,
deviceName: DEVICE_NAME,
...viewGrid(),
kind: "tmux",
create: (cols, rows, role, onSshFailure) => {
const openChannel: OpenLineChannel = (command, listener) =>
openSshChannel(endpoint(), { type: "exec", command }, {
onOpen: () => listener.onOpen(),
onText: (line) => listener.onLine(line),
onStderr: (line) => listener.onStderr(line),
onClosed: (info) => listener.onClosed(info.exitStatus ?? null),
onFailure: (failure) => {
onSshFailure?.(failure);
listener.onFailure(describeSshFailure(failure));
},
});
return new TmuxClient({ openChannel, label, cols, rows, stateKey: role === "control" ? connectionId : "" });
},
};
}
function sshPasswordSecretId(connectionId: string): string {
return `terminal.password.${connectionId}`;
}
/** Failures that retrying can't fix: the user has to verify a key or supply credentials. */
function sshFailureNeedsUser(failure: SshFailure): boolean {
return failure.kind === "hostkey-unknown" || failure.kind === "hostkey-mismatch" || failure.kind === "auth";
}
/**
* A control's SSH channel failed. If the user has to act, remember why, and
* if they're looking at the hub's lists, open the page that fixes it.
*/
function noteSshFailure(control: ControlConnection, failure: SshFailure): void {
if (!sshFailureNeedsUser(failure) || controls.get(control.config.id) !== control || !control.client) return;
control.sshIssue = failure;
renderHubWindows();
for (const window of windows.values()) {
if (window.kind === "hub" && window.foreground && (window.mode === "sessions" || window.mode === "connections")) {
openSshIssuePage(window, control);
break;
}
}
}
/**
* Reconcile the live control clients with the stored connection list: start
* enabled connections, stop disabled or removed ones, restart ones whose
@@ -672,6 +838,7 @@ function syncControlsFromSettings(): void {
control = {
config: connection,
client: null,
sshIssue: null,
state: null,
unsubscribers: [],
reconnectTimer: null,
@@ -693,12 +860,13 @@ function syncControlsFromSettings(): void {
function startControl(control: ControlConnection): void {
stopControl(control);
const options = clientOptionsFor(control.config);
if (!options) {
const recipe = clientOptionsFor(control.config);
if (!recipe) {
control.state = null;
return;
}
const client = new G2MirrorClient(options);
const grid = viewGrid();
const client = recipe.create(grid.cols, grid.rows, "control", (failure) => noteSshFailure(control, failure));
const connectionId = control.config.id;
control.client = client;
control.state = client.state();
@@ -712,6 +880,7 @@ function startControl(control: ControlConnection): void {
control.state = state;
if (state.phase === "connected") {
control.reconnectDelayMs = RECONNECT_MIN_DELAY_MS;
control.sshIssue = null;
maybeCacheServerName(control, state.serverName);
}
if (state.phase === "failed") scheduleControlReconnect(control);
@@ -786,6 +955,8 @@ function scheduleControlReconnect(control: ControlConnection): void {
if (!terminalAutoReconnectSetting.get()) return;
if (windows.size === 0 && !hasTerminalBackgroundWork()) return;
if (!control.config.enabled) return;
// Waiting on the user (host key, password) or on the host (no usable tmux).
if (control.sshIssue || control.state?.retryable === false) return;
const delayMs = control.reconnectDelayMs;
control.reconnectDelayMs = Math.min(control.reconnectDelayMs * 2, RECONNECT_MAX_DELAY_MS);
control.reconnectTimer = setTimeout(() => {
@@ -952,7 +1123,7 @@ function createViewWindow(
const cell = getTerminalFontConfig();
const gridCols = Math.floor(viewport.width / cell.cellWidth);
const gridRows = Math.floor(viewport.height / cell.cellHeight);
const client = new G2MirrorClient({ ...view.options, cols: gridCols, rows: gridRows });
const client = view.options.create(gridCols, gridRows, "view");
const window: ViewWindow = {
kind: "view",
hub: null,
@@ -1247,6 +1418,11 @@ function handleInput(window: TerminalWindow, event: InputEvent, frameId: number)
renderAndSubmit(window, frameId);
return;
}
if (window.kind === "hub" && window.mode === "page") {
window.page?.onBack();
renderAndSubmit(window, frameId);
return;
}
if (window.kind === "hub" && window.mode === "connections") {
setHubMode(window, "sessions");
renderAndSubmit(window, frameId);
@@ -1424,6 +1600,154 @@ function setHubMode(window: HubWindow, mode: HubMode): void {
window.addError = "";
}
function openHubPage(window: HubWindow, page: HubPage): void {
if (window.mode === "add") endAddConnection(window);
if (window.mode === "page") window.page?.onLeave?.();
window.page = page;
window.mode = "page";
scheduleRender(window);
}
/** Leave the current page (if any) for `mode`. */
function closeHubPage(window: HubWindow, mode: HubMode): void {
const page = window.page;
window.page = null;
page?.onLeave?.();
setHubMode(window, mode);
scheduleRender(window);
}
/** The list a page returns to: the one it was opened from. */
function hubListMode(window: HubWindow): HubMode {
return window.mode === "connections" ? "connections" : "sessions";
}
function openSshIssuePage(window: HubWindow, control: ControlConnection): void {
const issue = control.sshIssue;
if (!issue) return;
if (issue.kind === "hostkey-unknown" && issue.hostKey) {
openHostKeyPage(window, control, issue.hostKey);
} else if (issue.kind === "hostkey-mismatch" && issue.hostKey) {
openHostKeyChangedPage(window, control, issue.hostKey);
} else if (issue.kind === "auth" && issue.passwordAllowed) {
openPasswordPage(window, control, Boolean(issue.passwordTried));
} else if (issue.kind === "auth") {
openClientKeyPage(window, `${connectionDisplayName(control.config)} didn't accept this device's key (and doesn't take passwords).\n`);
}
}
function hostKeyTypeName(type: string): string {
if (type === "ssh-ed25519") return "ED25519";
if (type.startsWith("ecdsa-")) return "ECDSA";
if (type === "ssh-rsa") return "RSA";
return type;
}
function hostKeyFile(type: string): string {
if (type === "ssh-ed25519") return "/etc/ssh/ssh_host_ed25519_key.pub";
if (type.startsWith("ecdsa-")) return "/etc/ssh/ssh_host_ecdsa_key.pub";
return "/etc/ssh/ssh_host_rsa_key.pub";
}
/** First connection to an SSH host: show the key's fingerprint; click trusts it. */
function openHostKeyPage(window: HubWindow, control: ControlConnection, hostKey: SshHostKey): void {
const returnMode = hubListMode(window);
openHubPage(window, {
title: "Verify host key",
body: () =>
`First connection to ${connectionStringHostLabel(control.config.url)}. Its ${hostKeyTypeName(hostKey.type)} host key fingerprint is:\n` +
`${hostKey.fingerprint}\n\n` +
`To check it, run this on the host and compare:\nssh-keygen -lf ${hostKeyFile(hostKey.type)}`,
hint: `click trust and connect ${GESTURE_DOUBLE_CLICK} cancel`,
onClick: () => {
const hostKeys = [...control.config.hostKeys.filter((key) => key !== hostKey.key), hostKey.key];
control.config.hostKeys = hostKeys;
updateConnection(control.config.id, { hostKeys });
control.sshIssue = null;
closeHubPage(window, returnMode);
connectControl(control);
},
onBack: () => closeHubPage(window, returnMode),
});
}
function openHostKeyChangedPage(window: HubWindow, control: ControlConnection, hostKey: SshHostKey): void {
const returnMode = hubListMode(window);
openHubPage(window, {
title: "HOST KEY CHANGED",
body: () =>
`${connectionStringHostLabel(control.config.url)} presented a different host key than the one trusted before: ` +
`${hostKeyTypeName(hostKey.type)} ${hostKey.fingerprint}\n\n` +
"Someone may be intercepting the connection, so Faceclaw won't connect. If the host was reinstalled or its keys " +
'were regenerated, use "Forget host key" on this connection in Manage Connections, then verify the new fingerprint.',
hint: `${GESTURE_DOUBLE_CLICK} back`,
onBack: () => closeHubPage(window, returnMode),
});
}
/** Ask for the host's password on the phone (masked editor); click saves it and connects. */
function openPasswordPage(window: HubWindow, control: ControlConnection, rejected: boolean): void {
const returnMode = hubListMode(window);
terminalSshPasswordSetting.set("");
post({ type: "start-text-setting-edit", settingId: terminalSshPasswordSetting.id });
openHubPage(window, {
title: "SSH password",
body: () => {
const typed = terminalSshPasswordSetting.get();
return (
(rejected ? "The host refused the saved password.\n" : "") +
`Type the password for ${connectionStringHostLabel(control.config.url)} in the phone app, then click to connect. ` +
"It is saved encrypted on this phone.\n\n" +
(typed ? "*".repeat(Math.min(typed.length, 32)) : "(nothing typed yet)")
);
},
hint: `click connect ${GESTURE_DOUBLE_CLICK} cancel`,
onClick: () => {
const password = terminalSshPasswordSetting.get();
if (!password) return;
setSshSecret(sshPasswordSecretId(control.config.id), password);
control.sshIssue = null;
closeHubPage(window, returnMode);
connectControl(control);
},
onBack: () => closeHubPage(window, returnMode),
onLeave: () => {
terminalSshPasswordSetting.set("");
post({ type: "end-text-setting-edit" });
},
});
}
/** This device's SSH public key (the private half never leaves the keystore); click copies it. */
function openClientKeyPage(window: HubWindow, intro = ""): void {
const returnMode = hubListMode(window);
let key: { authorizedKey: string; fingerprint: string } | null = null;
let error = "";
try {
key = sshClientKey(SSH_KEY_COMMENT);
} catch (caught) {
error = String((caught as Error)?.message ?? caught);
}
let copied = false;
openHubPage(window, {
title: "This device's SSH key",
body: () =>
key
? `${intro}Add this line to ~/.ssh/authorized_keys on each host to log in with this phone's key:\n` +
`${key.authorizedKey}\n${key.fingerprint}` +
(copied ? "\n\nCopied to the phone's clipboard." : "")
: `Couldn't create this device's key: ${error}`,
hint: key ? `click copy to phone clipboard ${GESTURE_DOUBLE_CLICK} back` : `${GESTURE_DOUBLE_CLICK} back`,
onClick: key
? () => {
copyToPhoneClipboard("SSH public key", key!.authorizedKey);
copied = true;
}
: undefined,
onBack: () => closeHubPage(window, returnMode),
});
}
/**
* One control connection's sessions in this hub window's display order:
* most-recently-updated first as of when the window became visible, with
@@ -1479,6 +1803,7 @@ function hubSessionItems(window: HubWindow): HubItem[] {
];
const multiHost = controls.size > 1;
const canLaunch = launchPresetNames().length > 0;
const isTmux = (control: ControlConnection) => clientOptionsFor(control.config)?.kind === "tmux";
// Every configured host is listed under its own heading, in stored order,
// whatever its connection state: a connected host lists its sessions, any
// other shows its state on the heading plus a Connect row (unless it is
@@ -1488,10 +1813,17 @@ function hubSessionItems(window: HubWindow): HubItem[] {
const name = connectionDisplayName(control.config);
if (!isControlConnected(control)) {
items.push({ label: `${name} (${controlStatusWord(control)})`, heading: true });
if (control.sshIssue && control.config.enabled) {
items.push({ label: sshIssueAction(control.sshIssue), onSelect: () => openSshIssuePage(window, control) });
continue;
}
const connecting = control.config.enabled && control.state?.phase === "connecting";
if (!connecting && clientOptionsFor(control.config)) {
// A failure retrying can't fix (tmux missing or too old) says why;
// selecting it retries once the host is fixed.
const unfixable = control.config.enabled && control.state?.retryable === false;
items.push({
label: control.reconnectTimer ? "Connect now" : "Connect",
label: unfixable ? control.state!.status : control.reconnectTimer ? "Connect now" : "Connect",
onSelect: () => connectControl(control),
});
}
@@ -1500,7 +1832,8 @@ function hubSessionItems(window: HubWindow): HubItem[] {
items.push({
label: name,
heading: true,
onSelect: canLaunch ? () => launchOnHost(window, control) : undefined,
// tmux hosts can always start a shell, presets or not.
onSelect: canLaunch || isTmux(control) ? () => launchOnHost(window, control) : undefined,
});
const sessions = orderedSessions(window, control);
for (const session of sessions) {
@@ -1516,7 +1849,11 @@ function hubSessionItems(window: HubWindow): HubItem[] {
}
if (!sessions.length) {
items.push({
label: multiHost ? "(no live sessions)" : "(no live sessions; run g2mirror <command>)",
label: isTmux(control)
? "(no tmux sessions; select the host to start one)"
: multiHost
? "(no live sessions)"
: "(no live sessions; run g2mirror <command>)",
onSelect: () => control.client?.listSessions(),
});
}
@@ -1537,6 +1874,10 @@ function hubConnectionItems(window: HubWindow): HubItem[] {
label: "Add connection",
onSelect: () => beginAddConnection(window),
},
{
label: "This device's SSH key",
onSelect: () => openClientKeyPage(window),
},
{
label: "Done",
onSelect: () => setHubMode(window, "sessions"),
@@ -1547,6 +1888,13 @@ function hubConnectionItems(window: HubWindow): HubItem[] {
function controlStatusWord(control: ControlConnection): string {
if (!control.config.enabled) return "off";
const issue = control.sshIssue;
if (issue) {
if (issue.kind === "hostkey-unknown") return "verify host key";
if (issue.kind === "hostkey-mismatch") return "HOST KEY CHANGED";
if (issue.passwordTried) return "password rejected";
return issue.passwordAllowed ? "password needed" : "key not authorized";
}
switch (control.state?.phase) {
case "connected":
case "attached":
@@ -1579,6 +1927,32 @@ function openConnectionActions(window: HubWindow, control: ControlConnection): v
connectControl(control);
},
},
...(control.config.hostKeys.length
? [
{
label: "Forget host key",
onSelect: (ctx: { stack: { pop(): unknown } }) => {
ctx.stack.pop();
control.config.hostKeys = [];
updateConnection(control.config.id, { hostKeys: [] });
control.sshIssue = null;
if (control.config.enabled) startControl(control);
renderHubWindows();
},
},
]
: []),
...(isSshConnection(control) && getSshSecret(sshPasswordSecretId(control.config.id))
? [
{
label: "Forget saved password",
onSelect: (ctx: { stack: { pop(): unknown } }) => {
ctx.stack.pop();
removeSshSecret(sshPasswordSecretId(control.config.id));
},
},
]
: []),
{
label: `Remove ${name}`,
onSelect: (ctx) => {
@@ -1596,6 +1970,11 @@ function openConnectionActions(window: HubWindow, control: ControlConnection): v
windowMenu(window).open(items);
}
function isSshConnection(control: ControlConnection): boolean {
const kind = clientOptionsFor(control.config)?.kind;
return kind === "tmux" || kind === "ssh-g2mirror";
}
/** Enable and (re)connect now; also the manual retry path, so reset backoff. */
function connectControl(control: ControlConnection): void {
control.reconnectDelayMs = RECONNECT_MIN_DELAY_MS;
@@ -1616,6 +1995,7 @@ function disconnectControl(control: ControlConnection): void {
function removeControl(control: ControlConnection): void {
stopControl(control);
removeSshSecret(sshPasswordSecretId(control.config.id));
controls.delete(control.config.id);
saveConnections(loadConnections().filter((connection) => connection.id !== control.config.id));
renderHubWindows();
@@ -1624,7 +2004,7 @@ function removeControl(control: ControlConnection): void {
/**
* Enter the Add-connection screen: clear the draft and ask the shell to open
* the phone text editor on it. The user types (or voice-inputs) the
* g2mirror:// string, then clicks to save or double-clicks to cancel.
* connection string, then clicks to save or double-clicks to cancel.
*/
function beginAddConnection(window: HubWindow): void {
terminalNewConnectionSetting.set("");
@@ -1634,15 +2014,15 @@ function beginAddConnection(window: HubWindow): void {
function saveAddConnection(window: HubWindow): void {
const url = terminalNewConnectionSetting.get();
if (!parseConnectionString(url)) {
if (!parseAnyConnectionString(url)) {
window.addError = url
? "Not a g2mirror://token@host connection string."
: "Enter a g2mirror:// connection string first.";
? "Not an ssh://user@host or g2mirror://token@host string."
: "Enter a connection string first.";
scheduleRender(window);
return;
}
const connections = loadConnections();
connections.push({ id: `c${Date.now()}`, url, serverName: null, enabled: true });
connections.push({ id: `c${Date.now()}`, url, serverName: null, enabled: true, hostKeys: [] });
saveConnections(connections);
endAddConnection(window);
setHubMode(window, "connections");
@@ -1672,6 +2052,15 @@ function handleHubInput(window: HubWindow, event: InputEvent, frameId: number):
frameTimings.finishFrame(frameId, "discarded: terminal add-connection ignored input");
return;
}
if (window.mode === "page") {
if (event.type === "click" && window.page?.onClick) {
window.page.onClick();
renderAndSubmit(window, frameId);
return;
}
frameTimings.finishFrame(frameId, "discarded: terminal page ignored input");
return;
}
const list = hubMenu(window);
list.setItems(hubItems(window));
switch (event.type) {
@@ -1859,6 +2248,11 @@ function launchPresetNames(): string[] {
*/
function launchOnHost(window: HubWindow, control: ControlConnection): void {
const presets = launchPresetNames();
if (presets.length === 0) {
// A tmux host with no presets configured: a new session running the login shell.
launchFromUi(control, "shell");
return;
}
if (presets.length === 1) {
launchFromUi(control, presets[0]!);
return;
@@ -1903,6 +2297,9 @@ function paintHub(window: HubWindow): GrayImage {
if (window.mode === "add") {
return paintAddConnection(window);
}
if (window.mode === "page" && window.page) {
return paintHubPage(window, window.page);
}
const { viewportWidth: width, viewportHeight: height, padding } = window;
const image = new GrayImage(width, height, 0);
const font = chromeFont();
@@ -1917,7 +2314,7 @@ function paintHub(window: HubWindow): GrayImage {
let listTop = header.listTop;
if (window.mode === "sessions" && controls.size === 0) {
image.drawText(font, header.titleX, listTop, "Add a g2mirror:// connection to get started, see:", 150);
image.drawText(font, header.titleX, listTop, "Add an ssh:// (tmux) or g2mirror:// connection to get started, see:", 150);
image.drawText(font, header.titleX, listTop + step, "https://github.com/jimrandomh/g2mirror", 190);
listTop += 2 * step + 6;
}
@@ -1959,8 +2356,8 @@ function paintAddConnection(window: HubWindow): GrayImage {
image.drawText(font, padding.left, padding.top, "Add connection", 220);
const bodyX = padding.left + PAGE_BODY_INDENT;
const instructionsY = padding.top + 10 + step;
image.drawText(font, bodyX, instructionsY, "Type the g2mirror://token@host string in the", 170);
image.drawText(font, bodyX, instructionsY + step, "phone app (or use voice input from the menu).", 170);
image.drawText(font, bodyX, instructionsY, "Type ssh://user@host (tmux) or g2mirror://token@host in", 170);
image.drawText(font, bodyX, instructionsY + step, "the phone app (or use voice input from the menu).", 170);
const draftY = instructionsY + 3 * step;
const draft = terminalNewConnectionSetting.get();
image.drawText(font, bodyX, draftY, truncateLabel(draft || "(empty)", 52), 220);
@@ -1971,6 +2368,34 @@ function paintAddConnection(window: HubWindow): GrayImage {
return image;
}
/** A page of text: title at the top padding, wrapped body, hint on the bottom padding. */
function paintHubPage(window: HubWindow, page: HubPage): GrayImage {
const { viewportWidth: width, viewportHeight: height, padding } = window;
const image = new GrayImage(width, height, 0);
const font = chromeFont();
const step = lineStep(font);
image.drawText(font, padding.left, padding.top, page.title, 220);
const bodyX = padding.left + PAGE_BODY_INDENT;
const hintY = height - padding.bottom - font.lineHeight;
const lines = wrapText(font, page.body(), Math.max(1, width - padding.right - bodyX), { breakLongWords: true });
let y = padding.top + 10 + step;
for (const line of lines) {
if (y + step > hintY) break;
image.drawText(font, bodyX, y, line, 190);
y += step;
}
image.drawText(font, bodyX, hintY, page.hint, 110);
return image;
}
/** The action row under a host whose SSH connection needs the user. */
function sshIssueAction(issue: SshFailure): string {
if (issue.kind === "hostkey-unknown") return "Verify host key...";
if (issue.kind === "hostkey-mismatch") return "Host key changed!";
if (issue.passwordAllowed) return issue.passwordTried ? "Re-enter password..." : "Enter password...";
return "Show this device's SSH key...";
}
function truncateLabel(text: string, maxLength: number): string {
return text.length <= maxLength ? text : `${text.slice(0, Math.max(0, maxLength - 3))}...`;
}
+44
View File
@@ -0,0 +1,44 @@
import type {
G2MirrorHistoryReply,
G2MirrorPhase,
G2MirrorSession,
G2MirrorState,
} from "../../native/terminal-session-types";
/**
* What the Terminal worker needs from a session backend. G2MirrorClient (a
* g2mirror server, directly or tunnelled over SSH) and TmuxClient (tmux
* control mode over SSH) both provide it. The model is g2mirror's: a client
* starts "connecting", reaches "connected" (it can list and launch sessions,
* and reports bells/activity/titles for them), and can then attach to one
* session, view it (snapshot + live output), page its scrollback, and type
* into it.
*/
export interface TerminalClient {
state(): G2MirrorState;
onStateChange(listener: (state: G2MirrorState) => void): () => void;
/** Raw VT100/xterm bytes to feed the emulator. Snapshot implies reset-first. */
onTerminalData(listener: (data: Uint8Array, kind: "snapshot" | "output") => void): () => void;
onSessionAttached(listener: (command: string) => void): () => void;
onSessionDetached(listener: (reason: string) => void): () => void;
onBell(listener: (socket: string, lastBellAtMs: number) => void): () => void;
onActivity(listener: (socket: string, lastOutputAtMs: number) => void): () => void;
onTitle(listener: (socket: string, title: string) => void): () => void;
/** Fired after a snapshot's terminal data, with its scrollback splice point. */
onSnapshot(listener: (historyNext: number, historyOldest: number) => void): () => void;
onHistoryLines(listener: (reply: G2MirrorHistoryReply) => void): () => void;
setViewport(cols: number, rows: number): void;
start(): void;
stop(): void;
listSessions(): void;
launchSession(preset: string): Promise<string>;
connectSession(socket: string): void;
disconnectSession(): void;
view(): void;
unview(): void;
requestHistory(before: number, limit?: number): void;
sendInput(text: string): void;
submitInput(text: string): void;
}
export type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState };
File diff suppressed because it is too large. Load diff
+62
View File
@@ -0,0 +1,62 @@
/**
* Date and calendar-event text for the assistant's tool results. Pure (no
* native imports) so it can be unit-tested.
*/
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
export type FormattableEvent = {
title: string;
startMs: number;
endMs: number;
allDay: boolean;
location?: string;
};
export function formatEvent(event: FormattableEvent): string {
const location = event.location ? ` @ ${event.location}` : "";
return `- ${event.title || "(untitled)"} — ${formatEventSpan(event)}${location}`;
}
/**
* When an event happens, end included: a multi-day all-day event names its last
* day (all-day ends are exclusive, at the midnight after it), a timed event its
* end time. Without the end, an event that started yesterday and runs through
* tomorrow reads as yesterday's.
*/
export function formatEventSpan(event: Pick<FormattableEvent, "startMs" | "endMs" | "allDay">): string {
const start = new Date(event.startMs);
if (event.allDay) {
const lastDay = new Date(Math.max(event.startMs, event.endMs - 1));
return sameDay(start, lastDay)
? `${formatDate(start)} (all day)`
: `${formatDate(start)} – ${formatDate(lastDay)} (all day)`;
}
if (!(event.endMs > event.startMs)) return formatDateTime(start);
const end = new Date(event.endMs);
return sameDay(start, end)
? `${formatDateTime(start)} – ${formatTime(end)}`
: `${formatDateTime(start)} – ${formatDateTime(end)}`;
}
export function formatDateTime(date: Date): string {
return `${formatDate(date)}, ${formatTime(date)}`;
}
export function formatDate(date: Date): string {
return `${WEEKDAYS[date.getDay()]} ${MONTHS[date.getMonth()]} ${date.getDate()}`;
}
export function formatTime(date: Date): string {
let hours = date.getHours();
const minutes = date.getMinutes().toString().padStart(2, "0");
const meridiem = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
if (hours === 0) hours = 12;
return `${hours}:${minutes} ${meridiem}`;
}
function sameDay(a: Date, b: Date): boolean {
return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}
+2 -27
View File
@@ -1,10 +1,11 @@
import { readUpcomingEventsAsync, type CalendarEvent } from "../native/calendar";
import { readUpcomingEventsAsync } from "../native/calendar";
import { hasCalendarPermission } from "../native/calendar-permissions";
import { mediaControllerBridge } from "../native/media-controller";
import { spotifyService } from "../native/spotify";
import { dismissNotification, readActiveNotifications } from "../native/notification-icons";
import { shell } from "../ui/shell/shell";
import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registry";
import { formatDateTime, formatEvent } from "./date-format";
/**
* Registers the always-available system tools into the registry. Called once at
@@ -12,9 +13,6 @@ import { toolRegistry, type ToolRegistry, type ToolResult } from "./tool-registr
* media, notifications); nothing here needs an app window to be open.
*/
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
let registered = false;
export function registerSystemTools(registry: ToolRegistry = toolRegistry): void {
@@ -244,35 +242,12 @@ function describeNowPlaying(): string {
return "Nothing is currently playing.";
}
function formatEvent(event: CalendarEvent): string {
const when = event.allDay ? `${formatDate(new Date(event.startMs))} (all day)` : formatDateTime(new Date(event.startMs));
const location = event.location ? ` @ ${event.location}` : "";
return `- ${event.title || "(untitled)"} — ${when}${location}`;
}
function formatNotification(notification: { key: string; appName: string; title: string; text: string; customText?: string[] }): string {
const title = notification.title || notification.customText?.join(" ") || "(no title)";
const body = notification.text ? `: ${notification.text}` : "";
return `- [${notification.appName}] ${title}${body} (key: ${notification.key})`;
}
function formatDateTime(date: Date): string {
return `${formatDate(date)}, ${formatTime(date)}`;
}
function formatDate(date: Date): string {
return `${WEEKDAYS[date.getDay()]} ${MONTHS[date.getMonth()]} ${date.getDate()}`;
}
function formatTime(date: Date): string {
let hours = date.getHours();
const minutes = date.getMinutes().toString().padStart(2, "0");
const meridiem = hours >= 12 ? "PM" : "AM";
hours = hours % 12;
if (hours === 0) hours = 12;
return `${hours}:${minutes} ${meridiem}`;
}
function clampNumber(value: unknown, min: number, max: number, fallback: number): number {
const num = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(num)) return fallback;
+17
View File
@@ -68,6 +68,23 @@ export function extractG2Mac(mfg: Uint8Array): string | null {
return humanReadableAddressFromWireBytes(mfg.subarray(16, 22));
}
/**
* G2 manufacturer data (hex) carrying `serial` and `address`, for an arm known
* only from a saved pairing: what `extractG2Serial` and `extractG2Mac` read
* back, with the serial zero-padded and no flag byte. Null when the serial is
* not up to 14 printable ASCII characters or the address is not a MAC.
*/
export function g2ManufacturerData(serial: string, address: string): string | null {
const wire = wireBytesFromHumanReadableAddress(address);
if (!wire || !/^[\x20-\x7e]{1,14}$/.test(serial)) return null;
const bytes = new Uint8Array(22);
bytes[0] = 0x45;
bytes[1] = 0x52;
for (let i = 0; i < serial.length; i++) bytes[2 + i] = serial.charCodeAt(i);
bytes.set(wire, 16);
return bytesToHex(bytes);
}
/** Preserve the final G2 manufacturer-data byte without guessing its meaning. */
export function extractG2AdvertisementFlag(mfg: Uint8Array): number | null {
if (mfg.length < 23 || !hasEvenManufacturerSignature(mfg)) return null;
+1 -1
View File
@@ -26,7 +26,7 @@ export type FirmwareInfo = {
};
/** The Faceclaw firmware revision this build of the app needs. */
export const REQUIRED_FACECLAW_FIRMWARE_VERSION = 39;
export const REQUIRED_FACECLAW_FIRMWARE_VERSION = 40;
const FACECLAW_PREFIX = "Faceclaw/";
const LEGACY_PREFIX = "EVENCFW";
+76 -40
View File
@@ -19,42 +19,42 @@ export type FirmwarePatchSet = {
export const CFW_PATCH_SET: FirmwarePatchSet = {
"base": "g2_2.3.0.24.bin",
"baseSha256": "187ccf2bcc5c17a212106e8a376745511e8289c4232b634a7ea94b9bf25a0979",
"outputSha256": "e43be9d04031d261574f96d45cb1e0edd67bfb39f0213f323ff82d8560ae454d",
"outputSha256": "2a31417f04cec16ecd4e4c3e575d89ce77fb3c5386b47cdb49b9753aaefb1c32",
"patches": [
{
"offset": 1379947,
"old": "0ef009fa",
"new": "0af3b8fb",
"new": "08f3a6fc",
"desc": "DM callback allocation: retain keyboard lifecycle on queue exhaustion"
},
{
"offset": 1380027,
"old": "0ef0e1f9",
"new": "0af316fb",
"new": "08f304fc",
"desc": "ATT callback allocation: expose lost keyboard events as relay gaps"
},
{
"offset": 2649417,
"old": "0a681279",
"new": "d4f167fb",
"new": "d2f155fc",
"desc": "SMP Pairing I/O capability: KeyboardDisplay only for owned keyboard"
},
{
"offset": 2651811,
"old": "0a681279",
"new": "d3f1bafe",
"new": "d1f1a8ff",
"desc": "SMP Pairing I/O capability: KeyboardDisplay only for owned keyboard"
},
{
"offset": 1385975,
"old": "38b584b0",
"new": "08f3d4be",
"new": "06f3c2bf",
"desc": "BLE app dispatcher: isolate explicitly enabled keyboard connection"
},
{
"offset": 1045797,
"old": "38b584b0",
"new": "5df31bb9",
"new": "5bf309ba",
"desc": "ring receiver entry: timestamped unfiltered reports under framebuffer lease"
},
{
@@ -66,49 +66,49 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1437923,
"old": "fef788ff",
"new": "fdf24cfe",
"new": "fbf23aff",
"desc": "cfw_ancs_event"
},
{
"offset": 1437951,
"old": "fef7e8fb",
"new": "fdf27afb",
"new": "fbf268fc",
"desc": "cfw_ancs_open"
},
{
"offset": 1437969,
"old": "fef7e7fb",
"new": "fdf295fb",
"new": "fbf283fc",
"desc": "cfw_ancs_close"
},
{
"offset": 1388387,
"old": "39694d00",
"new": "79647d00",
"new": "55467d00",
"desc": "connection-bound ANCS EUS write callback"
},
{
"offset": 971497,
"old": "fff717f8",
"new": "6ff34bfa",
"new": "6df339fb",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 971845,
"old": "fef769ff",
"new": "6ff39df9",
"new": "6df38bfa",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 979579,
"old": "fdf74ef8",
"new": "6df382fa",
"new": "6bf370fb",
"desc": "bl faceclaw_input_bridge_received (ring relay and ordered private transport before worker pool)"
},
{
"offset": 1428895,
"old": "f8f76cfd",
"new": "fbf2acfa",
"new": "f9f2d0fb",
"desc": "bl cfw_receive_packet (private SID-f0 probe before TPL reassembly)"
},
{
@@ -132,7 +132,7 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
{
"offset": 1058287,
"old": "fff754fb",
"new": "5af3ecf8",
"new": "58f3daf9",
"desc": "bl ble_classify_link (only a <= 11.25 ms / latency-0 link is 'already fast')"
},
{
@@ -141,148 +141,184 @@ export const CFW_PATCH_SET: FirmwarePatchSet = {
"new": "5ff43332",
"desc": "reserve final 1 KiB of primary TLSF arena for CFW context anchor"
},
{
"offset": 1130241,
"old": "5ff44d22",
"new": "5ff40622",
"desc": "LVGL arena size 0xcd000 -> 0x86000 (fixed CFW buffers follow it)"
},
{
"offset": 2697223,
"old": "9c212020",
"new": "9c192320",
"desc": "EvenHub arena base 0x2020219c -> 0x2023199c"
},
{
"offset": 2697133,
"old": "5ff4e121",
"new": "5ff48221",
"desc": "EvenHub arena clear length 0x70800 -> 0x41000"
},
{
"offset": 2697149,
"old": "5ff4e121",
"new": "5ff48221",
"desc": "EvenHub TLSF pool size 0x70800 -> 0x41000"
},
{
"offset": 2245731,
"old": "5ff4e125",
"new": "5ff48225",
"desc": "EvenHub heap total in the stock usage log 0x70800 -> 0x41000"
},
{
"offset": 4394495,
"old": "9b212020",
"new": "9bb11b20",
"desc": "MPU region 6 (non-cacheable) ends with the shrunk LVGL arena"
},
{
"offset": 1248487,
"old": "d4f712fb",
"new": "29f396f8",
"new": "27f3a0f9",
"desc": "bl settings_send_wrapper (append caps field 100)"
},
{
"offset": 1246183,
"old": "f5f7e2f8",
"new": "29f394fa",
"new": "27f3befb",
"desc": "bl settings_decode_wrapper (Faceclaw lease field 101)"
},
{
"offset": 975219,
"old": "02f083fc",
"new": "6bf3f6fa",
"new": "69f320fc",
"desc": "bl faceclaw_display_start @ 0x467d68 (fail-open wake takeover)"
},
{
"offset": 975411,
"old": "02f023fc",
"new": "6bf364fb",
"new": "69f38efc",
"desc": "bl faceclaw_display_start_headup @ 0x467e28 (fail-open wake takeover)"
},
{
"offset": 975103,
"old": "07f085fb",
"new": "6ef350fa",
"new": "6cf33efb",
"desc": "bl headup_gate (idle input gate: tap/long/release -> field-102 events, stock result kept)"
},
{
"offset": 830549,
"old": "19f03efb",
"new": "91f325fc",
"new": "8ff313fd",
"desc": "bl gesture_ring_press_mode (ring touch-down 14, head up 12 / down 15; stock dispatch preserved)"
},
{
"offset": 830795,
"old": "1ff071ff",
"new": "91f3defb",
"new": "8ff3ccfc",
"desc": "bl gesture_press (owned event 9 before stock menu gate)"
},
{
"offset": 830887,
"old": "1ff043ff",
"new": "91f3d8fb",
"new": "8ff3c6fc",
"desc": "bl gesture_short_long (Faceclaw lease gates event 11 vs stock Menu path)"
},
{
"offset": 831763,
"old": "1ff08dfd",
"new": "91f30efa",
"new": "8ff3fcfa",
"desc": "bl gesture_release (owned event 10 before stock menu gate)"
},
{
"offset": 1570209,
"old": "7fb50600",
"new": "daf227bc",
"new": "d8f231bd",
"desc": "even_ai_display_ctrl entry -> conditional Faceclaw lease trampoline"
},
{
"offset": 1051545,
"old": "f6f787f9",
"new": "54f31dfe",
"new": "54f359fe",
"desc": "bl display_copy_hook @ 0x47a78e (640x480 direct framebuffer)"
},
{
"offset": 1051861,
"old": "f6f7e9f8",
"new": "54f37ffd",
"new": "54f3bbfd",
"desc": "bl display_copy_hook @ 0x47a8ca (640x480 direct framebuffer)"
},
{
"offset": 1262237,
"old": "d9f7d0fd",
"new": "25f3c3f9",
"new": "23f3edfa",
"desc": "bl faceclaw_send_wear_event @ 0x4ade92 (outside onboarding)"
},
{
"offset": 1262337,
"old": "d9f79efd",
"new": "25f391f9",
"new": "23f3bbfa",
"desc": "bl faceclaw_send_wear_event @ 0x4adef6 (outside onboarding)"
},
{
"offset": 1309405,
"old": "67f02dff",
"new": "19f35ffa",
"new": "17f397fb",
"desc": "bl compass_decode_capture (sample-matched GAF diagnostics)"
},
{
"offset": 1307865,
"old": "fff7c9fb",
"new": "19f3e1fd",
"new": "17f319ff",
"desc": "bl compass_report_event (stock UI + heading with diagnostics over BLE)"
},
{
"offset": 1300937,
"old": "00210170",
"new": "1bf3bffa",
"new": "19f3f7fb",
"desc": "bl compass_preserve_accuracy (retain magnetic calibration under Faceclaw framebuffer lease)"
},
{
"offset": 4537963,
"old": "",
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf80b5002a18bf10f0030301d186460ce000f1010c864600bf013a0ef8011b04d01cf003030cf1010cf6d1102a11d35ffa81fc4ff001330cfb03fc00bf103acef80cc0cef808c0cef804c04ef810cb0f2af4d8042a0bd35ffa81fc4ff001330cfb03fc00bf043a032a4ef804cbfad8002a08bf80bdaef10103013a03f8011ffbd180bd00bf2de9f04fc7b04ff29c5bc2f2290b4ff6ff754ff47e740027012647f67f784ff07f0a1191cde90f3007e000bf48f2a351c0f24501bff32f8f8847dbf80090bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66c62ccf2ff02914203d14068b0f57e7f3ed04ff47e7006f017fa002800f01b816ff0070142180831b1f57c7f177257729772d772177357739773d773f2d14ef66c61ccf2ff01016044608673a0f8c48180f8c3a1058445848584c584058545858585c585058645868586c586058745878587c5875be8001f4945a9d1bff35f8f4be8000121b15be8001f4945f8d09fe74ff47e7800264ff0010a47f67f797f2707e000bf48f2a351c0f24501bff32f8f8847dbf80040bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66c62ccf2ff02914203d14168b1f57e7f40d04ff47e7006f0adf9002800f0b1806ff0070142180831b1f57c7f167256729672d672167356739673d673f2d14ef66c61ccf2ff010160c0f8048080f80ea0a0f8c49180f8c371058445848584c584058545858585c585058645868586c586058745878587c5875be8001fa142a7d1bff35f8f4be8000121b15be8001fa142f8d09de7d0f8948242f6f76ac0f2440ab8f1000fbff35f8f4ad00af19a0240464ff0ff314ff0ff379047002840f036811198002860d010980778a7f1170002285ad811980c2840f02381109c6078a178084300f01d81e0780138022800f21881a279e379667a42ea0322237a207942ea034242ea0663a27ae67a6179192f42ea062200f08481172f40f09a81002a40f0ff80fe2800f0b285812800f0a585002840f0b88551ea030040f0f28000f002be04460020d047e0b104f5257151e8008fb8f1000f0cd1bff35f8f00bf41e80002002a00f08b8051e8008fb8f1000ff5d00021bff32f8f0029bff35f8f7ad0804693e74ff0ff37d1e047f6df40c0f24f00cdf83880804700274ff47e784ff0010947f67f764ff07f0a1397adf8507006e048f2a351c0f24501bff32f8f8847dbf80040bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66c62ccf2ff02914203d14168b1f57e7f47d04ff47e7006f0bdf8002840d06ff0070100bf42180831b1f57c7f177257729772d772177357739773d773f2d14ef66c61ccf2ff010160c0f8048080f80e90a0f8c46180f8c3a1058445848584c584058545858585c585058645868586c586058745878587c5875be8001fa142a7d1bff35f8f4be8000159b15be8001fa142f8d09de70af5a971884716e701217ae70020109f42f6f76addf83880c0f2440a9fb1119989b1397801f07f02b2f10b0418bf0124b2f11c0618bf01268a2924dc0b2926d01c2924d03ce00f9012a803f055fd4ff0ff3701269df85100002812a818bf4ff0ff3703f019fe054646b99df8500028b94af21f30c0f247004c3080470f98002818bf056114e09c2901d08b2918d168b14af21f31c0f247010746884797f8681121b997f824133846109f49b14ff0ff370af5807140468847384647b0bde8f08f0f9012a8264003f017fd387800f07f041e2c05d11199384608f048fd0746b9e71d2c00f07e0018bf1a2819d1dbf800100322cff680720a40b2f1005fbff35f8f12d10a684ef66c63ccf2ff039a420bd14a68b2f57e7f04bf002281f8a12303e0a4f115010129e1d90f2c2cdd142c40f3bb81152c00f0ba82162c00f0c4821f2c40f088831198012840f0588438781f2840f0548445f64d54c0f24604a047012841f0388041f21051c0f2010104f5e2777944e02029220023b8470746002818bf4ff0ff3766e7092c00f3a980052c00f0f081072c40f05e830d9600264ff0010947f67f744ff07f083ae000294ff0ff3708bf002b7ff47caf1328bff479af102a4ff0000138bf01211228b2fa82f218bf510901297ff46caf00f07abc182f4ff0ff3708bf00297ff463af002b7ff460af352800f36483002800f05284012800f05e84312840f05084082abff451af00f05fbc48f2a351c0f24501bff32f8f8847dbf80070bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0bd101684ef66c62ccf2ff02914204d14168b1f57e7f00f060854ff47e7005f051ff002800f058856ff0070142180831b1f57c7f167256729672d672167356739673d673f2d14ef66c61ccf2ff0101604ff47e71416080f80e90a0f8c44180f8c381058445848584c584058545858585c585058645868586c586058745878587c5875be8001fb942a5d1bff35f8f4be80001002900f021855be8001fb942f6d099e70a2c00f0bc810b2c40f0b582dbf800500320cff680702840b0f1005fbff35f8f40f0698728684ef66c61ccf2ff01884240f0618768680027b0f57e7f7ff49baed5f8900342f68d49c0f244090028a5f8a07318bfc8470021a5f8d013c5f8cc13c5f86c1185f86a1185f86811d5f87001c5f8641185f86911c5f87011c5f82013a5f88c1320b148f2a351c0f245018847d5f89802002818bf03f099fd0024c5f89842d5f8880320b148f2a351c0f245018847c5f88843a5f88c43686ca5f8484040b1c847686c09f166018847002804bf002068644bf63940c0f251008047dbf800400320cff680702040b0f1005fbff35f8f48d120684ef66c61ccf2ff01884241d16068b0f57e7f3dd194f87b014Line truncated
"new": "b0b581ea00039b0701d0034637e0c2b110f0030315d000f1010ca2f1010e0023cc5c9e45c45403f1010404d0634413f003032346f4d121440319121b102a14d302e00346102a10d3d1f800c0d1f804e0cc688d68103adc609d60c3f804e043f810cb0f2a01f11001eed8042a07d300bf51f8045b043a032a43f8045bf8d8002a08bfb0bd0139013b11f8015f013a03f8015ff9d1b0bd00bf884218bf002a00d1704710b50b1a38bf431a934207d288420ad281ea00039b0726d0034669e0fff79fffbde81040704781ea000300eb020c9b0701eb020e42d15fea8c732bd0a0f1010c00bf8b1813f801ec8418531e04f801ec04d0624412f003021a46f2d101eb030e00eb030c17e0830736d0a2f1010c00f1010e002300bfcc5c9c45c45403f1010404d0734413f003032346f4d1121b2144031922e01346042b0ed3aef10402acf1040152f80449043b032b41f80449f8d802f1040e01f1040c1a4653b1aef10101acf1010300bf11f80149013a03f80149f9d1bde8104070470346042a06d351f8044b043a032a43f8044bf8d8002af0d00139013b00bf11f8014f013a03f8014ff9d1e6e700bf80b5002a18bf10f0030301d186460ce000f1010c864600bf013a0ef8011b04d01cf003030cf1010cf6d1102a11d35ffa81fc4ff001330cfb03fc00bf103acef80cc0cef808c0cef804c04ef810cb0f2af4d8042a0bd35ffa81fc4ff001330cfb03fc00bf043a032a4ef804cbfad8002a08bf80bdaef10103013a03f8011ffbd180bd00bf2de9f04fc7b04ff29c5bc2f2290b4ff6ff784ff47e740027012647f67f754ff07f0a1191cde90f3007e000bf48f2a351c0f24501bff32f8f8847dbf80090bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66d62ccf2ff02914203d14068b0f57e7f4ed04ff47e7002f0f9f9002800f027816ff0070142180831b1f57c7f177257729772d772177357739773d773f2d14ef66d61ccf2ff01016044608673a0f8c85180f8c7a1a0f82080a0f82280a0f82480a0f82680a0f82880a0f82a80a0f82c80a0f82e80a0f83080a0f83280a0f83480a0f83680a0f83880a0f83a80a0f83c80a0f83e805be8001f494599d1bff35f8f4be8000121b15be8001f4945f8d08fe74ff47e7a00254ff0010947f67f777f2407e000bf48f2a351c0f24501bff32f8f8847dbf80060bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66d62ccf2ff02914203d14168b1f57e7f50d04ff47e7002f07ff9002800f0ad806ff0070142180831b1f57c7f157255729572d572157355739573d573f2d14ef66d61ccf2ff010160c0f804a080f80e90a0f8c87180f8c741a0f82080a0f82280a0f82480a0f82680a0f82880a0f82a80a0f82c80a0f82e80a0f83080a0f83280a0f83480a0f83680a0f83880a0f83a80a0f83c80a0f83e805be8001fb14297d1bff35f8f4be8000121b15be8001fb142f8d08de7d0f8984242f6f76ac0f2440abff35f8fdcb30af19a0220464ff0ff314ff0ff379047002840f02e81119800284ed010980778a7f11700022848d811980c2821d1109d6878a97808431cd0e8780138022818d8aa79eb796e7a42ea03222b7a287942ea034242ea0663aa7aee7a6979192f42ea062200f07f81172f40f09581002a00f04e834ff0ff37f8e004460020d047c8b104f5267151e8004f54b9bff35f8f41e80002002a00f0998051e8004f002cf6d00021bff32f8f0029bff35f8f00f089800446a5e74ff0ff37dbe047f6df40c0f24f000e94804700274ff47e79012647f67f744ff07f0a13978df8507006e048f2a351c0f24501bff32f8f8847dbf80050bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0ad101684ef66d62ccf2ff02914203d14168b1f57e7f57d04ff47e7002f095f8002850d06ff0070100bf42180831b1f57c7f177257729772d772177357739773d773f2d14ef66d61ccf2ff010160c0f804908673a0f8c84180f8c7a1a0f82080a0f82280a0f82480a0f82680a0f82880a0f82a80a0f82c80a0f82e80a0f83080a0f83280a0f83480a0f83680a0f83880a0f83a80a0f83c80a0f83e805be8001fa94298d1bff35f8f00bf4be8000159b15be8001fa942f8d08de70af5a97188471ae701216be70020109f42f6f76ac0f2440a9fb1119989b1397801f07f02b2f10b0418bf0124b2f11c0518bf01258a291edc0b2920d01c291ed03ae00f9012a801f06dfe4ff0ff37012612a801f037ff054646b99df8500028b94af21f30c0f247004c3080470f98002818bf056117e09c2901d08b291cd180b14af21f31c0f247010646884796f86811bff35f8f29b996f824133046bff35f8f51b14ff0ff370e9c0af5807120468847384647b0bde8f08f0f9012a804ea050601f030fe387800f07f041e2c05d11199384606f01ffe0746bae71d2c00f07e0018bf1a2819d1dbf800100322cff680720a40b2f1005fbff35f8f12d10a684ef66d63ccf2ff039a420bd14a68b2f57e7f04bf002281f8a12303e0a4f115010129e1d90f2c2cdd142c40f3ad81152c00f0c882162c00f0d2821f2c40f095831198012840f0648438781f2840f0608445f64d54c0f24604a047012841f05e8041f2de01c0f2010104f5e2777944e02029220023b8470746002818bf4ff0ff3767e7092c00f3b880052c00f0ee81072c40f06b830d9600264ff0010947f67f777f243ae000294ff0ff3708bf002b7ff47caf1328bff479af102a4ff0000138bf01211228b2fa82f218bf510901297ff46caf00f087bc182f4ff0ff3708bf00297ff463af002b7ff460af352800f37083002800f05f84012800f06b84312840f05d84082abff451af00f06cbc48f2a351c0f24501bff32f8f8847dbf80050bff35f8fdbf800000321cff680710140b1f1005fbff35f8f0bd101684ef66d62ccf2ff02914204d14168b1f57e7f00f077854ff47e7001f01dff002800f06f856ff0070142180831b1f57c7f167256729672d672167356739673d673f2d14ef66d61ccf2ff0101604ff47e71416080f80e90a0f8c87180f8c741a0f82080a0f82280a0f82480a0f82680a0f82880a0f82a80a0f82c80a0f82e80a0f83080a0f83280a0f83480a0f83680a0f83880a0f83a80a0f83c80a0f83e805be8001fa94295d1bff35f8f4be80001002900f028855be8001fa942f6d089e70a2c00f0bb810b2c40f0b382dbf800500320cff680702840b0f1005fbff35f8f40f0808728684ef66d61ccf2ff01884240f0788768680027b0f57e7f7ff48daed5f8900342f68d49c0f244090028a5f8a07318bfc8470021a5f8d013c5f8cc13c5f8701185f86c11bff35f8f85f86811686c85f86b11c5f87411c5f82013c5f88813a5f88c13a5f8481040b1c847686c09f166018847002804bf002068644bf63940c0f251008047dbf800400320cff680702040b0f1005fbff35f8f46d120684ef66Line truncated
"desc": "append injected blobs to main-app payload"
},
{
"offset": 779123,
"old": "805a3900",
"new": "187c3a00",
"new": "10783a00",
"desc": "main-app subheader payload size (ps)"
},
{
"offset": 152,
"old": "005b3900",
"new": "987c3a00",
"new": "90783a00",
"desc": "main-app TOC entry size (ps + 128)"
},
{
"offset": 779243,
"old": "805a3904",
"new": "187c3a04",
"new": "10783a04",
"desc": "main-app preamble length (low 24 bits)"
},
{
"offset": 779247,
"old": "effdbcea",
"new": "ed6f6deb",
"new": "adc5378e",
"desc": "[5] ota/s200_firmware_ota.bin preamble crc32"
},
{
"offset": 156,
"old": "c0c6322a",
"new": "7141aa39",
"new": "0c2e1c3e",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (TOC)"
},
{
"offset": 779127,
"old": "c0c6322a",
"new": "7141aa39",
"new": "0c2e1c3e",
"desc": "[5] ota/s200_firmware_ota.bin component crc32c (subheader)"
}
]
+26 -1
View File
@@ -10,10 +10,15 @@
* (a terminal session), since that is the point of binding a remote's
* few buttons.
* 2. Built-in bindings that also apply there: Escape with Shift, Ctrl or
* Alt goes back, which is the way out of a terminal session.
* Alt goes back, which is the way out of a terminal session; and a
* mouse's buttons and wheel, which are never typed.
* 3. Built-in navigation, only for keys no window took: the arrows are the
* watch's four swipes, Enter selects, Escape goes back.
*
* A keyboard's touchpad or mouse arrives here as keys too: "MouseButton1"
* (left), "MouseButton2" (right), "MouseButton3" (middle) and so on, and
* "WheelUp" / "WheelDown" / "WheelLeft" / "WheelRight" (see pointer.ts).
*
* No platform imports: this runs under node in the tests.
*/
import type { KeyEvent } from "./keys";
@@ -113,6 +118,8 @@ const CODE_LABELS: Record<string, string> = {
BrightnessUp: "Brightness Up", BrightnessDown: "Brightness Down",
BrowserSearch: "Search", BrowserHome: "Browser Home", BrowserBack: "Browser Back", BrowserForward: "Browser Forward",
LaunchMail: "Mail", LaunchApplication1: "App 1", LaunchApplication2: "App 2",
MouseButton1: "Left button", MouseButton2: "Right button", MouseButton3: "Middle button",
WheelUp: "Wheel up", WheelDown: "Wheel down", WheelLeft: "Wheel left", WheelRight: "Wheel right",
};
/** A key as a person would name it. Unknown keys keep their HID usage number, which is all there is. */
@@ -125,6 +132,8 @@ function codeLabel(code: string): string {
if (match) return match[1]!;
match = /^Numpad(.+)$/.exec(code);
if (match) return `Numpad ${match[1]}`;
match = /^MouseButton([0-9]+)$/.exec(code);
if (match) return `Mouse button ${match[1]}`;
match = /^Usage([0-9a-f]+)$/.exec(code);
if (match) return `Key 0x${match[1]}`;
match = /^Consumer([0-9a-f]+)$/.exec(code);
@@ -174,12 +183,26 @@ export function keyBindingMap(bindings: readonly KeyBinding[]): Map<string, KeyA
return new Map(bindings.map((binding) => [chordId(binding.chord), binding.action]));
}
/** What a mouse does unless bound otherwise: the ring's tap, double tap, hold and scroll. */
const MOUSE_DEFAULTS: Record<string, KeyGesture | undefined> = {
MouseButton1: "click",
MouseButton2: "double-click",
MouseButton3: "long-press",
WheelUp: "scroll-up",
WheelDown: "scroll-down",
};
/**
* The built-in meaning of a key press, or null when it has none.
* `overridesTyping`: it holds even where the focused window takes keys.
* Built-ins go by the logical key, so both Enter keys select.
*/
export function defaultKeyAction(event: KeyEvent): { action: KeyGesture; overridesTyping: boolean } | null {
// A mouse's buttons and wheel are the ring's gestures: tap, double tap,
// hold, and scroll. Nothing types them, so they hold everywhere, whatever
// is held on the keyboard.
const mouse = MOUSE_DEFAULTS[event.key];
if (mouse) return { action: mouse, overridesTyping: true };
const { shift, ctrl, alt, meta } = event.modifiers;
if (meta) return null;
if (event.key === "Escape") {
@@ -208,6 +231,8 @@ export function defaultKeyAction(event: KeyEvent): { action: KeyGesture; overrid
export const DEFAULT_KEYS_HELP =
"Arrow keys: swipe up, down, left and right, as on the watch. Enter: select. Esc: back.\n\n" +
"In a terminal session those keys are typed instead, and Shift+Esc (or Ctrl+Esc, Alt+Esc) goes back.\n\n" +
"Mouse or touchpad: the left button selects, the right button goes back, the middle button opens the system menu, " +
"and the wheel scrolls. These work in a terminal session too.\n\n" +
"A custom keybinding replaces these for its key and works everywhere, terminals included. " +
"\"Nothing\" turns a key's meaning here off without stopping it being typed.";
+9 -2
View File
@@ -12,7 +12,7 @@
* No platform imports: this runs under node in the tests.
*/
import { KeyboardClient, KeyboardClientError, type KeyboardStatus } from "./client";
import type { HidKeyEvent } from "./hid";
import type { HidKeyEvent, HidPointerSample } from "./hid";
import {
KeyboardDm,
KeyboardError,
@@ -56,6 +56,8 @@ export type KeyboardBridgeSnapshot = {
busy: boolean;
/** The remembered keyboard is away and the bridge keeps trying to bring it back. */
waiting: boolean;
/** The connected keyboard has a touchpad or mouse buttons. */
pointer: boolean;
};
export type KeyboardBridgeHost = {
@@ -65,6 +67,8 @@ export type KeyboardBridgeHost = {
storeSaved(saved: SavedKeyboard | null): void;
/** Key transitions from the keyboard (including forced releases). */
onKeys(events: HidKeyEvent[]): void;
/** A report from the keyboard's touchpad or mouse (including a forced release of its buttons). */
onPointer(sample: HidPointerSample): void;
/** The keyboard stopped being usable; drop held-key state without releases. */
onKeyboardGone(): void;
/** Something in snapshot() changed. */
@@ -129,6 +133,7 @@ export class KeyboardBridge {
scanResults: sortAdverts(this.scanResults),
busy: this.busy,
waiting: this.available && !!this.saved && !this.ready && !this.userDisconnected && !this.busy,
pointer: this.ready && this.client?.configuration?.pointer === true,
};
}
@@ -328,6 +333,7 @@ export class KeyboardBridge {
(record) => live() && this.host.send(record),
{
keys: (events) => { if (live() && this.ready) this.host.onKeys(events); },
pointer: (sample) => { if (live() && this.ready) this.host.onPointer(sample); },
advert: (advert) => { if (live()) this.addAdvert(advert); },
status: (status) => { if (live()) this.onStatus(status); },
dm: (event, status) => { if (live()) this.onDm(event, status); },
@@ -380,7 +386,8 @@ export class KeyboardBridge {
}
this.host.log(
`keyboard ready: ${keyboard.name || keyboard.address}, ${config.watched.length} of ` +
`${config.reports.filter((r) => r.type === 1).length} input reports subscribed, epoch ${config.epoch}`);
`${config.reports.filter((r) => r.type === 1).length} input reports subscribed` +
`${config.pointer ? ", with a pointer" : ""}, epoch ${config.epoch}`);
this.setState("connected");
} catch (e) {
if (!live()) return;
+65 -20
View File
@@ -10,7 +10,16 @@
* numbers found by configure() are only good for one connection epoch.
* No platform imports: this runs under node in the tests.
*/
import { HidKeys, parseReportMap, reportHasKeys, type HidKeyEvent, type HidReport } from "./hid";
import {
HidKeys,
parseReportMap,
reportHasKeys,
reportHasPointer,
reportPointer,
type HidKeyEvent,
type HidPointerSample,
type HidReport,
} from "./hid";
import {
KeyboardDm,
KeyboardError,
@@ -42,6 +51,12 @@ export type KeyboardStatus = {
export type KeyboardClientEvents = {
/** Key transitions from one input report (or the releases a gap forces). */
keys?(events: HidKeyEvent[]): void;
/**
* One report from the keyboard's touchpad or mouse: the buttons now held
* (across all its pointer reports) and the movement and wheel since the
* last one. Also sent with everything zero when a gap forces a release.
*/
pointer?(sample: HidPointerSample): void;
advert?(advert: KeyboardAdvert): void;
status?(status: KeyboardStatus): void;
/** The stream may have lost records; held keys were released. */
@@ -78,8 +93,10 @@ export type KeyboardConfiguration = {
epoch: number;
/** Every report found, input or not. */
reports: KeyboardReport[];
/** Handles of the input reports subscribed for keys. */
/** Handles of the input reports subscribed: those that carry keys, or a pointer's buttons and movement. */
watched: number[];
/** Whether any of them is a pointer's (a touchpad, mouse buttons, a wheel). */
pointer: boolean;
serviceChanged?: number;
};
@@ -109,7 +126,7 @@ type Pending = {
timer: ReturnType<typeof setTimeout>;
};
type Waiter = { test: () => boolean; resolve: () => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> };
type Input = { report: HidReport; id: number; service: number };
type Input = { report: HidReport; id: number; service: number; keys: boolean; pointer: boolean };
const COMMAND_TIMEOUT_MS = 32_000;
const MAX_PENDING = 8;
@@ -159,6 +176,8 @@ export class KeyboardClient {
private readonly pending = new Map<number, Pending>();
private readonly waiters = new Set<Waiter>();
private readonly keys = new HidKeys();
/** Pointer buttons held, by the report that says so (as HidKeys does for keys). */
private readonly pointerButtons = new Map<number, number>();
private inputs = new Map<number, Input>();
private readonly records = new KeyboardRecords(() => this.gap());
private readonly randomPasskey: () => number;
@@ -248,18 +267,35 @@ export class KeyboardClient {
this.gap();
return;
}
try {
const events = this.keys.update(r.handle, input.report, r.data);
if (events.length) this.events.keys?.(events);
} catch (e) {
this.release();
this.events.error?.(messageOf(e));
if (input.keys) {
try {
const events = this.keys.update(r.handle, input.report, r.data);
if (events.length) this.events.keys?.(events);
} catch (e) {
this.release();
this.events.error?.(messageOf(e));
}
}
if (input.pointer) {
const sample = reportPointer(input.report, r.data);
this.pointerButtons.set(r.handle, sample.buttons);
this.events.pointer?.({ ...sample, buttons: this.heldButtons() });
}
}
private heldButtons(): number {
let buttons = 0;
for (const held of this.pointerButtons.values()) buttons |= held;
return buttons;
}
/** Nothing is held any more, as far as anyone can tell: say so. */
private release(): void {
const events = this.keys.reset();
if (events.length) this.events.keys?.(events);
const buttons = this.heldButtons();
this.pointerButtons.clear();
if (buttons) this.events.pointer?.({ buttons: 0, dx: 0, dy: 0, wheel: 0, pan: 0 });
}
private gap(): void {
@@ -524,13 +560,13 @@ export class KeyboardClient {
/**
* Discover every HID service, its Report Map and each report's Report
* Reference; select Report Protocol and subscribe the input reports that
* can carry keys. Needs an encrypted link. No handle is assumed.
* carry keys or a pointer's buttons and movement. Needs an encrypted link.
* No handle is assumed.
*
* Only what typing needs is required of the keyboard: a Report Map that
* parses, and at least one key-bearing input report with a Report
* Reference and a CCC. A report that can't be placed is skipped and
* logged, as is anything wrong with an external report (the battery
* level, usually).
* Only what input needs is required of the device: a Report Map that
* parses, and at least one such input report with a Report Reference and
* a CCC. A report that can't be placed is skipped and logged, as is
* anything wrong with an external report (the battery level, usually).
*/
async configure(): Promise<KeyboardConfiguration> {
const epoch = this.epoch;
@@ -543,6 +579,7 @@ export class KeyboardClient {
log(`gatt ${attrs.map((a) => `${a.handle}=${typeof a.uuid === "number" ? a.uuid.toString(16) : a.uuid}`).join(" ")}`);
const reports: KeyboardReport[] = [];
const watched: KeyboardReport[] = [];
let pointerFound = false;
const skipped: string[] = [];
const descriptorsFor = (handle: number): Attribute[] => {
const end = attrs.find((a) => a.handle > handle &&
@@ -576,8 +613,14 @@ export class KeyboardClient {
const layout = parsed.get(id);
if (!layout) return skip(a, `input report id ${id} is not in the Report Map`);
if (ccc === undefined || (properties !== undefined && !(properties & 0x10))) return skip(a, "input report can't notify");
if (reportHasKeys(layout)) watched.push(report);
else log(`report ${a.handle} (id ${id}) carries no keys; not subscribed`);
const keys = reportHasKeys(layout);
const pointer = reportHasPointer(layout);
if (keys || pointer) watched.push(report);
else log(`report ${a.handle} (id ${id}) carries no keys or pointer; not subscribed`);
if (pointer) {
pointerFound = true;
log(`report ${a.handle} (id ${id}) is a pointer's${keys ? ", with keys" : ""}`);
}
}
reports.push(report);
log(`report ${a.handle}: id ${id} type ${type} ccc ${ccc ?? "-"} properties ${properties ?? "?"}`);
@@ -625,7 +668,7 @@ export class KeyboardClient {
if (this.closed || this.epoch !== epoch) throw new KeyboardClientError("The keyboard link changed during setup");
if (!watched.length) {
throw new KeyboardClientError(reports.length || skipped.length
? `No usable keyboard input report (${skipped.join("; ") || "none carries keys"})`
? `No usable keyboard input report (${skipped.join("; ") || "none carries keys or a pointer"})`
: "This device has no HID service");
}
if (watched.length > MAX_WATCHES) throw new KeyboardClientError("Keyboard has more than 16 input reports");
@@ -634,7 +677,9 @@ export class KeyboardClient {
const watches = watched.map((r) => r.handle);
if (changed && changedCcc && watches.length < MAX_WATCHES) watches.push(changed.handle);
const serviceChanged = changed && changedCcc && watches.includes(changed.handle) ? changed.handle : undefined;
const config: KeyboardConfiguration = { epoch: this.epoch, reports, watched: watched.map((r) => r.handle), serviceChanged };
const config: KeyboardConfiguration = {
epoch: this.epoch, reports, watched: watched.map((r) => r.handle), pointer: pointerFound, serviceChanged,
};
this.restore(config);
try {
await this.command(KeyboardOp.watch, [watches.length, ...watches.flatMap(le16)]);
@@ -671,7 +716,7 @@ export class KeyboardClient {
if (!r.map.length || r.map.length > MAX_VALUE) throw new KeyboardClientError("Invalid restored Report Map");
const report = parseReportMap(r.map).get(r.id);
if (!report) throw new KeyboardClientError("Restored Report ID missing");
inputs.set(r.handle, { report, id: r.id, service: r.service });
inputs.set(r.handle, { report, id: r.id, service: r.service, keys: reportHasKeys(report), pointer: reportHasPointer(report) });
}
if (!inputs.size || inputs.size > MAX_WATCHES) throw new KeyboardClientError("Invalid restored input count");
this.release();
+92 -12
View File
@@ -6,8 +6,9 @@
*
* HID over GATT carries the Report ID out of band (in each characteristic's
* Report Reference descriptor), so byte zero of a report value is data: it is
* never stripped as USB HID would. Only the keyboard/keypad page (7) and the
* consumer page (12) produce keys; pointer axes and padding are ignored.
* never stripped as USB HID would. The keyboard/keypad page (7) and the
* consumer page (12) produce keys. A mouse's or touchpad's report (buttons,
* relative X/Y, wheel) is read by reportPointer.
* No platform imports: this runs under node in the tests.
*/
@@ -20,6 +21,8 @@ type Field = {
size: number;
count: number;
variable: boolean;
/** Reports a change since the last report (a mouse's axes and wheel), not a state. */
relative: boolean;
min: number;
max: number;
usages: HidUsage[];
@@ -90,7 +93,8 @@ export function parseReportMap(bytes: Uint8Array): Map<number, HidReport> {
reports.set(g.id, r);
}
const field: Field = {
bit: r.bits, size: g.size, count: g.count, variable: !!(v & 2), min: g.min, max: g.max, usages: [...usages],
bit: r.bits, size: g.size, count: g.count, variable: !!(v & 2), relative: !!(v & 4),
min: g.min, max: g.max, usages: [...usages],
};
if (lo || hi) {
if (!lo || !hi || lo.page !== hi.page || hi.usage < lo.usage) fail("usage range");
@@ -98,8 +102,8 @@ export function parseReportMap(bytes: Uint8Array): Map<number, HidReport> {
}
r.bits += g.size * g.count;
if (r.bits > 4096) fail("report exceeds 512 bytes");
// Constant padding and relative pointer axes are not keys.
if (!(v & 1) && !(v & 4)) r.fields.push(field);
// Constant fields are padding.
if (!(v & 1)) r.fields.push(field);
} else if (tag !== 9 && tag !== 11) fail("unknown main item");
usages = [];
lo = hi = undefined;
@@ -130,7 +134,86 @@ function usageAt(f: Field, index: number): HidUsage | undefined {
*/
export function reportHasKeys(report: HidReport): boolean {
const isKeyPage = (u: HidUsage): boolean => u.page === HID_PAGE_KEYBOARD || u.page === HID_PAGE_CONSUMER;
return report.fields.some((f) => f.usages.some(isKeyPage) || (f.range !== undefined && isKeyPage(f.range[0])));
return report.fields.some((f) => !f.relative && (f.usages.some(isKeyPage) || (f.range !== undefined && isKeyPage(f.range[0]))));
}
/** One field's `index`th value, sign-extended when the field is signed. Bits past the data read as zero. */
function fieldValue(f: Field, index: number, data: Uint8Array): number {
let value = 0;
for (let j = 0; j < f.size; j++) {
const bit = f.bit + index * f.size + j;
if ((data[bit >>> 3] ?? 0) & (1 << (bit & 7))) value += 2 ** j;
}
if (f.min < 0 && value >= 2 ** (f.size - 1)) value -= 2 ** f.size;
return value;
}
/** What one report from a mouse or touchpad says. */
export type HidPointerSample = {
/** Buttons held, bit 0 for button 1 (left), bit 1 for button 2 (right), bit 2 for button 3 (middle). */
buttons: number;
/** Movement since the last report, in the device's counts; +x right, +y down. */
dx: number;
dy: number;
/** Wheel detents since the last report; positive is away from the user ("up"). */
wheel: number;
/** Horizontal wheel (AC Pan); positive is right. */
pan: number;
};
const HID_PAGE_GENERIC_DESKTOP = 1;
const HID_PAGE_BUTTON = 9;
const USAGE_X = 0x30;
const USAGE_Y = 0x31;
const USAGE_WHEEL = 0x38;
const USAGE_AC_PAN = 0x238;
/** Buttons past this are not tracked; a mouse with more is rare and has nothing to bind them to anyway. */
const MAX_POINTER_BUTTONS = 8;
/** Which part of a pointer sample a field's usage feeds, if any. */
function pointerRole(f: Field, u: HidUsage | undefined): "button" | "dx" | "dy" | "wheel" | "pan" | null {
if (!u || !f.variable) return null;
if (u.page === HID_PAGE_BUTTON) return !f.relative && u.usage >= 1 && u.usage <= MAX_POINTER_BUTTONS ? "button" : null;
if (!f.relative) return null; // an absolute X/Y is a touchscreen or a digitizer, not a mouse
if (u.page === HID_PAGE_GENERIC_DESKTOP) {
if (u.usage === USAGE_X) return "dx";
if (u.usage === USAGE_Y) return "dy";
if (u.usage === USAGE_WHEEL) return "wheel";
}
if (u.page === HID_PAGE_CONSUMER && u.usage === USAGE_AC_PAN) return "pan";
return null;
}
/** Whether an input report carries a mouse's buttons, movement or wheel. */
export function reportHasPointer(report: HidReport): boolean {
return report.fields.some((f) => {
for (let i = 0; i < f.count; i++) if (pointerRole(f, usageAt(f, i))) return true;
return false;
});
}
/**
* Read a mouse or touchpad report. Lenient about length, unlike reportKeys:
* some devices leave the wheel bytes off when there is nothing to say, and a
* missing byte is zero either way.
*/
export function reportPointer(report: HidReport, data: Uint8Array): HidPointerSample {
const sample: HidPointerSample = { buttons: 0, dx: 0, dy: 0, wheel: 0, pan: 0 };
for (const f of report.fields) {
for (let i = 0; i < f.count; i++) {
const u = usageAt(f, i);
const role = pointerRole(f, u);
if (!role) continue;
const value = fieldValue(f, i, data);
if (value < f.min || value > f.max) continue; // out of range: no reading
if (role === "button") {
if (value) sample.buttons |= 1 << (u!.usage - 1);
} else {
sample[role] += value;
}
}
}
return sample;
}
/** The keys one input report says are held. Throws on a length mismatch or a rollover report. */
@@ -138,13 +221,10 @@ export function reportKeys(report: HidReport, data: Uint8Array): HidUsage[] {
if (data.length !== Math.ceil(report.bits / 8)) throw new Error("HID input length does not match Report Map");
const keys = new Map<string, HidUsage>();
for (const f of report.fields) {
// A relative field is a movement, not a key that is down.
if (f.relative) continue;
for (let i = 0; i < f.count; i++) {
let value = 0;
for (let j = 0; j < f.size; j++) {
const bit = f.bit + i * f.size + j;
if (data[bit >>> 3]! & (1 << (bit & 7))) value += 2 ** j;
}
if (f.min < 0 && value >= 2 ** (f.size - 1)) value -= 2 ** f.size;
const value = fieldValue(f, i, data);
if (value < f.min || value > f.max) continue; // null state
const u = usageAt(f, f.variable ? i : value - f.min);
if (!u || (f.variable && value === 0) || !u.usage) continue;
+10 -8
View File
@@ -38,9 +38,10 @@ export type KeyRouterHost = {
};
/**
* A held key repeats twenty times a second, faster than a list can repaint
* over the glasses' link. Repeats are dropped while a gesture is still being
* handled, and closer together than this.
* A held key repeats twenty times a second, and a wheel or a two-finger
* scroll reports faster still: more than a list can repaint over the
* glasses' link. Those are dropped while a gesture is still being handled,
* and closer together than this.
*/
const REPEAT_MIN_INTERVAL_MS = 100;
@@ -73,13 +74,14 @@ export class KeyRouter {
return;
}
const resolution = resolveKey(event, host.bindings());
const droppable = event.repeat || event.burst === true;
if (resolution.consume) {
this.consumed.add(event.code);
if (resolution.gesture) this.perform(resolution.gesture, event.repeat);
if (resolution.gesture) this.perform(resolution.gesture, droppable);
return;
}
if (host.offerToWindow(event)) return;
if (resolution.gesture) this.perform(resolution.gesture, event.repeat);
if (resolution.gesture) this.perform(resolution.gesture, droppable);
}
/**
@@ -91,7 +93,7 @@ export class KeyRouter {
const host = this.host;
if (event.phase !== "down" || this.capture || !host.ready() || host.locked() || !host.screenOn()) return;
const resolution = resolveKey(event, host.bindings());
if (!resolution.consume && resolution.gesture) this.perform(resolution.gesture, event.repeat);
if (!resolution.consume && resolution.gesture) this.perform(resolution.gesture, event.repeat || event.burst === true);
}
/**
@@ -124,9 +126,9 @@ export class KeyRouter {
capture(chordOf(event));
}
private perform(gesture: KeyGesture, repeat: boolean): void {
private perform(gesture: KeyGesture, droppable: boolean): void {
const now = this.host.now ? this.host.now() : Date.now();
if (repeat && (this.gesturesInFlight > 0 || now - this.lastGestureAtMs < REPEAT_MIN_INTERVAL_MS)) return;
if (droppable && (this.gesturesInFlight > 0 || now - this.lastGestureAtMs < REPEAT_MIN_INTERVAL_MS)) return;
this.lastGestureAtMs = now;
void this.run(gesture, this.scheme.originFor(gesture));
}
+23 -2
View File
@@ -24,12 +24,19 @@ export type KeyEvent = {
modifiers: KeyModifiers;
/** A synthesized auto-repeat of a held key. */
repeat: boolean;
/**
* One of a stream that can arrive faster than it can be acted on (a wheel
* turning): whoever acts on it may drop some rather than fall behind.
*/
burst?: boolean;
/** Date.now() when the phone saw the transition. */
timestampMs: number;
};
const HID_PAGE_KEYBOARD = 7;
const HID_PAGE_CONSUMER = 12;
/** A mouse's buttons, which arrive here as keys: usage 1 is the left button, 2 the right, 3 the middle. */
export const HID_PAGE_BUTTON = 9;
const USAGE_CAPS_LOCK = 57;
/** [unshifted, shifted, code] for US-layout punctuation on the keyboard page. */
@@ -159,6 +166,7 @@ export function translateUsage(page: number, usage: number, shift: boolean, caps
const name = CONSUMER[usage];
return name ? { key: name, code: name } : { key: "Unidentified", code: `Consumer${usage.toString(16)}` };
}
if (page === HID_PAGE_BUTTON) return { key: `MouseButton${usage}`, code: `MouseButton${usage}` };
return { key: "Unidentified", code: `Page${page.toString(16)}Usage${usage.toString(16)}` };
}
@@ -217,8 +225,9 @@ export class KeyTranslator {
if (modifier) this.modifiers[modifier] = true;
if (event.page === HID_PAGE_KEYBOARD && event.usage === USAGE_CAPS_LOCK) this.capsLock = !this.capsLock;
this.emit("down", event.page, event.usage, false);
// The newest non-modifier key is the one that repeats, as on a PC.
if (!modifier) this.startRepeat(event.page, event.usage);
// The newest non-modifier key is the one that repeats, as on a PC. A
// mouse button neither repeats nor takes the repeat from a held key.
if (!modifier && event.page !== HID_PAGE_BUTTON) this.startRepeat(event.page, event.usage);
} else {
if (!this.held.delete(id)) return;
if (modifier) this.modifiers[modifier] = this.otherHeld(event.usage, modifier);
@@ -227,6 +236,18 @@ export class KeyTranslator {
}
}
/**
* A press and release in one, for input that has no "held" (a wheel's
* detent): `name` is both the key and the code, e.g. "WheelUp". Carries
* the modifiers held on the keyboard, like any key.
*/
pulse(name: string): void {
const timestampMs = this.now();
for (const phase of ["down", "up"] as const) {
this.emitEvent({ phase, key: name, code: name, modifiers: { ...this.modifiers }, repeat: false, burst: true, timestampMs });
}
}
/** The keyboard went away: forget everything without emitting releases. */
reset(): void {
this.stopRepeat();
+83
View File
@@ -0,0 +1,83 @@
/**
* A keyboard's touchpad or mouse, as the rest of the keyboard support sees
* it. Its buttons and wheel become keys ("MouseButton1", "WheelUp"), so
* they get default meanings and custom keybindings like any key
* (bindings.ts). Its movement goes nowhere unless something has taken the
* pointer (the cursor test page): there is no cursor in the main UI.
* No platform imports: this runs under node in the tests.
*/
import type { HidKeyEvent, HidPointerSample } from "./hid";
import { HID_PAGE_BUTTON } from "./keys";
/** The names a wheel's detents arrive under, as keys. */
export type WheelKey = "WheelUp" | "WheelDown" | "WheelLeft" | "WheelRight";
export type PointerInputHost = {
/** Button transitions, as HID usages on the Button page. */
buttons(events: HidKeyEvent[]): void;
/** One wheel report in a direction, however many detents it claimed. */
wheel(key: WheelKey): void;
};
export class PointerInput {
/** The buttons the host has been told are down. */
private reported = 0;
/** The buttons actually down, as of the last sample. */
private held = 0;
/** Buttons that went down while the pointer was taken: not keys until they have come up. */
private ignored = 0;
private grab: ((sample: HidPointerSample) => void) | null = null;
constructor(private readonly host: PointerInputHost) {}
/** One report from the pointer (see KeyboardClientEvents.pointer). */
handle(sample: HidPointerSample): void {
this.held = sample.buttons;
if (this.grab) {
this.grab(sample);
return;
}
this.ignored &= sample.buttons;
this.report(sample.buttons & ~this.ignored);
// One step per report: a touchpad's two-finger scroll sends many small
// ones, and the gesture they turn into is rate-limited downstream.
if (sample.wheel) this.host.wheel(sample.wheel > 0 ? "WheelUp" : "WheelDown");
if (sample.pan) this.host.wheel(sample.pan > 0 ? "WheelRight" : "WheelLeft");
}
/**
* Take the pointer: every sample goes to `listener`, movement included,
* and its buttons and wheel stop acting as keys. Buttons held at that
* moment are released first, so nothing is left down. Returns a function
* that gives the pointer back.
*/
take(listener: (sample: HidPointerSample) => void): () => void {
this.report(0);
this.grab = listener;
return () => {
if (this.grab !== listener) return;
this.grab = null;
// A button still down was pressed for the listener, not as a key: its
// release is nobody's business either.
this.ignored = this.held;
};
}
/** The keyboard went away: nothing is held, and nobody is told. */
reset(): void {
this.reported = 0;
this.held = 0;
this.ignored = 0;
}
private report(buttons: number): void {
const changed = buttons ^ this.reported;
if (!changed) return;
const events: HidKeyEvent[] = [];
for (let bit = 0; bit < 8; bit++) {
if (changed & (1 << bit)) events.push({ page: HID_PAGE_BUTTON, usage: bit + 1, down: !!(buttons & (1 << bit)) });
}
this.reported = buttons;
this.host.buttons(events);
}
}
+19
View File
@@ -23,8 +23,10 @@ import {
type KeyGesture,
} from "./bindings";
import { KeyboardBridge, type KeyboardBridgeSnapshot, type SavedKeyboard } from "./bridge";
import type { HidPointerSample } from "./hid";
import { KeyRouter } from "./key-router";
import { KeyTranslator, type KeyEvent } from "./keys";
import { PointerInput } from "./pointer";
declare const java: any;
declare const arc4random_uniform: ((bound: number) => number) | undefined;
@@ -92,6 +94,11 @@ class KeyboardService {
log: (line) => console.log(`[keyboard] ${line}`),
});
private readonly translator = new KeyTranslator({ emit: (event) => this.router.handleKey(event) });
/** The touchpad's buttons and wheel go in as keys; see pointer.ts. */
private readonly pointer = new PointerInput({
buttons: (events) => this.translator.handle(events),
wheel: (key) => this.translator.pulse(key),
});
readonly bridge = new KeyboardBridge({
send: (record) => {
@@ -106,8 +113,10 @@ class KeyboardService {
loadSaved: loadSavedKeyboard,
storeSaved: (saved) => setStringSetting(SAVED_KEYBOARD_KEY, saved ? JSON.stringify(saved) : ""),
onKeys: (events) => this.translator.handle(events),
onPointer: (sample) => this.pointer.handle(sample),
onKeyboardGone: () => {
this.translator.reset();
this.pointer.reset();
this.router.reset();
},
onChanged: () => {
@@ -206,6 +215,16 @@ class KeyboardService {
return this.router.captureNextKey(onChord);
}
/**
* Take the keyboard's touchpad or mouse: every report goes to `listener`,
* movement included, and its buttons and wheel stop acting as keys until
* the returned function is called. For the cursor test page; the main UI
* has no cursor.
*/
takePointer(listener: (sample: HidPointerSample) => void): () => void {
return this.pointer.take(listener);
}
private storeBindings(bindings: KeyBinding[]): void {
this.bindings = bindings;
this.bindingMap = keyBindingMap(bindings);
+20 -2
View File
@@ -3,11 +3,18 @@ import type { DiscoveryEvents } from './device-discovery'
import type { RawAdvertisement } from '../g2/even-advertisement'
export { buildAddressSet } from './device-discovery-common'
/**
* How often a scan re-reads which arms the system is connected to. Each read refreshes
* their rows, which age out like advertisements once the link drops and they go quiet.
*/
const CONNECTED_ARMS_POLL_MS = 2000
export class DeviceDiscoveryBridge {
private ble = iosBluetooth()
private off: (() => void) | null = null
private generation = 0
private cancelCollection: (() => void) | null = null
private connectedArmsTimer: ReturnType<typeof setInterval> | null = null
get bluetoothEnabled(): boolean { return this.ble.state === 5 }
get scanning(): boolean { return !!this.off && this.ble.scanning }
startScan(events: DiscoveryEvents): boolean {
@@ -21,16 +28,27 @@ export class DeviceDiscoveryBridge {
void this.ble.startScan(24 * 60 * 60 * 1000).catch(error => {
if (generation === this.generation) events.onScanFailed?.(-1, String(error.message ?? error))
})
// A connected arm doesn't advertise (iOS holds the right arm's ANCS link open after a
// session ends), so the scan alone would show those glasses one-armed.
const reportConnectedArms = () => { for (const device of this.ble.systemConnectedDevices()) events.onAdvertisement(device) }
reportConnectedArms()
this.connectedArmsTimer = setInterval(reportConnectedArms, CONNECTED_ARMS_POLL_MS)
return true
}
stopScan(): void {
++this.generation; this.cancelCollection?.()
if (this.connectedArmsTimer) { clearInterval(this.connectedArmsTimer); this.connectedArmsTimer = null }
if (this.off) { this.off(); this.off = null; this.ble.stopScan() }
}
// CoreBluetooth does not expose the phone's bond list. Fresh advertisements
// supply both identity and the UUID mapping that iOS needs for connections.
// supply both identity and the UUID mapping that iOS needs for connections;
// startScan() reports the arms the system is connected to.
emitBondedDevices(): void {}
async getBondedCandidates(): Promise<RawAdvertisement[]> { return [...this.ble.devices.values()] }
async getBondedCandidates(): Promise<RawAdvertisement[]> {
const devices = new Map(this.ble.devices)
for (const device of this.ble.systemConnectedDevices()) if (!devices.has(device.address)) devices.set(device.address, device)
return [...devices.values()]
}
async scanCandidates(timeoutMs = 6000): Promise<RawAdvertisement[]> {
const generation = this.generation
await this.ble.ensureReady()
+12 -51
View File
@@ -1,5 +1,6 @@
import { openSocket } from "./socket";
import { openSocket, type SocketConnection, type SocketListener } from "./socket";
import { toUint8Array } from "../util/array-util";
import type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState } from "./terminal-session-types";
declare const android: any;
declare const java: any;
@@ -19,54 +20,7 @@ const LAUNCH_REPLY_TIMEOUT_MS = 10_000;
// otherwise treat the "\r" as a pasted newline instead of the Enter key.
const SUBMIT_DELAY_MS = 150;
export type G2MirrorSession = {
socket: string;
pid: number;
cwdHint: string;
/** Unix epoch ms of the terminal's last bell, or null if none observed. */
lastBellAt: number | null;
/**
* Unix epoch ms (host clock) of the app's last output, or null if none
* observed. Fresh to within the wrapper's 2s activity reporting interval
* while we're connected; compare against other host timestamps, not the
* phone clock (see the worker's local-receive-time activity tracking).
*/
lastOutputAt: number | null;
/** Window title the app last set (xterm OSC 0/2), or null if none observed. */
title: string | null;
};
export type G2MirrorPhase =
| "idle"
| "connecting"
| "connected" // handshake accepted; can list/attach
| "attached" // relaying to one session
| "failed";
export type G2MirrorState = {
phase: G2MirrorPhase;
status: string;
sessions: G2MirrorSession[];
attachedCommand: string;
/**
* server_name from the init success reply: a human-readable name for the
* machine the server runs on. "" until the handshake succeeds (or when an
* older server omits the field).
*/
serverName: string;
};
/** A page of archived scrollback lines (see PROTOCOL.md "Scrollback history"). */
export type G2MirrorHistoryReply = {
/** Absolute index of lines[0]; the page covers [start, start + lines.length). */
start: number;
/** Oldest index still retained by the wrapper (older requests return nothing). */
oldest: number;
/** Current splice point (next line to be archived). */
next: number;
/** Plain text, ANSI-stripped, oldest-to-newest. */
lines: string[];
};
export type { G2MirrorHistoryReply, G2MirrorPhase, G2MirrorSession, G2MirrorState };
export type G2MirrorClientOptions = {
/** TLS (g2mirrors:// → wss) vs plain (g2mirror:// → ws). */
@@ -77,6 +31,12 @@ export type G2MirrorClientOptions = {
deviceName: string;
cols: number;
rows: number;
/**
* Opens the websocket some other way than dialing host:port directly
* (e.g. through an SSH tunnel); `label` then names the endpoint in status
* lines instead of host:port.
*/
transport?: { open: (listener: SocketListener) => SocketConnection; label: string };
};
type TerminalDataKind = "snapshot" | "output";
@@ -180,7 +140,8 @@ export class G2MirrorClient {
this.stopped = false;
const generation = ++this.connectionGeneration;
const url = `${this.options.secure ? "wss" : "ws"}://${this.options.host}:${this.options.port}`;
this.setState("connecting", `Connecting to ${this.options.host}:${this.options.port}...`);
const transport = this.options.transport;
this.setState("connecting", `Connecting to ${transport ? transport.label : `${this.options.host}:${this.options.port}`}...`);
this.listenerProxy = {
onOpen: () => {
if (this.stopped || generation !== this.connectionGeneration) return;
@@ -208,7 +169,7 @@ export class G2MirrorClient {
},
};
try {
this.ws = openSocket(url, this.listenerProxy);
this.ws = transport ? transport.open(this.listenerProxy!) : openSocket(url, this.listenerProxy);
} catch (error) {
this.ws = null;
this.handleConnectionLost(`Connection failed: ${shortenError(String((error as Error)?.message ?? error))}`);
+74 -4
View File
@@ -1,4 +1,7 @@
import { ApplicationSettings } from '@nativescript/core'
import { loadPairedGlassesIdentity } from '../g2/device-addresses'
import { g2ManufacturerData } from '../g2/even-advertisement'
import { serialKey } from '../g2/glasses-hardware-identity'
import { identifyIosPeripheral, type IosAdvertisement, type IosDevice } from '../g2/ios-peripheral-identity'
import { hexToBytes } from '../util/hex-util'
import { kotlinListener } from './kotlin-listener.ios'
@@ -10,6 +13,13 @@ export const BLE_STATE_UNSUPPORTED = 2, BLE_STATE_UNAUTHORIZED = 3, BLE_STATE_PO
/** CBManagerAuthorization.allowedAlways. */
const BLE_AUTHORIZATION_ALLOWED = 3
/**
* Per address, the peripheral identifier and side last heard there and (since 2026-11-16)
* the advertisement itself, from which an arm that has stopped advertising is rebuilt.
*/
const PERIPHERAL_KEY_PREFIX = 'ios.ble.peripheral.'
type RememberedPeripheral = { identifier: string; role: string; name?: string; manufacturerData?: string }
export type BluetoothEvent =
| { kind: 'state'; state: number; authorization: number }
| { kind: 'advertisement'; identifier: string; name: string; manufacturerData: string; rssi: number; connectable: boolean }
@@ -28,6 +38,8 @@ export class IosBluetooth {
private readonly native = FaceclawKitIosBleCentral.alloc().initWithPlatform(FaceclawKitIosProtocolPlatform.shared)
private readonly listeners = new Set<(event: BluetoothEvent) => void>()
readonly devices = new Map<string, IosDevice>()
/** The record last written per settings key, so repeated advertisements don't rewrite it. */
private readonly rememberedValues = new Map<string, string>()
private scanTimer: ReturnType<typeof setTimeout> | null = null
private scanGeneration = 0
private readonly scanListener: object
@@ -47,12 +59,68 @@ export class IosBluetooth {
const device = identifyIosPeripheral(raw)
if (device) {
this.devices.set(device.address, device)
ApplicationSettings.setString(`ios.ble.peripheral.${device.address}`, JSON.stringify({ identifier: device.identifier, role: device.role }))
this.remember(device)
this.emit({ kind: 'device', device })
}
},
})
}
/** Persists what `device` advertised; skips the write when nothing changed (scans report duplicates). */
private remember(device: IosDevice): void {
const key = `${PERIPHERAL_KEY_PREFIX}${device.address}`
const record: RememberedPeripheral = { identifier: device.identifier, role: device.role, name: device.name, manufacturerData: device.manufacturerData }
const value = JSON.stringify(record)
if (this.rememberedValues.get(key) === value) return
this.rememberedValues.set(key, value)
ApplicationSettings.setString(key, value)
}
/**
* Even arms the system is connected to, rebuilt from what they last advertised here. A
* connected arm doesn't advertise, and iOS keeps the right arm's ANCS link open after a
* session ends (even after pairing other glasses), so a scan alone hears only the left
* arm. An arm this phone has never heard advertise can't be rebuilt: its MAC and the
* pair's serial come only from the advertisement. The device has no signal strength.
*/
systemConnectedDevices(): IosDevice[] {
if (this.state !== BLE_STATE_POWERED_ON) return []
let connected: any
try {
connected = this.native.systemConnectedG2Arms()
} catch (error) {
// Scanning still works without this; don't let it take the pairing page down.
console.log(`[IosBluetooth] systemConnectedG2Arms failed: ${error}`)
return []
}
if (!connected?.count) return []
const records = new Map<string, { address: string; record: RememberedPeripheral }>()
for (const key of ApplicationSettings.getAllKeys()) {
if (!key.startsWith(PERIPHERAL_KEY_PREFIX)) continue
try {
const record = JSON.parse(ApplicationSettings.getString(key, '{}')) as RememberedPeripheral
if (typeof record.identifier === 'string') records.set(record.identifier.toUpperCase(), { address: key.slice(PERIPHERAL_KEY_PREFIX.length), record })
} catch { /* Malformed: a fresh advertisement rewrites it. */ }
}
const identity = loadPairedGlassesIdentity()
const devices: IosDevice[] = []
for (let i = 0; i < connected.count; i++) {
const peripheral = connected.objectAtIndex(i)
const identifier = String(peripheral.identifier)
const remembered = records.get(identifier)
if (!remembered) continue
const { address, record } = remembered
let name = record.name ?? ''
let manufacturerData = record.manufacturerData ?? ''
if (!manufacturerData && identity && (address === identity.leftAddress || address === identity.rightAddress)) {
// Remembered before advertisements were: the saved pairing supplies the serial.
const side = address === identity.leftAddress ? 'left' : 'right'
name ||= side === 'left' ? identity.leftName : identity.rightName
manufacturerData = g2ManufacturerData(serialKey(identity.serial) ?? '', address) ?? ''
}
const device = identifyIosPeripheral({ identifier, name: name || String(peripheral.name ?? ''), manufacturerData, rssi: 0, connectable: true })
if (device?.address === address && device.role === record.role) devices.push({ ...device, rssi: null, source: 'paired' })
}
return devices
}
onEvent(listener: (event: BluetoothEvent) => void): () => void {
this.listeners.add(listener); return () => { this.listeners.delete(listener) }
}
@@ -111,7 +179,7 @@ export class IosBluetooth {
const live = this.devices.get(address)
if (live && live.role !== role) throw new Error(`${address} advertises as ${live.role}, not ${role}. Check Configure devices.`)
try {
const saved = JSON.parse(ApplicationSettings.getString(`ios.ble.peripheral.${address}`, '{}'))
const saved = JSON.parse(ApplicationSettings.getString(`${PERIPHERAL_KEY_PREFIX}${address}`, '{}'))
if (saved.role === role && typeof saved.identifier === 'string') result[role] = saved.identifier
} catch { /* A fresh scan can recover malformed settings. */ }
}
@@ -138,13 +206,15 @@ export class IosBluetooth {
/** The peripheral last heard at this address, if it was on this side. */
peripheralIdentifier(address: string, role: string): string | null {
try {
const saved = JSON.parse(ApplicationSettings.getString(`ios.ble.peripheral.${address}`, '{}'))
const saved = JSON.parse(ApplicationSettings.getString(`${PERIPHERAL_KEY_PREFIX}${address}`, '{}'))
return saved.role === role && typeof saved.identifier === 'string' ? saved.identifier : null
} catch {
return null
}
}
forget(address: string): void { ApplicationSettings.remove(`ios.ble.peripheral.${address}`); this.devices.delete(address) }
forget(address: string): void {
ApplicationSettings.remove(`${PERIPHERAL_KEY_PREFIX}${address}`); this.rememberedValues.delete(`${PERIPHERAL_KEY_PREFIX}${address}`); this.devices.delete(address)
}
}
let instance: IosBluetooth | null = null
export function iosBluetooth(): IosBluetooth { return instance ??= new IosBluetooth() }
+153
View File
@@ -0,0 +1,153 @@
/**
* Platform-independent half of the SSH transport bindings (ssh.ts /
* ssh.ios.ts): the types the app uses and the decoding of the Go
* transport's events (native/ssh/faceclawssh.go, Listener).
*/
/** Where and as whom to connect. */
export type SshEndpoint = {
host: string;
port: number;
user: string;
/** Pinned host keys (SSH wire format, base64). Empty: first connection reports hostkey-unknown. */
hostKeys: string[];
/** Saved password, or "" to try only the device key. */
password: string;
/** Offer the device's client key. */
useKey: boolean;
};
export type SshChannelSpec =
| {
/** Run a command on the host; text is exchanged a line at a time. */
type: "exec";
command: string;
}
| {
/** WebSocket to a URL resolved on the host's side (e.g. ws://127.0.0.1:8737/). */
type: "websocket";
url: string;
};
export type SshHostKey = {
/** SSH key type, e.g. "ssh-ed25519". */
type: string;
/** OpenSSH-style "SHA256:..." fingerprint. */
fingerprint: string;
/** SSH wire format, base64: the value to pin in SshEndpoint.hostKeys. */
key: string;
};
export type SshFailureKind =
| "hostkey-unknown"
| "hostkey-mismatch"
| "auth"
| "network"
| "channel"
| "config"
| "internal";
export type SshFailure = {
kind: SshFailureKind;
message: string;
/** For hostkey-*: the key the host presented. */
hostKey?: SshHostKey;
/** For auth: the host takes passwords / we sent one / we offered our key. */
passwordAllowed?: boolean;
passwordTried?: boolean;
keyTried?: boolean;
};
export type SshClosed = {
/** Exec channels: the command's exit status (and signal, if killed). */
exitStatus?: number;
signal?: string;
/** WebSocket channels: the close frame's code and reason. */
code?: number;
reason?: string;
};
export type SshChannelListener = {
onOpen(): void;
onText(text: string): void;
onStderr?(line: string): void;
/** Terminal: the channel ended normally. */
onClosed(info: SshClosed): void;
/** Terminal: the channel couldn't open or was lost. */
onFailure(failure: SshFailure): void;
};
export type SshChannel = {
/** Queue a websocket text frame / an exec stdin line. False once closed. */
send(text: string): boolean;
/** Flush queued sends, then end the channel. No events follow. */
close(): void;
};
export type SshClientKey = {
/** "ecdsa-sha2-nistp256 AAAA... comment", for ~/.ssh/authorized_keys. */
authorizedKey: string;
fingerprint: string;
};
/** Build the Go transport's openSpec JSON. */
export function encodeSshSpec(endpoint: SshEndpoint, channel: SshChannelSpec): string {
return JSON.stringify({
host: endpoint.host,
port: endpoint.port,
user: endpoint.user,
password: endpoint.password,
hostKeys: endpoint.hostKeys,
useKey: endpoint.useKey,
channel,
});
}
/** Route one transport event to the listener. Unknown kinds are ignored. */
export function dispatchSshEvent(listener: SshChannelListener, kind: string, payload: string): void {
switch (kind) {
case "open":
listener.onOpen();
return;
case "text":
listener.onText(payload);
return;
case "stderr":
listener.onStderr?.(payload);
return;
case "closed":
listener.onClosed(parseJson(payload) ?? {});
return;
case "failure": {
const failure = parseJson(payload);
listener.onFailure(
failure && typeof failure.kind === "string"
? failure
: { kind: "internal", message: `bad failure payload: ${payload}` },
);
return;
}
}
}
function parseJson(text: string): any {
try {
return JSON.parse(text);
} catch {
return null;
}
}
/** Human summary of a failure for status lines. */
export function describeSshFailure(failure: SshFailure): string {
switch (failure.kind) {
case "hostkey-unknown":
return "Host key not yet trusted.";
case "hostkey-mismatch":
return "HOST KEY CHANGED; refusing to connect.";
case "auth":
return failure.message || "Authentication failed.";
default:
return failure.message || failure.kind;
}
}
+69
View File
@@ -0,0 +1,69 @@
import {
dispatchSshEvent,
encodeSshSpec,
type SshChannel,
type SshChannelListener,
type SshChannelSpec,
type SshClientKey,
type SshEndpoint,
} from "./ssh-common";
export * from "./ssh-common";
declare const FaceclawSshChannel: any;
declare const FaceclawSshKeys: any;
// Like socket.ios.ts: Go delivers events on its own threads, so the native
// side queues them and this isolate drains the queue on a timer.
const POLL_INTERVAL_MS = 25;
/** iOS SSH transport: FaceclawSshChannel (ObjC) over the gomobile-bound Go package in native/ssh. */
export function openSshChannel(endpoint: SshEndpoint, channel: SshChannelSpec, listener: SshChannelListener): SshChannel {
const native = FaceclawSshChannel.alloc().initWithSpecUseKey(encodeSshSpec(endpoint, channel), endpoint.useKey);
let ended = false;
const stop = () => {
if (ended) return;
ended = true;
clearInterval(timer);
native.close();
};
const timer = setInterval(() => {
const events = JSON.parse(String(native.takeEvents())) as Array<{ kind: string; payload: string }>;
for (const event of events) {
if (ended) break;
if (event.kind === "closed" || event.kind === "failure") {
// Terminal events: stop polling, then deliver.
ended = true;
clearInterval(timer);
}
dispatchSshEvent(listener, event.kind, event.payload);
}
}, POLL_INTERVAL_MS);
return {
send: (text) => !ended && native.send(text) === true,
close: stop,
};
}
export function sshClientKey(comment: string): SshClientKey {
const authorizedKey = FaceclawSshKeys.authorizedKeyWithComment(comment);
const fingerprint = FaceclawSshKeys.fingerprint();
if (!authorizedKey || !fingerprint) throw new Error("Could not create the SSH client key.");
return { authorizedKey: String(authorizedKey), fingerprint: String(fingerprint) };
}
export function getSshSecret(id: string): string {
return String(FaceclawSshKeys.secretForId(id) ?? "");
}
export function setSshSecret(id: string, value: string): void {
FaceclawSshKeys.setSecretForId(value, id);
}
export function removeSshSecret(id: string): void {
FaceclawSshKeys.removeSecretForId(id);
}
export function copyToPhoneClipboard(_label: string, text: string): void {
FaceclawSshKeys.copyToClipboard(text);
}
+66
View File
@@ -0,0 +1,66 @@
import { Utils } from "@nativescript/core";
import {
dispatchSshEvent,
encodeSshSpec,
type SshChannel,
type SshChannelListener,
type SshChannelSpec,
type SshClientKey,
type SshEndpoint,
} from "./ssh-common";
export * from "./ssh-common";
declare const com: any;
/**
* Android SSH transport: FaceclawSshChannel (Kotlin) over the gomobile-bound
* Go package in native/ssh. Callable from the main isolate or a worker;
* events arrive on the calling isolate's thread.
*/
export function openSshChannel(endpoint: SshEndpoint, channel: SshChannelSpec, listener: SshChannelListener): SshChannel {
let closed = false;
const proxy = new com.faceclaw.app.FaceclawSshListener({
onEvent: (kind: string, payload: string) => {
if (closed) return;
dispatchSshEvent(listener, String(kind), payload == null ? "" : String(payload));
},
});
const native = new com.faceclaw.app.FaceclawSshChannel(encodeSshSpec(endpoint, channel), endpoint.useKey, proxy);
return {
send: (text) => !closed && native.send(text) === true,
close: () => {
if (closed) return;
closed = true;
native.close();
},
};
}
function context(): any {
return Utils.android.getApplicationContext();
}
/** The device's SSH client key (generated on first use). */
export function sshClientKey(comment: string): SshClientKey {
return {
authorizedKey: String(com.faceclaw.app.FaceclawSshKeys.authorizedKey(comment)),
fingerprint: String(com.faceclaw.app.FaceclawSshKeys.fingerprint()),
};
}
export function getSshSecret(id: string): string {
return String(com.faceclaw.app.FaceclawSshKeys.getSecret(context(), id) ?? "");
}
export function setSshSecret(id: string, value: string): void {
com.faceclaw.app.FaceclawSshKeys.setSecret(context(), id, value);
}
export function removeSshSecret(id: string): void {
com.faceclaw.app.FaceclawSshKeys.removeSecret(context(), id);
}
export function copyToPhoneClipboard(label: string, text: string): void {
com.faceclaw.app.FaceclawSshKeys.copyToClipboard(context(), label, text);
}
+59
View File
@@ -0,0 +1,59 @@
/**
* Session-list and connection-state types shared by the Terminal app's
* backends (g2mirror-client.ts, apps/terminal/tmux-client.ts). Kept free of
* platform imports so the tmux client can be unit-tested under node.
*/
export type G2MirrorSession = {
socket: string;
pid: number;
cwdHint: string;
/** Unix epoch ms of the terminal's last bell, or null if none observed. */
lastBellAt: number | null;
/**
* Unix epoch ms (host clock) of the app's last output, or null if none
* observed. Fresh to within the wrapper's 2s activity reporting interval
* while we're connected; compare against other host timestamps, not the
* phone clock (see the worker's local-receive-time activity tracking).
*/
lastOutputAt: number | null;
/** Window title the app last set (xterm OSC 0/2), or null if none observed. */
title: string | null;
};
export type G2MirrorPhase =
| "idle"
| "connecting"
| "connected" // handshake accepted; can list/attach
| "attached" // relaying to one session
| "failed";
export type G2MirrorState = {
phase: G2MirrorPhase;
status: string;
sessions: G2MirrorSession[];
attachedCommand: string;
/**
* server_name from the init success reply: a human-readable name for the
* machine the server runs on. "" until the handshake succeeds (or when an
* older server omits the field).
*/
serverName: string;
/**
* False when reconnecting can't help until the user changes something on
* the host (e.g. tmux missing or too old). Absent means retryable.
*/
retryable?: boolean;
};
/** A page of archived scrollback lines (see PROTOCOL.md "Scrollback history"). */
export type G2MirrorHistoryReply = {
/** Absolute index of lines[0]; the page covers [start, start + lines.length). */
start: number;
/** Oldest index still retained by the wrapper (older requests return nothing). */
oldest: number;
/** Current splice point (next line to be archived). */
next: number;
/** Plain text, ANSI-stripped, oldest-to-newest. */
lines: string[];
};
+18 -1
View File
@@ -1340,11 +1340,28 @@ export const terminalNewConnectionSetting = new ConfigSettingString({
label: "New connection",
storageKey: "terminal.newConnectionDraft",
defaultValue: "",
editorTitle: "g2mirror connection string (g2mirror://token@host)",
editorTitle: "Connection (ssh://user@host or g2mirror://token@host)",
glassesEditTitle: "Add connection",
normalize: (value) => (value ?? "").replace(/[\x00-\x1f]+/g, "").trim(),
});
/**
* Staging buffer for the Terminal app's SSH password prompt: the worker opens
* the phone's (masked) text editor on it, then moves what was typed into the
* platform keystore (app/native/ssh) and clears it as soon as the user
* confirms or cancels on the glasses. Not listed in the Settings app.
*/
export const terminalSshPasswordSetting = new ConfigSettingString({
id: "terminal-ssh-password",
label: "SSH password",
storageKey: "terminal.sshPasswordDraft",
defaultValue: "",
inputKind: "password",
editorTitle: "SSH password",
glassesEditTitle: "SSH password",
normalize: (value) => (value ?? "").replace(/[\r\n]+/g, ""),
});
/**
* Staging buffer for the T3 Code app's Pair-environment screen: the phone
* text editor types the `t3 pair` link into it, and the app reads it back
+2 -2
View File
@@ -27,7 +27,7 @@ class KeyCaptureLayer extends TextPageLayer {
constructor(private readonly onChord: (chord: KeyChord, ctx: LayerContext) => void) {
super(
"Add keybinding",
"Press the key to bind, on the keyboard. Hold Shift, Ctrl or Alt with it to bind the combination.",
"Press the key to bind, on the keyboard: a key, a mouse button, or a turn of the wheel. Hold Shift, Ctrl or Alt with it to bind the combination.",
);
}
@@ -137,7 +137,7 @@ export function keybindingsMenuItem(): MenuItem {
return {
label: "Keybindings",
description:
"Choose what keys do: arrows, Enter and Esc navigate by default, and any key (or a remote's button) can be bound to select, back, a swipe, a scroll or a menu.",
"Choose what keys do: arrows, Enter, Esc and a mouse's buttons and wheel navigate by default, and any key (or a remote's button) can be bound to select, back, a swipe, a scroll or a menu.",
onSelect: (ctx) => new KeybindingsLayer(ctx.stack.getBaseSize()).open(ctx),
render: ({ image, x, y, width }) => {
const count = keyboardService.keyBindings().length;
+25
View File
@@ -39,6 +39,8 @@ const PAGE_TITLE_OFFSET_Y = 2;
const PAGE_TITLE_GAP = 4;
/** Room a page menu keeps right of its rows for the scrollbar. */
const PAGE_SCROLLBAR_GUTTER = 6;
/** A heading row's text: dimmer than a row's, brighter than a disabled row's. */
const MENU_HEADING_VALUE = 90;
export type MenuLayout = {
/** Stereo depth of the menu surface, including the selected row. */
@@ -111,6 +113,12 @@ export type MenuItem = {
description?: string;
/** Disabled rows stay visible but render dimly and ignore clicks. */
disabled?: boolean | (() => boolean);
/**
* A label for the group of rows after it (see menuHeadingItem). MenuLayer's
* highlight skips it; a list that doesn't know headings shows it as a
* disabled row.
*/
heading?: boolean;
onSelect: (ctx: LayerContext, menu: MenuLayer) => Promise<void> | void;
render?: (args: MenuItemRenderArgs) => void;
};
@@ -214,6 +222,22 @@ export function submenuItem(
};
}
/**
* A heading for the rows that follow it, splitting a long menu into sections:
* dim capitals in the rows' text column, never selected.
*/
export function menuHeadingItem(label: string): MenuItem {
return {
label,
heading: true,
disabled: true,
onSelect: () => {},
render: ({ image, x, y, text }) => {
image.drawText(getDefaultSmallFont(), x, y + LIST_ROW_TEXT_INSET, text.toUpperCase(), MENU_HEADING_VALUE);
},
};
}
export function drawToggleMenuItem(
image: GrayImage,
font: UiFont,
@@ -281,6 +305,7 @@ export class MenuLayer implements Layer {
wrap: true,
rowGap: 1,
getHeight: () => listRowHeight(getDefaultSmallFont()),
isSelectable: (item) => !item.heading,
draw: ({ image, item, x, y, width, height, selected }) => {
const font = getDefaultSmallFont();
const disabled = isMenuItemDisabled(item);
+4 -1
View File
@@ -1,8 +1,11 @@
const { buildKotlin, checkAndroidRuntime } = require('../../scripts/kotlin-build.cjs');
const { buildGoSsh } = require('../../scripts/go-ssh-build.cjs');
module.exports = function (hookArgs) {
// NativeScript parses hooks with an older JavaScript parser; avoid optional chaining.
const { platform, release } = hookArgs.prepareData;
if (platform === 'android') checkAndroidRuntime();
return buildKotlin(platform, release ? 'release' : 'debug');
return buildKotlin(platform, release ? 'release' : 'debug').then(function () {
return buildGoSsh(platform);
});
};
@@ -0,0 +1,9 @@
package com.faceclaw.app
/**
* Events from FaceclawSshChannel, delivered on the thread that opened the
* channel. See native/ssh/faceclawssh.go (Listener) for the kinds and payloads.
*/
interface FaceclawSshListener {
fun onEvent(kind: String?, payload: String?): Unit
}
@@ -12,6 +12,12 @@ import kotlin.jvm.JvmStatic
*/
class BleProtocol {
companion object {
/** The service holding [WRITE_CHAR_UUID] and [NOTIFY_CHAR_UUID]. */
const val PROTOCOL_SERVICE_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e5450"
/** The service holding [RENDER_NOTIFY_UUID]. */
const val RENDER_SERVICE_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e6450"
const val WRITE_CHAR_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e5401"
const val NOTIFY_CHAR_UUID: String = "00002760-08c2-11e1-9073-0e8ac72e5402"
@@ -20,11 +20,18 @@ class CachedResource @JvmOverloads constructor(bytes: ByteArray, val owner: Stri
*/
class ResourceCacheState {
companion object {
/** Mirrors g2flash/patches/resource_cache.h. */
const val CACHE_SIZE = 196608
/**
* Mirrors g2flash/patches/resource_cache.h: the id table, then 320 KiB shared by the
* resources and their block headers. Firmware before Faceclaw/40 had 192 KiB in all,
* so this must not grow past what REQUIRED_FACECLAW_FIRMWARE_VERSION guarantees.
* RayNeo iO sessions use the same budget: that firmware's own copy of the header
* (faceclaw-rayneo-cfw patches/fc/resource_cache.h) needs at least this much before
* it reports the required revision.
*/
const val RESOURCE_COUNT = 512
const val TABLE_BYTES = RESOURCE_COUNT * 4
const val ARENA_BYTES = CACHE_SIZE - TABLE_BYTES
const val ARENA_BYTES = 320 * 1024
const val CACHE_SIZE = TABLE_BYTES + ARENA_BYTES
const val MAX_RESOURCE_SIZE = 65536
const val BLOCK_HEADER_BYTES = 16
@@ -507,7 +507,7 @@ class GlassesSessionCore(
// Preview/screenshot/recording callers render those explicitly on demand.
internal val compositor = SurfaceCompositor(false)
// Phone-side model of the CFW's 192 KiB resource cache.
// Phone-side model of the CFW's resource cache (ResourceCacheState.CACHE_SIZE).
// Reset whenever the image pipeline / EvenHub session is torn down: the
// firmware frees the cache with the fb lease, and after any resync the
// cheap safe assumption is an empty cache (glyphs re-upload lazily).
@@ -2001,13 +2001,13 @@ class GlassesSessionCore(
tap(data.copyOf())
return
}
logDebug("onNotification: address=" + address + " characteristicUuid=" + characteristicUuid + " data.length=" + data.size)
val frame = BleProtocol.parseFrame(data)
if (frame.ok && frame.sid == BleProtocol.SID_UI_SETTING) {
// CFW keyboard-bridge records (field 131) come from whichever temple hosts the
// keyboard. They are their own stream: neither an ACK nor glasses input, and the
// once-a-second status record among them must not count as user activity (which
// would hold off battery polling).
// would hold off battery polling). A touchpad sends a hundred of them a second
// while a finger is on it, so they are not logged one by one either.
val keyboardEvent = BleProtocol.parseFaceclawKeyboardEvent(frame.pb)
if (keyboardEvent != null) {
monitor.withLock { lastIncomingAtMs = now() }
@@ -2015,6 +2015,7 @@ class GlassesSessionCore(
return
}
}
logDebug("onNotification: address=" + address + " characteristicUuid=" + characteristicUuid + " data.length=" + data.size)
val decodedWearState = BleProtocol.parseWearState(frame)
val compassEvent = if (address.equals(rightAddress, ignoreCase = true))
BleProtocol.parseCompassEvent(frame)
@@ -29,6 +29,7 @@ import platform.CoreBluetooth.CBPeripheralDelegateProtocol
import platform.CoreBluetooth.CBPeripheralStateConnected
import platform.CoreBluetooth.CBPeripheralStateDisconnected
import platform.CoreBluetooth.CBService
import platform.CoreBluetooth.CBUUID
import platform.Foundation.NSData
import platform.Foundation.NSError
import platform.Foundation.NSNumber
@@ -47,6 +48,9 @@ interface IosBleScanListener {
fun onAdvertisement(identifier: String, name: String, manufacturerDataHex: String, rssi: Int, connectable: Boolean)
}
/** A peripheral the system holds a connection to; see [IosBleCentral.systemConnectedG2Arms]. */
class IosConnectedPeripheral(val identifier: String, val name: String)
/** ANCS authorization changes for a connected peripheral; delivered on the BLE queue. */
fun interface IosAncsAuthorizationListener {
fun onAncsAuthorization(identifier: String, authorized: Boolean)
@@ -214,6 +218,25 @@ class IosBleCentral(private val platform: ProtocolPlatform = IosProtocolPlatform
manager.scanForPeripheralsWithServices(null, mapOf(CBCentralManagerScanOptionAllowDuplicatesKey to true))
}
/**
* G2 arms the system is connected to, through this app, another app or iOS itself. A
* connected arm stops advertising, and iOS keeps the right arm's ANCS link open after a
* session ends, so a scan alone never hears it. Empty until Bluetooth is powered on.
*/
fun systemConnectedG2Arms(): List<IosConnectedPeripheral> {
val found = ArrayList<IosConnectedPeripheral>()
dispatch_sync(queue) {
val manager = central ?: return@dispatch_sync
if (manager.state != CBManagerStatePoweredOn) return@dispatch_sync
val services = listOf(BleProtocol.PROTOCOL_SERVICE_UUID, BleProtocol.RENDER_SERVICE_UUID).map { CBUUID.UUIDWithString(it) }
for (item in manager.retrieveConnectedPeripheralsWithServices(services)) {
val peripheral = item as? CBPeripheral ?: continue
found.add(IosConnectedPeripheral(peripheral.identifier.UUIDString.uppercase(), peripheral.name ?: ""))
}
}
return found
}
/** Known peripheral identifiers from this process's scans/retrievals (uppercase). */
fun knownIdentifiers(): List<String> = cond.withLock { peers.keys.toList() }
+43
View File
@@ -0,0 +1,43 @@
# Faceclaw SSH transport
The Terminal app's SSH client: a small Go package over
[golang.org/x/crypto/ssh](https://pkg.go.dev/golang.org/x/crypto/ssh), bound
into the apps with gomobile. It provides text-message channels over SSH:
- **exec**: run a command on the host, exchanging newline-delimited text
(used for tmux control mode and the tmux session poller; see
`app/apps/terminal/tmux-client.ts`).
- **websocket**: a WebSocket to an address as seen from the host, through a
`direct-tcpip` channel (used to tunnel g2mirror-server's protocol).
Channels to the same host and credentials share one SSH connection, with a
keepalive that fails them promptly when the peer silently disappears. Host
keys are pinned by the app (first connection reports the presented key so
the user can verify its fingerprint). Authentication uses a non-exportable
ECDSA P-256 key held by the platform keystore (Android Keystore/StrongBox,
iOS Secure Enclave; see `FaceclawSsh.kt` / `FaceclawSsh.m`) and, if the
server allows it, a password saved encrypted on the phone.
## Building
`scripts/go-ssh-build.cjs` runs `gomobile bind` (pinned in `go.mod`'s tool
block) from the NativeScript before-prepare hook and stages
`faceclaw-ssh.aar` / `Faceclawssh.xcframework` into the local
`@faceclaw/kotlin` plugin. It needs Go 1.26+ on PATH, plus the Android NDK
(Android) or Xcode (iOS); a content stamp skips rebuilds when the Go sources
haven't changed.
## Testing
`go test -race ./...` runs the transport against an in-process SSH server
(host-key pinning, password and keyboard-interactive auth, key auth through
a fake platform signer, exec framing, the websocket tunnel, connection
sharing and loss).
## Keeping it current
x/crypto/ssh is the security boundary against a malicious host or a
man in the middle; update it promptly when advisories appear
(`go get golang.org/x/crypto@latest && go mod tidy`). A Go panic in any
goroutine terminates the app: the package recovers in the goroutines it
owns, but not inside the library's own.
+254
View File
@@ -0,0 +1,254 @@
package faceclawssh
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"net/url"
"strings"
"time"
"unicode/utf8"
"github.com/gorilla/websocket"
"golang.org/x/crypto/ssh"
)
type closedPayload struct {
ExitStatus *int `json:"exitStatus,omitempty"`
Signal string `json:"signal,omitempty"`
Code *int `json:"code,omitempty"`
Reason string `json:"reason,omitempty"`
}
// runExec runs command on the host and relays newline-delimited text both
// ways until the command exits, the connection drops, or Close.
func (c *Channel) runExec(conn *pooledConn, command string) {
session, err := conn.client.NewSession()
if err != nil {
c.fail(channelOpenFailure(conn, err))
return
}
defer session.Close()
stdin, err1 := session.StdinPipe()
stdout, err2 := session.StdoutPipe()
stderr, err3 := session.StderrPipe()
if err := errors.Join(err1, err2, err3); err != nil {
c.fail(&failure{Kind: "channel", Message: err.Error()})
return
}
if err := session.Start(command); err != nil {
c.fail(&failure{Kind: "channel", Message: "could not run command: " + err.Error()})
return
}
go func() {
<-c.ctx.Done()
session.Close()
}()
c.markOpen()
go func() {
defer c.guard()
for text := range c.sendQ {
if _, err := io.WriteString(stdin, text+"\n"); err != nil {
return
}
}
// Close was called and the queue has drained: EOF tells the command
// we're done (tmux control mode detaches on it).
stdin.Close()
}()
stderrDone := make(chan struct{})
go func() {
defer close(stderrDone)
defer c.guard()
readLines(stderr, func(line string) { c.emit("stderr", line) })
}()
readErr := readLines(stdout, func(line string) { c.emit("text", line) })
// Deliver the command's last words (e.g. "tmux: command not found")
// before the close event, but don't hang on a stderr that never ends.
select {
case <-stderrDone:
case <-time.After(500 * time.Millisecond):
}
if c.ctx.Err() != nil {
return
}
waitErr := session.Wait()
var exitErr *ssh.ExitError
var missing *ssh.ExitMissingError
switch {
case waitErr == nil:
status := 0
c.finish("closed", closedPayload{ExitStatus: &status})
case errors.As(waitErr, &exitErr):
status := exitErr.ExitStatus()
c.finish("closed", closedPayload{ExitStatus: &status, Signal: exitErr.Signal()})
case errors.As(waitErr, &missing):
// The channel closed without an exit status: usually the connection
// went away under it.
c.fail(lostFailure(conn, readErr))
default:
c.fail(lostFailure(conn, waitErr))
}
}
// readLines calls emit for each line of r (without its newline) and returns
// the read error that ended it (nil at EOF). Lines may be arbitrarily long.
func readLines(r io.Reader, emit func(string)) error {
reader := bufio.NewReaderSize(r, 64*1024)
for {
line, err := reader.ReadBytes('\n')
if len(line) > 0 {
if line[len(line)-1] == '\n' {
line = line[:len(line)-1]
}
emit(escapeLine(line))
}
if err == io.EOF {
return nil
}
if err != nil {
return err
}
}
}
// escapeLine makes a line safe to hand across the gomobile boundary as a
// string (which must be valid UTF-8). Valid UTF-8 passes through. Otherwise
// every byte >= 0x80 becomes "\ooo" (backslash, three octal digits): the same
// escape tmux control mode uses for control characters and backslashes in
// %output, so a %output line split mid-character still decodes back to its
// exact bytes. (Outside %output a literal backslash is ambiguous with this
// escape; such lines are only ever displayed.)
func escapeLine(line []byte) string {
if utf8.Valid(line) {
return string(line)
}
var b strings.Builder
for _, c := range line {
if c >= 0x80 {
fmt.Fprintf(&b, "\\%03o", c)
} else {
b.WriteByte(c)
}
}
return b.String()
}
// runWebSocket opens rawURL (ws://host:port/path) through the SSH
// connection — host:port is resolved on the SSH server's side — and relays
// text frames.
func (c *Channel) runWebSocket(conn *pooledConn, rawURL string) {
parsed, err := url.Parse(rawURL)
if err != nil || parsed.Scheme != "ws" || parsed.Host == "" {
c.fail(&failure{Kind: "config", Message: fmt.Sprintf("bad websocket URL %q", rawURL)})
return
}
target := parsed.Host
if parsed.Port() == "" {
target = net.JoinHostPort(parsed.Hostname(), "80")
}
dialer := websocket.Dialer{
NetDialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
forwarded, err := conn.client.DialContext(ctx, "tcp", target)
if err != nil {
return nil, err
}
return noDeadlineConn{forwarded}, nil
},
}
// The handshake timeout rides the context: SSH channels can't do deadlines.
handshakeCtx, cancelHandshake := context.WithTimeout(c.ctx, defaultConnectTimeout)
ws, _, err := dialer.DialContext(handshakeCtx, rawURL, nil)
cancelHandshake()
if err != nil {
if c.ctx.Err() != nil {
return
}
c.fail(channelOpenFailure(conn, fmt.Errorf("could not reach %s on the host: %w", target, err)))
return
}
defer ws.Close()
go func() {
<-c.ctx.Done()
ws.Close()
}()
c.markOpen()
go func() {
defer c.guard()
for text := range c.sendQ {
if err := ws.WriteMessage(websocket.TextMessage, []byte(text)); err != nil {
return
}
}
ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "bye"),
time.Now().Add(time.Second))
}()
for {
kind, data, err := ws.ReadMessage()
if err != nil {
if c.ctx.Err() != nil {
return
}
var closeErr *websocket.CloseError
if errors.As(err, &closeErr) {
code := closeErr.Code
c.finish("closed", closedPayload{Code: &code, Reason: closeErr.Text})
return
}
c.fail(lostFailure(conn, err))
return
}
if kind == websocket.TextMessage {
c.emit("text", string(data))
}
}
}
// noDeadlineConn adapts an SSH direct-tcpip channel for the websocket
// library, which sets deadlines the channel doesn't support. Timeouts come
// from contexts and the SSH keepalive instead.
type noDeadlineConn struct{ net.Conn }
func (noDeadlineConn) SetDeadline(time.Time) error { return nil }
func (noDeadlineConn) SetReadDeadline(time.Time) error { return nil }
func (noDeadlineConn) SetWriteDeadline(time.Time) error { return nil }
// channelOpenFailure classifies a failure to open a channel: if the SSH
// connection itself is gone it's a network failure (reconnect), otherwise
// the host refused this particular channel.
func channelOpenFailure(conn *pooledConn, err error) *failure {
if isConnDead(conn) {
return &failure{Kind: "network", Message: "connection lost: " + err.Error()}
}
return &failure{Kind: "channel", Message: err.Error()}
}
func lostFailure(conn *pooledConn, err error) *failure {
message := "connection lost"
if err != nil && !errors.Is(err, io.EOF) {
message += ": " + err.Error()
}
if !isConnDead(conn) {
// The connection is fine; only this channel ended abruptly.
return &failure{Kind: "channel", Message: "channel closed unexpectedly"}
}
return &failure{Kind: "network", Message: message}
}
func isConnDead(conn *pooledConn) bool {
// client.Wait's goroutine marks the connection dead slightly after the
// channels see their streams end; give it a moment to catch up.
deadline := time.Now().Add(200 * time.Millisecond)
for {
poolMu.Lock()
dead := conn.dead
poolMu.Unlock()
if dead || time.Now().After(deadline) {
return dead
}
time.Sleep(10 * time.Millisecond)
}
}
+304
View File
@@ -0,0 +1,304 @@
// Package faceclawssh is Faceclaw's SSH transport, bound into the Android and
// iOS apps with gomobile. It exposes text-message channels over SSH:
//
// - "exec": run a command on the host and exchange newline-delimited text
// with it (stdin lines in, stdout lines out). Used for tmux control mode
// and the tmux session poller.
// - "websocket": open a direct-tcpip channel to an address as seen from the
// host (normally g2mirror-server on 127.0.0.1:8737) and speak WebSocket
// text frames over it.
//
// Channels to the same host, user and credentials share one SSH connection
// (see pool.go). Host keys are pinned by the caller: a connection whose host
// presents a key that isn't in the spec's hostKeys fails with a
// "hostkey-unknown" or "hostkey-mismatch" failure carrying the presented key,
// so the app can show the fingerprint and retry once the user has trusted it.
// Authentication uses a platform-held, non-exportable ECDSA P-256 key (the
// Signer interface; Android Keystore / iOS Secure Enclave) and, if the server
// allows it, a password.
//
// Everything crossing the gomobile boundary is a string, []byte or one of the
// interfaces below; structured values are JSON strings.
package faceclawssh
import (
"context"
"encoding/json"
"fmt"
"runtime/debug"
"sync"
"time"
)
// Signer is implemented by the platform: an ECDSA P-256 key whose private
// half never leaves the device's keystore.
type Signer interface {
// PublicKey returns the key's public half, either as X.509
// SubjectPublicKeyInfo DER (Android's PublicKey.getEncoded()) or as an
// uncompressed X9.62 point, 0x04 || X || Y (iOS's
// SecKeyCopyExternalRepresentation).
PublicKey() []byte
// Sign returns the ASN.1 DER ECDSA signature of SHA-256(data).
Sign(data []byte) ([]byte, error)
}
// Listener receives a channel's events. Calls arrive on arbitrary goroutines
// (never concurrently for one channel); the platform wrapper hops them onto
// the thread that owns the channel.
//
// Event kinds and payloads:
// - "open": the channel is ready; payload empty. Sends made before this are
// queued and delivered once open.
// - "text": one message (websocket text frame, or one stdout line without
// its newline). Exec lines that aren't valid UTF-8 have every byte >= 0x80
// escaped as a backslash and three octal digits, matching tmux control
// mode's escaping of control characters (see escapeLine).
// - "stderr": one stderr line of an exec channel, escaped the same way.
// - "closed": the channel ended normally; payload is JSON
// {"exitStatus": n, "signal": "...", "code": n, "reason": "..."} with the
// fields that apply (exec exit status/signal, websocket close code/reason).
// Terminal: no events follow.
// - "failure": the channel could not be opened or was lost; payload is a
// JSON Failure. Terminal: no events follow.
type Listener interface {
OnEvent(kind string, payload string)
}
// Failure describes why a channel failed, as the JSON payload of a "failure"
// event.
type failure struct {
// "hostkey-unknown": no host key is pinned yet; HostKey is what the host
// presented. "hostkey-mismatch": the host presented a key that isn't
// pinned. "auth": the host refused every credential we have.
// "network": couldn't reach the host, or the connection dropped.
// "channel": the SSH connection is fine but the channel couldn't be
// opened (exec refused, nothing listening at the forwarded address...).
// "config": the spec was malformed. "internal": a bug.
Kind string `json:"kind"`
Message string `json:"message"`
HostKey *hostKeyInfo `json:"hostKey,omitempty"`
// For "auth": the host accepts password (or keyboard-interactive)
// authentication, whether a password was sent, and whether our key was
// offered.
PasswordAllowed bool `json:"passwordAllowed,omitempty"`
PasswordTried bool `json:"passwordTried,omitempty"`
KeyTried bool `json:"keyTried,omitempty"`
}
func (f *failure) Error() string { return f.Message }
type hostKeyInfo struct {
// SSH key type, e.g. "ssh-ed25519".
Type string `json:"type"`
// OpenSSH-style SHA-256 fingerprint, "SHA256:<base64>".
Fingerprint string `json:"fingerprint"`
// The key in SSH wire format, base64: what goes in a spec's hostKeys.
Key string `json:"key"`
}
type channelSpec struct {
// "exec" or "websocket".
Type string `json:"type"`
// exec: the command line, run by the user's login shell.
Command string `json:"command"`
// websocket: ws:// URL, resolved on the host's side of the connection.
URL string `json:"url"`
}
type openSpec struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
// Pinned host keys, SSH wire format, base64. Empty: the first connection
// fails with "hostkey-unknown".
HostKeys []string `json:"hostKeys"`
// Offer the platform key (the Signer passed to Open).
UseKey bool `json:"useKey"`
ConnectTimeoutMs int `json:"connectTimeoutMs"`
KeepaliveIntervalMs int `json:"keepaliveIntervalMs"`
Channel channelSpec `json:"channel"`
}
const (
defaultConnectTimeout = 15 * time.Second
defaultKeepaliveInterval = 20 * time.Second
// Messages queued on a channel before Send starts refusing them.
sendQueueCapacity = 4096
// How long Close waits for queued messages to flush and the far end to
// finish before tearing the channel down.
closeGracePeriod = 2 * time.Second
)
// Channel is one open (or opening) channel. Methods are safe to call from
// any thread.
type Channel struct {
listener Listener
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
closed bool // Close was called: no more sends, no more events
opened bool
sendQ chan string
finishOnce sync.Once
}
// Open starts opening a channel described by spec (a JSON openSpec) and
// returns immediately; progress arrives as listener events. signer may be
// nil (no key authentication).
func Open(spec string, signer Signer, listener Listener) *Channel {
ctx, cancel := context.WithCancel(context.Background())
c := &Channel{
listener: listener,
ctx: ctx,
cancel: cancel,
sendQ: make(chan string, sendQueueCapacity),
}
go c.run(spec, signer)
return c
}
// Send queues one message: a websocket text frame, or a line for an exec
// channel's stdin (the newline is added). Returns false if the channel is
// closed or its queue is full.
func (c *Channel) Send(text string) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return false
}
select {
case c.sendQ <- text:
return true
default:
return false
}
}
// Close ends the channel. Messages already queued are still sent (so a
// parting "unview" reaches the host), then the channel's write side is
// closed and, after a short grace period, the channel is torn down. No
// events are delivered after Close.
func (c *Channel) Close() {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return
}
c.closed = true
opened := c.opened
close(c.sendQ)
c.mu.Unlock()
if !opened {
c.cancel()
return
}
time.AfterFunc(closeGracePeriod, c.cancel)
}
func (c *Channel) isClosed() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.closed
}
func (c *Channel) emit(kind, payload string) {
if c.isClosed() {
return
}
c.listener.OnEvent(kind, payload)
}
func (c *Channel) markOpen() {
c.mu.Lock()
c.opened = true
c.mu.Unlock()
c.emit("open", "")
}
// finish delivers the channel's one terminal event ("closed" or "failure").
func (c *Channel) finish(kind string, payload any) {
c.finishOnce.Do(func() {
encoded, err := json.Marshal(payload)
if err != nil {
encoded = []byte(`{"kind":"internal","message":"unencodable event"}`)
}
c.emit(kind, string(encoded))
c.cancel()
})
}
func (c *Channel) fail(f *failure) { c.finish("failure", f) }
// guard turns a panic in one of our goroutines into a failure event instead
// of crashing the app (an unrecovered Go panic kills the whole process).
func (c *Channel) guard() {
if r := recover(); r != nil {
c.fail(&failure{Kind: "internal", Message: fmt.Sprintf("internal error: %v\n%s", r, debug.Stack())})
}
}
func (c *Channel) run(specJSON string, signer Signer) {
defer c.guard()
var spec openSpec
if err := json.Unmarshal([]byte(specJSON), &spec); err != nil {
c.fail(&failure{Kind: "config", Message: "bad channel spec: " + err.Error()})
return
}
if spec.Host == "" || spec.User == "" {
c.fail(&failure{Kind: "config", Message: "host and user are required"})
return
}
if spec.Port == 0 {
spec.Port = 22
}
if !spec.UseKey {
signer = nil
}
conn, err := acquire(c.ctx, &spec, signer)
if err != nil {
if c.ctx.Err() != nil {
return
}
c.fail(asFailure(err))
return
}
defer conn.release()
switch spec.Channel.Type {
case "exec":
c.runExec(conn, spec.Channel.Command)
case "websocket":
c.runWebSocket(conn, spec.Channel.URL)
default:
c.fail(&failure{Kind: "config", Message: fmt.Sprintf("unknown channel type %q", spec.Channel.Type)})
}
}
func asFailure(err error) *failure {
if f, ok := err.(*failure); ok {
return f
}
return &failure{Kind: "network", Message: err.Error()}
}
// AuthorizedKey formats a platform public key (see Signer.PublicKey) as an
// authorized_keys line: "ecdsa-sha2-nistp256 AAAA... comment".
func AuthorizedKey(publicKey []byte, comment string) (string, error) {
key, err := sshPublicKey(publicKey)
if err != nil {
return "", err
}
return authorizedKeyLine(key, comment), nil
}
// Fingerprint returns the OpenSSH SHA-256 fingerprint ("SHA256:...") of a
// platform public key.
func Fingerprint(publicKey []byte) (string, error) {
key, err := sshPublicKey(publicKey)
if err != nil {
return "", err
}
return fingerprint(key), nil
}
+526
View File
@@ -0,0 +1,526 @@
package faceclawssh
import (
"bufio"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/gorilla/websocket"
"golang.org/x/crypto/ssh"
)
// ---- test SSH server ----
type testServer struct {
addr string
hostKey ssh.Signer
accepts atomic.Int32
listener net.Listener
}
type serverOptions struct {
password string // "" = password auth disabled
keyboardInteractive bool // offer the password via keyboard-interactive instead
authorizedKey ssh.PublicKey
}
func newTestServer(t *testing.T, opts serverOptions) *testServer {
t.Helper()
_, priv, _ := ed25519.GenerateKey(rand.Reader)
hostKey, err := ssh.NewSignerFromKey(priv)
if err != nil {
t.Fatal(err)
}
config := &ssh.ServerConfig{}
if opts.password != "" && !opts.keyboardInteractive {
config.PasswordCallback = func(_ ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
if string(password) == opts.password {
return nil, nil
}
return nil, fmt.Errorf("wrong password")
}
}
if opts.password != "" && opts.keyboardInteractive {
config.KeyboardInteractiveCallback = func(_ ssh.ConnMetadata, challenge ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
answers, err := challenge("", "", []string{"Password: "}, []bool{false})
if err != nil {
return nil, err
}
if len(answers) == 1 && answers[0] == opts.password {
return nil, nil
}
return nil, fmt.Errorf("wrong password")
}
}
if opts.authorizedKey != nil {
config.PublicKeyCallback = func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
if string(key.Marshal()) == string(opts.authorizedKey.Marshal()) {
return nil, nil
}
return nil, fmt.Errorf("unknown key")
}
}
config.AddHostKey(hostKey)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := &testServer{addr: listener.Addr().String(), hostKey: hostKey, listener: listener}
t.Cleanup(func() { listener.Close() })
go func() {
for {
tcp, err := listener.Accept()
if err != nil {
return
}
server.accepts.Add(1)
go server.serve(tcp, config)
}
}()
return server
}
func (s *testServer) serve(tcp net.Conn, config *ssh.ServerConfig) {
conn, chans, reqs, err := ssh.NewServerConn(tcp, config)
if err != nil {
tcp.Close()
return
}
defer conn.Close()
go ssh.DiscardRequests(reqs) // replies false to keepalives, which still counts as alive
for newChannel := range chans {
switch newChannel.ChannelType() {
case "session":
go serveSession(newChannel)
case "direct-tcpip":
go serveDirectTCPIP(newChannel)
default:
newChannel.Reject(ssh.UnknownChannelType, "nope")
}
}
}
// serveSession implements a few fake commands:
// - "echo": echo stdin lines back with a "> " prefix until EOF, exit 0
// - "bytes": print an invalid-UTF-8 line and a stderr line, exit 3
func serveSession(newChannel ssh.NewChannel) {
channel, requests, err := newChannel.Accept()
if err != nil {
return
}
defer channel.Close()
for req := range requests {
if req.Type != "exec" {
req.Reply(false, nil)
continue
}
var payload struct{ Command string }
ssh.Unmarshal(req.Payload, &payload)
req.Reply(true, nil)
status := 0
switch payload.Command {
case "echo":
scanner := bufio.NewScanner(channel)
for scanner.Scan() {
fmt.Fprintf(channel, "> %s\n", scanner.Text())
}
case "bytes":
channel.Write([]byte("%output %1 caf\xc3\n%output %1 \xa9 ok\nplain ✓\n"))
channel.Stderr().Write([]byte("oops\n"))
status = 3
default:
channel.Stderr().Write([]byte("unknown command\n"))
status = 127
}
channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{uint32(status)}))
return
}
}
func serveDirectTCPIP(newChannel ssh.NewChannel) {
var target struct {
Host string
Port uint32
OriginHost string
OriginPort uint32
}
if err := ssh.Unmarshal(newChannel.ExtraData(), &target); err != nil {
newChannel.Reject(ssh.ConnectionFailed, "bad payload")
return
}
upstream, err := net.Dial("tcp", net.JoinHostPort(target.Host, fmt.Sprint(target.Port)))
if err != nil {
newChannel.Reject(ssh.ConnectionFailed, err.Error())
return
}
channel, requests, err := newChannel.Accept()
if err != nil {
upstream.Close()
return
}
go ssh.DiscardRequests(requests)
go func() { io.Copy(upstream, channel); upstream.Close() }()
io.Copy(channel, upstream)
channel.Close()
}
// ---- test client plumbing ----
type event struct{ kind, payload string }
type recorder struct {
events chan event
}
func newRecorder() *recorder { return &recorder{events: make(chan event, 256)} }
func (r *recorder) OnEvent(kind, payload string) { r.events <- event{kind, payload} }
func (r *recorder) next(t *testing.T) event {
t.Helper()
select {
case e := <-r.events:
return e
case <-time.After(10 * time.Second):
t.Fatal("timed out waiting for event")
return event{}
}
}
func (r *recorder) expect(t *testing.T, kind string) event {
t.Helper()
e := r.next(t)
if e.kind != kind {
t.Fatalf("got event %s(%s), want %s", e.kind, e.payload, kind)
}
return e
}
func (r *recorder) expectFailure(t *testing.T) failure {
t.Helper()
e := r.expect(t, "failure")
var f failure
if err := json.Unmarshal([]byte(e.payload), &f); err != nil {
t.Fatal(err)
}
return f
}
type softwareSigner struct{ key *ecdsa.PrivateKey }
func newSoftwareSigner(t *testing.T) *softwareSigner {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
return &softwareSigner{key: key}
}
func (s *softwareSigner) PublicKey() []byte {
der, _ := x509.MarshalPKIXPublicKey(&s.key.PublicKey)
return der
}
func (s *softwareSigner) Sign(data []byte) ([]byte, error) {
digest := sha256.Sum256(data)
return ecdsa.SignASN1(rand.Reader, s.key, digest[:])
}
func (s *softwareSigner) sshKey(t *testing.T) ssh.PublicKey {
key, err := ssh.NewPublicKey(&s.key.PublicKey)
if err != nil {
t.Fatal(err)
}
return key
}
func specFor(server *testServer, mutate func(*openSpec)) string {
host, port, _ := net.SplitHostPort(server.addr)
var portNumber int
fmt.Sscan(port, &portNumber)
spec := openSpec{
Host: host,
Port: portNumber,
User: "jim",
HostKeys: []string{base64.StdEncoding.EncodeToString(server.hostKey.PublicKey().Marshal())},
Channel: channelSpec{Type: "exec", Command: "echo"},
}
if mutate != nil {
mutate(&spec)
}
encoded, _ := json.Marshal(spec)
return string(encoded)
}
func resetPool() {
poolMu.Lock()
defer poolMu.Unlock()
for key, conn := range pool {
conn.client.Close()
delete(pool, key)
}
}
// ---- tests ----
func TestHostKeyPinning(t *testing.T) {
defer resetPool()
server := newTestServer(t, serverOptions{password: "pw"})
wantKey := base64.StdEncoding.EncodeToString(server.hostKey.PublicKey().Marshal())
rec := newRecorder()
Open(specFor(server, func(s *openSpec) { s.HostKeys = nil; s.Password = "pw" }), nil, rec)
f := rec.expectFailure(t)
if f.Kind != "hostkey-unknown" || f.HostKey == nil || f.HostKey.Key != wantKey ||
f.HostKey.Type != ssh.KeyAlgoED25519 || !strings.HasPrefix(f.HostKey.Fingerprint, "SHA256:") {
t.Fatalf("unexpected failure %+v", f)
}
_, otherPriv, _ := ed25519.GenerateKey(rand.Reader)
other, _ := ssh.NewSignerFromKey(otherPriv)
rec = newRecorder()
Open(specFor(server, func(s *openSpec) {
s.HostKeys = []string{base64.StdEncoding.EncodeToString(other.PublicKey().Marshal())}
s.Password = "pw"
}), nil, rec)
f = rec.expectFailure(t)
if f.Kind != "hostkey-mismatch" || f.HostKey.Key != wantKey {
t.Fatalf("unexpected failure %+v", f)
}
rec = newRecorder()
ch := Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec)
rec.expect(t, "open")
ch.Close()
}
func TestPasswordAuth(t *testing.T) {
for _, interactive := range []bool{false, true} {
t.Run(fmt.Sprintf("keyboardInteractive=%v", interactive), func(t *testing.T) {
defer resetPool()
server := newTestServer(t, serverOptions{password: "secret", keyboardInteractive: interactive})
rec := newRecorder()
Open(specFor(server, nil), nil, rec)
f := rec.expectFailure(t)
if f.Kind != "auth" || !f.PasswordAllowed || f.PasswordTried {
t.Fatalf("no password: %+v", f)
}
rec = newRecorder()
Open(specFor(server, func(s *openSpec) { s.Password = "wrong" }), nil, rec)
f = rec.expectFailure(t)
if f.Kind != "auth" || !f.PasswordTried {
t.Fatalf("wrong password: %+v", f)
}
rec = newRecorder()
ch := Open(specFor(server, func(s *openSpec) { s.Password = "secret" }), nil, rec)
rec.expect(t, "open")
ch.Send("hi")
if e := rec.expect(t, "text"); e.payload != "> hi" {
t.Fatalf("got %q", e.payload)
}
ch.Close()
})
}
}
func TestKeyAuth(t *testing.T) {
defer resetPool()
signer := newSoftwareSigner(t)
server := newTestServer(t, serverOptions{authorizedKey: signer.sshKey(t)})
rec := newRecorder()
ch := Open(specFor(server, func(s *openSpec) { s.UseKey = true }), signer, rec)
rec.expect(t, "open")
ch.Close()
// A key the server doesn't know, and no password support.
resetPool()
rec = newRecorder()
Open(specFor(server, func(s *openSpec) { s.UseKey = true }), newSoftwareSigner(t), rec)
f := rec.expectFailure(t)
if f.Kind != "auth" || !f.KeyTried || f.PasswordAllowed {
t.Fatalf("unexpected failure %+v", f)
}
line, err := AuthorizedKey(signer.PublicKey(), "Faceclaw on my phone")
if err != nil || !strings.HasPrefix(line, "ecdsa-sha2-nistp256 AAAA") || !strings.HasSuffix(line, " Faceclaw-on-my-phone") {
t.Fatalf("AuthorizedKey = %q, %v", line, err)
}
parsed, _, _, _, err := ssh.ParseAuthorizedKey([]byte(line))
if err != nil || string(parsed.Marshal()) != string(signer.sshKey(t).Marshal()) {
t.Fatalf("authorized key does not round-trip: %v", err)
}
// The uncompressed-point form iOS hands us parses to the same key.
point := elliptic.Marshal(elliptic.P256(), signer.key.X, signer.key.Y) //nolint:staticcheck
fromPoint, err := Fingerprint(point)
fromDER, _ := Fingerprint(signer.PublicKey())
if err != nil || fromPoint != fromDER {
t.Fatalf("fingerprints differ: %s vs %s (%v)", fromPoint, fromDER, err)
}
}
func TestExecFraming(t *testing.T) {
defer resetPool()
server := newTestServer(t, serverOptions{password: "pw"})
rec := newRecorder()
Open(specFor(server, func(s *openSpec) { s.Password = "pw"; s.Channel.Command = "bytes" }), nil, rec)
rec.expect(t, "open")
var texts, stderr []string
var closed closedPayload
for done := false; !done; {
e := rec.next(t)
switch e.kind {
case "text":
texts = append(texts, e.payload)
case "stderr":
stderr = append(stderr, e.payload)
case "closed":
json.Unmarshal([]byte(e.payload), &closed)
done = true
default:
t.Fatalf("unexpected %s(%s)", e.kind, e.payload)
}
}
want := []string{`%output %1 caf\303`, `%output %1 \251 ok`, "plain ✓"}
if strings.Join(texts, "|") != strings.Join(want, "|") {
t.Fatalf("texts = %q, want %q", texts, want)
}
if len(stderr) != 1 || stderr[0] != "oops" {
t.Fatalf("stderr = %q", stderr)
}
if closed.ExitStatus == nil || *closed.ExitStatus != 3 {
t.Fatalf("closed = %+v", closed)
}
}
func TestWebSocketTunnelAndSharing(t *testing.T) {
defer resetPool()
upgrader := websocket.Upgrader{}
var serverConns sync.WaitGroup
wsServer := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
serverConns.Add(1)
defer serverConns.Done()
defer conn.Close()
for {
kind, data, err := conn.ReadMessage()
if err != nil {
return
}
if string(data) == "quit" {
conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(4000, "asked to quit"))
return
}
conn.WriteMessage(kind, append([]byte("echo:"), data...))
}
})}
wsListener, _ := net.Listen("tcp", "127.0.0.1:0")
go wsServer.Serve(wsListener)
defer wsServer.Close()
server := newTestServer(t, serverOptions{password: "pw"})
wsSpec := specFor(server, func(s *openSpec) {
s.Password = "pw"
s.Channel = channelSpec{Type: "websocket", URL: "ws://" + wsListener.Addr().String() + "/"}
})
recA, recB := newRecorder(), newRecorder()
a := Open(wsSpec, nil, recA)
b := Open(wsSpec, nil, recB)
// Sent before open: queued until the channel is up.
a.Send(`{"type":"init"}`)
recA.expect(t, "open")
recB.expect(t, "open")
if e := recA.expect(t, "text"); e.payload != `echo:{"type":"init"}` {
t.Fatalf("got %q", e.payload)
}
b.Send("quit")
e := recB.expect(t, "closed")
var closed closedPayload
json.Unmarshal([]byte(e.payload), &closed)
if closed.Code == nil || *closed.Code != 4000 || closed.Reason != "asked to quit" {
t.Fatalf("closed = %+v", closed)
}
if n := server.accepts.Load(); n != 1 {
t.Fatalf("expected both channels on one SSH connection, got %d connections", n)
}
// Close flushes queued messages before tearing down.
a.Send("last words")
a.Close()
time.Sleep(300 * time.Millisecond)
select {
case e := <-recA.events:
t.Fatalf("event after Close: %s(%s)", e.kind, e.payload)
default:
}
// Nothing listening at the forwarded address: a channel failure, not a
// network one (the SSH connection is fine).
recC := newRecorder()
Open(specFor(server, func(s *openSpec) {
s.Password = "pw"
s.Channel = channelSpec{Type: "websocket", URL: "ws://127.0.0.1:1/"}
}), nil, recC)
if f := recC.expectFailure(t); f.Kind != "channel" {
t.Fatalf("unexpected failure %+v", f)
}
}
func TestConnectionLoss(t *testing.T) {
defer resetPool()
server := newTestServer(t, serverOptions{password: "pw"})
rec := newRecorder()
Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec)
rec.expect(t, "open")
// Kill the SSH connection under the channel.
poolMu.Lock()
for _, conn := range pool {
conn.client.Close()
}
poolMu.Unlock()
if f := rec.expectFailure(t); f.Kind != "network" {
t.Fatalf("unexpected failure %+v", f)
}
// The next channel dials a fresh connection.
rec = newRecorder()
ch := Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec)
rec.expect(t, "open")
ch.Close()
if n := server.accepts.Load(); n != 2 {
t.Fatalf("expected a second connection, got %d", n)
}
}
func TestNetworkFailure(t *testing.T) {
rec := newRecorder()
Open(`{"host":"127.0.0.1","port":1,"user":"jim","channel":{"type":"exec","command":"x"}}`, nil, rec)
if f := rec.expectFailure(t); f.Kind != "network" {
t.Fatalf("unexpected failure %+v", f)
}
rec = newRecorder()
Open(`not json`, nil, rec)
if f := rec.expectFailure(t); f.Kind != "config" {
t.Fatalf("unexpected failure %+v", f)
}
}
+21
View File
@@ -0,0 +1,21 @@
module github.com/jimrandomh/faceclaw/native/ssh
go 1.26.0
require (
github.com/gorilla/websocket v1.5.3
golang.org/x/crypto v0.59.0
)
require (
golang.org/x/mobile v0.0.0-20261011034528-197770444867 // indirect
golang.org/x/mod v0.42.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/tools v0.52.0 // indirect
)
tool (
golang.org/x/mobile/cmd/gobind
golang.org/x/mobile/cmd/gomobile
)
+16
View File
@@ -0,0 +1,16 @@
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/mobile v0.0.0-20261011034528-197770444867 h1:rav73cdd7OQUPgt1aIFbZQTiPNnjfueKXvfOiLCY0Ss=
golang.org/x/mobile v0.0.0-20261011034528-197770444867/go.mod h1:HR/iBzuQmVTl/us733QPwrqHp43a8m9ZLgyKXD3ST6U=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk=
golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
+58
View File
@@ -0,0 +1,58 @@
package faceclawssh
import (
"encoding/json"
"net"
"os"
"strconv"
"testing"
)
// TestOpenSSHInterop checks the parts of the handshake that need no
// credentials against a real sshd: key exchange, host key reporting and
// pinning, and how an authentication refusal is classified. Opt-in:
//
// FACECLAW_SSH_INTEROP_ADDR=127.0.0.1:22 go test -run Interop -v
//
// Compare the logged fingerprint with `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub`.
// It makes one failed login attempt (no password, an unknown key) as
// FACECLAW_SSH_INTEROP_USER (default: $USER).
func TestOpenSSHInterop(t *testing.T) {
addr := os.Getenv("FACECLAW_SSH_INTEROP_ADDR")
if addr == "" {
t.Skip("FACECLAW_SSH_INTEROP_ADDR not set")
}
defer resetPool()
user := os.Getenv("FACECLAW_SSH_INTEROP_USER")
if user == "" {
user = os.Getenv("USER")
}
host, portText, err := net.SplitHostPort(addr)
if err != nil {
t.Fatal(err)
}
port, _ := strconv.Atoi(portText)
spec := func(hostKeys []string) string {
encoded, _ := json.Marshal(openSpec{
Host: host, Port: port, User: user, HostKeys: hostKeys, UseKey: true,
Channel: channelSpec{Type: "exec", Command: "true"},
})
return string(encoded)
}
rec := newRecorder()
Open(spec(nil), newSoftwareSigner(t), rec)
f := rec.expectFailure(t)
if f.Kind != "hostkey-unknown" || f.HostKey == nil {
t.Fatalf("first contact: %+v", f)
}
t.Logf("host key: %s %s", f.HostKey.Type, f.HostKey.Fingerprint)
rec = newRecorder()
Open(spec([]string{f.HostKey.Key}), newSoftwareSigner(t), rec)
auth := rec.expectFailure(t)
if auth.Kind != "auth" || !auth.KeyTried {
t.Fatalf("pinned, unknown key: %+v", auth)
}
t.Logf("auth refusal: %+v", auth)
}
+91
View File
@@ -0,0 +1,91 @@
package faceclawssh
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"crypto/x509"
"encoding/asn1"
"encoding/base64"
"errors"
"fmt"
"io"
"math/big"
"strings"
"golang.org/x/crypto/ssh"
)
// platformSigner adapts the platform's keystore-backed Signer to ssh.Signer.
// The platform signs SHA-256(data) with ECDSA P-256 and returns ASN.1 DER;
// SSH wants the signature as two mpints (RFC 5656 §3.1.2).
type platformSigner struct {
signer Signer
pub ssh.PublicKey
}
func newPlatformSigner(signer Signer) (*platformSigner, error) {
pub, err := sshPublicKey(signer.PublicKey())
if err != nil {
return nil, err
}
return &platformSigner{signer: signer, pub: pub}, nil
}
func (p *platformSigner) PublicKey() ssh.PublicKey { return p.pub }
func (p *platformSigner) Sign(_ io.Reader, data []byte) (*ssh.Signature, error) {
der, err := p.signer.Sign(data)
if err != nil {
return nil, fmt.Errorf("platform key signing failed: %w", err)
}
var sig struct{ R, S *big.Int }
rest, err := asn1.Unmarshal(der, &sig)
if err != nil || len(rest) != 0 || sig.R == nil || sig.S == nil || sig.R.Sign() <= 0 || sig.S.Sign() <= 0 {
return nil, errors.New("platform key returned a malformed signature")
}
blob := ssh.Marshal(struct{ R, S *big.Int }{sig.R, sig.S})
return &ssh.Signature{Format: p.pub.Type(), Blob: blob}, nil
}
// sshPublicKey parses a platform public key (SubjectPublicKeyInfo DER or an
// uncompressed P-256 point) into an ecdsa-sha2-nistp256 SSH key.
func sshPublicKey(encoded []byte) (ssh.PublicKey, error) {
var pub *ecdsa.PublicKey
if len(encoded) == 65 && encoded[0] == 4 {
parsed, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), encoded)
if err != nil {
return nil, fmt.Errorf("bad P-256 point: %v", err)
}
pub = parsed
} else {
parsed, err := x509.ParsePKIXPublicKey(encoded)
if err != nil {
return nil, fmt.Errorf("bad public key: %v", err)
}
ecdsaKey, ok := parsed.(*ecdsa.PublicKey)
if !ok {
return nil, fmt.Errorf("unsupported public key type %T", parsed)
}
pub = ecdsaKey
}
if pub.Curve != elliptic.P256() {
return nil, errors.New("only P-256 keys are supported")
}
return ssh.NewPublicKey(pub)
}
func authorizedKeyLine(key ssh.PublicKey, comment string) string {
line := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key)))
comment = strings.Join(strings.Fields(comment), "-")
if comment != "" {
line += " " + comment
}
return line
}
// fingerprint is OpenSSH's SHA256 fingerprint format (unpadded base64).
func fingerprint(key ssh.PublicKey) string {
sum := sha256.Sum256(key.Marshal())
return "SHA256:" + base64.RawStdEncoding.EncodeToString(sum[:])
}
+416
View File
@@ -0,0 +1,416 @@
package faceclawssh
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"log"
"net"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
)
// SSH connections are shared between channels with the same host, port,
// user, credentials and pinned keys: the Terminal app's session poller and
// each of its view windows ride one TCP connection. A connection with no
// channels left lingers briefly (a view window closing and reopening shouldn't
// pay a fresh handshake) and is then closed. A keepalive probe closes
// connections whose peer has silently gone away, which fails every channel on
// them so the app's reconnect logic takes over.
const idleLinger = 15 * time.Second
type pooledConn struct {
key string
client *ssh.Client
// Guarded by poolMu.
refs int
dead bool
linger *time.Timer
}
type dialCall struct {
done chan struct{}
err error
}
var (
poolMu sync.Mutex
pool = map[string]*pooledConn{}
dialing = map[string]*dialCall{}
)
func poolKey(spec *openSpec, signer *platformSigner) string {
h := sha256.New()
fmt.Fprintf(h, "%s\x00%d\x00%s\x00%s\x00", spec.Host, spec.Port, spec.User, spec.Password)
for _, key := range spec.HostKeys {
fmt.Fprintf(h, "%s\x00", key)
}
if signer != nil {
h.Write(signer.pub.Marshal())
}
fmt.Fprintf(h, "\x00%d", spec.KeepaliveIntervalMs)
return hex.EncodeToString(h.Sum(nil))
}
// acquire returns a live pooled connection for spec, dialing one if needed
// (concurrent callers for the same key share a single dial). The caller must
// release() it.
func acquire(ctx context.Context, spec *openSpec, signer Signer) (*pooledConn, error) {
var ps *platformSigner
if signer != nil {
var err error
if ps, err = newPlatformSigner(signer); err != nil {
return nil, &failure{Kind: "config", Message: "client key unusable: " + err.Error()}
}
}
key := poolKey(spec, ps)
for {
poolMu.Lock()
if conn := pool[key]; conn != nil && !conn.dead {
conn.refs++
if conn.linger != nil {
conn.linger.Stop()
conn.linger = nil
}
poolMu.Unlock()
return conn, nil
}
if call := dialing[key]; call != nil {
poolMu.Unlock()
select {
case <-call.done:
case <-ctx.Done():
return nil, ctx.Err()
}
if call.err != nil {
return nil, call.err
}
continue
}
call := &dialCall{done: make(chan struct{})}
dialing[key] = call
poolMu.Unlock()
conn, err := dial(spec, ps, key)
poolMu.Lock()
delete(dialing, key)
if err == nil {
pool[key] = conn
}
call.err = err
close(call.done)
poolMu.Unlock()
if err != nil {
return nil, err
}
// Loop around to take a reference like any other caller.
}
}
func (conn *pooledConn) release() {
poolMu.Lock()
defer poolMu.Unlock()
conn.refs--
if conn.refs > 0 || conn.dead {
return
}
conn.linger = time.AfterFunc(idleLinger, func() {
poolMu.Lock()
idle := conn.refs == 0 && !conn.dead
if idle {
conn.dead = true
if pool[conn.key] == conn {
delete(pool, conn.key)
}
}
poolMu.Unlock()
if idle {
conn.client.Close()
}
})
}
// markDead removes a connection from the pool once its transport has ended,
// so the next acquire dials afresh.
func (conn *pooledConn) markDead() {
poolMu.Lock()
defer poolMu.Unlock()
conn.dead = true
if conn.linger != nil {
conn.linger.Stop()
conn.linger = nil
}
if pool[conn.key] == conn {
delete(pool, conn.key)
}
}
// hostKeyChecker pins the host key: only keys listed in the spec are
// accepted, and whatever the host presented is kept for the failure report.
type hostKeyChecker struct {
known [][]byte
presented ssh.PublicKey
rejected bool
}
func newHostKeyChecker(encoded []string) (*hostKeyChecker, error) {
checker := &hostKeyChecker{}
for _, entry := range encoded {
wire, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entry))
if err != nil {
return nil, fmt.Errorf("bad pinned host key: %v", err)
}
if _, err := ssh.ParsePublicKey(wire); err != nil {
return nil, fmt.Errorf("bad pinned host key: %v", err)
}
checker.known = append(checker.known, wire)
}
return checker, nil
}
func (h *hostKeyChecker) check(_ string, _ net.Addr, key ssh.PublicKey) error {
h.presented = key
wire := key.Marshal()
for _, known := range h.known {
if bytes.Equal(known, wire) {
return nil
}
}
h.rejected = true
return errors.New("host key not trusted")
}
// algorithms lists host key algorithms with the pinned keys' types first, so
// a host with several host keys presents the one we pinned rather than
// whichever the default preference order favors.
func (h *hostKeyChecker) algorithms() []string {
var preferred []string
seen := map[string]bool{}
add := func(algorithm string) {
if !seen[algorithm] {
seen[algorithm] = true
preferred = append(preferred, algorithm)
}
}
for _, wire := range h.known {
key, err := ssh.ParsePublicKey(wire)
if err != nil {
continue
}
if key.Type() == ssh.KeyAlgoRSA {
add(ssh.KeyAlgoRSASHA512)
add(ssh.KeyAlgoRSASHA256)
continue
}
add(key.Type())
}
if len(preferred) == 0 {
return nil // the library default
}
for _, algorithm := range ssh.SupportedAlgorithms().HostKeys {
add(algorithm)
}
return preferred
}
func (h *hostKeyChecker) failure() *failure {
if h.presented == nil {
return nil
}
info := &hostKeyInfo{
Type: h.presented.Type(),
Fingerprint: fingerprint(h.presented),
Key: base64.StdEncoding.EncodeToString(h.presented.Marshal()),
}
if len(h.known) == 0 {
return &failure{Kind: "hostkey-unknown", Message: "Unknown host key " + info.Fingerprint, HostKey: info}
}
return &failure{Kind: "hostkey-mismatch", Message: "Host key changed: now " + info.Fingerprint, HostKey: info}
}
// errNoPassword aborts authentication when the host would accept a password
// but we don't have one; the "auth" failure then asks the app to prompt.
var errNoPassword = errors.New("password required")
type authState struct {
mu sync.Mutex
passwordAllowed bool
passwordTried bool
keyTried bool
}
func (a *authState) set(update func(*authState)) {
a.mu.Lock()
update(a)
a.mu.Unlock()
}
func authMethods(spec *openSpec, signer *platformSigner, state *authState) []ssh.AuthMethod {
var methods []ssh.AuthMethod
if signer != nil {
methods = append(methods, ssh.PublicKeysCallback(func() ([]ssh.Signer, error) {
state.set(func(a *authState) { a.keyTried = true })
return []ssh.Signer{signer}, nil
}))
}
password := spec.Password
methods = append(methods,
ssh.PasswordCallback(func() (string, error) {
state.set(func(a *authState) { a.passwordAllowed = true })
if password == "" {
return "", errNoPassword
}
state.set(func(a *authState) { a.passwordTried = true })
return password, nil
}),
// Many hosts (PAM-backed sshd, e.g. macOS) take passwords through
// keyboard-interactive. Answer hidden prompts with the password and
// visible ones with nothing.
ssh.KeyboardInteractive(func(_, _ string, questions []string, echos []bool) ([]string, error) {
if len(questions) == 0 {
return nil, nil
}
state.set(func(a *authState) { a.passwordAllowed = true })
if password == "" {
return nil, errNoPassword
}
state.set(func(a *authState) { a.passwordTried = true })
answers := make([]string, len(questions))
for i := range questions {
if !echos[i] {
answers[i] = password
}
}
return answers, nil
}),
)
return methods
}
func dial(spec *openSpec, signer *platformSigner, key string) (*pooledConn, error) {
timeout := defaultConnectTimeout
if spec.ConnectTimeoutMs > 0 {
timeout = time.Duration(spec.ConnectTimeoutMs) * time.Millisecond
}
checker, err := newHostKeyChecker(spec.HostKeys)
if err != nil {
return nil, &failure{Kind: "config", Message: err.Error()}
}
addr := net.JoinHostPort(spec.Host, strconv.Itoa(spec.Port))
dialer := net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second}
tcp, err := dialer.Dial("tcp", addr)
if err != nil {
return nil, &failure{Kind: "network", Message: describeNetError(err)}
}
// Bound the whole handshake, not just the TCP connect.
tcp.SetDeadline(time.Now().Add(timeout))
state := &authState{}
config := &ssh.ClientConfig{
User: spec.User,
Auth: authMethods(spec, signer, state),
HostKeyCallback: checker.check,
HostKeyAlgorithms: checker.algorithms(),
ClientVersion: "SSH-2.0-Faceclaw",
Timeout: timeout,
}
sshConn, chans, reqs, err := ssh.NewClientConn(tcp, addr, config)
if err != nil {
tcp.Close()
if checker.rejected {
return nil, checker.failure()
}
state.mu.Lock()
defer state.mu.Unlock()
if errors.Is(err, errNoPassword) || strings.Contains(err.Error(), "unable to authenticate") {
message := "The host refused this device's key."
switch {
case state.passwordTried:
message = "The host refused the password."
case state.passwordAllowed:
message = "The host wants a password."
case signer == nil:
message = "The host accepts neither passwords nor keys we have."
}
return nil, &failure{
Kind: "auth",
Message: message,
PasswordAllowed: state.passwordAllowed,
PasswordTried: state.passwordTried,
KeyTried: state.keyTried,
}
}
return nil, &failure{Kind: "network", Message: "SSH handshake failed: " + describeNetError(err)}
}
tcp.SetDeadline(time.Time{})
client := ssh.NewClient(sshConn, chans, reqs)
conn := &pooledConn{key: key, client: client}
log.Printf("faceclawssh: connected to %s@%s", spec.User, addr)
go func() {
err := client.Wait()
log.Printf("faceclawssh: connection to %s ended: %v", addr, err)
conn.markDead()
}()
interval := defaultKeepaliveInterval
if spec.KeepaliveIntervalMs > 0 {
interval = time.Duration(spec.KeepaliveIntervalMs) * time.Millisecond
}
go keepalive(conn, interval)
return conn, nil
}
// keepalive probes the host every interval and closes the connection if a
// probe goes unanswered for a whole interval, so a dead peer (phone switched
// networks, laptop asleep) fails the channels promptly instead of hanging.
func keepalive(conn *pooledConn, interval time.Duration) {
defer func() {
if r := recover(); r != nil {
log.Printf("faceclawssh: keepalive panic: %v", r)
conn.client.Close()
}
}()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
poolMu.Lock()
dead := conn.dead
poolMu.Unlock()
if dead {
return
}
reply := make(chan error, 1)
go func() {
_, _, err := conn.client.SendRequest("keepalive@openssh.com", true, nil)
reply <- err
}()
select {
case err := <-reply:
if err != nil {
conn.client.Close()
return
}
case <-time.After(interval):
log.Printf("faceclawssh: keepalive timed out; closing")
conn.client.Close()
return
}
}
}
func describeNetError(err error) string {
message := err.Error()
// "dial tcp 1.2.3.4:22: connect: connection refused" → keep the tail.
if index := strings.LastIndex(message, ": "); index >= 0 && strings.HasPrefix(message, "dial ") {
return message[index+2:]
}
return message
}
+129
View File
@@ -0,0 +1,129 @@
// Builds the Go SSH transport (native/ssh) with gomobile and stages it into
// the local @faceclaw/kotlin NativeScript plugin next to the shared Kotlin
// artifacts: platforms/android/faceclaw-ssh.aar and
// platforms/ios/Faceclawssh.xcframework. Run from the before-prepare hook;
// a content stamp skips the (~10 s) gomobile build when nothing changed.
const { spawn, spawnSync } = require('node:child_process');
const crypto = require('node:crypto');
const { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } = require('node:fs');
const path = require('node:path');
const root = path.resolve(__dirname, '..');
const source = path.join(root, 'native/ssh');
const buildDir = path.join(source, 'build');
const plugin = path.join(root, 'native/kotlin/plugin/platforms');
// Bump to force a rebuild when the gomobile invocation below changes.
const BUILD_RECIPE = 2;
function sourceHash(platform) {
const hash = crypto.createHash('sha256');
hash.update(`${BUILD_RECIPE}\n${platform}\n`);
const files = readdirSync(source)
.filter(name => (name.endsWith('.go') && !name.endsWith('_test.go')) || name === 'go.mod' || name === 'go.sum')
.sort();
for (const name of files) {
hash.update(`${name}\n`);
hash.update(readFileSync(path.join(source, name)));
}
return hash.digest('hex');
}
function findGo() {
const probe = spawnSync('go', ['version'], { encoding: 'utf8' });
if (probe.status !== 0) {
throw new Error('Building the SSH transport needs Go 1.26 or newer on PATH (e.g. "brew install go").');
}
}
function newestNdk() {
if (process.env.ANDROID_NDK_HOME && existsSync(process.env.ANDROID_NDK_HOME)) return process.env.ANDROID_NDK_HOME;
const sdk = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT;
if (!sdk) throw new Error('ANDROID_HOME must be set to build the SSH transport for Android.');
const ndkRoot = path.join(sdk, 'ndk');
const versions = existsSync(ndkRoot) ? readdirSync(ndkRoot).sort((a, b) => b.localeCompare(a, undefined, { numeric: true })) : [];
if (!versions.length) throw new Error(`No Android NDK under ${ndkRoot}; install one with the SDK manager.`);
return path.join(ndkRoot, versions[0]);
}
// gomobile's ObjC headers say "@import Foundation;", which fails wherever
// Clang modules are off (the NativeScript app target's compile, and its
// metadata generator). A plain #import means the same thing everywhere.
function patchGomobileHeaders(xcframework) {
const walk = (dir) => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const file = path.join(dir, entry.name);
if (entry.isDirectory()) walk(file);
else if (entry.name.endsWith('.h')) {
const text = readFileSync(file, 'utf8');
const patched = text.replace(/^@import Foundation;$/gm, '#import <Foundation/Foundation.h>');
if (patched !== text) writeFileSync(file, patched);
}
}
};
walk(xcframework);
}
function run(command, args, env) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { cwd: source, stdio: 'inherit', env });
child.on('error', reject);
child.on('exit', (code, signal) => {
if (code === 0) resolve();
else reject(new Error(`${command} ${args[0]} failed (${signal || code})`));
});
});
}
async function buildGoSsh(platform) {
if (!['android', 'ios'].includes(platform)) throw new Error(`Unsupported platform: ${platform}`);
const stampFile = path.join(buildDir, `.stamp-${platform}`);
const output = platform === 'android'
? path.join(buildDir, 'faceclaw-ssh.aar')
: path.join(buildDir, 'Faceclawssh.xcframework');
const staged = platform === 'android'
? path.join(plugin, 'android/faceclaw-ssh.aar')
: path.join(plugin, 'ios/Faceclawssh.xcframework');
const hash = sourceHash(platform);
const fresh = existsSync(output) && existsSync(stampFile) && readFileSync(stampFile, 'utf8') === hash;
if (!fresh) {
findGo();
console.log(`[go-ssh] Building ${platform}`);
mkdirSync(path.join(buildDir, 'bin'), { recursive: true });
const env = { ...process.env, PATH: `${path.join(buildDir, 'bin')}${path.delimiter}${process.env.PATH}` };
// gomobile bind finds gobind on PATH; build both from the versions pinned
// in go.mod's tool block.
await run('go', ['build', '-o', path.join(buildDir, 'bin') + path.sep, 'golang.org/x/mobile/cmd/gomobile', 'golang.org/x/mobile/cmd/gobind'], env);
const common = ['-ldflags=-s -w', '-trimpath'];
rmSync(output, { recursive: true, force: true });
if (platform === 'android') {
env.ANDROID_NDK_HOME = newestNdk();
await run('gomobile', ['bind', '-target=android/arm64', '-androidapi', '24', '-javapkg', 'com.faceclaw.ssh', ...common, '-o', output, '.'], env);
} else {
await run('gomobile', ['bind', '-target=ios,iossimulator', '-iosversion', '15.0', ...common, '-o', output, '.'], env);
patchGomobileHeaders(output);
}
writeFileSync(stampFile, hash);
}
// Stage only when the staged copy is missing or stale; preserve mtimes on
// no-op builds (NativeScript uses them to detect changes).
const stagedStamp = path.join(buildDir, `.staged-${platform}`);
if (existsSync(staged) && existsSync(stagedStamp) && readFileSync(stagedStamp, 'utf8') === hash) return;
mkdirSync(path.dirname(staged), { recursive: true });
rmSync(staged, { recursive: true, force: true });
cpSync(output, staged, { recursive: true });
writeFileSync(stagedStamp, hash);
if (platform === 'android') {
// As in kotlin-build.cjs: NativeScript's metadata task tracks jars by
// path, so force it to regenerate for the new classes.
rmSync(path.join(root, 'platforms/android/app/src/main/assets/metadata'), { recursive: true, force: true });
}
}
module.exports = { buildGoSsh };
if (require.main === module) {
buildGoSsh(process.argv[2]).catch(error => {
console.error(error);
process.exitCode = 1;
});
}
@@ -1,8 +1,11 @@
const { buildKotlin, checkAndroidRuntime } = require('../../scripts/kotlin-build.cjs');
const { buildGoSsh } = require('../../scripts/go-ssh-build.cjs');
module.exports = function (hookArgs) {
// NativeScript parses hooks with an older JavaScript parser; avoid optional chaining.
const { platform, release } = hookArgs.prepareData;
if (platform === 'android') checkAndroidRuntime();
return buildKotlin(platform, release ? 'release' : 'debug');
return buildKotlin(platform, release ? 'release' : 'debug').then(function () {
return buildGoSsh(platform);
});
};
+47
View File
@@ -0,0 +1,47 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
// Local-time day arithmetic: pin the zone so the expectations hold on any machine.
process.env.TZ = 'Europe/Brussels';
function load(file) {
const sandbox = { exports: {}, require: id => { throw new Error(`Unstubbed import: ${id}`); } };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, sandbox);
return sandbox.exports;
}
const { listingDayMs, spansDays, spanLabel } = load('app/apps/calendar/event-days.ts');
const local = (y, m, d, h = 0, min = 0) => new Date(y, m - 1, d, h, min).getTime();
// Mon Nov 16 – Wed Nov 18, all day, as the provider stores it (end = midnight after the last day).
const threeDays = { startMs: local(2026, 11, 16), endMs: local(2026, 11, 19), allDay: true };
test('an all-day event still going is listed under today, not its first day', () => {
assert.equal(listingDayMs(threeDays, local(2026, 11, 18, 0, 24)), local(2026, 11, 18));
assert.equal(listingDayMs(threeDays, local(2026, 11, 17, 9)), local(2026, 11, 17));
});
test('events that have not started are listed under their start day', () => {
assert.equal(listingDayMs(threeDays, local(2026, 11, 14, 12)), local(2026, 11, 16));
const meeting = { startMs: local(2026, 11, 19, 9), endMs: local(2026, 11, 19, 12), allDay: false };
assert.equal(listingDayMs(meeting, local(2026, 11, 18, 0, 24)), local(2026, 11, 19));
});
test('a timed event running past midnight is listed under today the next morning', () => {
const lateShift = { startMs: local(2026, 11, 17, 22), endMs: local(2026, 11, 18, 2), allDay: false };
assert.equal(listingDayMs(lateShift, local(2026, 11, 18, 0, 30)), local(2026, 11, 18));
assert.equal(spansDays(lateShift), true);
});
test('only events covering more than one day get a span, and it reads naturally', () => {
assert.equal(spansDays(threeDays), true);
assert.equal(spanLabel(threeDays), 'Mon 16 – Wed 18 Nov');
assert.equal(spansDays({ startMs: local(2026, 11, 16), endMs: local(2026, 11, 17), allDay: true }), false);
assert.equal(spansDays({ startMs: local(2026, 11, 19, 9), endMs: local(2026, 11, 19, 12), allDay: false }), false);
assert.equal(spanLabel({ startMs: local(2026, 11, 30), endMs: local(2026, 12, 2), allDay: true }), 'Mon 30 Nov – Tue 1 Dec');
});
+45
View File
@@ -0,0 +1,45 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
// Local-time formatting: pin the zone so the expectations hold on any machine.
process.env.TZ = 'Europe/Brussels';
function load(file) {
const sandbox = { exports: {}, require: id => { throw new Error(`Unstubbed import: ${id}`); } };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(path.join(__dirname, '..', file), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, sandbox);
return sandbox.exports;
}
const { formatEvent, formatEventSpan } = load('app/assistant/date-format.ts');
const local = (y, m, d, h = 0, min = 0) => new Date(y, m - 1, d, h, min).getTime();
test('a multi-day all-day event names its last day (all-day ends are exclusive)', () => {
// Mon Nov 16 – Wed Nov 18, as the calendar provider stores it: end = midnight after the last day.
const span = formatEventSpan({ startMs: local(2026, 11, 16), endMs: local(2026, 11, 19), allDay: true });
assert.equal(span, 'Mon Nov 16 – Wed Nov 18 (all day)');
});
test('a one-day all-day event stays a single date', () => {
assert.equal(formatEventSpan({ startMs: local(2026, 11, 16), endMs: local(2026, 11, 17), allDay: true }), 'Mon Nov 16 (all day)');
});
test('a timed event shows its end time, and the end date when it crosses midnight', () => {
assert.equal(formatEventSpan({ startMs: local(2026, 11, 19, 9), endMs: local(2026, 11, 19, 12), allDay: false }), 'Thu Nov 19, 9:00 AM – 12:00 PM');
assert.equal(formatEventSpan({ startMs: local(2026, 11, 19, 22), endMs: local(2026, 11, 20, 2), allDay: false }), 'Thu Nov 19, 10:00 PM – Fri Nov 20, 2:00 AM');
});
test('a timed event without a usable end keeps the old start-only form', () => {
assert.equal(formatEventSpan({ startMs: local(2026, 11, 19, 9), endMs: local(2026, 11, 19, 9), allDay: false }), 'Thu Nov 19, 9:00 AM');
});
test('formatEvent keeps the title and location around the span', () => {
const line = formatEvent({ title: 'Office', startMs: local(2026, 11, 16), endMs: local(2026, 11, 19), allDay: true, location: 'HQ' });
assert.equal(line, '- Office — Mon Nov 16 – Wed Nov 18 (all day) @ HQ');
assert.equal(formatEvent({ title: '', startMs: local(2026, 11, 16), endMs: local(2026, 11, 17), allDay: true, location: '' }), '- (untitled) — Mon Nov 16 (all day)');
});
+24
View File
@@ -275,3 +275,27 @@ test("names that only look like a G1 are not admitted", () => {
assert.equal(classifyAdvertisement(g1Raw(name, "")), null, name);
}
});
test("an iOS arm rebuilt from a saved pairing joins its advertising other arm", () => {
const { g2ManufacturerData } = require("../.test-build/app/g2/even-advertisement.js");
const { identifyIosPeripheral } = require("../.test-build/app/g2/ios-peripheral-identity.js");
const { DiscoveryAggregator } = require("../.test-build/app/g2/pairing-candidates.js");
const mfg = g2ManufacturerData("S211GBBC180304", "E0:12:14:B6:EC:E1");
assert.equal(extractG2Serial(hexToBytes(mfg)), "S211GBBC180304");
assert.equal(extractG2Mac(hexToBytes(mfg)), "E0:12:14:B6:EC:E1");
const right = identifyIosPeripheral({ identifier: "14b99254-0798-d1a8-3eec-b141bdabfae8", name: "Even G2_32_R_B6ECE1",
manufacturerData: mfg, rssi: 0, connectable: true });
assert.equal(right.address, "E0:12:14:B6:EC:E1");
assert.equal(right.role, "right");
assert.equal(right.note, null);
const aggregator = new DiscoveryAggregator();
aggregator.ingest(raw({}));
aggregator.ingest({ ...right, rssi: null, source: "paired" });
const [pair] = aggregator.pairs();
assert.equal(pair.completeness, "complete");
assert.equal(pair.rssi, -55);
assert.equal(g2ManufacturerData("S211GBBC180304XX", "E0:12:14:B6:EC:E1"), null);
assert.equal(g2ManufacturerData("", "E0:12:14:B6:EC:E1"), null);
assert.equal(g2ManufacturerData("S211GBBC180304", "not a mac"), null);
});
+2 -1
View File
@@ -163,7 +163,7 @@ function screenFixture() {
'util/numeric-util': { clamp: (n, min, max) => Math.max(min, Math.min(max, n)) },
};
const modules = depth => Object.fromEntries(Object.entries(common).map(([key, value]) => [depth + key, value]));
const calendar = load('app/apps/calendar/calendar.ts', modules('../../'));
const calendar = load('app/apps/calendar/calendar.ts', { ...modules('../../'), './event-days': load('app/apps/calendar/event-days.ts') });
const widget = load('app/apps/glanceboard/widgets/calendar-widget.ts', {
...modules('../../../'), '../../calendar/calendar': calendar,
'../glance-font': { glanceFont: { small: () => font, medium: () => font } },
@@ -243,6 +243,7 @@ test('iOS assistant calendar tool awaits events, reports denied access and failu
'../native/media-controller': { mediaControllerBridge: { start: async () => {} } },
'../native/spotify': { spotifyService: () => null },
'../native/notification-icons': {}, '../ui/shell/shell': {}, './tool-registry': {},
'./date-format': load('app/assistant/date-format.ts'),
}, { global: { isIOS: true } });
registerSystemTools({ registerSystemTool: (definition, handler) => registered.set(definition.name, handler) });
assert.deepEqual([...registered.keys()], ['glasses.get_state', 'glasses.show_alert', 'calendar.list_events',
+3 -3
View File
@@ -359,9 +359,9 @@ test('a paired keyboard: the bridge follows the G2 link, and its keys\' gestures
// Connected is not enough: the firmware has to be one with the bridge.
f.bridge.emitState('connected');
assert.ok(!f.keyboard.calls.includes('ready'));
f.bridge.listeners.firmware({ leftVersion: '2.3.0.24', rightVersion: '2.3.0.24', extension: 'Faceclaw/38' });
assert.ok(!f.keyboard.calls.includes('ready'));
f.bridge.listeners.firmware({ leftVersion: '2.3.0.24', rightVersion: '2.3.0.24', extension: 'Faceclaw/39' });
assert.ok(!f.keyboard.calls.includes('ready'));
f.bridge.listeners.firmware({ leftVersion: '2.3.0.24', rightVersion: '2.3.0.24', extension: 'Faceclaw/40' });
assert.equal(f.keyboard.calls.at(-1), 'ready');
assert.equal(f.keyboard.host.ready(), true);
// The link dropping on its own ends it without a word to the firmware; coming back restores it.
@@ -398,7 +398,7 @@ test('a keyboard needs a G2: other glasses never bring the bridge up', async ()
const f = fixture();
await f.connect();
f.bridge.emitState('connected');
f.bridge.listeners.firmware({ leftVersion: 'g1v0 0.5.66', rightVersion: 'g1v0 0.5.66', extension: 'Faceclaw/39' });
f.bridge.listeners.firmware({ leftVersion: 'g1v0 0.5.66', rightVersion: 'g1v0 0.5.66', extension: 'Faceclaw/40' });
assert.ok(!f.keyboard.calls.includes('ready'), f.keyboard.calls.join());
} finally { glassesType = 'g2'; }
});
+1
View File
@@ -511,6 +511,7 @@ test('the assistant offers Spotify search-and-play once signed in and refreshes
snapshot: () => ({ accessEnabled: true, playbackState: 'playing', title: 'Song', artist: 'Band', appName: 'Spotify' }) } },
'../native/spotify': { spotifyService: () => spotify },
'../native/notification-icons': {}, '../ui/shell/shell': {}, './tool-registry': {},
'./date-format': load('app/assistant/date-format.ts'),
}, { global: { isIOS: true } });
registerSystemTools({
registerSystemTool: (definition, handler) => systemTools.set(definition.name, handler),
+57
View File
@@ -243,3 +243,60 @@ test('router: capturing a key for a new keybinding takes the chord and nothing e
r.handleKey(key('x', { code: 'KeyX' }))
assert.deepEqual(captured.at(-1), chord('KeyX'))
})
test('a mouse by default: left taps, right double taps, middle holds, the wheel is the ring\'s scroll', () => {
const action = (k, overrides) => defaultKeyAction(key(k, overrides))
// Nothing types a mouse button, so these hold in a terminal session too.
assert.deepEqual(action('MouseButton1'), { action: 'click', overridesTyping: true })
assert.deepEqual(action('MouseButton2'), { action: 'double-click', overridesTyping: true })
assert.deepEqual(action('MouseButton3'), { action: 'long-press', overridesTyping: true })
assert.deepEqual(action('WheelUp'), { action: 'scroll-up', overridesTyping: true })
assert.deepEqual(action('WheelDown'), { action: 'scroll-down', overridesTyping: true })
// Whatever is held on the keyboard.
assert.deepEqual(action('MouseButton1', { modifiers: { ctrl: true, shift: true } }), { action: 'click', overridesTyping: true })
// Extra buttons and the horizontal wheel mean nothing until bound.
for (const k of ['MouseButton4', 'MouseButton5', 'WheelLeft', 'WheelRight']) assert.equal(action(k), null)
const said = code => describeChord(chord(code))
assert.equal(said('MouseButton1'), 'Left button'); assert.equal(said('MouseButton2'), 'Right button')
assert.equal(said('MouseButton3'), 'Middle button'); assert.equal(said('MouseButton4'), 'Mouse button 4')
assert.equal(said('WheelUp'), 'Wheel up'); assert.equal(describeChord(chord('WheelDown', { ctrl: true })), 'Ctrl+Wheel down')
assert.deepEqual(parseChordId('Shift+MouseButton2'), chord('MouseButton2', { shift: true }))
})
test('router: the mouse works where keys are being typed, its wheel is paced, and its buttons can be rebound', async () => {
const { r, state } = router({ bindings: [{ chord: chord('MouseButton4'), action: 'short-then-long-press' }, { chord: chord('MouseButton2'), action: 'none' }] })
const wheel = k => { r.handleKey(key(k, { burst: true })); r.handleKey(up(k, { burst: true })) }
state.windowTakesKeys = true
r.handleKey(key('MouseButton1')); r.handleKey(up('MouseButton1'))
r.handleKey(key('MouseButton3')); r.handleKey(up('MouseButton3'))
await flush(); state.now += 500
wheel('WheelDown')
// The wheel is the ring's scroll, and what follows it is the ring's too.
await flush(); state.now += 500
r.handleKey(key('MouseButton1')); r.handleKey(up('MouseButton1'))
assert.deepEqual(state.gestures, ['click/watch', 'long-press/watch', 'scroll-down/ring', 'click/ring'])
assert.deepEqual(state.offered, [], 'never typed')
// A custom keybinding for an extra button; "Nothing" on the right button leaves it inert.
state.gestures.length = 0
r.handleKey(key('MouseButton4')); r.handleKey(up('MouseButton4')); r.handleKey(key('MouseButton2')); r.handleKey(up('MouseButton2'))
assert.deepEqual(state.gestures, ['short-then-long-press/ring'])
// A two-finger scroll reports far faster than the display can follow: every 100 ms at most.
state.gestures.length = 0; state.offered.length = 0
for (let i = 0; i < 40; i++) { await flush(); state.now += 25; wheel('WheelUp') }
assert.equal(state.gestures.length, 10); assert.ok(state.gestures.every(g => g === 'scroll-up/ring'))
// On a dark display a click wakes it and does nothing else.
state.screenOn = false; state.gestures.length = 0
r.handleKey(key('MouseButton1')); r.handleKey(up('MouseButton1'))
assert.equal(state.wakes, 1); assert.deepEqual(state.gestures, [])
})
test('router: a mouse button or a turn of the wheel can be captured for a keybinding', () => {
const { r, state } = router()
const captured = []
r.captureNextKey(c => captured.push(c))
r.handleKey(key('MouseButton2')); r.handleKey(up('MouseButton2'))
r.captureNextKey(c => captured.push(c))
r.handleKey(key('WheelUp', { burst: true, modifiers: { shift: true } })); r.handleKey(up('WheelUp', { burst: true }))
assert.deepEqual(captured, [chord('MouseButton2'), chord('WheelUp', { shift: true })])
assert.deepEqual(state.gestures, [])
})
+82 -8
View File
@@ -1,6 +1,6 @@
const test = require('node:test')
const assert = require('node:assert/strict')
const { HidKeys, parseReportMap, reportKeys } = require('../.test-build/app/g2/keyboard/hid.js')
const { HidKeys, parseReportMap, reportHasKeys, reportHasPointer, reportKeys, reportPointer } = require('../.test-build/app/g2/keyboard/hid.js')
const {
KeyboardRecords, keyboardControl, le16, u16, parseKeyboardAdvert, mergeKeyboardAdverts,
parseKeyboardAddress, formatKeyboardAddress,
@@ -69,6 +69,41 @@ test('descriptor resource bounds and malformed items', () => {
}
})
// A wheel mouse as most are described: three buttons, 8-bit X/Y and wheel.
const mouseMap = Uint8Array.from([0x05,1,0x09,2,0xa1,1,0x09,1,0xa1,0,0x05,9,0x19,1,0x29,3,0x15,0,0x25,1,0x75,1,0x95,3,0x81,2,
0x75,5,0x95,1,0x81,1,0x05,1,0x09,0x30,0x09,0x31,0x09,0x38,0x15,0x81,0x25,0x7f,0x75,8,0x95,3,0x81,6,0xc0,0xc0])
test('a mouse report: buttons, movement and wheel; not keys', () => {
const r = parseReportMap(mouseMap).get(0)
assert.equal(reportHasPointer(r), true); assert.equal(reportHasKeys(r), false)
assert.deepEqual(reportPointer(r, Uint8Array.of(0, 0, 0, 0)), { buttons: 0, dx: 0, dy: 0, wheel: 0, pan: 0 })
assert.deepEqual(reportPointer(r, Uint8Array.of(0b101, 10, 0xf6, 1)), { buttons: 5, dx: 10, dy: -10, wheel: 1, pan: 0 })
assert.deepEqual(reportPointer(r, Uint8Array.of(0b010, 0, 0, 0xff)), { buttons: 2, dx: 0, dy: 0, wheel: -1, pan: 0 })
// Some devices leave trailing bytes off; what is missing is zero. Extra bytes are ignored.
assert.deepEqual(reportPointer(r, Uint8Array.of(1, 3)), { buttons: 1, dx: 3, dy: 0, wheel: 0, pan: 0 })
assert.deepEqual(reportPointer(r, Uint8Array.of(0, 1, 1, 1, 9, 9)), { buttons: 0, dx: 1, dy: 1, wheel: 1, pan: 0 })
// -128 is outside the declared range: no reading, rather than a jump.
assert.deepEqual(reportPointer(r, Uint8Array.of(0, 0x80, 0, 0)), { buttons: 0, dx: 0, dy: 0, wheel: 0, pan: 0 })
assert.deepEqual(reportKeys(r, Uint8Array.of(7, 1, 1, 1)), [])
// A keyboard's report is not a pointer's.
assert.equal(reportHasPointer(parseReportMap(boot).get(0)), false)
})
test('a touchpad with 12-bit axes and a horizontal wheel; an absolute digitizer is not a mouse', () => {
// Five buttons, 3 bits of padding, X/Y packed 12 bits each, wheel, then AC Pan from the consumer page.
const map = Uint8Array.from([0x05,1,0x09,2,0xa1,1,0x05,9,0x19,1,0x29,5,0x15,0,0x25,1,0x75,1,0x95,5,0x81,2,
0x75,3,0x95,1,0x81,1,0x05,1,0x09,0x30,0x09,0x31,0x16,0x01,0xf8,0x26,0xff,0x07,0x75,12,0x95,2,0x81,6,
0x09,0x38,0x15,0x81,0x25,0x7f,0x75,8,0x95,1,0x81,6,0x05,0x0c,0x0a,0x38,0x02,0x81,6,0xc0])
const r = parseReportMap(map).get(0)
assert.equal(reportHasPointer(r), true)
// X = 0x123 (291), Y = 0xfff (-1): packed little endian, 12 bits each.
assert.deepEqual(reportPointer(r, Uint8Array.of(0b10000, 0x23, 0xf1, 0xff, 2, 0xfe)), { buttons: 16, dx: 291, dy: -1, wheel: 2, pan: -2 })
// The pan field is on the consumer page, but it is a movement, not a key going down.
assert.equal(reportHasKeys(r), false); assert.deepEqual(reportKeys(r, Uint8Array.of(0, 0, 0, 0, 0, 5)), [])
// Absolute X/Y (a touchscreen, a pen) is something else, and is left alone.
const absolute = parseReportMap(Uint8Array.of(0x05,1,0x09,0x30,0x09,0x31,0x15,0,0x26,0xff,0x0f,0x75,16,0x95,2,0x81,2)).get(0)
assert.equal(reportHasPointer(absolute), false)
assert.deepEqual(reportPointer(absolute, Uint8Array.of(1, 2, 3, 4)), { buttons: 0, dx: 0, dy: 0, wheel: 0, pan: 0 })
})
test('control records, UUIDs and addresses', () => {
assert.deepEqual([...keyboardControl(4,0x1234,0x5678,[1,2,3,4,5,6,7])], [75,66,1,4,0x34,0x12,0x78,0x56,1,2,3,4,5,6,7])
assert.throws(() => keyboardControl(13,1,1))
@@ -238,23 +273,39 @@ function makeCombo(g) {
g.attrs.clear(); for (const [handle, attr] of sorted) g.attrs.set(handle, attr)
}
for (const declarations of ['short', 'refused']) {
test(`client: a keyboard with a trackpad whose stack answers declaration reads ${declarations} still types`, async () => {
const events = [], logs = []
test(`client: a keyboard with a trackpad whose stack answers declaration reads ${declarations} types and points`, async () => {
const events = [], pointer = [], logs = []
let client
const g = fakeGlasses(payload => client.accept(payload))
makeCombo(g); g.declarations = declarations
client = new KeyboardClient(g.send, { keys: e => events.push(...e), log: line => logs.push(line) })
client = new KeyboardClient(g.send, { keys: e => events.push(...e), pointer: p => pointer.push(p), log: line => logs.push(line) })
await client.enable(); await client.connect(1, new Uint8Array(6)); const config = await client.configure()
// Keys and media keys are subscribed; the pointer and the battery are not.
assert.deepEqual(config.watched, [27,31]); assert.deepEqual(g.watches, [27,31,3]); assert.deepEqual(g.writes, [25,4,28,32])
// Keys, media keys and the trackpad are subscribed; the battery level is not.
assert.deepEqual(config.watched, [27,31,35]); assert.equal(config.pointer, true)
assert.deepEqual(g.watches, [27,31,35,3]); assert.deepEqual(g.writes, [25,4,28,32,36])
assert.deepEqual(config.reports.map(r => [r.handle, r.id]), [[27,1],[31,2],[35,4]])
assert.deepEqual(config.reports.map(r => r.properties), declarations === 'short' ? [0x12,0x12,0x12] : [undefined,undefined,undefined])
g.input(27, [0,0,4,0,0,0,0,0])
assert.deepEqual(events.map(e => [e.usage,e.down]), [[4,true]])
// The trackpad: movement and buttons, and never a key.
g.input(35, [0, 5, 0xfd]); g.input(35, [1, 0, 0]); g.input(35, [5, 0x81, 0x7f])
assert.deepEqual(pointer, [
{ buttons: 0, dx: 5, dy: -3, wheel: 0, pan: 0 },
{ buttons: 1, dx: 0, dy: 0, wheel: 0, pan: 0 },
{ buttons: 5, dx: -127, dy: 127, wheel: 0, pan: 0 },
])
assert.equal(events.length, 1)
// A record lost on the way: the held buttons are let go along with the held keys.
g.seq++; g.status()
assert.deepEqual(pointer.at(-1), { buttons: 0, dx: 0, dy: 0, wheel: 0, pan: 0 })
assert.deepEqual([events.at(-1).usage, events.at(-1).down], [4, false])
// With nothing held, another gap has nothing to say.
const count = pointer.length; g.seq++; g.status()
assert.equal(pointer.length, count)
// What was skipped, and why, is in the log; so is the table it came from.
assert.ok(logs.some(line => /^gatt 1=2800 2=2803 /.test(line)), logs.join('\n'))
assert.ok(logs.some(line => /report 42 skipped: no Report Reference/.test(line)), logs.join('\n'))
assert.ok(logs.some(line => /report 35 \(id 4\) carries no keys/.test(line)), logs.join('\n'))
assert.ok(logs.some(line => /report 35 \(id 4\) is a pointer's/.test(line)), logs.join('\n'))
assert.ok(logs.some(line => line.startsWith('report map 22: 0501')))
client.close()
})
@@ -313,7 +364,7 @@ test('client: firmware errors carry their code, and a dead link rejects at once'
})
function bridgeSetup(saved = null) {
const host = { keys: [], gone: 0, changes: 0, logs: [], prompts: [], saved, reconnect: true }
const host = { keys: [], pointer: [], gone: 0, changes: 0, logs: [], prompts: [], saved, reconnect: true }
let bridge
const g = fakeGlasses(payload => bridge.accept(payload))
bridge = new KeyboardBridge({
@@ -321,6 +372,7 @@ function bridgeSetup(saved = null) {
loadSaved: () => host.saved,
storeSaved: value => { host.saved = value },
onKeys: events => host.keys.push(...events),
onPointer: sample => host.pointer.push(sample),
onKeyboardGone: () => { host.gone++ },
onChanged: () => {
host.changes++
@@ -479,6 +531,28 @@ test('bridge: a scan started by hand takes over from an attempt in flight, and n
assert.deepEqual(g.ops, [])
bridge.linkLost()
})
test('bridge: a keyboard\'s touchpad is passed on while it is in use, and the snapshot says it has one', async () => {
const plain = bridgeSetup()
plain.bridge.linkReady(); await plain.bridge.connect(K380)
assert.equal(plain.bridge.snapshot().pointer, false)
plain.bridge.linkLost()
const { bridge, g, host } = bridgeSetup()
makeCombo(g)
bridge.linkReady()
assert.equal(bridge.snapshot().pointer, false)
await bridge.connect(K380)
assert.equal(bridge.snapshot().pointer, true)
assert.ok(host.logs.some(line => /keyboard ready: K380, 3 of 3 input reports subscribed, with a pointer/.test(line)), host.logs.join('\n'))
g.input(35, [2, 1, 1])
assert.deepEqual(host.pointer, [{ buttons: 2, dx: 1, dy: 1, wheel: 0, pan: 0 }])
// The keyboard drops with a button down: the button is let go, as held keys
// are, before the host hears the keyboard is gone; and the snapshot follows.
g.close(); await settle()
assert.deepEqual(host.pointer.at(-1), { buttons: 0, dx: 0, dy: 0, wheel: 0, pan: 0 }); assert.equal(host.pointer.length, 2)
assert.equal(host.gone, 1); assert.equal(bridge.snapshot().pointer, false)
bridge.linkLost()
})
test('bridge: leaving on purpose tells the glasses to let the keyboard go', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] })
const { bridge, g } = bridgeSetup(K380)
+21
View File
@@ -142,3 +142,24 @@ test('terminal: Shift+PageUp and Shift+PageDown page the scrollback instead', ()
assert.equal(page('PageUp', {}), null); assert.equal(page('PageUp', { shift: true, ctrl: true }), null)
assert.equal(page('PageUp', { shift: true }, 'up'), null); assert.equal(page('ArrowUp', { shift: true }), null)
})
test('mouse buttons are keys that neither repeat nor take the repeat from a held key; a wheel detent is a press and release', () => {
const { t, events, advance } = translator()
t.handle([down(A)])
t.handle([{ page: 9, usage: 1, down: true }])
assert.deepEqual([events.at(-1).key, events.at(-1).code, events.at(-1).text], ['MouseButton1', 'MouseButton1', undefined])
// The held key goes on repeating; the held button never does.
advance(500)
assert.ok(events.filter(e => e.repeat).every(e => e.key === 'a')); assert.ok(events.some(e => e.repeat))
t.handle([up(A), { page: 9, usage: 1, down: false }])
assert.deepEqual([events.at(-1).phase, events.at(-1).key], ['up', 'MouseButton1'])
assert.equal(translateUsage(9, 3, false, false).code, 'MouseButton3')
// The wheel: down and up at once, marked as droppable, with the keyboard's modifiers.
events.length = 0
t.handle([down(SHIFT)]); t.pulse('WheelUp')
assert.deepEqual(events.slice(1).map(e => [e.phase, e.key, e.code, e.burst, e.repeat, e.modifiers.shift]),
[['down', 'WheelUp', 'WheelUp', true, false, true], ['up', 'WheelUp', 'WheelUp', true, false, true]])
const count = events.length; advance(2000)
assert.equal(events.length, count)
})
+58
View File
@@ -0,0 +1,58 @@
const test = require('node:test')
const assert = require('node:assert/strict')
const { PointerInput } = require('../.test-build/app/g2/keyboard/pointer.js')
const sample = (buttons, extra = {}) => ({ buttons, dx: 0, dy: 0, wheel: 0, pan: 0, ...extra })
function pointer() {
const out = []
const input = new PointerInput({
buttons: events => out.push(...events.map(e => `${e.down ? 'down' : 'up'}:${e.page}:${e.usage}`)),
wheel: key => out.push(key),
})
return { input, out }
}
test('buttons become key transitions; the wheel a key per report; movement nothing', () => {
const { input, out } = pointer()
input.handle(sample(0, { dx: 40, dy: -3 }))
assert.deepEqual(out, [])
input.handle(sample(0b001)); input.handle(sample(0b001, { dx: 2 })); input.handle(sample(0b110)); input.handle(sample(0))
assert.deepEqual(out, ['down:9:1', 'up:9:1', 'down:9:2', 'down:9:3', 'up:9:2', 'up:9:3'])
out.length = 0
// However many detents a report claims, it is one step; a two-finger scroll sends many.
input.handle(sample(0, { wheel: 1 })); input.handle(sample(0, { wheel: -3 })); input.handle(sample(0, { pan: 2 })); input.handle(sample(0, { pan: -1 }))
assert.deepEqual(out, ['WheelUp', 'WheelDown', 'WheelRight', 'WheelLeft'])
})
test('taking the pointer: samples go to the taker, held buttons are let go first, and its clicks are nobody else\'s', () => {
const { input, out } = pointer()
const taken = []
input.handle(sample(0b001))
const release = input.take(s => taken.push(s))
assert.deepEqual(out, ['down:9:1', 'up:9:1'])
out.length = 0
input.handle(sample(0b001, { dx: 5 })); input.handle(sample(0b011, { wheel: 1 })); input.handle(sample(0b010))
assert.deepEqual(taken, [sample(0b001, { dx: 5 }), sample(0b011, { wheel: 1 }), sample(0b010)])
assert.deepEqual(out, [])
// Given back with the right button still down: its release is not a key-up for anyone.
release()
input.handle(sample(0)); input.handle(sample(0b100)); input.handle(sample(0))
assert.deepEqual(out, ['down:9:3', 'up:9:3'])
// A stale release function can't take the pointer away from a later taker.
const second = []
const releaseSecond = input.take(s => second.push(s))
release()
input.handle(sample(0, { dx: 1 }))
assert.equal(second.length, 1)
releaseSecond()
})
test('the keyboard going away forgets held buttons without reporting releases', () => {
const { input, out } = pointer()
input.handle(sample(0b001))
input.reset()
assert.deepEqual(out, ['down:9:1'])
// The next keyboard starts clean: a press is a press.
input.handle(sample(0b001))
assert.deepEqual(out, ['down:9:1', 'down:9:1'])
})
@@ -347,9 +347,9 @@ class DisplayListTest {
val gray = ByteArray(640 * 480) { 48 }; val app = BmpUtil.pack4bppFromGray8(gray, 640, 480)
fun layer(key: Int, y: Int, h: Int, nibble: Int, depth: Int = 0) =
ShellScene.Layer(key, 14, y, 612, h, 256, ByteArray(306 * h) { (nibble * 17).toByte() }, depth = depth)
// Each 612x214 layer is just under the 64 KiB resource cap; three exceed the arena on their own.
// Each 612x200 layer takes 60 KiB of the 320 KiB arena: five fit and six exceed it on their own.
fun chrome(depth: Int) = layer(1, 444, 36, 7, depth)
val modals = listOf(layer(2, 10, 214, 9), layer(3, 120, 214, 11), layer(4, 230, 214, 13, depth = 4))
val modals = (0..5).map { layer(2 + it, 10 + 50 * it, 200, 8 + it, depth = if (it == 5) 4 else 0) }
val overflow = ShellScene(listOf(chrome(6)) + modals)
val plan = planner.plan(app, 640, 480, null, overflow, 1)
assertEquals(2, plan.bakedLayers); assertFalse(plan.bakedSelections)
@@ -363,7 +363,7 @@ class DisplayListTest {
assertContentEquals(BmpUtil.pack4bppFromGray8(expected.preview(gray, 640, 480, glasses.right), 640, 480), glasses.composition)
}
// Once the shell fits again, the next frame is fully live and the screen is the app's again.
val fits = ShellScene(listOf(chrome(0), modals[2]))
val fits = ShellScene(listOf(chrome(0), modals.last()))
val next = planner.plan(app, 640, 480, null, fits, plan.nextFid)
assertEquals(0, next.bakedLayers)
for (glasses in lenses) {
@@ -372,13 +372,13 @@ class DisplayListTest {
assertContentEquals(BmpUtil.pack4bppFromGray8(fits.preview(gray, 640, 480, glasses.right), 640, 480), glasses.composition)
}
}
@Test fun noisyFramesRemainBoundedAndResourceBudgetIs192KiB() {
@Test fun noisyFramesRemainBoundedAndResourceBudgetIs322KiB() {
val cache=ResourceCacheState();val planner=ScenePlanner(cache);val glasses=Glasses()
val app=ByteArray(640*480/2){(it*37).toByte()}
val plan=planner.plan(app,640,480,null,ShellScene.EMPTY,1)
assertTrue(plan.commands.all { it.size<=65535 });glasses.apply(plan.commands)
assertContentEquals(app,glasses.screen);assertContentEquals(app,glasses.composition)
assertEquals(196608,ResourceCacheState.CACHE_SIZE)
assertEquals(2048+320*1024,ResourceCacheState.CACHE_SIZE)
}
/** Revision 35. Same calls and expectations as ClipTest in g2flash/tests/test_display_list.py. */
@Test fun clipRectsNarrowEveryOpNestThroughListsAndMoveWithDepth() {
@@ -64,10 +64,12 @@ class ResourceCacheTest {
@Test fun lruEvictsByBytesAndProtectsAllCurrentFrameHits() {
val cache = ResourceCacheState()
// Five of these fill the 320 KiB arena; a sixth needs an eviction.
val a = resource(60000, 1); val b = resource(60000, 2); val c = resource(60000, 3); val d = resource(60000, 4)
assertContentEquals(intArrayOf(0, 1, 2), cache.prepare(listOf(a, b, c)))
val e = resource(60000, 5); val f = resource(60000, 6)
assertContentEquals(intArrayOf(0, 1, 2, 3, 4), cache.prepare(listOf(a, b, c, e, f)))
cache.drainCommands(3600)
cache.prepare(listOf(a)); cache.drainCommands(3600) // b is oldest now.
cache.prepare(listOf(a, e, f)); cache.drainCommands(3600) // b is oldest now.
assertContentEquals(intArrayOf(1, 2), cache.prepare(listOf(d, c))) // protect later hit c before d.
val commands = cache.drainCommands(3600)
assertContentEquals(byteArrayOf(22, 1, 0, 1, 0), commands.first())
@@ -75,10 +77,10 @@ class ResourceCacheTest {
assertEquals(0, cache.resourceId(a)); assertEquals(2, cache.resourceId(c))
assertEquals(1, cache.resourceId(d))
assertContentEquals(d.bytes, uploaded(commands).getValue(1))
val tooLarge = cache.prepare(listOf(a, c, d, b))
val tooLarge = cache.prepare(listOf(a, c, d, e, f, b))
assertEquals(-1, tooLarge.last())
assertTrue(cache.drainCommands(3600).isEmpty())
assertEquals(3, cache.residentCount())
assertEquals(5, cache.residentCount())
}
@Test fun idPressureUsesLruEvenWhenBytesAreAvailable() {
@@ -96,15 +98,15 @@ class ResourceCacheTest {
@Test fun rejectedPlansRestoreResidencyAndLru() {
val cache = ResourceCacheState()
val resources = (0..3).map { resource(65536, it) }
cache.prepare(resources.take(3)); cache.drainCommands(3600)
val resources = (0..5).map { resource(60000, it) } // five fit, the sixth evicts
assertContentEquals(intArrayOf(0, 1, 2, 3, 4), cache.prepare(resources.take(5))); cache.drainCommands(3600)
val rollback = cache.checkpoint()
cache.prepare(listOf(resources[3]))
cache.prepare(listOf(resources[5]))
assertEquals(-1, cache.resourceId(resources[0]))
rollback()
assertEquals(0, cache.resourceId(resources[0])); assertEquals(-1, cache.resourceId(resources[3]))
assertEquals(0, cache.resourceId(resources[0])); assertEquals(-1, cache.resourceId(resources[5]))
assertTrue(cache.drainCommands(3600).isEmpty())
cache.prepare(listOf(resources[3]))
cache.prepare(listOf(resources[5]))
assertContentEquals(byteArrayOf(22, 1, 0, 0, 0), cache.drainCommands(3600).first())
}
+26 -1
View File
@@ -17,7 +17,7 @@ const font={lineHeight:12,ascent:10,descent:2,measureText:text=>text.length*4,
const menuCore=load('app/ui/menu-core.ts',{
'../graphics/image':graphics,'./menu-highlight-motion': require('../.test-build/app/ui/menu-highlight-motion.js'), '../graphics/menu-scroll-list': require('../.test-build/app/graphics/menu-scroll-list.js'), './menu-scroll-motion': require('../.test-build/app/ui/menu-scroll-motion.js'), '../graphics/draw-expression': require('../.test-build/app/graphics/draw-expression.js'),
});
const {MenuLayer,TextPageLayer}=load('app/ui/menu.ts',{
const {MenuLayer,TextPageLayer,menuHeadingItem}=load('app/ui/menu.ts',{
'./menu-animation-pref': require('../.test-build/app/ui/menu-animation-pref.js'), './animation-speed': require('../.test-build/app/ui/animation-speed.js'), '../native/settings-store': { getStringSetting: (_key, fallback) => fallback }, '../graphics/screen-size': { screenWidth: () => 640, screenHeight: () => 480 },
'../graphics/image':graphics,'../graphics/textwrap':{wrapText:(_font,text)=>text.split('\n')},'../graphics/ui-fonts':{getDefaultSmallFont:()=>font},
'../util/numeric-util':{clamp:(n,a,b)=>Math.max(a,Math.min(b,n))},'./gestures':{},
@@ -81,6 +81,31 @@ test('a submenu that replaces its parent menu skips the parent plane and dims th
stack.pop();stack.pop();
assert.equal(stack.paint().length,2);
});
test('heading rows label a section and are never selected',async()=>{
const picked=[];
const row=label=>({label,onSelect(){picked.push(label);}});
const layer=new MenuLayer(null,[menuHeadingItem('First'),row('A'),row('B'),menuHeadingItem('Second'),row('C')],
{x:0,y:0,width:120,minHeight:150,maxHeight:150,squareCorners:true,showBorder:false});
const context={stack:{getBaseSize:()=>({width:120,height:150}),isFocused:()=>true}};
const paint=()=>layer.paint(context,()=>new graphics.GrayImage(120,150));
const move=async type=>{await layer.handleInput({type},context);paint();return layer.selectedIndex;};
// The highlight starts below the first heading and steps over the second, both ways and when wrapping.
paint();assert.equal(layer.selectedIndex,1);
assert.equal(await move('scroll-down'),2);
assert.equal(await move('scroll-down'),4);
assert.equal(await move('scroll-down'),1);
assert.equal(await move('scroll-up'),4);
assert.equal(await move('scroll-up'),2);
await layer.handleInput({type:'click'},context);assert.deepEqual(picked,['B']);
// A heading asked for by index lands on the row under it.
layer.selectItem(3);assert.equal(layer.selectedIndex,4);
// Headings draw dim, in capitals (4px per character in this font), in the rows' text column.
const image=paint().withDrawsBaked(false),inkAt=y=>{const xs=[];for(let x=0;x<120;x++) if(image.pixels[y*120+x]>=8) xs.push([x,image.pixels[y*120+x]]);return xs;};
const heading=inkAt(8+4+2),unselected=inkAt(8+20+4+2);
assert.equal(heading[0][0],unselected[0][0]);
assert.ok(heading.every(([,value])=>value===90));assert.ok(unselected.every(([,value])=>value===200));
assert.equal(heading.length,'FIRST'.length*2);
});
test('text page paints at the stack size, not the lens size',()=>{
// An app window's stack is its viewport; a lens-sized plane is rejected by
// the compositor as larger than the window surface.
+136
View File
@@ -0,0 +1,136 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const ts = require('typescript');
function load(file, modules, globals = {}) {
const source = fs.readFileSync(path.join(__dirname, '..', file), 'utf8');
const context = { exports: {}, console, ...globals, require(name) { assert.ok(name in modules, name); return modules[name]; } };
vm.runInNewContext(ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const graphics = require('../.test-build/app/graphics/image.js');
const { bordered } = require('./helpers/viewport.cjs');
const { BdfFont } = load('app/graphics/bdffont.ts', { '@nativescript/core': {} });
const font = BdfFont.parse(fs.readFileSync(path.join(__dirname, '../app/fonts/terminus/ter-u12n.bdf'), 'utf8'));
/** The page over a fake keyboard service, shell and clock. */
function fixture({ state = 'connected', pointer = true } = {}) {
let now = 10_000, visible = true, renders = 0, nextTimer = 1;
const timers = new Map();
const service = {
listener: null, takes: 0, releases: 0,
snapshot: () => ({ state, pointer }),
takePointer(listener) {
this.takes++; this.listener = listener;
return () => { if (this.listener === listener) this.listener = null; this.releases++; };
},
};
const globals = {
Date: { now: () => now },
setInterval: (fn, ms) => { timers.set(nextTimer, { fn, ms, at: now + ms, repeat: true }); return nextTimer++; },
setTimeout: (fn, ms) => { timers.set(nextTimer, { fn, ms, at: now + ms, repeat: false }); return nextTimer++; },
clearInterval: id => timers.delete(id), clearTimeout: id => timers.delete(id),
};
const { MouseTestLayer } = load('app/apps/developer/mouse-test.ts', {
'../../graphics/ui-fonts': { getDefaultSmallFont: () => font }, '../../graphics/image': graphics,
'../../g2/keyboard/service': { keyboardService: service },
'../../ui/shell/shell': { shell: { isWindowVisible: () => visible } },
'../../util/numeric-util': { clamp: (n, lo, hi) => Math.max(lo, Math.min(hi, n)) },
'../../ui/gestures': {}, '../../ui/layers': {},
}, globals);
const layer = new MouseTestLayer('developer', () => { renders++; });
const viewport = bordered(576, 260);
const popped = [];
const ctx = { stack: { getBaseSize: () => viewport, pop: () => popped.push(1) } };
function advance(ms) {
const end = now + ms;
for (;;) {
const due = [...timers].filter(([, t]) => t.at <= end).sort((a, b) => a[1].at - b[1].at)[0];
if (!due) break;
const [id, timer] = due;
now = timer.at;
if (timer.repeat) timer.at += timer.ms; else timers.delete(id);
timer.fn();
}
now = end;
}
const sample = (buttons, extra = {}) => service.listener({ buttons, dx: 0, dy: 0, wheel: 0, pan: 0, ...extra });
return { layer, service, ctx, viewport, timers, popped, advance, sample, paint: () => layer.paint(ctx),
renders: () => renders, setVisible: value => { visible = value; } };
}
/** Whether the arrow's tip (its top-left pixel, full white) is at (x, y) and nowhere it shouldn't be. */
const tipAt = (image, x, y) => image.getPixel(x, y) === 255 && image.getPixel(x, y + 1) === 255 && image.getPixel(x + 1, y + 2) === 70;
test('the arrow follows the touchpad, stays on the page, and repaints at a rate the link can carry', () => {
const f = fixture();
assert.equal(f.service.takes, 1, 'takes the pointer while the page shows');
f.paint();
const { width, height } = f.viewport;
// The first movement starts from the middle of the page.
f.sample(0, { dx: 10, dy: -20 });
assert.ok(tipAt(f.paint(), width / 2 + 10, height / 2 - 20));
// A hundred reports in a second are one repaint per 33 ms, not a hundred.
const before = f.renders();
for (let i = 0; i < 100; i++) { f.sample(0, { dx: 1 }); f.advance(10); }
assert.ok(f.renders() - before >= 20 && f.renders() - before <= 31, String(f.renders() - before));
assert.ok(tipAt(f.paint(), width / 2 + 110, height / 2 - 20));
// Pushed past an edge it stops there.
f.sample(0, { dx: 5000, dy: 5000 });
let image = f.paint();
assert.equal(image.getPixel(width - 1, height - 1), 255);
f.sample(0, { dx: -9000, dy: -9000 });
assert.ok(tipAt(f.paint(), 0, 0));
});
test('buttons and wheel show on the page; a left click leaves a mark and a right click clears them', () => {
const f = fixture();
f.paint();
f.sample(0, { dx: 100, dy: 40 });
const { width, height } = f.viewport;
const at = { x: width / 2 + 100, y: height / 2 + 40 };
f.sample(1);
f.sample(0, { dx: -60, wheel: 2 });
let image = f.paint();
// The mark: a small cross where the click was, after the arrow has moved off it.
assert.equal(image.getPixel(at.x - 4, at.y), 140); assert.equal(image.getPixel(at.x, at.y + 4), 140);
assert.ok(tipAt(image, at.x - 60, at.y));
f.sample(2);
image = f.paint();
assert.equal(image.getPixel(at.x - 4, at.y), 0);
f.sample(0);
assert.doesNotThrow(() => f.paint());
});
test('the pointer is only held while the page can be seen, and given back when the page goes', () => {
const f = fixture();
f.paint();
f.sample(1);
// Another window comes to the front: the buttons go back to being keys.
f.setVisible(false); f.advance(400);
assert.equal(f.service.releases, 1); assert.equal(f.service.listener, null);
f.setVisible(true); f.advance(400);
assert.equal(f.service.takes, 2);
// Double tap (or Esc, which is one) leaves; leaving gives the pointer back and stops the timers.
f.layer.handleInput({ type: 'double-click' }, f.ctx);
assert.equal(f.popped.length, 1);
f.layer.onRemoved();
assert.equal(f.service.releases, 2); assert.equal(f.timers.size, 0);
const renders = f.renders();
f.advance(5000);
assert.equal(f.renders(), renders);
});
test('without a keyboard, or with one that has no pointer, the page says so', () => {
for (const options of [{ state: 'idle' }, { state: 'connected', pointer: false }]) {
const f = fixture(options);
const image = f.paint();
assert.ok(image instanceof graphics.GrayImage);
f.layer.onRemoved();
}
});
+56
View File
@@ -0,0 +1,56 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const settings = new Map();
const connections = loader({}, {
'../../native/settings-store': {
getStringSetting: (key, fallback) => (settings.has(key) ? settings.get(key) : fallback),
setStringSetting: (key, value) => settings.set(key, value),
},
})('app/apps/terminal/connections.ts');
// vm-realm objects: compare as plain JSON.
const plain = (value) => JSON.parse(JSON.stringify(value));
test('ssh:// strings select tmux by default', () => {
assert.deepEqual(plain(connections.parseSshConnectionString('ssh://jim@laptop')), { user: 'jim', host: 'laptop', port: 22, mode: 'tmux' });
assert.deepEqual(plain(connections.parseSshConnectionString('ssh://jim@laptop:2222/')), { user: 'jim', host: 'laptop', port: 2222, mode: 'tmux' });
assert.deepEqual(plain(connections.parseSshConnectionString('ssh://jim@[fd7a::1]:22')), { user: 'jim', host: 'fd7a::1', port: 22, mode: 'tmux' });
assert.equal(connections.parseSshConnectionString('ssh://jim%40corp@laptop').user, 'jim@corp');
});
test('?g2mirror= tunnels a g2mirror server over ssh', () => {
assert.deepEqual(plain(connections.parseSshConnectionString('ssh://jim@laptop?g2mirror=tok')), {
user: 'jim', host: 'laptop', port: 22, mode: 'g2mirror', authToken: 'tok', targetHost: '127.0.0.1', targetPort: 8737,
});
const custom = connections.parseSshConnectionString('ssh://jim@laptop?g2mirror=tok@en@localhost:9000');
assert.equal(custom.authToken, 'tok@en');
assert.equal(custom.targetHost, 'localhost');
assert.equal(custom.targetPort, 9000);
});
test('malformed ssh:// strings are rejected', () => {
for (const url of ['ssh://laptop', 'ssh://jim@', 'ssh://jim@laptop:0', 'ssh://jim@laptop?mode=tmux', 'ssh://jim@laptop?g2mirror=', 'ssh://jim@laptop?g2mirror=tok@host:99999', 'ssh://jim@laptop?g2mirror']) {
assert.equal(connections.parseSshConnectionString(url), null, url);
}
});
test('any-kind parsing and host labels', () => {
assert.equal(connections.parseAnyConnectionString('g2mirror://tok@laptop').kind, 'g2mirror');
assert.equal(connections.parseAnyConnectionString('ssh://jim@laptop').kind, 'ssh');
assert.equal(connections.parseAnyConnectionString('http://laptop'), null);
assert.equal(connections.connectionStringHostLabel('ssh://jim@laptop?g2mirror=secret'), 'jim@laptop');
assert.equal(connections.connectionStringHostLabel('ssh://jim@laptop:2222'), 'jim@laptop:2222');
assert.equal(connections.connectionStringHostLabel('ssh://jim@[fd7a::1]'), 'jim@[fd7a::1]');
assert.equal(connections.connectionStringHostLabel('g2mirror://tok@laptop'), 'laptop');
});
test('stored connections keep pinned host keys', () => {
connections.saveConnections([{ id: 'c1', url: 'ssh://jim@laptop', serverName: null, enabled: true, hostKeys: ['AAAA'] }]);
connections.updateConnection('c1', { hostKeys: ['AAAA', 'BBBB'] });
assert.deepEqual(plain(connections.loadConnections()[0].hostKeys), ['AAAA', 'BBBB']);
// Entries saved before SSH support have no hostKeys.
settings.set(connections.TERMINAL_CONNECTIONS_KEY, JSON.stringify([{ id: 'c2', url: 'g2mirror://t@h', enabled: true }]));
assert.deepEqual(plain(connections.loadConnections()[0].hostKeys), []);
});
+9
View File
@@ -117,6 +117,12 @@ function terminal({ sessions = ['vim', 'top'], presets = '', bellWake = true } =
},
'../../ui/gestures': { GESTURE_DOUBLE_CLICK: 'double-tap' },
'../../native/g2mirror-client': { G2MirrorClient: FakeClient },
'../../native/ssh': {
copyToPhoneClipboard() {}, describeSshFailure: (failure) => failure.message, getSshSecret: () => '',
openSshChannel() { throw new Error('no SSH in this test'); }, removeSshSecret() {}, setSshSecret() {},
sshClientKey: () => ({ authorizedKey: 'ecdsa-sha2-nistp256 AAAA test', fingerprint: 'SHA256:test' }),
},
'./tmux-client': { TmuxClient: class {} },
'../../native/settings-store': { onSettingsStoreChanged() {} },
'../../ui/dashboard-settings': {
enumSettingMenuItem() {}, textSettingMenuItem() {}, toggleSettingMenuItem() {},
@@ -124,6 +130,7 @@ function terminal({ sessions = ['vim', 'top'], presets = '', bellWake = true } =
terminalDisplayLayoutSetting: setting('default'),
terminalLaunchPresetsSetting: setting(presets),
terminalNewConnectionSetting: setting(''),
terminalSshPasswordSetting: setting(''),
terminalWakeOnBellSetting: setting(bellWake),
},
'../../ui/font-picker': { terminalFontPickerMenuItem() {} },
@@ -132,6 +139,8 @@ function terminal({ sessions = ['vim', 'top'], presets = '', bellWake = true } =
connectionDisplayName: (config) => config.id,
loadConnections: () => [{ id: 'c1', url: 'ok', serverName: 'host', enabled: true }],
parseConnectionString: () => ({ host: 'host' }),
parseAnyConnectionString: () => ({ kind: 'g2mirror', secure: false, host: 'host', port: 8737, authToken: 'token' }),
connectionStringHostLabel: () => 'host',
saveConnections() {}, updateConnection() {},
},
'./terminal-emulator': { TerminalEmulator: FakeEmulator },
+202
View File
@@ -0,0 +1,202 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawn, spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const tmux = require('../.test-build/app/apps/terminal/tmux-client.js');
// ---- pure helpers ----
test('tmux version gate', () => {
assert.deepEqual(tmux.parseTmuxVersion('tmux 3.2a'), [3, 2]);
assert.equal(tmux.tmuxVersionSupported('tmux 3.2a'), true);
assert.equal(tmux.tmuxVersionSupported('tmux 3.8'), true);
assert.equal(tmux.tmuxVersionSupported('tmux 3.1c'), false);
assert.equal(tmux.tmuxVersionSupported('tmux 2.7'), false);
assert.equal(tmux.tmuxVersionSupported('tmux next-3.9'), true);
assert.equal(tmux.tmuxVersionSupported('tmux master'), true);
});
test('decodeTmuxOutput undoes tmux and transport escaping', () => {
const bytes = (text) => Array.from(tmux.decodeTmuxOutput(text));
assert.deepEqual(bytes('a\\015\\012b'), [0x61, 0x0d, 0x0a, 0x62]);
assert.deepEqual(bytes('back\\134slash'), [...Buffer.from('back\\slash')]);
assert.deepEqual(bytes('héllo ✓'), [...Buffer.from('héllo ✓')]);
// A UTF-8 character split across two %output lines arrives escaped.
assert.deepEqual([...bytes('caf\\303'), ...bytes('\\251')], [...Buffer.from('café')]);
// A lone backslash without three octal digits is literal.
assert.deepEqual(bytes('\\9'), [0x5c, 0x39]);
});
test('hostCommand keeps scripts portable across login shells', () => {
assert.equal(tmux.hostCommand('echo hi'), "exec /bin/sh -c 'echo hi'");
assert.throws(() => tmux.hostCommand("echo 'hi'"));
assert.throws(() => tmux.hostCommand('echo \\\\'));
for (const command of [tmux.pollerCommand(), tmux.viewerCommand('$3'), tmux.launchCommand('shell'), tmux.launchCommand('htop -d 5')]) {
assert.match(command, /^exec \/bin\/sh -c '[^']*'$/);
}
assert.throws(() => tmux.viewerCommand('work'));
assert.throws(() => tmux.launchCommand('rm -rf ~; echo $HOME'));
});
test('pane rows and labels', () => {
const fields = ['%3', '$1', 'work', '@2', '1', 'zsh', '2', '0', '4242', '0', '1700000000', '3', 'zsh', '/home/jim/src', 'build\twatcher'];
const row = tmux.parsePaneRow(fields.join('\t'));
assert.equal(row.title, 'build\twatcher');
assert.equal(row.bells, 3);
assert.equal(row.windowPanes, 2);
assert.equal(tmux.paneLabel(row, 'laptop.local', '/home/jim'), 'work:1.0 build\twatcher');
assert.equal(tmux.paneLabel({ ...row, title: 'laptop.local' }, 'laptop.local', '/home/jim'), 'work:1.0 zsh ~/src');
assert.equal(tmux.paneLabel({ ...row, title: 'laptop', windowPanes: 1 }, 'laptop.local', '/home/jim'), 'work:1 zsh ~/src');
assert.equal(tmux.parsePaneRow('garbage'), null);
});
test('snapshot bytes restore cursor and key modes', () => {
const state = tmux.parsePaneState('%1|4|1|1|1|0|1|0|0|0|1|80|2|10|57|5|0');
assert.equal(state.historyNext, 57);
assert.equal(state.historyOldest, 5);
const text = Buffer.from(tmux.snapshotBytes(state, ['$ ls', 'a b'], [])).toString();
assert.equal(text, '$ ls\x1b[0m\r\na b\x1b[0m\x1b[2;5H\x1b[?1h');
// Without history_added (tmux < 3.8), history_size stands in.
assert.equal(tmux.parsePaneState('%1|0|0|1|0|0|1|0|0|0|23|80|24|10||||').historyNext, 10);
});
test('send-keys commands are hex and chunked', () => {
const commands = tmux.sendKeysCommands('%4', new Uint8Array(300).fill(0x41));
assert.equal(commands.length, 2);
assert.match(commands[0], /^send-keys -t %4 -H 41 41 /);
});
// ---- against a real tmux server ----
const tmuxVersion = spawnSync('tmux', ['-V'], { encoding: 'utf8' });
const haveTmux = tmuxVersion.status === 0 && tmux.tmuxVersionSupported(tmuxVersion.stdout);
/** Mimic the SSH transport: run through a shell, split stdout/stderr into lines, escape non-UTF-8 lines. */
function localChannel(env) {
return (command, listener) => {
const child = spawn('/bin/sh', ['-c', command], { env, stdio: ['pipe', 'pipe', 'pipe'] });
let closed = false;
// Like the SSH transport, a write to a channel whose command just exited is dropped, not thrown.
child.stdin.on('error', () => {});
const lines = (stream, emit) => {
let buffered = Buffer.alloc(0);
stream.on('data', (chunk) => {
buffered = Buffer.concat([buffered, chunk]);
let index;
while ((index = buffered.indexOf(0x0a)) >= 0) {
emit(escapeLine(buffered.subarray(0, index)));
buffered = buffered.subarray(index + 1);
}
});
};
lines(child.stdout, (line) => !closed && listener.onLine(line));
lines(child.stderr, (line) => !closed && listener.onStderr(line));
child.on('spawn', () => listener.onOpen());
child.on('exit', (status) => { if (!closed) { closed = true; listener.onClosed(status); } });
return {
send: (line) => { if (closed) return false; child.stdin.write(`${line}\n`); return true; },
close: () => { if (closed) return; closed = true; child.stdin.end(); setTimeout(() => child.kill(), 500); },
};
};
}
function escapeLine(bytes) {
const text = bytes.toString('utf8');
if (Buffer.from(text, 'utf8').equals(bytes)) return text;
return Array.from(bytes, (byte) => (byte >= 0x80 ? `\\${byte.toString(8).padStart(3, '0')}` : String.fromCharCode(byte))).join('');
}
function waitFor(predicate, what, timeoutMs = 10_000) {
return new Promise((resolve, reject) => {
const started = Date.now();
const timer = setInterval(() => {
let value;
try { value = predicate(); } catch (error) { clearInterval(timer); reject(error); return; }
if (value) { clearInterval(timer); resolve(value); }
else if (Date.now() - started > timeoutMs) { clearInterval(timer); reject(new Error(`timed out waiting for ${what}`)); }
}, 50);
});
}
test('TmuxClient against a local tmux server', { skip: !haveTmux && 'tmux >= 3.2 not installed' }, async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fc-tmux-'));
const env = { ...process.env, TMUX_TMPDIR: dir, SHELL: '/bin/sh', PS1: '$ ' };
delete env.TMUX;
const tm = (...args) => spawnSync('tmux', args, { env, encoding: 'utf8' });
const openChannel = localChannel(env);
const clients = [];
try {
tm('new-session', '-d', '-s', 'work', '-x', '120', '-y', '40', '/bin/sh');
const control = new tmux.TmuxClient({ openChannel, label: 'test', cols: 80, rows: 20, stateKey: 'test-connection' });
clients.push(control);
const bells = [];
control.onBell((socket) => bells.push(socket));
control.start();
await waitFor(() => control.state().phase === 'connected' && control.state().sessions.length === 1, 'listing');
assert.equal(control.state().sessions[0].socket, '%0');
assert.match(control.state().sessions[0].title, /^work:0 /);
// A bell in the session's current window (tmux's own bell flag misses these).
tm('send-keys', '-t', '%0', '-l', "printf '\\a'");
tm('send-keys', '-t', '%0', 'Enter');
await waitFor(() => bells.includes('%0'), 'bell');
const launched = await control.launchSession('shell');
assert.match(launched, /^%\d+$/);
await waitFor(() => control.state().sessions.some((s) => s.socket === launched), 'launched pane in listing');
// View the original pane.
const view = new tmux.TmuxClient({ openChannel, label: 'test', cols: 80, rows: 20, stateKey: '' });
clients.push(view);
let screen = '';
const snapshots = [];
const histories = [];
view.onTerminalData((data, kind) => {
if (kind === 'snapshot') { screen = ''; snapshots.push(Buffer.from(data).toString()); }
screen += Buffer.from(data).toString();
});
view.onSnapshot((next, oldest) => snapshots.push({ next, oldest }));
view.onHistoryLines((reply) => histories.push(reply));
view.onStateChange((state) => {
if (state.phase === 'connected' && !view.requested) { view.requested = true; view.connectSession('%0'); }
});
view.onSessionAttached(() => view.view());
view.start();
await waitFor(() => snapshots.length >= 2, 'snapshot');
assert.equal(view.state().phase, 'attached');
assert.equal(tm('display', '-p', '-t', '%0', '#{window_width}x#{window_height}').stdout.trim(), '80x20');
view.sendInput('for i in $(seq 1 60); do echo row$i; done\r');
await waitFor(() => screen.includes('row60'), 'typed command output');
// Re-snapshot: rows have scrolled into the history; page some back.
view.unview();
view.view();
await waitFor(() => snapshots.length >= 4, 'second snapshot');
const { next } = snapshots[snapshots.length - 1];
assert.ok(next > 20, `history should have grown, next=${next}`);
view.requestHistory(next, 5);
await waitFor(() => histories.length === 1, 'history page');
assert.equal(histories[0].lines.length, 5);
assert.equal(histories[0].start, next - 5);
assert.ok(histories[0].lines.some((line) => /^row\d+$/.test(line)), JSON.stringify(histories[0].lines));
// Unviewing gives the window back its own size.
view.unview();
await waitFor(() => tm('display', '-p', '-t', '%0', '#{window_width}').stdout.trim() !== '80', 'size restored', 3000).catch(() => {});
// The pane going away ends the view.
let detached = null;
view.onSessionDetached((reason) => { detached = reason; });
view.view();
tm('kill-pane', '-t', '%0');
await waitFor(() => detached !== null, 'detach on pane exit');
} finally {
for (const client of clients) client.stop();
tm('kill-server');
fs.rmSync(dir, { recursive: true, force: true });
}
});
+4
View File
@@ -23,7 +23,11 @@
"../app/g2/keyboard/keys.ts",
"../app/g2/keyboard/bindings.ts",
"../app/g2/keyboard/key-router.ts",
"../app/g2/keyboard/pointer.ts",
"../app/apps/terminal/terminal-keys.ts",
"../app/native/terminal-session-types.ts",
"../app/apps/terminal/terminal-client.ts",
"../app/apps/terminal/tmux-client.ts",
"../app/phone-ui/ble-bandwidth-meter.ts",
"../app/apps/terminal/hub-header.ts",
"../app/g2/ios-peripheral-identity.ts",