change: improving adb connection

Signed-off-by: pakintada@gmail.com <Pakin>
This commit is contained in:
pakintada@gmail.com 2026-07-02 16:54:25 +07:00
parent fbbf0c12f4
commit d0a3b553a5
10 changed files with 320 additions and 56 deletions

View file

@ -0,0 +1,69 @@
<script lang="ts">
import { adbReconnect } from '$lib/core/stores/adbReconnectStore';
import * as adb from '$lib/core/adb/adb';
import Button from '$lib/components/ui/button/button.svelte';
import { addNotification } from '$lib/core/stores/noti';
import { page } from '$app/stores';
let pending = $derived($adbReconnect);
/**
* Determine which Android server channel to reconnect based on
* the current route — same logic as the authed layout's
* getAutoConnectChannel().
*/
function getReconnectChannel(pathname: string): 'brew' | 'recipe' | 'adb' {
if (pathname.startsWith('/tools/create-menu')) return 'recipe';
if (pathname.startsWith('/tools/brew')) return 'brew';
return 'adb';
}
async function handleConfirm() {
try {
const channel = getReconnectChannel($page.url.pathname);
if (channel === 'recipe') {
await adb.reconnectAndroidRecipeMenuServer();
} else {
await adb.reconnectAndroidServer();
}
adbReconnect.confirmReconnect();
addNotification('INFO:Android socket reconnected');
} catch (e) {
addNotification('ERR:Failed to reconnect Android socket');
// Keep the banner visible so the user can retry
}
}
function handleDismiss() {
adbReconnect.dismissReconnect();
}
</script>
{#if pending}
<div
class="fixed bottom-0 left-0 right-0 z-50 border-t border-amber-500/30 bg-amber-950/95 px-4 py-3 backdrop-blur-sm"
role="alert"
>
<div class="flex items-center justify-between gap-4">
<div class="flex items-center gap-3">
<div class="h-2.5 w-2.5 shrink-0 animate-pulse rounded-full bg-amber-400"></div>
<div>
<p class="text-sm font-medium text-amber-100">
{pending.reason}
</p>
<p class="text-xs text-amber-300/70">
Press Reconnect to restore the connection.
</p>
</div>
</div>
<div class="flex shrink-0 gap-2">
<Button variant="outline" size="sm" onclick={handleDismiss} class="border-amber-600/50 text-amber-200 hover:bg-amber-800/50">
Dismiss
</Button>
<Button size="sm" onclick={handleConfirm} class="bg-amber-600 hover:bg-amber-500">
Reconnect
</Button>
</div>
</div>
</div>
{/if}

View file

@ -32,7 +32,7 @@
import { sendCommand, sendReset } from '$lib/core/brew/command';
import { sendCommandRequest } from '$lib/core/handlers/ws_messageSender';
import { needPermission } from '$lib/core/handlers/permissionHandler';
import { isAdbWriterAvailable } from '$lib/core/stores/adbWriter';
import { isAdbWriterAlive } from '$lib/core/stores/adbWriter';
import { sendToAndroid } from '$lib/core/stores/adbWriter';
import { departmentStore } from '$lib/core/stores/departments';
@ -169,7 +169,7 @@
//
let inst = adb.getAdbInstance();
if (inst) {
logger.info('check adb writer', isAdbWriterAvailable());
logger.info('check adb writer', isAdbWriterAlive());
recipeDetailDispatch('brewNow');
} else {
logger.info('result check fail');

View file

@ -14,6 +14,7 @@ import { addNotification } from '../stores/noti';
import { handleAdbPayload } from '../handlers/adbPayloadHandler';
import { GlobalEventBus } from '../utils/eventBus';
import { adbWriter } from '../stores/adbWriter';
import { adbReconnect } from '../stores/adbReconnectStore';
import { WritableStream } from '@yume-chan/stream-extra';
import { env } from '$env/dynamic/public';
import { get } from 'svelte/store';
@ -340,6 +341,7 @@ export async function connectRecipeMenuDeviceByCred(
}
export async function reconnectAndroidRecipeMenuServer() {
adbWriter.set(null);
await connectToAndroidRecipeMenuServer(true);
}
@ -665,6 +667,9 @@ export async function pushBinary(
// NOTE: adb reverse is not work by unavailable features support
export async function reconnectAndroidServer() {
// Clear any stale writer before reconnecting so the new stream
// doesn't conflict with a dead one still referenced in the store.
adbWriter.set(null);
await connectToAndroidServer();
}
@ -707,13 +712,23 @@ async function connectToAndroidServer(maxRetries = 5) {
addNotification('INFO:Enable Brewing Mode T on machine');
(async () => {
while (true) {
const { value, done } = await reader.read();
if (done) break;
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
// Transfer ONLY the buffer, not the stream
// Type assertion (as any) fixes the overload error
(worker as any).postMessage({ type: 'CHUNK', payload: value }, [value.buffer]);
// Transfer ONLY the buffer, not the stream
// Type assertion (as any) fixes the overload error
(worker as any).postMessage({ type: 'CHUNK', payload: value }, [value.buffer]);
}
} catch (e) {
logger.error('Android server read error', e);
} finally {
adbWriter.set(null);
addNotification('WARN:Android server channel offline ...');
reader.cancel().catch(() => {});
// Prompt the user to reconnect instead of auto-reconnecting
adbReconnect.requestReconnect('Android server disconnected');
}
})();
return;
@ -827,18 +842,16 @@ async function connectToAndroidRecipeMenuServerOnce(notifyFailure = true, retryO
adbWriter.set(null);
addNotification('WARN:Android recipe menu channel offline ...');
reader.cancel().catch(() => {});
if (retryOnFailure) {
scheduleRecipeMenuAndroidServerReconnect();
}
// Prompt the user to reconnect instead of auto-scheduling
adbReconnect.requestReconnect('Android recipe menu disconnected');
}
})();
} catch (err) {
logger.error('Recipe menu connection failed. Suspect java running or not', err);
adbWriter.set(null);
if (notifyFailure) addNotification('ERR:Fail to enable Android recipe menu channel');
if (retryOnFailure) {
scheduleRecipeMenuAndroidServerReconnect();
}
// Prompt the user to reconnect instead of auto-scheduling
adbReconnect.requestReconnect('Android recipe menu connection failed');
}
}

