mobile-voice commit
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"plugins": {
|
||||
"figma": {
|
||||
"enabled": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
|
||||
|
||||
# dependencies
|
||||
node_modules/
|
||||
|
||||
# Expo
|
||||
.expo/
|
||||
dist/
|
||||
web-build/
|
||||
expo-env.d.ts
|
||||
|
||||
# Native
|
||||
.kotlin/
|
||||
*.orig.*
|
||||
*.jks
|
||||
*.p8
|
||||
*.p12
|
||||
*.key
|
||||
*.mobileprovision
|
||||
|
||||
# Metro
|
||||
.metro-health-check*
|
||||
|
||||
# debug
|
||||
npm-debug.*
|
||||
yarn-debug.*
|
||||
yarn-error.*
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
|
||||
app-example
|
||||
|
||||
# generated native folders
|
||||
/ios
|
||||
/android
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
# Mobile Voice
|
||||
|
||||
Expo app for voice dictation and OpenCode session monitoring.
|
||||
|
||||
## Current monitoring behavior
|
||||
|
||||
- Foreground: app reads OpenCode SSE (`GET /event`) and updates monitor status live.
|
||||
- Background/terminated: app relies on APNs notifications sent by `apn-relay`.
|
||||
- The app registers its native APNs device token with relay route `POST /v1/device/register`.
|
||||
|
||||
## App requirements
|
||||
|
||||
- Use a development build or production build (not Expo Go).
|
||||
- `expo-notifications` plugin is enabled with `enableBackgroundRemoteNotifications: true`.
|
||||
- Notification permission must be granted.
|
||||
|
||||
## Server entry fields in app
|
||||
|
||||
When adding a server, provide:
|
||||
|
||||
- OpenCode URL
|
||||
- APN relay URL
|
||||
- Relay shared secret
|
||||
|
||||
Default APN relay URL: `https://relay.opencode.ai`
|
||||
|
||||
The app uses these values to:
|
||||
|
||||
- send prompts to OpenCode
|
||||
- register/unregister APNs token with relay
|
||||
- receive background push updates for monitored sessions
|
||||
|
||||
## Local dev
|
||||
|
||||
```bash
|
||||
npx expo start
|
||||
```
|
||||
|
||||
Use your machine LAN IP / reachable host values for OpenCode and relay when testing on a physical device.
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
{
|
||||
"expo": {
|
||||
"name": "mobile-voice",
|
||||
"slug": "mobile-voice",
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/images/icon.png",
|
||||
"scheme": "mobilevoice",
|
||||
"userInterfaceStyle": "automatic",
|
||||
"ios": {
|
||||
"icon": "./assets/expo.icon",
|
||||
"bundleIdentifier": "com.anomalyco.mobilevoice",
|
||||
"infoPlist": {
|
||||
"NSMicrophoneUsageDescription": "This app needs microphone access for live speech-to-text dictation."
|
||||
}
|
||||
},
|
||||
"android": {
|
||||
"adaptiveIcon": {
|
||||
"backgroundColor": "#E6F4FE",
|
||||
"foregroundImage": "./assets/images/android-icon-foreground.png",
|
||||
"backgroundImage": "./assets/images/android-icon-background.png",
|
||||
"monochromeImage": "./assets/images/android-icon-monochrome.png"
|
||||
},
|
||||
"permissions": ["RECORD_AUDIO", "POST_NOTIFICATIONS"],
|
||||
"predictiveBackGestureEnabled": false
|
||||
},
|
||||
"web": {
|
||||
"output": "static",
|
||||
"favicon": "./assets/images/favicon.png"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
[
|
||||
"expo-splash-screen",
|
||||
{
|
||||
"backgroundColor": "#121212",
|
||||
"android": {
|
||||
"image": "./assets/images/splash-icon.png",
|
||||
"imageWidth": 76
|
||||
}
|
||||
}
|
||||
],
|
||||
"react-native-audio-api",
|
||||
"expo-asset",
|
||||
"expo-audio",
|
||||
[
|
||||
"expo-notifications",
|
||||
{
|
||||
"enableBackgroundRemoteNotifications": true
|
||||
}
|
||||
]
|
||||
],
|
||||
"experiments": {
|
||||
"typedRoutes": true,
|
||||
"reactCompiler": true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
|
@ -0,0 +1,3 @@
|
|||
<svg width="652" height="606" viewBox="0 0 652 606" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M353.554 0H298.446C273.006 0 249.684 14.6347 237.962 37.9539L4.37994 502.646C-1.04325 513.435 -1.45067 526.178 3.2716 537.313L22.6123 582.918C34.6475 611.297 72.5404 614.156 88.4414 587.885L309.863 222.063C313.34 216.317 319.439 212.826 326 212.826C332.561 212.826 338.659 216.317 342.137 222.063L563.559 587.885C579.46 614.156 617.352 611.297 629.388 582.918L648.728 537.313C653.451 526.178 653.043 513.435 647.62 502.646L414.038 37.9539C402.316 14.6347 378.994 0 353.554 0Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 608 B |
|
After Width: | Height: | Size: 52 KiB |
|
|
@ -0,0 +1,40 @@
|
|||
{
|
||||
"fill" : {
|
||||
"automatic-gradient" : "extended-srgb:0.00000,0.47843,1.00000,1.00000"
|
||||
},
|
||||
"groups" : [
|
||||
{
|
||||
"layers" : [
|
||||
{
|
||||
"image-name" : "expo-symbol 2.svg",
|
||||
"name" : "expo-symbol 2",
|
||||
"position" : {
|
||||
"scale" : 1,
|
||||
"translation-in-points" : [
|
||||
1.1008400065293245e-05,
|
||||
-16.046875
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"image-name" : "grid.png",
|
||||
"name" : "grid"
|
||||
}
|
||||
],
|
||||
"shadow" : {
|
||||
"kind" : "neutral",
|
||||
"opacity" : 0.5
|
||||
},
|
||||
"translucency" : {
|
||||
"enabled" : true,
|
||||
"value" : 0.5
|
||||
}
|
||||
}
|
||||
],
|
||||
"supported-platforms" : {
|
||||
"circles" : [
|
||||
"watchOS"
|
||||
],
|
||||
"squares" : "shared"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 384 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 780 KiB |
|
After Width: | Height: | Size: 324 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 215 B |
|
After Width: | Height: | Size: 347 B |
|
After Width: | Height: | Size: 468 B |
|
After Width: | Height: | Size: 253 B |
|
After Width: | Height: | Size: 343 B |
|
After Width: | Height: | Size: 479 B |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
|
@ -0,0 +1,7 @@
|
|||
module.exports = function (api) {
|
||||
api.cache(true);
|
||||
return {
|
||||
presets: ['babel-preset-expo'],
|
||||
plugins: ['react-native-reanimated/plugin'],
|
||||
};
|
||||
};
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
const { getDefaultConfig } = require('expo/metro-config');
|
||||
|
||||
const config = getDefaultConfig(__dirname);
|
||||
|
||||
// Required for react-native-executorch model files
|
||||
config.resolver.assetExts.push('pte', 'bin');
|
||||
|
||||
module.exports = config;
|
||||
|
|
@ -0,0 +1 @@
|
|||
- While the model is loading for the first time, there should be some fun little like onboarding sequence that you can go through that makes sure the model is automated properly.
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
{
|
||||
"name": "mobile-voice",
|
||||
"main": "expo-router/entry",
|
||||
"version": "1.0.0",
|
||||
"scripts": {
|
||||
"start": "expo start",
|
||||
"relay": "echo 'Use packages/apn-relay for APNs relay server'",
|
||||
"relay:legacy": "node ./relay/opencode-relay.mjs",
|
||||
"reset-project": "node ./scripts/reset-project.js",
|
||||
"android": "expo run:android",
|
||||
"ios": "expo run:ios",
|
||||
"web": "expo start --web",
|
||||
"lint": "expo lint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@react-navigation/bottom-tabs": "^7.15.5",
|
||||
"@react-navigation/elements": "^2.9.10",
|
||||
"@react-navigation/native": "^7.1.33",
|
||||
"expo": "~55.0.9",
|
||||
"expo-asset": "~55.0.10",
|
||||
"expo-audio": "~55.0.9",
|
||||
"expo-constants": "~55.0.9",
|
||||
"expo-device": "~55.0.10",
|
||||
"expo-file-system": "~55.0.12",
|
||||
"expo-font": "~55.0.4",
|
||||
"expo-glass-effect": "~55.0.8",
|
||||
"expo-haptics": "~55.0.9",
|
||||
"expo-image": "~55.0.6",
|
||||
"expo-linking": "~55.0.9",
|
||||
"expo-notifications": "~55.0.14",
|
||||
"expo-router": "~55.0.8",
|
||||
"expo-splash-screen": "~55.0.13",
|
||||
"expo-status-bar": "~55.0.4",
|
||||
"expo-symbols": "~55.0.5",
|
||||
"expo-system-ui": "~55.0.11",
|
||||
"expo-task-manager": "~55.0.10",
|
||||
"expo-web-browser": "~55.0.10",
|
||||
"react": "19.2.0",
|
||||
"react-dom": "19.2.0",
|
||||
"react-native": "0.83.4",
|
||||
"react-native-audio-api": "^0.11.7",
|
||||
"react-native-executorch": "^0.8.0",
|
||||
"react-native-executorch-expo-resource-fetcher": "^0.8.0",
|
||||
"react-native-gesture-handler": "~2.30.0",
|
||||
"react-native-reanimated": "4.2.1",
|
||||
"react-native-safe-area-context": "~5.6.2",
|
||||
"react-native-screens": "~4.23.0",
|
||||
"react-native-web": "~0.21.0",
|
||||
"react-native-worklets": "0.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "~19.2.2",
|
||||
"babel-preset-expo": "~55.0.8",
|
||||
"typescript": "~5.9.2"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
|
|
@ -0,0 +1,328 @@
|
|||
import { createServer } from 'node:http';
|
||||
|
||||
const PORT = Number(process.env.PORT || 8787);
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
const EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send';
|
||||
|
||||
/** @type {Map<string, {jobID: string, sessionID: string, opencodeBaseURL: string, relayBaseURL: string, expoPushToken: string, createdAt: number, done: boolean}>} */
|
||||
const jobs = new Map();
|
||||
|
||||
/** @type {Map<string, {key: string, opencodeBaseURL: string, abortController: AbortController, sessions: Set<string>, running: boolean}>} */
|
||||
const streams = new Map();
|
||||
|
||||
/** @type {Set<string>} */
|
||||
const dedupe = new Set();
|
||||
|
||||
function json(res, status, body) {
|
||||
const value = JSON.stringify(body);
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(value),
|
||||
});
|
||||
res.end(value);
|
||||
}
|
||||
|
||||
async function readJSON(req) {
|
||||
let raw = '';
|
||||
for await (const chunk of req) {
|
||||
raw += chunk;
|
||||
if (raw.length > 1_000_000) {
|
||||
throw new Error('Payload too large');
|
||||
}
|
||||
}
|
||||
if (!raw.trim()) return {};
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
|
||||
function extractSessionID(event) {
|
||||
const properties = event?.properties ?? {};
|
||||
if (typeof properties.sessionID === 'string') return properties.sessionID;
|
||||
if (properties.info && typeof properties.info === 'object' && typeof properties.info.sessionID === 'string') {
|
||||
return properties.info.sessionID;
|
||||
}
|
||||
if (properties.part && typeof properties.part === 'object' && typeof properties.part.sessionID === 'string') {
|
||||
return properties.part.sessionID;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function classifyEvent(event) {
|
||||
const type = String(event?.type || '');
|
||||
const lower = type.toLowerCase();
|
||||
|
||||
if (lower.includes('permission')) return 'permission';
|
||||
if (lower.includes('error')) return 'error';
|
||||
|
||||
if (type === 'session.status') {
|
||||
const statusType = event?.properties?.status?.type;
|
||||
if (statusType === 'idle') return 'complete';
|
||||
}
|
||||
|
||||
if (type === 'message.updated') {
|
||||
const info = event?.properties?.info;
|
||||
if (info && typeof info === 'object') {
|
||||
if (info.error) return 'error';
|
||||
if (info.role === 'assistant' && info.time && typeof info.time === 'object' && info.time.completed) {
|
||||
return 'complete';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function notificationBody(eventType) {
|
||||
if (eventType === 'complete') {
|
||||
return {
|
||||
title: 'Session complete',
|
||||
body: 'OpenCode finished your monitored prompt.',
|
||||
};
|
||||
}
|
||||
if (eventType === 'permission') {
|
||||
return {
|
||||
title: 'Action needed',
|
||||
body: 'OpenCode needs a permission decision.',
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: 'Session error',
|
||||
body: 'OpenCode reported an error for your monitored session.',
|
||||
};
|
||||
}
|
||||
|
||||
async function sendPush({ expoPushToken, eventType, sessionID, jobID }) {
|
||||
const dedupeKey = `${jobID}:${eventType}`;
|
||||
if (dedupe.has(dedupeKey)) return;
|
||||
dedupe.add(dedupeKey);
|
||||
|
||||
const text = notificationBody(eventType);
|
||||
|
||||
const payload = {
|
||||
to: expoPushToken,
|
||||
priority: 'high',
|
||||
_contentAvailable: true,
|
||||
data: {
|
||||
eventType,
|
||||
sessionID,
|
||||
jobID,
|
||||
title: text.title,
|
||||
body: text.body,
|
||||
dedupeKey,
|
||||
at: Date.now(),
|
||||
},
|
||||
};
|
||||
|
||||
const response = await fetch(EXPO_PUSH_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.text();
|
||||
throw new Error(`Push send failed (${response.status}): ${body || response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function* parseSSE(readable) {
|
||||
const reader = readable.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let pending = '';
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const next = await reader.read();
|
||||
if (next.done) break;
|
||||
|
||||
pending += decoder.decode(next.value, { stream: true });
|
||||
const blocks = pending.split(/\r?\n\r?\n/);
|
||||
pending = blocks.pop() || '';
|
||||
|
||||
for (const block of blocks) {
|
||||
const lines = block.split(/\r?\n/);
|
||||
const dataLines = [];
|
||||
for (const line of lines) {
|
||||
if (!line || line.startsWith(':')) continue;
|
||||
if (line.startsWith('data:')) {
|
||||
dataLines.push(line.slice(5).trimStart());
|
||||
}
|
||||
}
|
||||
if (dataLines.length > 0) {
|
||||
yield dataLines.join('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupStreamIfUnused(baseURL) {
|
||||
const key = baseURL.replace(/\/+$/, '');
|
||||
const entry = streams.get(key);
|
||||
if (!entry) return;
|
||||
|
||||
const stillUsed = Array.from(jobs.values()).some((job) => !job.done && job.opencodeBaseURL === key);
|
||||
if (stillUsed) return;
|
||||
|
||||
entry.abortController.abort();
|
||||
streams.delete(key);
|
||||
}
|
||||
|
||||
async function runStream(baseURL) {
|
||||
const key = baseURL.replace(/\/+$/, '');
|
||||
if (streams.has(key)) return;
|
||||
|
||||
const abortController = new AbortController();
|
||||
streams.set(key, {
|
||||
key,
|
||||
opencodeBaseURL: key,
|
||||
abortController,
|
||||
sessions: new Set(),
|
||||
running: true,
|
||||
});
|
||||
|
||||
while (!abortController.signal.aborted) {
|
||||
try {
|
||||
const response = await fetch(`${key}/event`, {
|
||||
signal: abortController.signal,
|
||||
headers: {
|
||||
Accept: 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok || !response.body) {
|
||||
throw new Error(`SSE connect failed (${response.status})`);
|
||||
}
|
||||
|
||||
for await (const data of parseSSE(response.body)) {
|
||||
if (abortController.signal.aborted) break;
|
||||
|
||||
let event;
|
||||
try {
|
||||
event = JSON.parse(data);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sessionID = extractSessionID(event);
|
||||
if (!sessionID) continue;
|
||||
|
||||
const eventType = classifyEvent(event);
|
||||
if (!eventType) continue;
|
||||
|
||||
const related = Array.from(jobs.values()).filter(
|
||||
(job) => !job.done && job.opencodeBaseURL === key && job.sessionID === sessionID,
|
||||
);
|
||||
if (related.length === 0) continue;
|
||||
|
||||
await Promise.allSettled(
|
||||
related.map(async (job) => {
|
||||
await sendPush({
|
||||
expoPushToken: job.expoPushToken,
|
||||
eventType,
|
||||
sessionID,
|
||||
jobID: job.jobID,
|
||||
});
|
||||
|
||||
if (eventType === 'complete' || eventType === 'error') {
|
||||
const current = jobs.get(job.jobID);
|
||||
if (current) current.done = true;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
if (abortController.signal.aborted) break;
|
||||
console.warn('[relay] SSE loop error:', error instanceof Error ? error.message : String(error));
|
||||
await new Promise((resolve) => setTimeout(resolve, 1200));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
if (!req.url || !req.method) {
|
||||
json(res, 400, { ok: false, error: 'Invalid request' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.url === '/health' && req.method === 'GET') {
|
||||
json(res, 200, {
|
||||
ok: true,
|
||||
activeJobs: Array.from(jobs.values()).filter((job) => !job.done).length,
|
||||
streams: streams.size,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.url === '/v1/monitor/start' && req.method === 'POST') {
|
||||
try {
|
||||
const body = await readJSON(req);
|
||||
const jobID = String(body.jobID || '').trim();
|
||||
const sessionID = String(body.sessionID || '').trim();
|
||||
const opencodeBaseURL = String(body.opencodeBaseURL || '').trim().replace(/\/+$/, '');
|
||||
const relayBaseURL = String(body.relayBaseURL || '').trim().replace(/\/+$/, '');
|
||||
const expoPushToken = String(body.expoPushToken || '').trim();
|
||||
|
||||
if (!jobID || !sessionID || !opencodeBaseURL || !expoPushToken) {
|
||||
json(res, 400, { ok: false, error: 'Missing required fields' });
|
||||
return;
|
||||
}
|
||||
|
||||
jobs.set(jobID, {
|
||||
jobID,
|
||||
sessionID,
|
||||
opencodeBaseURL,
|
||||
relayBaseURL,
|
||||
expoPushToken,
|
||||
createdAt: Date.now(),
|
||||
done: false,
|
||||
});
|
||||
|
||||
runStream(opencodeBaseURL).catch((error) => {
|
||||
console.warn('[relay] runStream failed:', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
json(res, 200, { ok: true });
|
||||
return;
|
||||
} catch (error) {
|
||||
json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (req.url === '/v1/monitor/stop' && req.method === 'POST') {
|
||||
try {
|
||||
const body = await readJSON(req);
|
||||
const jobID = String(body.jobID || '').trim();
|
||||
const token = String(body.expoPushToken || '').trim();
|
||||
|
||||
if (!jobID || !token) {
|
||||
json(res, 400, { ok: false, error: 'Missing required fields' });
|
||||
return;
|
||||
}
|
||||
|
||||
const job = jobs.get(jobID);
|
||||
if (job && job.expoPushToken === token) {
|
||||
job.done = true;
|
||||
cleanupStreamIfUnused(job.opencodeBaseURL);
|
||||
}
|
||||
|
||||
json(res, 200, { ok: true });
|
||||
return;
|
||||
} catch (error) {
|
||||
json(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
json(res, 404, { ok: false, error: 'Not found' });
|
||||
});
|
||||
|
||||
server.listen(PORT, HOST, () => {
|
||||
console.log(`[relay] listening on http://${HOST}:${PORT}`);
|
||||
});
|
||||
|
|
@ -0,0 +1,114 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* This script is used to reset the project to a blank state.
|
||||
* It deletes or moves the /src and /scripts directories to /example based on user input and creates a new /src/app directory with an index.tsx and _layout.tsx file.
|
||||
* You can remove the `reset-project` script from package.json and safely delete this file after running it.
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const readline = require("readline");
|
||||
|
||||
const root = process.cwd();
|
||||
const oldDirs = ["src", "scripts"];
|
||||
const exampleDir = "example";
|
||||
const newAppDir = "src/app";
|
||||
const exampleDirPath = path.join(root, exampleDir);
|
||||
|
||||
const indexContent = `import { Text, View, StyleSheet } from "react-native";
|
||||
|
||||
export default function Index() {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text>Edit src/app/index.tsx to edit this screen.</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
});
|
||||
`;
|
||||
|
||||
const layoutContent = `import { Stack } from "expo-router";
|
||||
|
||||
export default function RootLayout() {
|
||||
return <Stack />;
|
||||
}
|
||||
`;
|
||||
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
|
||||
const moveDirectories = async (userInput) => {
|
||||
try {
|
||||
if (userInput === "y") {
|
||||
// Create the app-example directory
|
||||
await fs.promises.mkdir(exampleDirPath, { recursive: true });
|
||||
console.log(`📁 /${exampleDir} directory created.`);
|
||||
}
|
||||
|
||||
// Move old directories to new app-example directory or delete them
|
||||
for (const dir of oldDirs) {
|
||||
const oldDirPath = path.join(root, dir);
|
||||
if (fs.existsSync(oldDirPath)) {
|
||||
if (userInput === "y") {
|
||||
const newDirPath = path.join(root, exampleDir, dir);
|
||||
await fs.promises.rename(oldDirPath, newDirPath);
|
||||
console.log(`➡️ /${dir} moved to /${exampleDir}/${dir}.`);
|
||||
} else {
|
||||
await fs.promises.rm(oldDirPath, { recursive: true, force: true });
|
||||
console.log(`❌ /${dir} deleted.`);
|
||||
}
|
||||
} else {
|
||||
console.log(`➡️ /${dir} does not exist, skipping.`);
|
||||
}
|
||||
}
|
||||
|
||||
// Create new /src/app directory
|
||||
const newAppDirPath = path.join(root, newAppDir);
|
||||
await fs.promises.mkdir(newAppDirPath, { recursive: true });
|
||||
console.log("\n📁 New /src/app directory created.");
|
||||
|
||||
// Create index.tsx
|
||||
const indexPath = path.join(newAppDirPath, "index.tsx");
|
||||
await fs.promises.writeFile(indexPath, indexContent);
|
||||
console.log("📄 src/app/index.tsx created.");
|
||||
|
||||
// Create _layout.tsx
|
||||
const layoutPath = path.join(newAppDirPath, "_layout.tsx");
|
||||
await fs.promises.writeFile(layoutPath, layoutContent);
|
||||
console.log("📄 src/app/_layout.tsx created.");
|
||||
|
||||
console.log("\n✅ Project reset complete. Next steps:");
|
||||
console.log(
|
||||
`1. Run \`npx expo start\` to start a development server.\n2. Edit src/app/index.tsx to edit the main screen.\n3. Put all your application code in /src, only screens and layout files should be in /src/app.${
|
||||
userInput === "y"
|
||||
? `\n4. Delete the /${exampleDir} directory when you're done referencing it.`
|
||||
: ""
|
||||
}`
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`❌ Error during script execution: ${error.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
rl.question(
|
||||
"Do you want to move existing files to /example instead of deleting them? (Y/n): ",
|
||||
(answer) => {
|
||||
const userInput = answer.trim().toLowerCase() || "y";
|
||||
if (userInput === "y" || userInput === "n") {
|
||||
moveDirectories(userInput).finally(() => rl.close());
|
||||
} else {
|
||||
console.log("❌ Invalid input. Please enter 'Y' or 'N'.");
|
||||
rl.close();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import React from 'react';
|
||||
import { Slot } from 'expo-router';
|
||||
import { LogBox } from 'react-native';
|
||||
import { initExecutorch } from 'react-native-executorch';
|
||||
import { ExpoResourceFetcher } from 'react-native-executorch-expo-resource-fetcher';
|
||||
import {
|
||||
configureNotificationBehavior,
|
||||
registerBackgroundNotificationTask,
|
||||
} from '@/notifications/monitoring-notifications';
|
||||
|
||||
// Initialize the ExecuTorch resource fetcher before any model hooks run
|
||||
initExecutorch({ resourceFetcher: ExpoResourceFetcher });
|
||||
|
||||
// Suppress known non-actionable warnings from third-party libs.
|
||||
LogBox.ignoreLogs([
|
||||
'RecordingNotificationManager is not implemented on iOS',
|
||||
'[React Native ExecuTorch] No content-length header',
|
||||
]);
|
||||
|
||||
configureNotificationBehavior();
|
||||
registerBackgroundNotificationTask().catch(() => {});
|
||||
|
||||
export default function RootLayout() {
|
||||
return <Slot />;
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
.expoLogoBackground {
|
||||
background-image: linear-gradient(180deg, #3c9ffe, #0274df);
|
||||
border-radius: 40px;
|
||||
width: 128px;
|
||||
height: 128px;
|
||||
}
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
import { Image } from 'expo-image';
|
||||
import { useState } from 'react';
|
||||
import { Dimensions, StyleSheet, View } from 'react-native';
|
||||
import Animated, { Easing, Keyframe } from 'react-native-reanimated';
|
||||
import { scheduleOnRN } from 'react-native-worklets';
|
||||
|
||||
const INITIAL_SCALE_FACTOR = Dimensions.get('screen').height / 90;
|
||||
const DURATION = 600;
|
||||
|
||||
export function AnimatedSplashOverlay() {
|
||||
const [visible, setVisible] = useState(true);
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
const splashKeyframe = new Keyframe({
|
||||
0: {
|
||||
transform: [{ scale: INITIAL_SCALE_FACTOR }],
|
||||
opacity: 1,
|
||||
},
|
||||
20: {
|
||||
opacity: 1,
|
||||
},
|
||||
70: {
|
||||
opacity: 0,
|
||||
easing: Easing.elastic(0.7),
|
||||
},
|
||||
100: {
|
||||
opacity: 0,
|
||||
transform: [{ scale: 1 }],
|
||||
easing: Easing.elastic(0.7),
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
entering={splashKeyframe.duration(DURATION).withCallback((finished) => {
|
||||
'worklet';
|
||||
if (finished) {
|
||||
scheduleOnRN(setVisible, false);
|
||||
}
|
||||
})}
|
||||
style={styles.backgroundSolidColor}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const keyframe = new Keyframe({
|
||||
0: {
|
||||
transform: [{ scale: INITIAL_SCALE_FACTOR }],
|
||||
},
|
||||
100: {
|
||||
transform: [{ scale: 1 }],
|
||||
easing: Easing.elastic(0.7),
|
||||
},
|
||||
});
|
||||
|
||||
const logoKeyframe = new Keyframe({
|
||||
0: {
|
||||
transform: [{ scale: 1.3 }],
|
||||
opacity: 0,
|
||||
},
|
||||
40: {
|
||||
transform: [{ scale: 1.3 }],
|
||||
opacity: 0,
|
||||
easing: Easing.elastic(0.7),
|
||||
},
|
||||
100: {
|
||||
opacity: 1,
|
||||
transform: [{ scale: 1 }],
|
||||
easing: Easing.elastic(0.7),
|
||||
},
|
||||
});
|
||||
|
||||
const glowKeyframe = new Keyframe({
|
||||
0: {
|
||||
transform: [{ rotateZ: '0deg' }],
|
||||
},
|
||||
100: {
|
||||
transform: [{ rotateZ: '7200deg' }],
|
||||
},
|
||||
});
|
||||
|
||||
export function AnimatedIcon() {
|
||||
return (
|
||||
<View style={styles.iconContainer}>
|
||||
<Animated.View entering={glowKeyframe.duration(60 * 1000 * 4)} style={styles.glow}>
|
||||
<Image style={styles.glow} source={require('@/assets/images/logo-glow.png')} />
|
||||
</Animated.View>
|
||||
|
||||
<Animated.View entering={keyframe.duration(DURATION)} style={styles.background} />
|
||||
<Animated.View style={styles.imageContainer} entering={logoKeyframe.duration(DURATION)}>
|
||||
<Image style={styles.image} source={require('@/assets/images/expo-logo.png')} />
|
||||
</Animated.View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
imageContainer: {
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
glow: {
|
||||
width: 201,
|
||||
height: 201,
|
||||
position: 'absolute',
|
||||
},
|
||||
iconContainer: {
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
width: 128,
|
||||
height: 128,
|
||||
zIndex: 100,
|
||||
},
|
||||
image: {
|
||||
position: 'absolute',
|
||||
width: 76,
|
||||
height: 71,
|
||||
},
|
||||
background: {
|
||||
borderRadius: 40,
|
||||
experimental_backgroundImage: `linear-gradient(180deg, #3C9FFE, #0274DF)`,
|
||||
width: 128,
|
||||
height: 128,
|
||||
position: 'absolute',
|
||||
},
|
||||
backgroundSolidColor: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
backgroundColor: '#208AEF',
|
||||
zIndex: 1000,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
import { Image } from 'expo-image';
|
||||
import { StyleSheet, View } from 'react-native';
|
||||
import Animated, { Keyframe, Easing } from 'react-native-reanimated';
|
||||
|
||||
import classes from './animated-icon.module.css';
|
||||
const DURATION = 300;
|
||||
|
||||
export function AnimatedSplashOverlay() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const keyframe = new Keyframe({
|
||||
0: {
|
||||
transform: [{ scale: 0 }],
|
||||
},
|
||||
60: {
|
||||
transform: [{ scale: 1.2 }],
|
||||
easing: Easing.elastic(1.2),
|
||||
},
|
||||
100: {
|
||||
transform: [{ scale: 1 }],
|
||||
easing: Easing.elastic(1.2),
|
||||
},
|
||||
});
|
||||
|
||||
const logoKeyframe = new Keyframe({
|
||||
0: {
|
||||
opacity: 0,
|
||||
},
|
||||
60: {
|
||||
transform: [{ scale: 1.2 }],
|
||||
opacity: 0,
|
||||
easing: Easing.elastic(1.2),
|
||||
},
|
||||
100: {
|
||||
transform: [{ scale: 1 }],
|
||||
opacity: 1,
|
||||
easing: Easing.elastic(1.2),
|
||||
},
|
||||
});
|
||||
|
||||
const glowKeyframe = new Keyframe({
|
||||
0: {
|
||||
transform: [{ rotateZ: '-180deg' }, { scale: 0.8 }],
|
||||
opacity: 0,
|
||||
},
|
||||
[DURATION / 1000]: {
|
||||
transform: [{ rotateZ: '0deg' }, { scale: 1 }],
|
||||
opacity: 1,
|
||||
easing: Easing.elastic(0.7),
|
||||
},
|
||||
100: {
|
||||
transform: [{ rotateZ: '7200deg' }],
|
||||
},
|
||||
});
|
||||
|
||||
export function AnimatedIcon() {
|
||||
return (
|
||||
<View style={styles.iconContainer}>
|
||||
<Animated.View entering={glowKeyframe.duration(60 * 1000 * 4)} style={styles.glow}>
|
||||
<Image style={styles.glow} source={require('@/assets/images/logo-glow.png')} />
|
||||
</Animated.View>
|
||||
|
||||
<Animated.View style={styles.background} entering={keyframe.duration(DURATION)}>
|
||||
<div className={classes.expoLogoBackground} />
|
||||
</Animated.View>
|
||||
|
||||
<Animated.View style={styles.imageContainer} entering={logoKeyframe.duration(DURATION)}>
|
||||
<Image style={styles.image} source={require('@/assets/images/expo-logo.png')} />
|
||||
</Animated.View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
alignItems: 'center',
|
||||
width: '100%',
|
||||
zIndex: 1000,
|
||||
position: 'absolute',
|
||||
top: 128 / 2 + 138,
|
||||
},
|
||||
imageContainer: {
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
glow: {
|
||||
width: 201,
|
||||
height: 201,
|
||||
position: 'absolute',
|
||||
},
|
||||
iconContainer: {
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
width: 128,
|
||||
height: 128,
|
||||
},
|
||||
image: {
|
||||
position: 'absolute',
|
||||
width: 76,
|
||||
height: 71,
|
||||
},
|
||||
background: {
|
||||
width: 128,
|
||||
height: 128,
|
||||
position: 'absolute',
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
// Not used - single page app. Kept to avoid breaking template imports.
|
||||
import { Slot } from 'expo-router';
|
||||
import React from 'react';
|
||||
|
||||
export default function AppTabs() {
|
||||
return <Slot />;
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
// Not used - single page app. Kept to avoid breaking template imports.
|
||||
import { Slot } from 'expo-router';
|
||||
import React from 'react';
|
||||
|
||||
export default function AppTabs() {
|
||||
return <Slot />;
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import { Href, Link } from 'expo-router';
|
||||
import { openBrowserAsync, WebBrowserPresentationStyle } from 'expo-web-browser';
|
||||
import { type ComponentProps } from 'react';
|
||||
|
||||
type Props = Omit<ComponentProps<typeof Link>, 'href'> & { href: Href & string };
|
||||
|
||||
export function ExternalLink({ href, ...rest }: Props) {
|
||||
return (
|
||||
<Link
|
||||
target="_blank"
|
||||
{...rest}
|
||||
href={href}
|
||||
onPress={async (event) => {
|
||||
if (process.env.EXPO_OS !== 'web') {
|
||||
// Prevent the default behavior of linking to the default browser on native.
|
||||
event.preventDefault();
|
||||
// Open the link in an in-app browser.
|
||||
await openBrowserAsync(href, {
|
||||
presentationStyle: WebBrowserPresentationStyle.AUTOMATIC,
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import React, { type ReactNode } from 'react';
|
||||
import { View, StyleSheet } from 'react-native';
|
||||
|
||||
import { ThemedText } from './themed-text';
|
||||
import { ThemedView } from './themed-view';
|
||||
|
||||
import { Spacing } from '@/constants/theme';
|
||||
|
||||
type HintRowProps = {
|
||||
title?: string;
|
||||
hint?: ReactNode;
|
||||
};
|
||||
|
||||
export function HintRow({ title = 'Try editing', hint = 'app/index.tsx' }: HintRowProps) {
|
||||
return (
|
||||
<View style={styles.stepRow}>
|
||||
<ThemedText type="small">{title}</ThemedText>
|
||||
<ThemedView type="backgroundSelected" style={styles.codeSnippet}>
|
||||
<ThemedText themeColor="textSecondary">{hint}</ThemedText>
|
||||
</ThemedView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
stepRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
},
|
||||
codeSnippet: {
|
||||
borderRadius: Spacing.two,
|
||||
paddingVertical: Spacing.half,
|
||||
paddingHorizontal: Spacing.two,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
import { Platform, StyleSheet, Text, type TextProps } from 'react-native';
|
||||
|
||||
import { Fonts, ThemeColor } from '@/constants/theme';
|
||||
import { useTheme } from '@/hooks/use-theme';
|
||||
|
||||
export type ThemedTextProps = TextProps & {
|
||||
type?: 'default' | 'title' | 'small' | 'smallBold' | 'subtitle' | 'link' | 'linkPrimary' | 'code';
|
||||
themeColor?: ThemeColor;
|
||||
};
|
||||
|
||||
export function ThemedText({ style, type = 'default', themeColor, ...rest }: ThemedTextProps) {
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
<Text
|
||||
style={[
|
||||
{ color: theme[themeColor ?? 'text'] },
|
||||
type === 'default' && styles.default,
|
||||
type === 'title' && styles.title,
|
||||
type === 'small' && styles.small,
|
||||
type === 'smallBold' && styles.smallBold,
|
||||
type === 'subtitle' && styles.subtitle,
|
||||
type === 'link' && styles.link,
|
||||
type === 'linkPrimary' && styles.linkPrimary,
|
||||
type === 'code' && styles.code,
|
||||
style,
|
||||
]}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
small: {
|
||||
fontSize: 14,
|
||||
lineHeight: 20,
|
||||
fontWeight: 500,
|
||||
},
|
||||
smallBold: {
|
||||
fontSize: 14,
|
||||
lineHeight: 20,
|
||||
fontWeight: 700,
|
||||
},
|
||||
default: {
|
||||
fontSize: 16,
|
||||
lineHeight: 24,
|
||||
fontWeight: 500,
|
||||
},
|
||||
title: {
|
||||
fontSize: 48,
|
||||
fontWeight: 600,
|
||||
lineHeight: 52,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 32,
|
||||
lineHeight: 44,
|
||||
fontWeight: 600,
|
||||
},
|
||||
link: {
|
||||
lineHeight: 30,
|
||||
fontSize: 14,
|
||||
},
|
||||
linkPrimary: {
|
||||
lineHeight: 30,
|
||||
fontSize: 14,
|
||||
color: '#3c87f7',
|
||||
},
|
||||
code: {
|
||||
fontFamily: Fonts.mono,
|
||||
fontWeight: Platform.select({ android: 700 }) ?? 500,
|
||||
fontSize: 12,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
import { View, type ViewProps } from 'react-native';
|
||||
|
||||
import { ThemeColor } from '@/constants/theme';
|
||||
import { useTheme } from '@/hooks/use-theme';
|
||||
|
||||
export type ThemedViewProps = ViewProps & {
|
||||
lightColor?: string;
|
||||
darkColor?: string;
|
||||
type?: ThemeColor;
|
||||
};
|
||||
|
||||
export function ThemedView({ style, lightColor, darkColor, type, ...otherProps }: ThemedViewProps) {
|
||||
const theme = useTheme();
|
||||
|
||||
return <View style={[{ backgroundColor: theme[type ?? 'background'] }, style]} {...otherProps} />;
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import { SymbolView } from 'expo-symbols';
|
||||
import { PropsWithChildren, useState } from 'react';
|
||||
import { Pressable, StyleSheet } from 'react-native';
|
||||
import Animated, { FadeIn } from 'react-native-reanimated';
|
||||
|
||||
import { ThemedText } from '@/components/themed-text';
|
||||
import { ThemedView } from '@/components/themed-view';
|
||||
import { Spacing } from '@/constants/theme';
|
||||
import { useTheme } from '@/hooks/use-theme';
|
||||
|
||||
export function Collapsible({ children, title }: PropsWithChildren & { title: string }) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const theme = useTheme();
|
||||
|
||||
return (
|
||||
<ThemedView>
|
||||
<Pressable
|
||||
style={({ pressed }) => [styles.heading, pressed && styles.pressedHeading]}
|
||||
onPress={() => setIsOpen((value) => !value)}>
|
||||
<ThemedView type="backgroundElement" style={styles.button}>
|
||||
<SymbolView
|
||||
name={{ ios: 'chevron.right', android: 'chevron_right', web: 'chevron_right' }}
|
||||
size={14}
|
||||
weight="bold"
|
||||
tintColor={theme.text}
|
||||
style={{ transform: [{ rotate: isOpen ? '-90deg' : '90deg' }] }}
|
||||
/>
|
||||
</ThemedView>
|
||||
|
||||
<ThemedText type="small">{title}</ThemedText>
|
||||
</Pressable>
|
||||
{isOpen && (
|
||||
<Animated.View entering={FadeIn.duration(200)}>
|
||||
<ThemedView type="backgroundElement" style={styles.content}>
|
||||
{children}
|
||||
</ThemedView>
|
||||
</Animated.View>
|
||||
)}
|
||||
</ThemedView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
heading: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: Spacing.two,
|
||||
},
|
||||
pressedHeading: {
|
||||
opacity: 0.7,
|
||||
},
|
||||
button: {
|
||||
width: Spacing.four,
|
||||
height: Spacing.four,
|
||||
borderRadius: 12,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
content: {
|
||||
marginTop: Spacing.three,
|
||||
borderRadius: Spacing.three,
|
||||
marginLeft: Spacing.four,
|
||||
padding: Spacing.four,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
import { version } from 'expo/package.json';
|
||||
import { Image } from 'expo-image';
|
||||
import React from 'react';
|
||||
import { useColorScheme, StyleSheet } from 'react-native';
|
||||
|
||||
import { ThemedText } from './themed-text';
|
||||
import { ThemedView } from './themed-view';
|
||||
|
||||
import { Spacing } from '@/constants/theme';
|
||||
|
||||
export function WebBadge() {
|
||||
const scheme = useColorScheme();
|
||||
|
||||
return (
|
||||
<ThemedView style={styles.container}>
|
||||
<ThemedText type="code" themeColor="textSecondary" style={styles.versionText}>
|
||||
v{version}
|
||||
</ThemedText>
|
||||
<Image
|
||||
source={
|
||||
scheme === 'dark'
|
||||
? require('@/assets/images/expo-badge-white.png')
|
||||
: require('@/assets/images/expo-badge.png')
|
||||
}
|
||||
style={styles.badgeImage}
|
||||
/>
|
||||
</ThemedView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
padding: Spacing.five,
|
||||
alignItems: 'center',
|
||||
gap: Spacing.two,
|
||||
},
|
||||
versionText: {
|
||||
textAlign: 'center',
|
||||
},
|
||||
badgeImage: {
|
||||
width: 123,
|
||||
aspectRatio: 123 / 24,
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
/**
|
||||
* Below are the colors that are used in the app. The colors are defined in the light and dark mode.
|
||||
* There are many other ways to style your app. For example, [Nativewind](https://www.nativewind.dev/), [Tamagui](https://tamagui.dev/), [unistyles](https://reactnativeunistyles.vercel.app), etc.
|
||||
*/
|
||||
|
||||
import '@/global.css';
|
||||
|
||||
import { Platform } from 'react-native';
|
||||
|
||||
export const Colors = {
|
||||
light: {
|
||||
text: '#000000',
|
||||
background: '#ffffff',
|
||||
backgroundElement: '#F0F0F3',
|
||||
backgroundSelected: '#E0E1E6',
|
||||
textSecondary: '#60646C',
|
||||
},
|
||||
dark: {
|
||||
text: '#ffffff',
|
||||
background: '#000000',
|
||||
backgroundElement: '#212225',
|
||||
backgroundSelected: '#2E3135',
|
||||
textSecondary: '#B0B4BA',
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type ThemeColor = keyof typeof Colors.light & keyof typeof Colors.dark;
|
||||
|
||||
export const Fonts = Platform.select({
|
||||
ios: {
|
||||
/** iOS `UIFontDescriptorSystemDesignDefault` */
|
||||
sans: 'system-ui',
|
||||
/** iOS `UIFontDescriptorSystemDesignSerif` */
|
||||
serif: 'ui-serif',
|
||||
/** iOS `UIFontDescriptorSystemDesignRounded` */
|
||||
rounded: 'ui-rounded',
|
||||
/** iOS `UIFontDescriptorSystemDesignMonospaced` */
|
||||
mono: 'ui-monospace',
|
||||
},
|
||||
default: {
|
||||
sans: 'normal',
|
||||
serif: 'serif',
|
||||
rounded: 'normal',
|
||||
mono: 'monospace',
|
||||
},
|
||||
web: {
|
||||
sans: 'var(--font-display)',
|
||||
serif: 'var(--font-serif)',
|
||||
rounded: 'var(--font-rounded)',
|
||||
mono: 'var(--font-mono)',
|
||||
},
|
||||
});
|
||||
|
||||
export const Spacing = {
|
||||
half: 2,
|
||||
one: 4,
|
||||
two: 8,
|
||||
three: 16,
|
||||
four: 24,
|
||||
five: 32,
|
||||
six: 64,
|
||||
} as const;
|
||||
|
||||
export const BottomTabInset = Platform.select({ ios: 50, android: 80 }) ?? 0;
|
||||
export const MaxContentWidth = 800;
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
:root {
|
||||
--font-display:
|
||||
Spline Sans, Inter, ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji,
|
||||
Segoe UI Symbol, Noto Color Emoji;
|
||||
--font-mono:
|
||||
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, Courier New, monospace;
|
||||
--font-rounded: 'SF Pro Rounded', 'Hiragino Maru Gothic ProN', Meiryo, 'MS PGothic', sans-serif;
|
||||
--font-serif: Georgia, 'Times New Roman', serif;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
export { useColorScheme } from 'react-native';
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useColorScheme as useRNColorScheme } from 'react-native';
|
||||
|
||||
/**
|
||||
* To support static rendering, this value needs to be re-calculated on the client side for web
|
||||
*/
|
||||
export function useColorScheme() {
|
||||
const [hasHydrated, setHasHydrated] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setHasHydrated(true);
|
||||
}, []);
|
||||
|
||||
const colorScheme = useRNColorScheme();
|
||||
|
||||
if (hasHydrated) {
|
||||
return colorScheme;
|
||||
}
|
||||
|
||||
return 'light';
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
/**
|
||||
* Learn more about light and dark modes:
|
||||
* https://docs.expo.dev/guides/color-schemes/
|
||||
*/
|
||||
|
||||
import { Colors } from '@/constants/theme';
|
||||
import { useColorScheme } from '@/hooks/use-color-scheme';
|
||||
|
||||
export function useTheme() {
|
||||
const scheme = useColorScheme();
|
||||
const theme = scheme === 'unspecified' ? 'light' : scheme;
|
||||
|
||||
return Colors[theme];
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
export type OpenCodeEvent = {
|
||||
type: string;
|
||||
properties?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type MonitorEventType = 'complete' | 'permission' | 'error';
|
||||
|
||||
export function extractSessionID(event: OpenCodeEvent): string | null {
|
||||
const props = event.properties ?? {};
|
||||
|
||||
const fromDirect = props.sessionID;
|
||||
if (typeof fromDirect === 'string' && fromDirect.length > 0) return fromDirect;
|
||||
|
||||
const info = props.info;
|
||||
if (info && typeof info === 'object') {
|
||||
const infoSessionID = (info as Record<string, unknown>).sessionID;
|
||||
if (typeof infoSessionID === 'string' && infoSessionID.length > 0) return infoSessionID;
|
||||
}
|
||||
|
||||
const part = props.part;
|
||||
if (part && typeof part === 'object') {
|
||||
const partSessionID = (part as Record<string, unknown>).sessionID;
|
||||
if (typeof partSessionID === 'string' && partSessionID.length > 0) return partSessionID;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function classifyMonitorEvent(event: OpenCodeEvent): MonitorEventType | null {
|
||||
const type = event.type;
|
||||
const lowerType = type.toLowerCase();
|
||||
|
||||
if (lowerType.includes('permission')) {
|
||||
return 'permission';
|
||||
}
|
||||
|
||||
if (lowerType.includes('error')) {
|
||||
return 'error';
|
||||
}
|
||||
|
||||
if (type === 'session.status') {
|
||||
const status = event.properties?.status;
|
||||
if (status && typeof status === 'object') {
|
||||
const statusType = (status as Record<string, unknown>).type;
|
||||
if (statusType === 'idle') {
|
||||
return 'complete';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'message.updated') {
|
||||
const info = event.properties?.info;
|
||||
if (info && typeof info === 'object') {
|
||||
const role = (info as Record<string, unknown>).role;
|
||||
const time = (info as Record<string, unknown>).time;
|
||||
if (role === 'assistant' && time && typeof time === 'object' && 'completed' in (time as Record<string, unknown>)) {
|
||||
return 'complete';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function formatMonitorEventLabel(eventType: MonitorEventType): string {
|
||||
switch (eventType) {
|
||||
case 'complete':
|
||||
return 'Session complete';
|
||||
case 'permission':
|
||||
return 'Action needed';
|
||||
case 'error':
|
||||
return 'Session error';
|
||||
default:
|
||||
return 'Session update';
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
export type RegisterDeviceInput = {
|
||||
relayBaseURL: string
|
||||
secret: string
|
||||
deviceToken: string
|
||||
bundleId?: string
|
||||
apnsEnv?: "sandbox" | "production"
|
||||
}
|
||||
|
||||
export type UnregisterDeviceInput = {
|
||||
relayBaseURL: string
|
||||
secret: string
|
||||
deviceToken: string
|
||||
}
|
||||
|
||||
function normalizeBase(url: string): string {
|
||||
return url.replace(/\/+$/, "")
|
||||
}
|
||||
|
||||
async function postRelay(path: string, relayBaseURL: string, body: Record<string, unknown>): Promise<void> {
|
||||
const relay = normalizeBase(relayBaseURL)
|
||||
const response = await fetch(`${relay}${path}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text()
|
||||
throw new Error(`Relay request failed (${response.status}): ${text || response.statusText}`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function registerRelayDevice(input: RegisterDeviceInput): Promise<void> {
|
||||
await postRelay("/v1/device/register", input.relayBaseURL, {
|
||||
secret: input.secret,
|
||||
deviceToken: input.deviceToken,
|
||||
bundleId: input.bundleId,
|
||||
apnsEnv: input.apnsEnv,
|
||||
})
|
||||
}
|
||||
|
||||
export async function unregisterRelayDevice(input: UnregisterDeviceInput): Promise<void> {
|
||||
await postRelay("/v1/device/unregister", input.relayBaseURL, {
|
||||
secret: input.secret,
|
||||
deviceToken: input.deviceToken,
|
||||
})
|
||||
}
|
||||
|
||||
export async function sendRelayTestEvent(input: {
|
||||
relayBaseURL: string
|
||||
secret: string
|
||||
sessionID: string
|
||||
}): Promise<void> {
|
||||
await postRelay("/v1/event", input.relayBaseURL, {
|
||||
secret: input.secret,
|
||||
eventType: "permission",
|
||||
sessionID: input.sessionID,
|
||||
title: "APN relay test",
|
||||
body: "If you can read this, APN relay registration is working.",
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
export type SSEMessage = {
|
||||
event?: string;
|
||||
data: string;
|
||||
id?: string;
|
||||
};
|
||||
|
||||
function parseBlock(block: string): SSEMessage | null {
|
||||
if (!block.trim()) return null;
|
||||
|
||||
const lines = block.split(/\r?\n/);
|
||||
let event: string | undefined;
|
||||
let id: string | undefined;
|
||||
const dataLines: string[] = [];
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line || line.startsWith(':')) continue;
|
||||
|
||||
const sep = line.indexOf(':');
|
||||
const field = sep === -1 ? line : line.slice(0, sep);
|
||||
const value = sep === -1 ? '' : line.slice(sep + 1).replace(/^\s/, '');
|
||||
|
||||
if (field === 'event') {
|
||||
event = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field === 'id') {
|
||||
id = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (field === 'data') {
|
||||
dataLines.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
if (dataLines.length === 0) return null;
|
||||
|
||||
return {
|
||||
event,
|
||||
id,
|
||||
data: dataLines.join('\n'),
|
||||
};
|
||||
}
|
||||
|
||||
export async function* parseSSEStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<SSEMessage> {
|
||||
const reader = stream.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let pending = '';
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const result = await reader.read();
|
||||
if (result.done) break;
|
||||
|
||||
pending += decoder.decode(result.value, { stream: true });
|
||||
const blocks = pending.split(/\r?\n\r?\n/);
|
||||
pending = blocks.pop() ?? '';
|
||||
|
||||
for (const block of blocks) {
|
||||
const parsed = parseBlock(block);
|
||||
if (parsed) yield parsed;
|
||||
}
|
||||
}
|
||||
|
||||
pending += decoder.decode();
|
||||
const tail = parseBlock(pending);
|
||||
if (tail) yield tail;
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
import * as Notifications from "expo-notifications"
|
||||
import * as TaskManager from "expo-task-manager"
|
||||
import { Platform } from "react-native"
|
||||
|
||||
const BACKGROUND_TASK_NAME = "monitoring-background-notification-task"
|
||||
|
||||
type BackgroundPayload = {
|
||||
eventType?: string
|
||||
sessionID?: string
|
||||
title?: string
|
||||
body?: string
|
||||
}
|
||||
|
||||
let configured = false
|
||||
|
||||
TaskManager.defineTask(BACKGROUND_TASK_NAME, async ({ data }: { data?: unknown }) => {
|
||||
const payload = data as BackgroundPayload | undefined
|
||||
const title = payload?.title ?? "OpenCode update"
|
||||
const body = payload?.body ?? "Your monitored session has a new update."
|
||||
|
||||
await Notifications.scheduleNotificationAsync({
|
||||
content: {
|
||||
title,
|
||||
body,
|
||||
data: payload ?? {},
|
||||
},
|
||||
trigger: null,
|
||||
})
|
||||
|
||||
return Notifications.BackgroundNotificationTaskResult.NewData
|
||||
})
|
||||
|
||||
export function configureNotificationBehavior(): void {
|
||||
if (configured) return
|
||||
configured = true
|
||||
|
||||
Notifications.setNotificationHandler({
|
||||
handleNotification: async () => ({
|
||||
shouldShowBanner: false,
|
||||
shouldShowList: false,
|
||||
shouldPlaySound: false,
|
||||
shouldSetBadge: false,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
export async function registerBackgroundNotificationTask(): Promise<void> {
|
||||
const already = await TaskManager.isTaskRegisteredAsync(BACKGROUND_TASK_NAME)
|
||||
if (already) return
|
||||
await Notifications.registerTaskAsync(BACKGROUND_TASK_NAME)
|
||||
}
|
||||
|
||||
export async function ensureNotificationPermissions(): Promise<boolean> {
|
||||
if (Platform.OS === "android") {
|
||||
await Notifications.setNotificationChannelAsync("monitoring", {
|
||||
name: "OpenCode Monitoring",
|
||||
importance: Notifications.AndroidImportance.HIGH,
|
||||
})
|
||||
}
|
||||
|
||||
const existing = await Notifications.getPermissionsAsync()
|
||||
let granted = existing.granted
|
||||
|
||||
if (!granted) {
|
||||
const requested = await Notifications.requestPermissionsAsync()
|
||||
granted = requested.granted
|
||||
}
|
||||
|
||||
return granted
|
||||
}
|
||||
|
||||
export async function getDevicePushToken(): Promise<string | null> {
|
||||
const result = await Notifications.getDevicePushTokenAsync()
|
||||
if (typeof result.data !== "string" || result.data.length === 0) {
|
||||
return null
|
||||
}
|
||||
return result.data
|
||||
}
|
||||
|
||||
export function onPushTokenChange(callback: (token: string) => void): { remove: () => void } {
|
||||
return Notifications.addPushTokenListener((next: { data: unknown }) => {
|
||||
if (typeof next.data !== "string" || next.data.length === 0) return
|
||||
callback(next.data)
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
{
|
||||
"extends": "expo/tsconfig.base",
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
],
|
||||
"@/assets/*": [
|
||||
"./assets/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".expo/types/**/*.ts",
|
||||
"expo-env.d.ts"
|
||||
]
|
||||
}
|
||||