Compare commits

..
23 changed files with 738 additions and 603 deletions

No files matched your search

@@ -1,47 +0,0 @@
package com.faceclaw.app
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.AtomicFile
import java.io.File
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/** This credential cannot be restored onto a device lacking its Keystore key. */
object FaceclawHealthExportSecret {
private const val ALIAS = "faceclaw.health.export"
private fun file(context: Context) = AtomicFile(File(context.noBackupFilesDir, "health-export-key"))
private fun key(): SecretKey {
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(store.getKey(ALIAS, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
}.generateKey()
}
@JvmStatic @Synchronized fun read(context: Context): String {
val held = file(context)
if (!held.baseFile.exists()) return ""
return try {
val bytes = held.readFully()
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, bytes.copyOfRange(0, 12)))
String(cipher.doFinal(bytes.copyOfRange(12, bytes.size)), Charsets.UTF_8)
} catch (_: Exception) { "" } // Require re-entry after key loss; never log the credential.
}
@JvmStatic @Synchronized fun write(context: Context, value: String) {
val held = file(context)
if (value.isEmpty()) { held.delete(); return }
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key())
val bytes = cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8))
val stream = held.startWrite()
try { stream.write(bytes); held.finishWrite(stream) }
catch (error: Exception) { held.failWrite(stream); throw error }
}
}
+131 -20
View File
@@ -8,7 +8,11 @@ import { IconGrid, ICON_GRID_BAND_INSET_X, ICON_GRID_HIGHLIGHT_INSET_Y, ICON_GRI
import { Layer, LayerActions, LayerContext } from "../../ui/layers";
import { MenuLayer, type MenuItem } from "../../ui/menu";
import { WINDOW_MENU_LAYOUT } from "../../ui/window-menu";
import { onAnySettingChanged } from "../../ui/dashboard-settings";
import {
onAnySettingChanged, launcherLayoutSetting, enumSettingMenuItem,
ConfigSettingString, EditTextSettingLayer,
} from "../../ui/dashboard-settings";
import { getLauncherLayoutFingerprint, orderLauncherEntries, moveLauncherEntry } from "./launcher-layout";
import { createInProcessWindow } from "../../ui/shell/in-process-window";
import {
getFolderAssignments,
@@ -16,6 +20,7 @@ import {
getFolderStateFingerprint,
setAppFolder,
unusedNewFolderName,
getExplicitFolderNames, createFolder, renameFolder, folderNameError, disbandFolder,
} from "./launcher-folders";
import { shell, type ShellWindow } from "../../ui/shell/shell";
@@ -66,6 +71,14 @@ type LauncherGridEntry =
* and is re-read every paint, so assistant folder tools take effect without
* the layer holding any copy of the state.
*/
const entryKey = (entry: LauncherGridEntry) => entry.kind === "app" ? `app:${entry.appId}` : `folder:${entry.name}`;
/** Reuse the phone text editor; dismiss it if the glasses leave this page. */
class FolderNameEditorLayer extends EditTextSettingLayer {
constructor(setting: ConfigSettingString, private readonly actions: LayerActions) { super(setting); }
onRemoved(): void { void this.actions.endTextSettingEdit(); }
}
class LauncherGridLayer implements Layer {
// Watch swipes are spatial: up/down move between rows, left/right between
// columns. From the leftmost column, left keeps going out: it leaves the
@@ -74,6 +87,12 @@ class LauncherGridLayer implements Layer {
readonly acceptsDirectional = true;
/** Folder whose contents the grid is showing, or null for the top grid. */
private currentFolder: string | null = null;
private editingFolder = false;
private moving: { key: string; label: string; folder: string | null } | null = null;
private sortEntries(entries: LauncherGridEntry[]): LauncherGridEntry[] {
return orderLauncherEntries(entries, entryKey, this.currentFolder, launcherLayoutSetting.get() === "custom");
}
private readonly grid = new IconGrid<LauncherGridEntry>({
items: () => this.entries(),
describe: (entry) => ({
@@ -104,25 +123,23 @@ class LauncherGridLayer implements Layer {
const members = (getFolders().get(this.currentFolder) ?? [])
.map((appId) => byAppId.get(appId))
.filter(Boolean) as LauncherAppEntry[];
if (members.length > 0) {
return members
.map((app): LauncherGridEntry => ({
if (members.length > 0 || getExplicitFolderNames().includes(this.currentFolder)) {
return this.sortEntries(members.map((app): LauncherGridEntry => ({
kind: "app",
label: app.label,
icon: app.icon,
appId: app.appId,
renderIcon: app.renderIcon,
}))
.sort((a, b) => a.label.localeCompare(b.label));
})));
}
this.currentFolder = null;
}
const assignments = getFolderAssignments();
const entries: LauncherGridEntry[] = [];
// A folder cell appears only when it holds at least one known app; stale
// assignments to removed apps are ignored.
// Legacy folders need a known member; explicitly created folders may be empty.
const explicit = new Set(getExplicitFolderNames());
for (const [name, members] of getFolders()) {
if (members.some((appId) => byAppId.has(appId))) {
if (explicit.has(name) || members.some((appId) => byAppId.has(appId))) {
entries.push({ kind: "folder", label: name, name });
}
}
@@ -137,7 +154,7 @@ class LauncherGridLayer implements Layer {
});
}
}
return entries.sort((a, b) => a.label.localeCompare(b.label));
return this.sortEntries(entries);
}
/** Leave the current folder, putting the selection back on its cell. */
@@ -151,6 +168,16 @@ class LauncherGridLayer implements Layer {
/** Enter a folder or launch an app; true when that left the grid (a launch). */
private async openEntry(entry: LauncherGridEntry): Promise<boolean> {
if (this.moving) {
const moving = this.moving;
this.moving = null;
if (launcherLayoutSetting.get() === "custom" && moving.folder === this.currentFolder) {
moveLauncherEntry(this.currentFolder, this.entries().map(entryKey), moving.key, entryKey(entry));
const index = this.entries().findIndex(item => entryKey(item) === moving.key);
if (index >= 0) this.grid.selectIndex(index);
}
return false;
}
if (entry.kind === "folder") {
this.currentFolder = entry.name;
this.grid.resetSelection();
@@ -166,6 +193,13 @@ class LauncherGridLayer implements Layer {
/** Leave the open folder, else yield to the sidebar; true when that left the grid. */
private back(): boolean {
if (this.moving) {
const key = this.moving.key;
this.moving = null;
const index = this.entries().findIndex(entry => entryKey(entry) === key);
if (index >= 0) this.grid.selectIndex(index);
return false;
}
if (this.currentFolder !== null) {
this.exitFolder();
return false;
@@ -175,14 +209,54 @@ class LauncherGridLayer implements Layer {
}
/**
* App-specific entries for the window's context menu. Only item mode
* pins the selection to a single cell, and only apps can move to folders,
* so anywhere else the menu falls back to just the defaults.
* Layout and folder creation are always available. Per-icon actions need
* item mode so row navigation never edits an ambiguous selection.
*/
menuItems(): MenuItem[] {
if (this.editingFolder) return [];
const entry = this.grid.selectedItem;
if (!entry || entry.kind !== "app") return [];
return [
const items: MenuItem[] = [
enumSettingMenuItem(launcherLayoutSetting, { onChange: () => { this.moving = null; this.grid.resetSelection(); } }),
{
label: "New folder",
onSelect: ctx => {
const name = unusedNewFolderName();
if (createFolder(name)) {
this.currentFolder = null;
this.moving = null;
this.grid.resetSelection();
this.grid.selectIndex(this.entries().findIndex(item => item.kind === "folder" && item.name === name));
}
ctx.stack.pop();
},
},
];
const folder = entry?.kind === "folder" ? entry.name : this.currentFolder;
if (folder !== null) {
items.push({ label: "Rename folder", onSelect: ctx => this.editFolderName(folder, ctx) }, {
label: "Delete folder",
onSelect: ctx => {
ctx.stack.pop();
ctx.stack.push(new MenuLayer("Delete folder? Apps stay installed.", [
{ label: "Delete folder", onSelect: confirm => {
disbandFolder(folder);
if (this.currentFolder === folder) this.currentFolder = null;
this.moving = null;
this.grid.resetSelection();
confirm.stack.pop();
} },
{ label: "Cancel", onSelect: confirm => confirm.stack.pop() },
], WINDOW_MENU_LAYOUT));
},
});
}
if (this.moving) items.push({ label: "Cancel move", onSelect: ctx => { this.back(); ctx.stack.pop(); } });
else if (entry && launcherLayoutSetting.get() === "custom") items.push({
label: "Move icon",
onSelect: ctx => { this.moving = { key: entryKey(entry), label: entry.label, folder: this.currentFolder }; ctx.stack.pop(); },
});
if (!entry || entry.kind !== "app") return items;
return [...items,
{
label: "Move to folder",
onSelect: (ctx) => {
@@ -221,6 +295,32 @@ class LauncherGridLayer implements Layer {
];
}
private editFolderName(folder: string, ctx: LayerContext): void {
ctx.stack.pop();
const setting = new ConfigSettingString({
id: "launcher-folder-name", label: "Folder name", storageKey: "launcher.folderNameDraft",
defaultValue: folder, normalize: value => value ?? "",
validate: value => folderNameError(value, folder), reportInAnalytics: false,
});
setting.set(folder);
this.editingFolder = true;
const editor = new FolderNameEditorLayer(setting, ctx.actions);
ctx.stack.push(editor);
void ctx.actions.startTextSettingsEdit([setting], "Rename folder", () => {
this.editingFolder = false;
if (renameFolder(folder, setting.get())) {
if (this.currentFolder === folder) this.currentFolder = setting.get().trim();
this.moving = null;
}
ctx.stack.popIfTop(layer => layer === editor);
ctx.actions.requestRender();
}, undefined, () => {
this.editingFolder = false;
ctx.stack.popIfTop(layer => layer === editor);
ctx.actions.requestRender();
});
}
/**
* The folder-picker submenu: every existing folder except the app's own,
* plus a generated-name "New folder" (ring input has no text entry) and,
@@ -242,7 +342,9 @@ class LauncherGridLayer implements Layer {
items.push({
label: "New folder",
onSelect: (ctx) => {
setAppFolder(appId, unusedNewFolderName());
const name = unusedNewFolderName();
createFolder(name);
setAppFolder(appId, name);
ctx.stack.pop();
},
});
@@ -263,8 +365,16 @@ class LauncherGridLayer implements Layer {
const { width, height } = ctx.stack.getBaseSize();
const image = new GrayImage(width, height, 0);
// The folder-name header band scales with the font.
const gridTop = this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : ROOT_GRID_TOP;
if (this.currentFolder !== null) {
const entries = this.entries();
if (this.moving && (launcherLayoutSetting.get() !== "custom" || this.moving.folder !== this.currentFolder ||
!entries.some(entry => entryKey(entry) === this.moving!.key))) this.moving = null;
const gridTop = this.moving ? GRID_TOP + 2 * (font.lineHeight + 2)
: this.currentFolder !== null ? GRID_TOP + font.lineHeight + 4 : ROOT_GRID_TOP;
if (this.moving) {
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, `Move ${this.moving.label}`, width - 16), 220);
image.drawText(font, 8, GRID_TOP + font.lineHeight, "Select position; double tap cancels", 160);
}
if (this.currentFolder !== null && !this.moving) {
image.drawText(font, 8, GRID_TOP - 2, truncateText(font, this.currentFolder, width - 16), 160);
}
// The grid runs to the window's bottom edge, so a row cut off there for
@@ -274,6 +384,7 @@ class LauncherGridLayer implements Layer {
}
async handleInput(event: InputEvent, ctx: LayerContext): Promise<void> {
if (this.moving && event.type === "double-click") { this.back(); return; }
await this.grid.handleInput(event, ctx);
}
@@ -311,9 +422,9 @@ export function createLauncherWindow(options: LauncherOptions): ShellWindow {
// keeps every unrelated setting change from repainting the launcher. The
// launcher is pinned for the app's lifetime, so the subscription never needs
// tearing down.
let lastState = `${getFolderStateFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
let lastState = `${getFolderStateFingerprint()}\n${getLauncherLayoutFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
onAnySettingChanged(() => {
const state = `${getFolderStateFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
const state = `${getFolderStateFingerprint()}\n${getLauncherLayoutFingerprint()}\n${launcherAppsFingerprint(options.apps())}`;
if (state === lastState) return;
lastState = state;
created.requestRender();
+51 -11
View File
@@ -1,14 +1,50 @@
/**
* Launcher folder state: which apps are grouped into which named folder.
* Stored as one JSON string (appId -> folder name) in the settings store, so
* it persists and its changes broadcast to every isolate. An unset value means
* the default grouping; any edit persists the whole map, so clearing out the
* defaults sticks. Folders exist only while at least one app is assigned to
* them — there is no separate create/delete step.
*/
/** Launcher assignments keep their legacy format; explicitly created folders may be empty. */
import { getStringSetting, setStringSetting } from "../../native/settings-store";
import { renameLauncherFolderOrder, removeLauncherFolderOrder } from "./launcher-layout";
const STORAGE_KEY = "launcher.folders";
const NAMES_KEY = "launcher.folderNames";
/** Only user-created/renamed folders persist after their last member leaves. */
export function getExplicitFolderNames(): string[] {
try {
const value = JSON.parse(getStringSetting(NAMES_KEY, "[]"));
return Array.isArray(value) ? [...new Set(value.filter((name): name is string =>
typeof name === "string" && !!name.trim()).map(name => name.trim()))] : [];
} catch { return []; }
}
export function folderNameError(input: string, previous?: string): string | null {
const name = input.trim();
if (!name) return "Enter a folder name.";
if (name.length > FOLDER_NAME_MAX_LENGTH) return `Use at most ${FOLDER_NAME_MAX_LENGTH} characters.`;
if (/[\u0000-\u001f\u007f]/.test(name)) return "Use a single-line folder name.";
if (previous !== undefined && !getFolders().has(previous)) return "This folder no longer exists.";
for (const existing of getFolders().keys()) {
if (existing !== previous && existing.toLowerCase() === name.toLowerCase()) return "A folder with this name already exists.";
}
return null;
}
export function createFolder(input: string): boolean {
if (folderNameError(input)) return false;
setStringSetting(NAMES_KEY, JSON.stringify([...getExplicitFolderNames(), input.trim()]));
return true;
}
export function renameFolder(previous: string, input: string): boolean {
if (folderNameError(input, previous)) return false;
const name = input.trim();
if (name === previous) return true;
const assignments = getFolderAssignments();
for (const appId of Object.keys(assignments)) if (assignments[appId] === previous) assignments[appId] = name;
// Preserve position and per-folder order when the visible name changes.
renameLauncherFolderOrder(previous, name);
setStringSetting(NAMES_KEY, JSON.stringify([...getExplicitFolderNames().filter(n => n !== previous), name]));
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
return true;
}
/** The out-of-the-box grouping, applied only while the setting is unset. */
const DEFAULT_ASSIGNMENTS: Record<string, string> = {
@@ -32,7 +68,7 @@ export function getFolderAssignments(): Record<string, string> {
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const assignments: Record<string, string> = {};
const assignments: Record<string, string> = Object.create(null);
for (const appId of Object.keys(parsed)) {
const folder = parsed[appId];
if (typeof folder === "string" && folder.trim()) {
@@ -58,6 +94,7 @@ export function getFolders(): Map<string, string[]> {
unsorted.set(folder, [appId]);
}
}
for (const name of getExplicitFolderNames()) if (!unsorted.has(name)) unsorted.set(name, []);
const folders = new Map<string, string[]>();
for (const name of Array.from(unsorted.keys()).sort((a, b) => a.localeCompare(b))) {
folders.set(name, unsorted.get(name)!);
@@ -86,6 +123,8 @@ export function disbandFolder(folder: string): number {
moved++;
}
}
setStringSetting(NAMES_KEY, JSON.stringify(getExplicitFolderNames().filter(name => name !== folder)));
removeLauncherFolderOrder(folder);
if (moved > 0) {
setStringSetting(STORAGE_KEY, JSON.stringify(assignments));
}
@@ -95,7 +134,7 @@ export function disbandFolder(folder: string): number {
/**
* An unused name for a ring-created folder ("New folder", "New folder 2", …).
* Ring input has no text entry, so new folders start with a generated name;
* the assistant's folder tools can regroup the apps under a better one.
* Rename folder uses the existing phone text editor for a custom name.
*/
export function unusedNewFolderName(): string {
const existing = new Set(Array.from(getFolders().keys()).map((name) => name.toLowerCase()));
@@ -119,5 +158,6 @@ export function resolveFolderName(input: string): string {
/** Raw stored value, for cheap change detection by the launcher window. */
export function getFolderStateFingerprint(): string {
return getStringSetting(STORAGE_KEY, "");
return JSON.stringify([getStringSetting(STORAGE_KEY, ""), getStringSetting(NAMES_KEY, ""),
getStringSetting("launcher.folderNameDraft", "")]);
}
+60
View File
@@ -0,0 +1,60 @@
import { getStringSetting, setStringSetting } from "../../native/settings-store";
const ORDER_KEY = "launcher.order";
const scopeKey = (folder: string | null) => folder === null ? "root" : `folder:${folder}`;
function readOrders(): Record<string, string[]> {
try {
const value = JSON.parse(getStringSetting(ORDER_KEY, "{}"));
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
return Object.fromEntries(Object.entries(value).filter(([, order]) => Array.isArray(order))
.map(([scope, order]) => [scope, [...new Set((order as unknown[]).filter((id): id is string => typeof id === "string"))]]));
} catch { return {}; }
}
export function setLauncherOrder(folder: string | null, ids: readonly string[]): void {
const orders = readOrders();
orders[scopeKey(folder)] = [...new Set(ids)];
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
/** Unseen apps append alphabetically; changing sort modes never destroys saved order. */
export function orderLauncherEntries<T extends { label: string }>(
entries: T[], key: (entry: T) => string, folder: string | null, custom: boolean,
): T[] {
const order = custom ? readOrders()[scopeKey(folder)] ?? [] : [];
const rank = new Map(order.map((id, index) => [id, index]));
return entries.sort((a, b) => (rank.get(key(a)) ?? Infinity) - (rank.get(key(b)) ?? Infinity) ||
a.label.localeCompare(b.label) || key(a).localeCompare(key(b)));
}
/** Move into the target's position, without moving apps across folders. */
export function moveLauncherEntry(folder: string | null, ids: string[], source: string, target: string): boolean {
const from = ids.indexOf(source), to = ids.indexOf(target);
if (from < 0 || to < 0) return false;
const next = ids.slice();
next.splice(from, 1);
next.splice(to, 0, source);
setLauncherOrder(folder, next);
return true;
}
export function renameLauncherFolderOrder(previous: string, next: string): void {
const orders = readOrders();
const oldScope = scopeKey(previous), newScope = scopeKey(next);
if (orders[oldScope]) orders[newScope] = orders[oldScope];
delete orders[oldScope];
if (orders.root) orders.root = orders.root.map(id => id === `folder:${previous}` ? `folder:${next}` : id);
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
export function removeLauncherFolderOrder(folder: string): void {
const orders = readOrders();
delete orders[scopeKey(folder)];
if (orders.root) orders.root = orders.root.filter(id => id !== `folder:${folder}`);
setStringSetting(ORDER_KEY, JSON.stringify(orders));
}
export function getLauncherLayoutFingerprint(): string {
return JSON.stringify([getStringSetting("launcher.layout", "alphabetical"), getStringSetting(ORDER_KEY, "")]);
}
+4 -3
View File
@@ -191,7 +191,7 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
const lines: string[] = [];
for (const [name, members] of getFolders()) {
const known = members.filter((appId) => appIds.indexOf(appId) >= 0).sort();
if (known.length) lines.push(`${name}: ${known.map(describeApp).join(", ")}`);
if (known.length || members.length === 0) lines.push(`${name}: ${known.length ? known.map(describeApp).join(", ") : "(empty)"}`);
}
const assignments = getFolderAssignments();
const ungrouped = appIds.filter((appId) => !assignments[appId]);
@@ -237,7 +237,7 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
{
name: "apps.remove_from_folder",
description:
"Move an app out of its launcher folder back to the top-level grid. A folder disappears when its last app is removed.",
"Move an app out of its launcher folder back to the top-level grid. Default folders disappear when their last app is removed; user-created folders can stay empty.",
inputSchema: {
type: "object",
properties: {
@@ -276,8 +276,9 @@ function registerTools(options: WindowToolsOptions, registry: ToolRegistry): voi
(args) => {
const folder = resolveFolderName(String(args?.folder ?? ""));
if (!folder) return err("folder must be a non-empty name");
const existed = getFolders().has(folder);
const moved = disbandFolder(folder);
if (moved === 0) {
if (moved === 0 && !existed) {
const names = Array.from(getFolders().keys());
return err(
names.length
-2
View File
@@ -1,4 +1,3 @@
import { startHealthExport } from "./health/health-export"
import { Application } from '@nativescript/core'
import { registerShareIntentHandler } from './native/share-intents'
import { installNativeUserAgent } from './util/http'
@@ -19,7 +18,6 @@ Application.on(Application.launchEvent, () => {
// they are closed would be lost if the process restarted first, so this keeps
// them reaching disk regardless. No-op when there is nothing new.
startLiveHealthSync()
startHealthExport()
// Collect from the ring on a wall-clock cadence (:01 and :31). Without this
// nothing drives a pull on a timer at all - only onRingReady() on reconnect -
-72
View File
@@ -1,72 +0,0 @@
import { healthStore } from "./health-store-files";
import { isFixtureData } from "./health-seed";
import { healthExportEnabledSetting, healthExportUrlSetting, healthExportKeySetting } from "../ui/dashboard-settings";
import { getStringSetting, setStringSetting } from "../native/settings-store";
import { fetchTextWithUserAgent } from "../util/http";
let running = false;
let started = false;
let status = "Not synchronized";
export function healthExportStatus(): string { return status; }
/** One bounded batch, with durable acknowledgement and no overlapping requests. */
export async function syncHealthExport(): Promise<void> {
if (running) return;
running = true;
try {
if (!healthExportEnabledSetting.get()) { status = "Export disabled"; return; }
if (isFixtureData()) { status = "Sample data is never exported"; return; }
const url = healthExportUrlSetting.get();
const key = healthExportKeySetting.get();
if (!url || healthExportUrlSetting.validationError() || !key) {
status = "Configure an HTTPS endpoint and API key";
return;
}
const generation = getStringSetting("health.export.generation", "0");
let held: { url?: string; generation?: string; offsets?: Record<string, number> } = {};
try { held = JSON.parse(getStringSetting("health.export.cursor", "{}")) ?? {}; } catch { /* First sync. */ }
const offsets = held.url === url && held.generation === generation ? held.offsets ?? {} : {};
let limit = 200;
let batch = healthStore().exportBatch(offsets, limit);
let body = JSON.stringify({ version: 1, samples: batch.samples, sleep: batch.sleep });
// Normalized records contain only ASCII keys, numbers and metric names.
// Large sleep histories must fit the server body limit as well as its record limit.
while (body.length > 240_000 && limit > 1) {
limit = Math.max(1, Math.floor(limit / 2));
batch = healthStore().exportBatch(offsets, limit);
body = JSON.stringify({ version: 1, samples: batch.samples, sleep: batch.sleep });
}
if (body.length > 240_000) { status = "A health record exceeds the export size limit"; return; }
if (!batch.scanned) { status = "Up to date"; return; }
if (batch.samples.length || batch.sleep.length) {
status = "Sending health data";
const response = await fetchTextWithUserAgent(url, {
method: "POST", headers: { "Authorization": `Bearer ${key}`, "Content-Type": "application/json" },
body,
timeoutMs: 30_000, dontFollowRedirects: true,
});
if (response.status !== 200) {
status = response.status === 401 || response.status === 403
? "API key refused; check configuration" : `Server refused batch (HTTP ${response.status}); will retry`;
return;
}
const ack = await response.json<{ accepted?: boolean }>();
if (ack.accepted !== true) { status = "Invalid server acknowledgement; will retry"; return; }
}
// An edit during the request must not acknowledge data on a different destination.
if (url !== healthExportUrlSetting.get() || generation !== getStringSetting("health.export.generation", "0")) return;
setStringSetting("health.export.cursor", JSON.stringify({ url, generation, offsets: batch.cursor }));
status = "Batch synchronized; remaining history follows automatically";
} catch {
// Errors may include request headers or data: never log or display them.
status = "Synchronization failed; will retry automatically";
} finally { running = false; }
}
/** Android app process only; no extra BLE pulls, wake locks, or background service. */
export function startHealthExport(): void {
if (started) return;
started = true;
setTimeout(() => { void syncHealthExport(); }, 10_000);
setInterval(() => { void syncHealthExport(); }, 60_000);
}
-19
View File
@@ -48,7 +48,6 @@
import {
HOUR_MS,
HEART_RATE_MEASUREMENT_SPAN_MS,
TEN_MINUTES_MS,
type HealthSample,
type SleepSession,
@@ -66,8 +65,6 @@ export type WireHourlyRecord = {
* zero bytes instead.
*/
anchorMs: number | null;
/** Latest reading, only from live pages; raw journal replay does not guess its clock. */
latest?: { timestampSeconds: number; value: number; receivedAtMs: number; clockOffsetMs: number };
groups: readonly { hourIndex: number; avg: number; max: number; min: number }[];
};
@@ -149,22 +146,6 @@ export function convertRecords(records: readonly WireRecord[]): ConversionResult
* guesses. Dropping loses a page; guessing corrupts the history silently.
*/
function convertHourly(record: WireHourlyRecord, result: ConversionResult): void {
if (record.metric === "heartRate" && record.latest) {
const { timestampSeconds, value, receivedAtMs, clockOffsetMs } = record.latest;
const startMs = timestampSeconds * 1000 - clockOffsetMs;
// Invert the existing handshake clock shift, never replace measurement time
// with reception time or snap it onto an invented ten-minute bucket.
// Older pages can mix clock domains: only accept a recent live reading.
if (Number.isSafeInteger(timestampSeconds) && Number.isSafeInteger(receivedAtMs)
&& Number.isFinite(clockOffsetMs) && Number.isInteger(value) && value > 0 && value <= 300
&& startMs >= 946684800000 && startMs <= receivedAtMs + 120_000
&& receivedAtMs - startMs <= 20 * 60_000) {
result.samples.push({ metric: "heartRate", startMs, spanMs: HEART_RATE_MEASUREMENT_SPAN_MS,
min: value, max: value, avg: value, total: value });
} else {
result.skipped.push({ what: "latest heart rate", why: "invalid, stale or unresolved measurement timestamp/value" });
}
}
if (record.anchorMs === null) {
result.skipped.push({
what: `${record.metric} page, ${record.groups.length} groups`,
+14 -17
View File
@@ -240,7 +240,7 @@ function accumulateStepBuckets(
return merged;
}
function toWire(record: any, includeLatest: boolean): WireRecord | null {
function toWire(record: any): WireRecord | null {
const cmdHi = Number(record.cmdHi);
const metric = HOURLY_METRIC[cmdHi];
@@ -256,12 +256,7 @@ function toWire(record: any, includeLatest: boolean): WireRecord | null {
min: Number(group.min),
});
}
const receivedAtMs = Number(record.receivedAtMs);
const latest = includeLatest && metric === "heartRate" && Number(record.tagRaw) > 0 ? {
timestampSeconds: Number(record.tagRaw), value: Number(record.current), receivedAtMs,
clockOffsetMs: ringClockOffsetMs(receivedAtMs),
} : undefined;
return { kind: "hourly", metric, anchorMs: anchorToMs(Number(record.anchorUnixSeconds), true), groups, latest };
return { kind: "hourly", metric, anchorMs: anchorToMs(Number(record.anchorUnixSeconds), true), groups };
}
if (cmdHi === CMD_STEPS) {
@@ -396,12 +391,12 @@ type StoreResult = Omit<LiveSyncResult, "seen">;
* fails, so the caller keeps whatever it would otherwise mark as consumed.
* Shared by the live batch and the journal replay.
*/
function storeRecords(records: JavaRecordList, includeLatest = true): StoreResult {
function storeRecords(records: JavaRecordList): StoreResult {
const wire: WireRecord[] = [];
const size = records.size();
for (let i = 0; i < size; i++) {
try {
const converted = toWire(records.get(i), includeLatest);
const converted = toWire(records.get(i));
if (converted) wire.push(converted);
} catch (error) {
console.warn("health live: skipped an undecodable record", error);
@@ -485,7 +480,7 @@ function replayFrameJournalOnce(): void {
const records: JavaRecordList = ringProtocol.decodeFrameJournal(File.fromPath(journalPath).readTextSync(), after);
const size = records.size();
if (size > 0) {
const result = storeRecords(records, false);
const result = storeRecords(records);
let through = after;
for (let i = 0; i < size; i++) through = Math.max(through, Number(records.get(i).receivedAtMs));
const next: ReplayCursor = { version: JOURNAL_DECODER_VERSION, throughReceivedAtMs: through };
@@ -548,7 +543,7 @@ export function syncLiveRecords(): LiveSyncResult {
/**
* Ask the ring for a fresh pull now, rather than waiting out the automatic
* ten-minute cycle. Returns immediately; the pull itself takes ~15s on the
* 30-minute cycle. Returns immediately; the pull itself takes ~15s on the
* communicator's worker thread and lands through the next `syncLiveRecords()`.
*
* Throttled communicator-side to one a minute — see
@@ -589,17 +584,19 @@ export function startLiveHealthSync(): void {
}
/**
* Pull the ring every ten minutes, one minute after each bucket boundary.
* Pull the ring on a wall-clock-aligned cadence: :01 and :31, every hour.
*
* This collects the latest heart-rate observation at roughly the cadence
* the stock app documents, as well as the existing historical buckets.
* It does not force the sensor to take a new measurement.
* Chris, 2026-09-12: *"I think we should be polling the ring on the 30 minute
* cycle (that was my intent, not a floor honestly)."* The 30-minute value in
* `RING_HEALTH_MIN_PULL_INTERVAL_MS` was always meant as a collection rhythm
* and got built as a throttle, so a connected, stable ring pulled never —
* nothing in the system drives a pull on a timer at all.
*
* Two reasons this is aligned to the wall clock rather than a plain interval:
*
* 1. **The ring's own step buckets close on 10-minute boundaries.** Pulling on
* the boundary collects a just-closed bucket instead of a half-formed one.
* 2. **An elapsed timer drifts.** A pull at :07 sets the next at :17, then :27,
* 2. **An elapsed timer drifts.** A pull at :07 sets the next at :37, then :07,
* wandering away from the boundary it is supposed to track. Re-arming
* against the clock each time cannot drift.
*
@@ -609,7 +606,7 @@ export function startLiveHealthSync(): void {
* This only *requests* a pull. The communicator still applies its own anti-spam
* floor, so an extra call here can never hammer the ring.
*/
const ALIGNED_PULL_MINUTES = [1, 11, 21, 31, 41, 51];
const ALIGNED_PULL_MINUTES = [1, 31];
let alignedPullTimer: ReturnType<typeof setTimeout> | null = null;
function msUntilNextAlignedPull(now: Date): number {
+4 -47
View File
@@ -59,7 +59,6 @@
import {
type HealthSample,
isHeartRateMeasurement,
type Rollup,
type SampleMetric,
type SleepSession,
@@ -229,51 +228,12 @@ export class HealthStore {
// -------------------------------------------------------------------------
// Reading
/** Append-journal cursor, committed by the exporter only after server acknowledgement.
* Revisions appended to an old month are exported too; a time watermark would lose them.
*/
exportBatch(cursor: Record<string, number>, limit = 200): {
cursor: Record<string, number>; samples: HealthSample[]; sleep: SleepSession[]; scanned: number;
} {
const next = { ...cursor };
const samples: HealthSample[] = [];
const sleep: SleepSession[] = [];
let scanned = 0;
for (const name of this.backend.list().filter(candidate => /^samples-\d{4}-\d{2}\.jsonl$/.test(candidate) || candidate === SLEEP_FILE).sort()) {
const text = this.backend.read(name);
if (text === null) throw new Error("Health export could not read history");
let offset = next[name] ?? 0;
if (!Number.isSafeInteger(offset) || offset < 0 || offset > text.length) offset = 0;
while (scanned < limit) {
const end = text.indexOf("\n", offset);
if (end < 0) break; // Never consume a partially written final record.
const line = text.slice(offset, end);
offset = end + 1;
scanned++;
if (name === SLEEP_FILE) {
try {
const session = JSON.parse(line) as SleepSession;
if (session?.timeResolved === true) sleep.push(session);
} catch { /* Ignore incomplete/corrupt journal lines as the local reader does. */ }
} else {
const sample = fromLine(line);
if (sample) samples.push(sample);
}
}
next[name] = offset;
if (scanned >= limit) break;
}
return { cursor: next, samples, sleep, scanned };
}
/** Bucket samples in [startMs, endMs). Point observations are opt-in so
* existing charts and daily averages never combine two overlapping series. */
samplesInRange(startMs: number, endMs: number, includeMeasurements = false): HealthSample[] {
/** Every stored sample overlapping [startMs, endMs). Exact - reads shards. */
samplesInRange(startMs: number, endMs: number): HealthSample[] {
const out: HealthSample[] = [];
for (const name of this.shardNamesInRange(startMs, endMs)) {
for (const sample of this.loadShard(name).values()) {
if (sample.startMs >= startMs && sample.startMs < endMs
&& (includeMeasurements || !isHeartRateMeasurement(sample))) out.push(sample);
if (sample.startMs >= startMs && sample.startMs < endMs) out.push(sample);
}
}
out.sort((a, b) => a.startMs - b.startMs);
@@ -337,7 +297,6 @@ export class HealthStore {
for (const name of this.backend.list()) {
if (!name.startsWith(SAMPLE_PREFIX) || !name.endsWith(SAMPLE_SUFFIX)) continue;
for (const sample of this.loadShard(name).values()) {
if (isHeartRateMeasurement(sample)) continue;
const key = dayKey(sample.startMs);
let byMetric = perDay.get(key);
if (!byMetric) {
@@ -364,9 +323,7 @@ export class HealthStore {
private updateRollupsFor(samples: readonly HealthSample[]): void {
const file = this.loadRollups();
const touched = new Set<string>();
for (const sample of samples) {
if (!isHeartRateMeasurement(sample)) touched.add(dayKey(sample.startMs));
}
for (const sample of samples) touched.add(dayKey(sample.startMs));
for (const key of touched) {
const parts = key.split("-").map(Number);
const dayStart = new Date(parts[0]!, parts[1]! - 1, parts[2]!).getTime();
-6
View File
@@ -36,12 +36,6 @@ export function isCumulative(metric: SampleMetric): boolean {
export const HOUR_MS = 3_600_000;
export const TEN_MINUTES_MS = 600_000;
/** Point observation, not a ten-minute average. Distinct from hourly buckets. */
export const HEART_RATE_MEASUREMENT_SPAN_MS = 1;
export function isHeartRateMeasurement(sample: HealthSample): boolean {
return sample.metric === "heartRate" && sample.spanMs === HEART_RATE_MEASUREMENT_SPAN_MS;
}
export const DAY_MS = 86_400_000;
/**
-13
View File
@@ -1,13 +0,0 @@
import { Utils } from "@nativescript/core";
declare const com: any;
/** Android Keystore-backed, excluded from backups. Never falls back to plain settings. */
export function readHealthExportSecret(): string {
if (!global.isAndroid) return "";
return String(com.faceclaw.app.FaceclawHealthExportSecret.read(Utils.android.getApplicationContext()));
}
export function writeHealthExportSecret(value: string): void {
if (!global.isAndroid) throw new Error("Health export is available on Android only");
com.faceclaw.app.FaceclawHealthExportSecret.write(Utils.android.getApplicationContext(), value);
}
+8 -35
View File
@@ -1,4 +1,3 @@
import { readHealthExportSecret, writeHealthExportSecret } from "../native/health-export-secret";
import { normalizeNightscoutThreshold, type NightscoutThresholds } from "../apps/nightscout/nightscout-alerts";
import { GESTURE_DOUBLE_CLICK, InputEvent } from "./gestures";
import { DEFAULT_BRIGHTNESS_CURVE, normalizeBrightnessCurve, brightnessCurveError } from "../g2/brightness-curve";
@@ -201,6 +200,13 @@ export class ConfigSettingEnum<TValue extends string, TId extends string = strin
}
}
export const launcherLayoutSetting = new ConfigSettingEnum({
id: "launcher-layout", label: "Layout", storageKey: "launcher.layout",
defaultValue: "alphabetical", values: ["alphabetical", "custom"] as const,
formatValue: value => value === "custom" ? "Custom" : "Alphabetical",
description: "Sort apps and folders alphabetically, or arrange icons yourself. Custom positions are remembered when switching layouts.",
});
type ConfigSettingStringOptions<TId extends string> = ConfigSettingOptions<string, TId> & {
editorTitle?: string;
glassesEditTitle?: string;
@@ -261,39 +267,6 @@ export class ConfigSettingString<TId extends string = string> extends ConfigSett
}
/** A changed credential starts a new delivery history without retaining the old secret. */
class HealthExportKeySetting extends ConfigSettingString {
get(): string { return readHealthExportSecret(); }
set(value: string): string {
const normalized = value.trim();
if (normalized !== this.get()) {
writeHealthExportSecret(normalized);
setStringSetting("health.export.cursor", "");
setStringSetting("health.export.generation", String(Number(getStringSetting("health.export.generation", "0")) + 1));
}
return normalized;
}
getValidValue(): string { return this.get(); }
}
export const healthExportEnabledSetting = new ConfigSettingBoolean({
id: "healthExportEnabled", label: "Export health data", storageKey: "health.export.enabled",
defaultValue: false, reportInAnalytics: false,
description: "Send saved R1 health history to your server over HTTPS. Retries while Faceclaw is running; phone storage is retained.",
});
export const healthExportUrlSetting = new ConfigSettingString({
id: "healthExportUrl", label: "Endpoint URL", storageKey: "health.export.url", defaultValue: "",
normalize: value => (value ?? "").trim(),
validate: value => !value || /^https:\/\/[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::\d{1,5})?(?:\/[^\s?#]*)?$/i.test(value)
? null : "Use an HTTPS URL without credentials, query or fragment",
description: "Full ingestion URL, for example https://health.undefined-dev.fr/v1/health",
});
export const healthExportKeySetting = new HealthExportKeySetting({
id: "healthExportKey", label: "API key", storageKey: "health.export.key", defaultValue: "",
inputKind: "password", formatValue: value => value ? "Configured" : "(empty)",
description: "Device-specific write-only key, stored using Android Keystore.",
});
export const batteryDisplayModeSetting = new ConfigSettingEnum<BatteryDisplayMode>({
id: "batteryDisplayMode",
label: "Style",
@@ -1714,7 +1687,7 @@ export class EditTextSettingLayer implements Layer {
for (let index = 0; index < message.length; index++) {
image.drawText(font, 22, messageTop + index * step, message[index]!, 200);
}
image.drawText(font, 22, messageTop + (message.length + 2) * step, truncateSetting(this.setting.inputKind === "password" ? this.setting.displayValue() : this.setting.get(), 52), 220);
image.drawText(font, 22, messageTop + (message.length + 2) * step, truncateSetting(this.setting.get(), 52), 220);
const error = this.setting.validationError();
if (error) wrapText(font, error, width - 48).forEach((line, index) =>
image.drawText(font, 22, messageTop + (message.length + 4 + index) * step, line, 180));
-14
View File
@@ -1,4 +1,3 @@
import { healthExportStatus, syncHealthExport } from "../../health/health-export";
import { remoteInputMenuItem } from "./remote-input-menu";
import { knownFolders } from "@nativescript/core";
import { getDefaultSmallFont } from "../../graphics/ui-fonts";
@@ -29,9 +28,6 @@ import type { LayerContext } from "../layers";
import { drawRightValueMenuItem, openModalMenu, submenuItem, type MenuItem } from "../menu";
import { shell } from "../shell/shell";
import {
healthExportEnabledSetting,
healthExportUrlSetting,
healthExportKeySetting,
anthropicApiKeySetting,
appSwitcherPositionSetting,
statusBarPositionSetting,
@@ -191,16 +187,6 @@ function settingsSections(): SettingsSection[] {
];
},
},
...(!global.isIOS ? [{
label: "Health export",
get items() { return [
toggleSettingMenuItem(healthExportEnabledSetting),
textSettingMenuItem(healthExportUrlSetting),
textSettingMenuItem(healthExportKeySetting),
{ label: "Sync now", description: healthExportStatus(), onSelect: () => { void syncHealthExport(); } },
{ label: healthExportStatus(), disabled: true, onSelect: () => {} },
]; },
}] : []),
{
label: "API Keys",
items: [
+50 -2
View File
@@ -326,7 +326,7 @@ class ShellOverlayMenuLayer extends MenuLayer {
*/
keepWindowFocus = false;
constructor(items: MenuItem[], footer: string | undefined, private readonly onClosed: () => void) {
constructor(items: MenuItem[], footer: string | undefined, private readonly onClosed: () => void, title = "System") {
// Aligned to the min-height window band (like the sidebar), wherever the
// vertical position setting currently puts it; centered over the
// application area, i.e. the part of the screen beside a side strip
@@ -334,7 +334,7 @@ class ShellOverlayMenuLayer extends MenuLayer {
// the strip overlays).
const width = 272;
const area = appViewportRect("min");
super("System", items, {
super(title, items, {
x: area.x + (((area.width - width) / 2) | 0),
y: area.y + 8,
width,
@@ -1304,6 +1304,43 @@ class Shell {
return hidden ? this.windows.filter((window) => window !== hidden) : this.windows;
}
/** Reorder visible app windows while keeping pinned/temporary slots and foreground stable. */
private moveSwitcherWindow(windowId: string, targetId: string): boolean {
const movable = this.switcherWindows().filter(window => window.closeable);
const from = movable.findIndex(window => window.windowId === windowId);
const to = movable.findIndex(window => window.windowId === targetId);
if (from < 0 || to < 0 || from === to) return false;
const foreground = this.foregroundWindow();
const ids = new Set(movable.map(window => window.windowId));
const [moved] = movable.splice(from, 1);
movable.splice(to, 0, moved!);
let index = 0;
this.windows = this.windows.map(window => ids.has(window.windowId) ? movable[index++]! : window);
if (foreground) this.selectedIndex = this.windows.indexOf(foreground);
this.config.onWindowsChanged?.();
this.config.requestShellRender();
return true;
}
/** Capture window IDs: changing titles or closing windows cannot redirect a pending move. */
private openSwitcherMoveMenu(windowId: string): void {
if (!this.screenOn || this.activeVoiceLayer || !this.stack.isAtBase()) return;
const movable = this.switcherWindows().filter(window => window.closeable);
const selected = movable.findIndex(window => window.windowId === windowId);
if (selected < 0 || movable.length < 2) return;
const items: MenuItem[] = movable.map((window, index) => ({
label: `${index + 1}. ${window.title}`,
onSelect: ctx => {
ctx.stack.pop();
this.moveSwitcherWindow(windowId, window.windowId);
},
}));
const layer = new ShellOverlayMenuLayer(items, undefined, () => this.yieldFocusToSidebar(), "Move app to position");
layer.selectItem(selected);
this.stack.push(layer);
this.config.requestShellRender();
}
/**
* The status bar items the switcher's selection can move onto, in order:
* with a bottom switcher (the selection reaches them past the last
@@ -1959,6 +1996,17 @@ class Shell {
},
}]),
);
const movableWindows = this.switcherWindows().filter(window => window.closeable);
if (movableWindows.length > 1 && movableWindows.includes(foreground)) {
items.push({
label: "Move in app switcher",
description: "Choose this open window's position in the app switcher.",
onSelect: ctx => {
ctx.stack.pop();
this.openSwitcherMoveMenu(foreground.windowId);
},
});
}
if (brightnessSetting.get() !== "auto") {
items.push({
label: "Brightness",
-71
View File
@@ -1,71 +0,0 @@
# R1 health export
Android Settings → Health export uses the existing toggle and text/password
editors. Export defaults off; URL and API key default empty. Only the API key
uses AES-GCM with Android Keystore and an AtomicFile in noBackupFilesDir. Keys
are masked on both glasses and phone. The URL/cursor use shared settings.
The API/image pipeline lives in the dedicated Infrastructure/FaceclawHealth Git
repository. Kubernetes manifests live in the Infrastructure repository under
FaceclawHealth, and SQL dashboards in GrafanaDashboards/Health. Protocol v1 sends normalized HealthSample/SleepSession
fields with original millisecond timestamps. Batches contain at most 200 records
and 240 KB. HTTPS is mandatory, redirects are refused, and only HTTP 200 with
accepted:true advances the cursor. No health content or keys are logged.
The exporter reads existing append journals, including revisions to old months,
without extra BLE pulls. Partial trailing lines are retried. Unresolved sleep
sessions and sample fixtures are excluded. Replayed data is upserted server-side.
A new URL/key resets delivery history safely. One batch runs per minute while
the Android process is alive; this adds no background service or wake lock and
does not promise synchronization while the app is stopped. Disable preserves
local history and existing server data. Watch/iOS export is outside this change.
Software validation: exporter tests for replay, revisions, failed/malformed
acknowledgements, redirects, destination/credential edits, fixtures, partial
records and overlapping requests; full JS suite, TypeScript and Android release
compilation. API tests additionally cover PostgreSQL rollback and deduplication.
Hardware/end-to-end validation remains pending: enable ring health sync, configure
the deployed URL/key, then compare measured timestamps/values and sleep durations
with Grafana. Test offline/reconnect, app restart, disable/re-enable and rotated
keys. Check key masking, log redaction and preservation of other preferences.
No firmware modification is needed.
## Latest heart-rate observations
Live HR pages also carry a last-measured timestamp and value. These are now
stored as `heartRate` with `spanMs: 1`, at the exact measurement timestamp:
this denotes a point observation, **not** a ten-minute average. Existing hourly
records retain `spanMs: 3600000`. The existing local and PostgreSQL keys include
span, so readings and summaries coexist without collisions. Equal BPM at a new
timestamp is a new measurement; repeated timestamps are deduplicated across
restarts and corrected values update the same observation. Local bucket charts
and daily rollups exclude points, including when the cache is rebuilt.
The existing aligned ring pull changes from :01/:31 to :01/:11/:21/:31/:41/:51.
This is a collection cadence, not a sensor setting or a guarantee of six readings
per hour. It uses the same ring worker, connection windows and anti-spam guards;
it makes more collection attempts than before. Offline gaps remain gaps and
there is no new background service. The exporter still sends at most one batch
per minute while the Android process runs.
Timestamp handling deliberately retains the current handshake's legacy clock
convention, inverting its existing phone-timezone offset once. Only a live point
within 20 minutes of page reception and no more than two minutes in the future
is accepted; invalid/missing timestamps and BPM outside 1–300 are skipped.
Reception time is never substituted for measurement time. Old frame-journal
replay continues restoring hourly history but does not reconstruct point readings:
old pages may mix clock domains. No firmware/time-sync migration is attempted.
A timezone change around measurement or an older value can therefore leave a gap;
correct placement across such transitions still requires hardware validation.
The deployed v1 API already accepts span 1 and upserts on device/metric/time/span.
No API image, schema migration, Infrastructure change or key rotation is needed.
The Grafana overview shows separate hourly-average and latest-reading series,
with point markers for readings, not interpolated ten-minute averages.
Software checks cover latest-page conversion, invalid/stale/future readings,
timezone offsets, restart/deduplication, unchanged hourly rollups, export and
all six scheduling slots. Hardware checks remain pending: record raw/current
measurement times across several pulls, compare BPM/time with the stock app,
and check reconnect, timezone/DST transitions and collection battery impact.
+23
View File
@@ -0,0 +1,23 @@
# Launcher folders and layouts
Open the Apps window's app menu (tap then hold by default). Layout and New folder are available even without a single icon selected. New folder creates a persistent empty folder with an unused generated name. Select a folder, or enter it, to rename it through the existing phone text editor. Rename commits on Submit; Cancel leaves the folder unchanged. Names must be non-empty, single-line, at most 24 characters, and unique ignoring case. Delete folder requires confirmation and returns its apps to the root without uninstalling them.
Layout offers Alphabetical (the existing default) and Custom. In Custom, select an app or folder icon and choose Move icon, navigate to its destination and click to place it at that position. Double tap cancels; the watch's back from the left edge also cancels. The phone mirror can select the destination too. Moves stay within the root or current folder; Move to folder and Remove from folder remain available for changing membership. Renaming a folder preserves its root position and internal order. New apps append alphabetically after saved icons. Switching to Alphabetical retains saved custom positions for later use.
Persistence uses the existing shared settings store. The legacy launcher.folders assignment map stays compatible; new launcher.folderNames metadata preserves explicitly created/renamed empty folders. Untouched legacy folders keep disappearing when their last app is removed. launcher.layout stores the mode, and launcher.order stores root and per-folder order. Assistant folder tools remain consistent with empty folders. Existing installations retain their grouping and alphabetical layout.
Software checks cover defaults, restart, existing assignments, empty folder creation/deletion, duplicate and invalid names, rename commit/cancel, independent root/folder positions, layout toggling, new/removed apps, malformed metadata, move cancellation and deletion confirmation. TypeScript and changed-source lint are checked separately.
Hardware validation remains pending: ring row/item selection, watch directional navigation and back, moving across scroll rows, phone-mirror placement, phone rename Submit/Cancel, reopening folders and app restart. No firmware was flashed.
Independent branch validation: 1073 JavaScript tests passed, 2 skipped, 0 failed; TypeScript and changed-source lint passed.
## Open app switcher order
The system menu adds Move in app switcher when the selected window can be moved and at least two app windows are open. Its numbered position picker shows the currently open app windows in switcher order, preselects the current position, and uses window IDs internally to distinguish windows with identical titles. Choose a destination to move there, or double tap to cancel.
This arranges existing open windows independently of the launcher's Alphabetical/Custom preference. Pinned windows keep their slots and temporary status-item windows do not participate. Reordering retains the same foreground window, attention state and most-recently-used history; closing a window still returns to the most recently viewed one. New windows append as before. Open-window order lasts for those windows' lifetime; reopening the app does not restore previously closed windows or write ephemeral window IDs to settings.
Software tests cover both directions, menu integration, duplicate titles, captured source IDs, cancellation, removed source/destination, temporary and pinned windows, appending/replacing windows, foreground identity and MRU close behavior. Hardware checks remain pending for ring/watch navigation in the position picker and left/right/bottom/popup switcher placements.
Independent branch after adding open-window ordering: 1080 JavaScript tests passed, 2 skipped; TypeScript and changed-source lint passed.
@@ -40,7 +40,6 @@ function settingsEnv(initialUrl = '', initialModel = 'openai-compatible') {
},
});
const load = loader({ global: { isIOS: false, isAndroid: true } }, {
'../../health/health-export': { healthExportStatus: () => 'Export disabled', syncHealthExport() {} },
'./remote-input-menu': { remoteInputMenuItem: () => ({ label: 'Remote input' }) },
'@nativescript/core': { knownFolders: {} },
'../../graphics/ui-fonts': { getDefaultSmallFont: () => ({}) },
-122
View File
@@ -1,122 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
function setup() {
const files = new Map();
const backend = { list: () => [...files.keys()], read: name => files.get(name) ?? null,
exists: name => files.has(name), append: (name, text) => files.set(name, (files.get(name) ?? '') + text),
write: (name, text) => files.set(name, text) };
const { HealthStore } = loader()('app/health/health-store.ts');
const store = new HealthStore(backend);
const settings = new Map();
let url = 'https://health.example/v1/health', key = 'private-test-key', enabled = true, fixture = false;
let response = { status: 200, json: async () => ({ accepted: true }) };
const requests = [];
const exporter = loader({ setTimeout, setInterval }, {
'./health-store-files': { healthStore: () => store },
'./health-seed': { isFixtureData: () => fixture },
'../ui/dashboard-settings': {
healthExportEnabledSetting: { get: () => enabled },
healthExportUrlSetting: { get: () => url, validationError: () => url.startsWith('https://') ? null : 'HTTPS required' },
healthExportKeySetting: { get: () => key },
},
'../native/settings-store': { getStringSetting: (k, d) => settings.get(k) ?? d, setStringSetting: (k, v) => settings.set(k, v) },
'../util/http': { fetchTextWithUserAgent: async (url, options) => { requests.push({ url, options }); return typeof response === 'function' ? response() : response; } },
})('app/health/health-export.ts');
return { store, files, settings, exporter, requests,
configure: options => { if ('url' in options) url=options.url; if ('enabled' in options) enabled=options.enabled; if ('fixture' in options) fixture=options.fixture; if ('response' in options) response=options.response; } };
}
const sample = { metric:'heartRate',startMs:1700000000000,spanMs:3600000,min:60,max:90,avg:75,total:0 };
test('exports original measurements, acknowledges durably and catches revisions to old buckets', async () => {
const h=setup();h.store.ingestSamples([sample]);
await h.exporter.syncHealthExport();
assert.equal(h.requests.length,1);
assert.deepEqual(JSON.parse(h.requests[0].options.body),{version:1,samples:[sample],sleep:[]});
assert.equal(h.requests[0].options.dontFollowRedirects,true);
assert.ok(!h.settings.get('health.export.cursor').includes('private-test-key'));
await h.exporter.syncHealthExport();assert.equal(h.requests.length,1);
h.store.ingestSamples([{...sample,avg:80}]);await h.exporter.syncHealthExport();
assert.equal(JSON.parse(h.requests[1].options.body).samples[0].avg,80);
h.configure({url:'https://another.example/v1/health'});await h.exporter.syncHealthExport();
assert.equal(h.requests.length,3);
});
test('failed or malformed acknowledgements retain cursor for replay; no secret in status', async () => {
for (const response of [{status:401},{status:503},{status:302},{status:200,json:async()=>({})},()=>Promise.reject(new Error('private-test-key'))]) {
const h=setup();h.store.ingestSamples([sample]);h.configure({response});await h.exporter.syncHealthExport();
assert.equal(h.settings.has('health.export.cursor'),false);
assert.ok(!h.exporter.healthExportStatus().includes('private-test-key'));
h.configure({response:{status:200,json:async()=>({accepted:true})}});
await h.exporter.syncHealthExport();assert.equal(h.requests.length,2);
}
});
test('disabled export, fixtures, missing key configuration and HTTP never upload', async () => {
for (const config of [{enabled:false},{fixture:true},{url:'http://health.example/v1/health'},{url:''}]) {
const h=setup();h.store.ingestSamples([sample]);h.configure(config);
await h.exporter.syncHealthExport();assert.equal(h.requests.length,0);
}
});
test('bounded batches preserve partial lines, unresolved sleep and late appends', () => {
const h=setup();h.store.ingestSamples([sample]);
const name=[...h.files.keys()].find(n=>n.startsWith('samples-'));
const first=h.store.exportBatch({},1);assert.equal(first.scanned,1);
const second=h.store.exportBatch(first.cursor,200);assert.equal(second.samples.length,1);
h.files.set(name,h.files.get(name)+'{"m":');
const partial=h.store.exportBatch(second.cursor);assert.equal(partial.scanned,0);
h.files.set(name,h.files.get(name)+'"hrv","t":1700000000000,"s":3600000,"n":1,"x":3,"a":2,"u":0}\n');
assert.equal(h.store.exportBatch(partial.cursor).samples[0].metric,'hrv');
h.files.set('sleep.jsonl',JSON.stringify({timeResolved:false,startMs:12})+'\n');
assert.equal(h.store.exportBatch({}).sleep.length,0);
});
test('concurrent ticks and changed credentials cannot incorrectly acknowledge a batch', async () => {
const h=setup();h.store.ingestSamples([sample]);let release;
h.configure({response:()=>new Promise(resolve=>{release=resolve;})});
const first=h.exporter.syncHealthExport();await h.exporter.syncHealthExport();
assert.equal(h.requests.length,1);
h.settings.set('health.export.generation','1');release({status:200,json:async()=>({accepted:true})});
await first;assert.equal(h.settings.has('health.export.cursor'),false);
});
test('large sleep histories split into bounded bodies without losing sessions', async () => {
const h=setup();
const sessions=Array.from({length:6},(_,i)=>({timeResolved:true,startMs:1700000000000+i*86400000,
endMs:1700028800000+i*86400000,dayStartMs:1699920000000+i*86400000,
totalSec:28000,wakeSec:800,remSec:4000,lightSec:18000,deepSec:6000,
segments:Array.from({length:2000},()=>({stageId:2,halfMinutes:1}))}));
h.files.set('sleep.jsonl',sessions.map(s=>JSON.stringify(s)+'\n').join(''));
for(let i=0;i<10;i++) await h.exporter.syncHealthExport();
assert.ok(h.requests.length>1);
assert.ok(h.requests.every(r=>r.options.body.length<=240000));
assert.equal(h.requests.reduce((n,r)=>n+JSON.parse(r.options.body).sleep.length,0),sessions.length);
});
test('point heart rates and hourly summaries export separately with original timestamps', async () => {
const h = setup();
const point = { ...sample, spanMs: 1, startMs: sample.startMs + 123456, min: 72, max: 72, avg: 72, total: 72 };
h.store.ingestSamples([sample, point]);
await h.exporter.syncHealthExport();
const body = JSON.parse(h.requests[0].options.body);
assert.deepEqual(body.samples, [sample, point]);
h.store.resetCache();
assert.equal(h.store.ingestSamples([point]), 0);
await h.exporter.syncHealthExport();
assert.equal(h.requests.length, 1);
});
test('a corrected point replaces its old value without changing hourly summaries', async () => {
const h = setup();
const point = { ...sample, spanMs: 1, min: 72, max: 72, avg: 72, total: 72 };
h.store.ingestSamples([sample, point]);
await h.exporter.syncHealthExport();
const correction = { ...point, min: 74, max: 74, avg: 74, total: 74 };
h.store.ingestSamples([correction]);
await h.exporter.syncHealthExport();
assert.deepEqual(JSON.parse(h.requests[1].options.body).samples, [correction]);
assert.equal(h.store.samplesInRange(sample.startMs, sample.startMs + 1, true).length, 2);
assert.equal(h.store.samplesInRange(sample.startMs, sample.startMs + 1)[0].avg, sample.avg);
});
@@ -1,48 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { loader } = require('./helpers/load-typescript.cjs');
const { convertRecords } = loader()('app/health/health-ingest.ts');
const receivedAtMs = Date.UTC(2026, 10, 8, 12);
const page = {
kind: 'hourly', metric: 'heartRate', anchorMs: receivedAtMs,
groups: [{ hourIndex: 0, min: 50, max: 90, avg: 65 }],
latest: { timestampSeconds: (receivedAtMs - 60000) / 1000, value: 72, receivedAtMs, clockOffsetMs: 0 },
};
test('latest observation remains a point, independent of hourly averages and page anchor', () => {
const result = convertRecords([{ ...page, anchorMs: null }]);
assert.equal(result.samples.length, 1);
assert.equal(result.samples[0].spanMs, 1);
assert.equal(result.samples[0].startMs, receivedAtMs - 60000);
assert.equal(result.samples[0].min, 72);
assert.equal(result.samples[0].max, 72);
assert.equal(result.samples[0].avg, 72);
});
test('legacy handshake timezone offset is inverted once, preserving exact timestamps', () => {
for (const clockOffsetMs of [-3600000, -7200000, 7 * 3600000, 0, -19800000]) {
const latest = { ...page.latest, clockOffsetMs,
timestampSeconds: (receivedAtMs - 60000 + clockOffsetMs) / 1000 };
const samples = convertRecords([{ ...page, latest }]).samples;
assert.equal(samples[0].startMs, receivedAtMs - 60000);
assert.equal(samples[1].spanMs, 3600000);
}
});
test('invalid, stale and future latest values never corrupt hourly history', () => {
for (const patch of [
{ value: 0 }, { value: -1 }, { value: 301 }, { value: NaN }, { value: 72.5 },
{ timestampSeconds: -1 }, { timestampSeconds: 0 }, { timestampSeconds: NaN },
{ timestampSeconds: receivedAtMs / 1000 + 121 },
{ timestampSeconds: receivedAtMs / 1000 - 1201 },
{ receivedAtMs: NaN }, { clockOffsetMs: NaN },
]) {
const result = convertRecords([{ ...page, latest: { ...page.latest, ...patch } }]);
assert.equal(result.samples.length, 1, JSON.stringify(patch));
assert.equal(result.samples[0].spanMs, 3600000);
assert.equal(result.skipped.length, 1);
}
for (const metric of ['spo2', 'hrv']) {
assert.equal(convertRecords([{ ...page, metric }]).samples.length, 1);
}
});
-53
View File
@@ -210,56 +210,3 @@ test("a failed journal replay is retried on the next sync and never blocks the l
live.syncLiveRecords();
assert.equal(failures, -1, "replay was not retried");
});
test("live latest heart rate retains measurement time and survives restart without duplicates", () => {
const measuredAt = Math.floor(Date.now() / 1000) * 1000 - 60_000;
function sync(previous, time) {
const env = liveEnvironment();
if (previous) for (const [name, text] of previous.files) env.files.set(name, text);
Object.assign(env.record, {
receivedAtMs: time + 60_000,
tagRaw: (time + new Date(time + 60_000).getTimezoneOffset() * 60_000) / 1000,
current: 72,
});
env.load("health-live").syncLiveRecords();
return env;
}
const first = sync(null, measuredAt);
const repeated = sync(first, measuredAt);
const next = sync(repeated, measuredAt + 600_000);
const store = next.load("health-store-files").healthStore();
const batch = store.exportBatch({});
const points = Array.from(batch.samples).filter(s => s.spanMs === 1);
assert.deepEqual(points.map(s => [s.startMs, s.avg]), [[measuredAt, 72], [measuredAt + 600_000, 72]]);
assert.equal(batch.samples.filter(s => s.spanMs === 3600000).length, 1);
assert.equal(store.samplesInRange(measuredAt - 86400000, measuredAt + 86400000).length, 1,
"existing health charts only see bucket samples");
const counts = () => Array.from(store.dailyRollups('heartRate', measuredAt - 86400000, measuredAt + 86400000).values()).reduce((n, r) => n + r.count, 0);
assert.equal(counts(), 1);
store.rebuildRollups();
assert.equal(counts(), 1, "rebuilding must not mix point readings with hourly aggregates");
});
test("aligned health collection requests all six ten-minute slots without timer drift", () => {
const { msUntilNextAlignedPull, ALIGNED_PULL_MINUTES } = liveEnvironment().load('health-live').__alignedPullInternals;
assert.deepEqual(Array.from(ALIGNED_PULL_MINUTES), [1, 11, 21, 31, 41, 51]);
for (const minute of ALIGNED_PULL_MINUTES) {
assert.equal(msUntilNextAlignedPull(new Date(2026, 10, 8, 12, minute, 0)), 600000);
assert.equal(msUntilNextAlignedPull(new Date(2026, 10, 8, 12, minute - 1, 30)), 30000);
}
assert.equal(msUntilNextAlignedPull(new Date(2026, 10, 8, 12, 59, 0)), 120000);
});
test("journal replay restores hourly history without assigning a clock to old point readings", () => {
const receivedAtMs = Math.floor(Date.now() / 1000) * 1000;
let replay;
const ringProtocol = { decodeFrameJournal: () => ({ size: () => 1, get: () => replay }) };
const env = liveEnvironment({ ringProtocol });
replay = { ...env.record, current: 80, receivedAtMs,
tagRaw: (receivedAtMs + new Date(receivedAtMs).getTimezoneOffset() * 60000) / 1000 };
env.files.set('/health/ring-frames.jsonl', 'synthetic journal');
env.load('health-live').syncLiveRecords();
const samples = env.load('health-store-files').healthStore().exportBatch({}).samples;
assert.equal(samples.length, 1);
assert.equal(samples[0].spanMs, 3600000);
});
+239
View File
@@ -0,0 +1,239 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
function fixture(store = new Map()) {
const storage = { getStringSetting: (key, fallback) => store.get(key) ?? fallback,
setStringSetting: (key, value) => store.set(key, value), onSettingsStoreChanged() {},
getBooleanSetting: (_key, fallback) => fallback, setBooleanSetting() {} };
function load(file, deps, suffix = '') {
const context = { exports: {}, global: { isIOS: false }, console,
require: id => deps(id) };
vm.runInNewContext(ts.transpileModule(fs.readFileSync(file, 'utf8') + suffix, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
return context.exports;
}
const layout = load('app/apps/launcher/launcher-layout.ts', () => storage);
const folders = load('app/apps/launcher/launcher-folders.ts', id => id === './launcher-layout' ? layout : storage);
const settings = load('app/ui/dashboard-settings.ts', id => {
if (id.includes('settings-store')) return storage;
if (id.includes('brightness-curve')) return require('../.test-build/app/g2/brightness-curve.js');
if (id.includes('animation-speed')) return require('../.test-build/app/ui/animation-speed.js');
return { Layer: class {}, ASSISTANT_MODEL_CHOICES: [] };
});
return { store, layout, folders, settings, load };
}
const plain = value => JSON.parse(JSON.stringify(value));
test('legacy assignments and alphabetical default survive creation, rename and restart', () => {
const f = fixture();
const original = plain(f.folders.getFolderAssignments());
assert.equal(f.settings.launcherLayoutSetting.get(), 'alphabetical');
assert.equal(f.folders.createFolder(' Français '), true);
assert.deepEqual(plain(f.folders.getFolders().get('Français')), []);
assert.deepEqual(plain(f.folders.getFolderAssignments()), original);
assert.equal(f.folders.renameFolder('Games', 'Jeux'), true);
const again = fixture(f.store);
assert.equal(again.folders.getFolderAssignments().blocks, 'Jeux');
assert.equal(again.folders.getFolderAssignments().calculator, 'Prototypes');
assert.equal(again.folders.getFolders().has('Français'), true);
assert.equal(again.folders.getFolders().has('Games'), false);
});
test('folder names reject blank, multiline, long and case-insensitive duplicate names', () => {
const f = fixture();
for (const name of ['', ' ', 'games', 'GAMES', 'x'.repeat(25), 'Two\nlines']) {
assert.equal(f.folders.createFolder(name), false, name);
assert.equal(f.folders.renameFolder('Prototypes', name), false, name);
}
assert.equal(f.folders.renameFolder('Games', 'games'), true);
assert.equal(f.folders.renameFolder('missing', 'New name'), false);
});
test('explicit empty folders persist, can be deleted and never reintroduce default assignments', () => {
const f = fixture(new Map([['launcher.folders', '{}']]));
assert.equal(f.folders.createFolder('Empty'), true);
f.folders.setAppFolder('test', 'Empty');
f.folders.setAppFolder('test', null);
assert.equal(fixture(f.store).folders.getFolders().has('Empty'), true);
assert.equal(f.folders.disbandFolder('Empty'), 0);
assert.equal(f.folders.getFolders().size, 0);
assert.equal(f.folders.unusedNewFolderName(), 'New folder');
f.folders.createFolder('New folder');
assert.equal(f.folders.unusedNewFolderName(), 'New folder 2');
});
test('deleting a non-empty folder ungroups all members without losing other assignments', () => {
const f = fixture();
assert.equal(f.folders.disbandFolder('Games'), 5);
assert.equal(f.folders.getFolderAssignments().blocks, undefined);
assert.equal(f.folders.getFolderAssignments().calculator, 'Prototypes');
assert.equal(fixture(f.store).folders.getFolders().has('Games'), false);
});
test('custom root and folder orders persist independently, survive renames and append new apps', () => {
const f = fixture();
const entries = [{ label: 'Alpha', id: 'app:a' }, { label: 'Beta', id: 'app:b' }, { label: 'Games', id: 'folder:Games' }];
const sort = (scope, custom = true) => plain(f.layout.orderLauncherEntries(entries.slice(), e => e.id, scope, custom)).map(e => e.id);
f.settings.launcherLayoutSetting.set('custom');
f.layout.moveLauncherEntry(null, entries.map(e => e.id), 'folder:Games', 'app:a');
f.layout.setLauncherOrder('Games', ['app:b', 'app:a']);
assert.deepEqual(sort(null), ['folder:Games', 'app:a', 'app:b']);
assert.deepEqual(sort('Games'), ['app:b', 'app:a', 'folder:Games']);
assert.deepEqual(sort(null, false), ['app:a', 'app:b', 'folder:Games']);
f.settings.launcherLayoutSetting.set('alphabetical');
f.settings.launcherLayoutSetting.set('custom');
assert.deepEqual(sort(null), ['folder:Games', 'app:a', 'app:b']);
f.folders.renameFolder('Games', 'Jeux');
const again = fixture(f.store);
assert.equal(again.settings.launcherLayoutSetting.get(), 'custom');
entries[2] = { label: 'Jeux', id: 'folder:Jeux' };
assert.deepEqual(sort(null), ['folder:Jeux', 'app:a', 'app:b']);
assert.deepEqual(sort('Jeux'), ['app:b', 'app:a', 'folder:Jeux']);
entries.push({ label: 'A newly installed app', id: 'app:new' });
assert.deepEqual(sort(null), ['folder:Jeux', 'app:a', 'app:b', 'app:new']);
f.folders.disbandFolder('Jeux');
f.folders.createFolder('Jeux');
assert.deepEqual(sort('Jeux'), ['app:new', 'app:a', 'app:b', 'folder:Jeux']);
});
test('malformed metadata is safe; moves tolerate removed apps and stale IDs', () => {
const f = fixture(new Map([['launcher.folderNames', '{bad'], ['launcher.order', '{bad']]));
assert.equal(f.folders.getExplicitFolderNames().length, 0);
assert.equal(f.layout.moveLauncherEntry(null, ['a', 'b'], 'missing', 'a'), false);
assert.equal(f.layout.moveLauncherEntry(null, ['a', 'b'], 'a', 'missing'), false);
assert.equal(f.layout.moveLauncherEntry(null, ['a', 'b'], 'a', 'b'), true);
assert.deepEqual(JSON.parse(f.store.get('launcher.order')).root, ['b', 'a']);
});
function launcherFixture() {
const f = fixture(new Map([['launcher.folders', '{}']]));
const layers = [], launches = [], deleted = [];
class IconGrid {
constructor(options) { this.options = options; this.index = null; }
get selectedItem() { return this.index === null ? null : this.options.items()[this.index] ?? null; }
resetSelection() { this.index = null; }
selectIndex(index) { this.index = index; }
enterRowMode() { this.index = null; }
async handleInput(event, ctx) {
if (event.type === 'click') await this.options.onActivate(this.selectedItem, ctx);
if (event.type === 'double-click' || event.type === 'swipe-left') this.options.onBack(ctx);
}
}
class MenuLayer { constructor(title, items) { this.title = title; this.items = items; } }
class EditTextSettingLayer { constructor(setting) { this.setting = setting; } }
let edit;
const ctx = { stack: {
push: layer => layers.push(layer), pop() { const layer = layers.pop(); layer?.onRemoved?.(); },
popIfTop(test) { if (layers.length && test(layers.at(-1))) { this.pop(); return true; } return false; },
}, actions: { requestRender() {}, endTextSettingEdit() {}, startTextSettingsEdit(settings, title, submit, toggle, cancel) {
edit = { setting: settings[0], submit, cancel };
} } };
const api = f.load('app/apps/launcher/launcher-app.ts', id => {
if (id === './launcher-folders') return f.folders;
if (id === './launcher-layout') return f.layout;
if (id.endsWith('/dashboard-settings')) return { ...f.settings, EditTextSettingLayer,
enumSettingMenuItem: setting => ({ label: setting.label }) };
if (id.endsWith('/icon-grid')) return { IconGrid, ICON_GRID_BAND_INSET_X: 0, ICON_GRID_HIGHLIGHT_INSET_Y: 0 };
if (id.endsWith('/menu')) return { MenuLayer };
if (id.endsWith('/shell/shell')) return { shell: { yieldFocusToSidebar() {} } };
return {};
}, '\nexport { LauncherGridLayer };');
const apps = [{ appId: 'a', label: 'Alpha', icon: 'a' }, { appId: 'b', label: 'Beta', icon: 'b' }, { appId: 'c', label: 'Gamma', icon: 'c' }];
const layer = new api.LauncherGridLayer({ apps: () => apps, launchApp: id => launches.push(id), uninstallApp: id => deleted.push(id) });
return { ...f, layer, ctx, layers, launches, deleted, apps, edit: () => edit,
choose(label) { const item = layer.menuItems().find(item => item.label === label); assert.ok(item, label); item.onSelect(ctx); } };
}
test('launcher menu is available in row mode and supports empty folder creation and entry', async () => {
const h = launcherFixture();
assert.deepEqual(plain(h.layer.menuItems().map(item => item.label)), ['Layout', 'New folder']);
h.choose('New folder');
const folder = h.layer.entries().find(entry => entry.kind === 'folder');
assert.equal(folder.name, 'New folder');
await h.layer.openEntry(folder);
assert.equal(h.layer.currentFolder, 'New folder');
assert.equal(h.layer.entries().length, 0);
assert.ok(h.layer.menuItems().some(item => item.label === 'Rename folder'));
});
test('folder rename uses the existing editor, commits on submit only, and preserves open folder', async () => {
const h = launcherFixture(); h.choose('New folder');
await h.layer.openEntry(h.layer.entries().find(entry => entry.kind === 'folder'));
h.choose('Rename folder');
h.edit().setting.set('Renommé');
assert.equal(h.layer.menuItems().length, 0);
assert.equal(h.folders.getFolders().has('New folder'), true);
h.edit().cancel();
assert.equal(h.folders.getFolders().has('Renommé'), false);
h.choose('Rename folder');
h.edit().setting.set('Renommé');
h.edit().submit();
assert.equal(h.layer.currentFolder, 'Renommé');
assert.equal(h.folders.getFolders().has('New folder'), false);
assert.equal(h.layers.length, 0);
});
test('moving icons reorders without launching; cancellation and alphabetical mode preserve order', async () => {
const h = launcherFixture();
h.layer.grid.selectIndex(0);
assert.equal(h.layer.menuItems().some(item => item.label === 'Move icon'), false);
h.settings.launcherLayoutSetting.set('custom');
h.choose('Move icon');
h.layer.grid.selectIndex(2);
await h.layer.handleInput({ type: 'click' }, h.ctx);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c', 'a']);
assert.equal(h.launches.length, 0);
h.choose('Move icon');
h.layer.grid.selectIndex(0);
await h.layer.handleInput({ type: 'double-click' }, h.ctx);
assert.equal(h.layer.moving, null);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c', 'a']);
h.settings.launcherLayoutSetting.set('alphabetical');
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['a', 'b', 'c']);
h.settings.launcherLayoutSetting.set('custom');
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c', 'a']);
});
test('folder moves stay inside their scope, folder deletion is confirmed and apps are not uninstalled', async () => {
const h = launcherFixture(); h.folders.createFolder('Dossier');
h.folders.setAppFolder('a', 'Dossier'); h.folders.setAppFolder('b', 'Dossier');
await h.layer.openEntry(h.layer.entries().find(entry => entry.kind === 'folder'));
h.settings.launcherLayoutSetting.set('custom'); h.layer.grid.selectIndex(0);
h.choose('Move icon'); await h.layer.openEntry(h.layer.entries()[1]);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'a']);
h.choose('Delete folder');
assert.equal(h.folders.getFolders().has('Dossier'), true);
h.layers.at(-1).items[0].onSelect(h.ctx);
assert.equal(h.folders.getFolders().has('Dossier'), false);
assert.equal(h.layer.currentFolder, null);
assert.equal(h.layer.entries().length, 3);
assert.equal(h.deleted.length, 0);
});
test('legacy folders with removed apps disappear while explicit empty folders remain', async () => {
const h = launcherFixture();
h.folders.setAppFolder('a', 'Legacy');
await h.layer.openEntry(h.layer.entries().find(entry => entry.kind === 'folder'));
h.apps.splice(0, 1);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c']);
assert.equal(h.layer.currentFolder, null);
h.folders.createFolder('Empty');
await h.layer.openEntry(h.layer.entries().find(entry => entry.kind === 'folder'));
assert.equal(h.layer.entries().length, 0);
assert.equal(h.layer.currentFolder, 'Empty');
});
test('removing the source during a move cancels without launching or corrupting order', async () => {
const h = launcherFixture(); h.settings.launcherLayoutSetting.set('custom');
h.layer.grid.selectIndex(0); h.choose('Move icon');
h.apps.splice(0, 1);
await h.layer.openEntry(h.layer.entries()[0]);
assert.equal(h.layer.moving, null);
assert.equal(h.launches.length, 0);
assert.deepEqual(plain(h.layer.entries().map(entry => entry.appId)), ['b', 'c']);
});
+154
View File
@@ -0,0 +1,154 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const ts = require('typescript');
function fixture() {
const source = ts.createSourceFile('shell.ts', fs.readFileSync('app/ui/shell/shell.ts', 'utf8'), ts.ScriptTarget.Latest, true);
const cls = source.statements.find(n => ts.isClassDeclaration(n) && n.name.text === 'Shell');
const names = new Set(['moveSwitcherWindow', 'openSwitcherMoveMenu', 'switcherWindows', 'foregroundWindow',
'openEscapeMenu', 'registerWindow', 'removeWindow', 'noteWindowVisible', 'mostRecentWindowIndex']);
const methods = cls.members.filter(n => names.has(n.name?.getText(source)));
assert.equal(methods.length, names.size);
const overlay = source.statements.find(n => ts.isClassDeclaration(n) && n.name.text === 'ShellOverlayMenuLayer');
class MenuLayer {
constructor(title, items) { this.title = title; this.items = items; }
selectItem(index) { this.selectedIndex = index; }
}
const context = { exports: {}, MenuLayer, appViewportRect: () => ({ x: 0, y: 0, width: 576 }),
CONTEXT_MENU_DIM: 0.5, brightnessSetting: { get: () => 'auto' }, makeInputEvent: e => e,
appFullscreenSetting: () => ({ get: () => false }), appKeepAwakeSetting: () => ({ label: 'Keep screen awake' }),
toggleSettingMenuItem: setting => ({ label: setting.label }),
swapMenuGesturesSetting: { get: () => false }, GESTURE_SHORT_THEN_LONG_PRESS: 'tap-hold',
};
vm.runInNewContext(ts.transpileModule(`${overlay.getText(source)}\nexport class Shell { ${methods.map(n => n.getText(source)).join('\n')} }`, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText, context);
const s = new context.exports.Shell();
const foregroundCalls = [], closed = [], input = [];
const window = (windowId, appId = windowId, closeable = true, title = windowId) => ({
windowId, appId, closeable, title, requestRender() {},
setForeground: value => foregroundCalls.push([windowId, value]),
close: () => closed.push(windowId), handleInput: event => input.push([windowId, event.type]),
});
const launcher = window('launcher', 'launcher', false, 'Apps');
const first = window('terminal:one', 'terminal', true, 'Terminal');
const second = window('terminal:two', 'terminal', true, 'Terminal');
const third = window('calendar', 'calendar', true, 'Calendar');
const layers = [];
let changed = 0, renders = 0;
Object.assign(s, {
windows: [launcher, first, second, third], selectedIndex: 1, focus: 'sidebar', screenOn: true,
attention: new Map(), mruWindowIds: ['terminal:one', 'calendar', 'terminal:two', 'launcher'],
config: { voiceInputEnabled: false, onWindowsChanged: () => changed++, requestShellRender: () => renders++ },
yieldFocusToSidebar() { this.focus = 'sidebar'; },
stack: { isAtBase: () => !layers.length, push: layer => layers.push(layer),
pop: () => layers.pop()?.onRemoved?.() },
});
return { s, launcher, first, second, third, window, foregroundCalls, closed, input,
ids: () => Array.from(s.windows, w => w.windowId), changed: () => changed, renders: () => renders,
menu: () => layers.at(-1), choose(label) {
const item = layers.at(-1).items.find(item => item.label === label);
assert.ok(item, label); item.onSelect({ stack: s.stack });
} };
}
test('moving open windows in either direction keeps foreground, MRU and pinned launcher stable', () => {
const h = fixture(); h.s.focus = 'window';
const mru = Array.from(h.s.mruWindowIds);
assert.equal(h.s.moveSwitcherWindow(h.first.windowId, h.third.windowId), true);
assert.deepEqual(h.ids(), ['launcher', 'terminal:two', 'calendar', 'terminal:one']);
assert.equal(h.s.foregroundWindow(), h.first);
assert.equal(h.s.selectedIndex, 3);
assert.equal(h.s.focus, 'window');
assert.deepEqual(Array.from(h.s.mruWindowIds), mru);
assert.deepEqual(h.foregroundCalls, []);
assert.deepEqual(h.closed, []);
assert.equal(h.changed(), 1); assert.equal(h.renders(), 1);
assert.equal(h.s.moveSwitcherWindow(h.first.windowId, h.second.windowId), true);
assert.deepEqual(h.ids(), ['launcher', 'terminal:one', 'terminal:two', 'calendar']);
assert.equal(h.s.foregroundWindow(), h.first);
});
test('system menu opens a numbered position picker and moves the captured window, even with duplicate titles', () => {
const h = fixture();
h.s.openEscapeMenu(); h.choose('Move in app switcher');
assert.equal(h.menu().title, 'Move app to position');
assert.deepEqual(Array.from(h.menu().items, item => item.label), ['1. Terminal', '2. Terminal', '3. Calendar']);
assert.equal(h.menu().selectedIndex, 0);
// A delayed focus change must not move a different app than the menu captured.
h.s.selectedIndex = 2;
h.choose('3. Calendar');
assert.deepEqual(h.ids(), ['launcher', 'terminal:two', 'calendar', 'terminal:one']);
assert.equal(h.s.foregroundWindow(), h.second);
assert.equal(h.menu(), undefined);
assert.equal(h.s.focus, 'sidebar');
});
test('cancelling the picker and choosing the current slot leave ordering unchanged', () => {
const h = fixture(); const before = h.ids();
h.s.openSwitcherMoveMenu(h.first.windowId); h.s.stack.pop();
assert.deepEqual(h.ids(), before);
h.s.openSwitcherMoveMenu(h.first.windowId); h.choose('1. Terminal');
assert.deepEqual(h.ids(), before);
assert.equal(h.changed(), 0);
});
test('closing the pending source or destination prevents a stale move from affecting another window', () => {
for (const removed of ['terminal:one', 'calendar']) {
const h = fixture(); h.s.openSwitcherMoveMenu(h.first.windowId);
h.s.removeWindow(removed);
const afterClose = h.ids();
h.choose('3. Calendar');
assert.deepEqual(h.ids(), afterClose);
assert.equal(h.menu(), undefined);
}
});
test('temporary status windows and pinned slots stay fixed, including selected status foreground', () => {
const h = fixture();
const hidden = h.window('notifications:temporary');
const pinned = h.window('another-pinned', 'pinned', false);
h.s.windows.splice(2, 0, hidden, pinned);
h.s.selectedIndex = 2;
h.s.selectedStatus = { transient: true, host: hidden, item: { key: 'notification' } };
assert.equal(h.s.moveSwitcherWindow(hidden.windowId, h.first.windowId), false);
h.s.moveSwitcherWindow(h.first.windowId, h.third.windowId);
assert.deepEqual(h.ids(), ['launcher', 'terminal:two', 'notifications:temporary', 'another-pinned', 'calendar', 'terminal:one']);
assert.equal(h.s.foregroundWindow(), hidden);
assert.equal(h.s.selectedStatus.host, hidden);
h.s.openEscapeMenu();
assert.ok(!h.menu().items.some(item => item.label === 'Move in app switcher'));
h.s.stack.pop();
h.s.openSwitcherMoveMenu(h.first.windowId);
assert.deepEqual(Array.from(h.menu().items, item => item.label), ['1. Terminal', '2. Calendar', '3. Terminal']);
});
test('new windows append, replacements keep their slot, and closing uses unchanged recency after a move', () => {
const h = fixture(); h.s.moveSwitcherWindow(h.first.windowId, h.third.windowId);
h.s.registerWindow(h.window('new'));
assert.equal(h.ids().at(-1), 'new');
const replacement = h.window(h.second.windowId, 'terminal', true, 'Renamed session');
h.s.registerWindow(replacement);
assert.equal(h.s.windows[1], replacement);
assert.equal(h.s.foregroundWindow(), h.first);
h.s.removeWindow(h.first.windowId);
assert.equal(h.s.foregroundWindow(), h.third);
});
test('pinned, missing, single-window, screen-off and overlay cases cannot start a reorder', () => {
const h = fixture(); const before = h.ids();
for (const [from, to] of [['launcher', 'calendar'], ['calendar', 'launcher'], ['missing', 'calendar']]) {
assert.equal(h.s.moveSwitcherWindow(from, to), false);
}
h.s.openSwitcherMoveMenu('missing'); assert.equal(h.menu(), undefined);
h.s.screenOn = false; h.s.openSwitcherMoveMenu(h.first.windowId); assert.equal(h.menu(), undefined);
h.s.screenOn = true; h.s.stack.push({});
h.s.openSwitcherMoveMenu(h.first.windowId); assert.equal(h.menu().title, undefined); h.s.stack.pop();
assert.deepEqual(h.ids(), before);
h.s.selectedIndex = 0; h.s.openEscapeMenu();
assert.ok(!h.menu().items.some(item => item.label === 'Move in app switcher')); h.s.stack.pop();
h.s.windows = [h.launcher, h.first]; h.s.selectedIndex = 1; h.s.openEscapeMenu();
assert.ok(!h.menu().items.some(item => item.label === 'Move in app switcher'));
});