View file

@ -0,0 +1,68 @@
/**
* ADB reconnection prompt store.
*
* When the Android server socket dies, instead of silently reconnecting
* in the background, we surface a persistent banner asking the user to
* confirm the reconnection. This gives the user control over when the
* USB/TCP handshake happens (it can be disruptive) while still making
* it obvious that the connection is down.
*
* Flow:
* 1. Stream dies or write fails `requestReconnect('reason')`
* 2. Banner appears on every authed page
* 3. User taps "Reconnect" `confirmReconnect()` fires the
* stored callback, then clears the pending state.
* 4. User dismisses `dismissReconnect()` clears the state
* without reconnecting.
*/
import { writable, get } from 'svelte/store';
export interface ReconnectRequest {
/** Human-readable reason (shown in the banner). */
reason: string;
/** Timestamp when the reconnect was requested. */
requestedAt: Date;
}
function createAdbReconnectStore() {
const { subscribe, set } = writable<ReconnectRequest | null>(null);
return {
subscribe,
/**
* Signal that the ADB socket has died and a reconnection is needed.
* This shows the banner the user must confirm before we actually
* reconnect.
*/
requestReconnect(reason: string = 'Android socket disconnected') {
// Don't overwrite if a request is already pending
if (get({ subscribe }) !== null) return;
set({ reason, requestedAt: new Date() });
},
/**
* The user confirmed they want to reconnect.
* Callers should perform the reconnection after calling this.
*/
confirmReconnect() {
set(null);
},
/**
* The user dismissed the banner without reconnecting.
*/
dismissReconnect() {
set(null);
},
/**
* Returns whether a reconnection is currently pending.
*/
isPending(): boolean {
return get({ subscribe }) !== null;
}
};
}
export const adbReconnect = createAdbReconnectStore();

View file

@ -1,12 +1,27 @@
import { logger } from '$lib/core/utils/logger';
import { get, writable } from 'svelte/store';
import { addNotification } from './noti';
import { adbReconnect } from './adbReconnectStore';
const adbWriter: any = writable(null);
/**
* Tracks whether the Android socket was ever alive in this session.
* Used to distinguish:
* - First visit (never connected) auto-connect silently
* - Reconnection (was alive, now dead) show reconnect banner
*/
let _wasEverAlive = false;
// Subscribe to writer changes to track liveness
adbWriter.subscribe((writer: any) => {
if (writer && writer.desiredSize !== null && writer.desiredSize !== undefined) {
_wasEverAlive = true;
}
});
async function sendToAndroid(message: any) {
let writer: any = get(adbWriter);
// logger.info('writer', writer);
if (!writer) {
addNotification('ERR:No active Android connection');
return false;
@ -15,26 +30,65 @@ async function sendToAndroid(message: any) {
const encoder = new TextEncoder();
const serializedMessage = JSON.stringify(message);
await writer.write(encoder.encode(serializedMessage + '\n'));
// logger.info('[ADB] sent', {
// type: message?.type,
// bytes: serializedMessage.length,
// productCode: message?.payload?.data?.productCode,
// batchCount: Array.isArray(message?.payload?.data) ? message.payload.data.length : undefined,
// batchProductCodes: Array.isArray(message?.payload?.data)
// ? message.payload.data.map((menu: any) => menu?.productCode)
// : undefined
// });
return true;
} catch (error) {
logger.error('write failed', error);
// The underlying stream is dead — clear the writer so
// callers don't keep trying to use a stale reference.
adbWriter.set(null);
addNotification('ERR:Failed to send message to Android');
// Prompt the user to reconnect (this was alive before → reconnection)
adbReconnect.requestReconnect('Android socket write failed');
return false;
}
}
// helper function for checking if connection is ok
/**
* Check whether the ADB writer store currently holds a reference.
*
* This only checks if a writer object is present it does NOT
* guarantee the underlying stream is alive. Use {@link isAdbWriterAlive}
* in page code to verify + reconnect if needed.
*/
function isAdbWriterAvailable() {
return get(adbWriter) != null;
}
export { sendToAndroid, adbWriter, isAdbWriterAvailable };
/**
* Attempt a lightweight probe to check if the writer's stream is still
* writable. Returns `true` if the writer appears alive, `false` if
* the stream has been closed or the writer is stale.
*
* The probe checks `writer.desiredSize` a standard
* `WritableStreamDefaultWriter` property that returns `null` once
* the stream has been closed or errored.
*
* If a stale writer is detected (was alive, now dead), the reconnect
* banner is triggered.
*/
function isAdbWriterAlive(): boolean {
const writer: any = get(adbWriter);
if (!writer) return false;
// WritableStreamDefaultWriter.desiredSize is null after close/error
if (writer.desiredSize === null) {
adbWriter.set(null);
adbReconnect.requestReconnect('Android socket is stale');
return false;
}
return true;
}
/**
* Returns `true` if the Android socket was ever successfully connected
* in this browser session.
*
* Used to decide between auto-connect (first visit) and prompted
* reconnect (socket died after being alive).
*/
function wasAndroidSocketEverAlive(): boolean {
return _wasEverAlive;
}
export { sendToAndroid, adbWriter, isAdbWriterAvailable, isAdbWriterAlive, wasAndroidSocketEverAlive };

View file

@ -15,18 +15,26 @@
* inspector.error('auth failure', uid) // always visible
*/
import { configureSync, getConfig, getConsoleSink, withFilter, getLogger } from '@logtape/logtape';
// ---------------------------------------------------------------------------
// Environment helpers
// ---------------------------------------------------------------------------
const IS_DEV = import.meta.env.DEV;
const ENV_LOG_LEVEL = (import.meta.env.PUBLIC_APP_LOG_LEVEL as string) || (IS_DEV ? 'trace' : 'info');
import type { LogLevel } from '@logtape/logtape';
// ---------------------------------------------------------------------------
// LogTape configuration (idempotent — uses getConfig() not a local flag)
// ---------------------------------------------------------------------------
/**
* Resolve the log level lazily (not at module-eval time).
*
* import.meta.env is undefined when Vite loads vite.config.ts, so we
* must not read it at the top level. Deferring to first use ensures
* Vite has finished initialising by the time we read it.
*/
function resolveLogLevel(): LogLevel {
const env = import.meta.env as Record<string, string | boolean | undefined> | undefined;
const isDev = env?.DEV ?? (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production');
const configured = env?.PUBLIC_APP_LOG_LEVEL as string | undefined;
return (configured || (isDev ? 'trace' : 'info')) as LogLevel;
}
function ensureConfigured() {
// Vite evaluates the config module twice during build (SSR + client).
// A local `_configured` boolean resets between evaluations, so we
@ -41,7 +49,7 @@ function ensureConfigured() {
{
category: ['supra-app'],
sinks: ['console'],
lowestLevel: ENV_LOG_LEVEL as 'trace' | 'debug' | 'info' | 'warning' | 'error' | 'fatal',
lowestLevel: resolveLogLevel(),
},
{
category: ['supra-app', 'inspector'],