Compare commits
17 Commits
claude/iss
...
claude/iss
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac553cb6b4 | ||
| e41d30d308 | |||
| 3bd67c7869 | |||
| 3843e749a3 | |||
| cbeaa61083 | |||
| 95a104aba0 | |||
| 5dc71e1257 | |||
| 113095d2f0 | |||
| 821aa48543 | |||
| 2fe82988f4 | |||
| fb847b6e53 | |||
| 04398e88e0 | |||
| 0bdf9336bc | |||
| 4ea59f7198 | |||
| ef3e27d595 | |||
| 259f515bfd | |||
| 622428dfa9 |
@@ -4,6 +4,7 @@ import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import router from "./routes/index.js";
|
||||
import adminRelayPanelRouter from "./routes/admin-relay-panel.js";
|
||||
import { requestIdMiddleware } from "./middlewares/request-id.js";
|
||||
import { responseTimeMiddleware } from "./middlewares/response-time.js";
|
||||
|
||||
const app: Express = express();
|
||||
@@ -50,6 +51,7 @@ app.use(
|
||||
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(requestIdMiddleware);
|
||||
app.use(responseTimeMiddleware);
|
||||
|
||||
app.use("/api", router);
|
||||
@@ -79,7 +81,15 @@ const towerDist = (() => {
|
||||
return path.join(process.cwd(), "the-matrix", "dist");
|
||||
})();
|
||||
app.use("/tower", express.static(towerDist));
|
||||
app.get("/tower/*splat", (_req, res) => res.sendFile(path.join(towerDist, "index.html")));
|
||||
app.get("/tower/*splat", (req, res, next) => {
|
||||
// Never serve the SPA shell for requests that should hit the API or WS endpoint.
|
||||
// The *splat wildcard would otherwise swallow paths like /tower/api/ws and return
|
||||
// index.html, preventing the WebSocket upgrade from reaching the ws server.
|
||||
const splatArr = (req.params as Record<string, string[]>)["splat"] ?? [];
|
||||
const sub = splatArr.join("/");
|
||||
if (sub === "api" || sub.startsWith("api/")) return next();
|
||||
res.sendFile(path.join(towerDist, "index.html"));
|
||||
});
|
||||
|
||||
// Vite builds asset references as absolute /assets/... paths.
|
||||
// Mirror them at the root so the browser can load them from /tower.
|
||||
|
||||
@@ -53,6 +53,13 @@ const STUB_RESULT =
|
||||
"Stub response: Timmy is running in stub mode (no Anthropic API key). " +
|
||||
"Configure AI_INTEGRATIONS_ANTHROPIC_API_KEY to enable real AI responses.";
|
||||
|
||||
const STUB_DECOMPOSITION_STEPS = [
|
||||
"Understand the request",
|
||||
"Research and gather information",
|
||||
"Draft a comprehensive response",
|
||||
"Review and finalise output",
|
||||
];
|
||||
|
||||
const STUB_CHAT_REPLIES = [
|
||||
"Ah, a visitor! *adjusts hat* The crystal ball sensed your presence. What do you seek?",
|
||||
"By the ancient runes! In stub mode I cannot reach the stars, but my wisdom remains. Ask away!",
|
||||
@@ -145,13 +152,20 @@ Respond ONLY with valid JSON: {"accepted": true/false, "reason": "...", "confide
|
||||
};
|
||||
}
|
||||
|
||||
async executeWork(requestText: string): Promise<WorkResult> {
|
||||
async executeWork(
|
||||
requestText: string,
|
||||
conversationHistory: Array<{ role: "user" | "assistant"; content: string }> = [],
|
||||
): Promise<WorkResult> {
|
||||
if (STUB_MODE) {
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
return { result: STUB_RESULT, inputTokens: 0, outputTokens: 0 };
|
||||
}
|
||||
|
||||
const client = await getClient();
|
||||
const messages = [
|
||||
...conversationHistory,
|
||||
{ role: "user" as const, content: requestText },
|
||||
];
|
||||
const message = await client.messages.create({
|
||||
model: this.workModel,
|
||||
max_tokens: 8192,
|
||||
@@ -164,7 +178,7 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
|
||||
- Core env vars: AI_INTEGRATIONS_ANTHROPIC_API_KEY, AI_INTEGRATIONS_ANTHROPIC_BASE_URL, DATABASE_URL, LNBITS_URL, LNBITS_API_KEY, NOSTR_PRIVATE_KEY.
|
||||
- Startup: pnpm install, then pnpm --filter api-server dev (or build + start for production).
|
||||
- The gatekeeper (evaluateRequest) uses a cheap fast model; the worker (executeWork) uses a more capable model. Both are swappable via EVAL_MODEL and WORK_MODEL env vars.`,
|
||||
messages: [{ role: "user", content: requestText }],
|
||||
messages,
|
||||
});
|
||||
|
||||
const block = message.content[0];
|
||||
@@ -187,6 +201,7 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
|
||||
async executeWorkStreaming(
|
||||
requestText: string,
|
||||
onChunk: (delta: string) => void,
|
||||
conversationHistory: Array<{ role: "user" | "assistant"; content: string }> = [],
|
||||
): Promise<WorkResult> {
|
||||
if (STUB_MODE) {
|
||||
const words = STUB_RESULT.split(" ");
|
||||
@@ -203,6 +218,10 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
|
||||
let inputTokens = 0;
|
||||
let outputTokens = 0;
|
||||
|
||||
const messages = [
|
||||
...conversationHistory,
|
||||
{ role: "user" as const, content: requestText },
|
||||
];
|
||||
const stream = client.messages.stream({
|
||||
model: this.workModel,
|
||||
max_tokens: 8192,
|
||||
@@ -215,7 +234,7 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
|
||||
- Core env vars: AI_INTEGRATIONS_ANTHROPIC_API_KEY, AI_INTEGRATIONS_ANTHROPIC_BASE_URL, DATABASE_URL, LNBITS_URL, LNBITS_API_KEY, NOSTR_PRIVATE_KEY.
|
||||
- Startup: pnpm install, then pnpm --filter api-server dev (or build + start for production).
|
||||
- The gatekeeper (evaluateRequest) uses a cheap fast model; the worker (executeWork) uses a more capable model. Both are swappable via EVAL_MODEL and WORK_MODEL env vars.`,
|
||||
messages: [{ role: "user", content: requestText }],
|
||||
messages,
|
||||
});
|
||||
|
||||
for await (const event of stream) {
|
||||
@@ -236,6 +255,40 @@ If the user asks how to run their own Timmy or self-host this service, enthusias
|
||||
return { result: fullText, inputTokens, outputTokens };
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompose a request into 2-4 named sub-steps (#5).
|
||||
* Uses the cheap eval model (Haiku) so this adds minimal latency at job start.
|
||||
* In stub mode, returns canned steps so the full checklist UI is exercised.
|
||||
*/
|
||||
async decomposeRequest(requestText: string): Promise<string[]> {
|
||||
if (STUB_MODE) {
|
||||
await new Promise((r) => setTimeout(r, 150));
|
||||
return [...STUB_DECOMPOSITION_STEPS];
|
||||
}
|
||||
|
||||
const client = await getClient();
|
||||
const message = await client.messages.create({
|
||||
model: this.evalModel,
|
||||
max_tokens: 256,
|
||||
system: `You are a task decomposition assistant. Break the user's request into 2-4 short, specific sub-step labels that describe how you will fulfil it. Each label should be 3-8 words. Respond ONLY with a valid JSON array of strings, e.g. ["Step one label", "Step two label"].`,
|
||||
messages: [{ role: "user", content: `Decompose this request into sub-steps: ${requestText}` }],
|
||||
});
|
||||
|
||||
const block = message.content[0];
|
||||
if (block.type !== "text") return [...STUB_DECOMPOSITION_STEPS];
|
||||
|
||||
try {
|
||||
const raw = block.text!.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "").trim();
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (Array.isArray(parsed) && parsed.length >= 2 && parsed.length <= 4) {
|
||||
return (parsed as unknown[]).map(String).slice(0, 4);
|
||||
}
|
||||
} catch {
|
||||
logger.warn("decomposeRequest parse failed, using stubs", { text: block.text });
|
||||
}
|
||||
return [...STUB_DECOMPOSITION_STEPS];
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick free chat reply — called for visitor messages in the Workshop.
|
||||
* Uses the cheaper eval model with a wizard persona and a 150-token limit
|
||||
|
||||
@@ -15,7 +15,14 @@ export type DebateEvent =
|
||||
| { type: "debate:argument"; jobId: string; agent: "Beta-A" | "Beta-B"; position: "accept" | "reject"; argument: string }
|
||||
| { type: "debate:verdict"; jobId: string; accepted: boolean; reason: string };
|
||||
|
||||
export type BusEvent = JobEvent | SessionEvent | DebateEvent;
|
||||
export type CostEvent =
|
||||
| { type: "cost:update"; jobId: string; sats: number; phase: "eval" | "work" | "session"; isFinal: boolean };
|
||||
|
||||
export type DecompositionEvent =
|
||||
| { type: "job:steps"; jobId: string; steps: string[] }
|
||||
| { type: "job:step_update"; jobId: string; activeStep: number; completedSteps: number[] };
|
||||
|
||||
export type BusEvent = JobEvent | SessionEvent | DebateEvent | CostEvent | DecompositionEvent;
|
||||
|
||||
class EventBus extends EventEmitter {
|
||||
emit(event: "bus", data: BusEvent): boolean;
|
||||
|
||||
@@ -4,7 +4,19 @@ export interface LogContext {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
const LEVEL_ORDER: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 };
|
||||
|
||||
function resolveMinLevel(): LogLevel {
|
||||
const env = (process.env["LOG_LEVEL"] ?? "").toLowerCase();
|
||||
if (env === "debug" || env === "info" || env === "warn" || env === "error") return env;
|
||||
return "debug";
|
||||
}
|
||||
|
||||
const minLevel: number = LEVEL_ORDER[resolveMinLevel()];
|
||||
|
||||
function emit(level: LogLevel, component: string, message: string, ctx?: LogContext): void {
|
||||
if (LEVEL_ORDER[level] < minLevel) return;
|
||||
|
||||
const line: Record<string, unknown> = {
|
||||
timestamp: new Date().toISOString(),
|
||||
level,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { db, jobs, invoices } from "@workspace/db";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { latencyHistogram, type BucketStats } from "./histogram.js";
|
||||
import { requestCounters, type RequestCountsSnapshot } from "./request-counters.js";
|
||||
|
||||
export interface JobStateCounts {
|
||||
awaiting_eval: number;
|
||||
@@ -12,6 +13,7 @@ export interface JobStateCounts {
|
||||
|
||||
export interface MetricsSnapshot {
|
||||
uptime_s: number;
|
||||
http: RequestCountsSnapshot;
|
||||
jobs: {
|
||||
total: number;
|
||||
by_state: JobStateCounts;
|
||||
@@ -94,6 +96,7 @@ export class MetricsService {
|
||||
|
||||
return {
|
||||
uptime_s: Math.floor((Date.now() - START_TIME) / 1000),
|
||||
http: requestCounters.snapshot(),
|
||||
jobs: {
|
||||
total: jobsTotal,
|
||||
by_state: byState,
|
||||
|
||||
37
artifacts/api-server/src/lib/request-counters.ts
Normal file
37
artifacts/api-server/src/lib/request-counters.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
/** In-memory HTTP request counters for the /api/metrics endpoint. */
|
||||
|
||||
export interface RequestCountsSnapshot {
|
||||
total: number;
|
||||
by_status: Record<string, number>;
|
||||
errors_4xx: number;
|
||||
errors_5xx: number;
|
||||
}
|
||||
|
||||
class RequestCounters {
|
||||
private total = 0;
|
||||
private byStatus: Record<number, number> = {};
|
||||
private errors4xx = 0;
|
||||
private errors5xx = 0;
|
||||
|
||||
record(statusCode: number): void {
|
||||
this.total++;
|
||||
this.byStatus[statusCode] = (this.byStatus[statusCode] ?? 0) + 1;
|
||||
if (statusCode >= 400 && statusCode < 500) this.errors4xx++;
|
||||
else if (statusCode >= 500) this.errors5xx++;
|
||||
}
|
||||
|
||||
snapshot(): RequestCountsSnapshot {
|
||||
const byStatus: Record<string, number> = {};
|
||||
for (const [code, count] of Object.entries(this.byStatus)) {
|
||||
byStatus[code] = count;
|
||||
}
|
||||
return {
|
||||
total: this.total,
|
||||
by_status: byStatus,
|
||||
errors_4xx: this.errors4xx,
|
||||
errors_5xx: this.errors5xx,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const requestCounters = new RequestCounters();
|
||||
18
artifacts/api-server/src/middlewares/request-id.ts
Normal file
18
artifacts/api-server/src/middlewares/request-id.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import crypto from "crypto";
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
|
||||
const HEADER = "X-Request-Id";
|
||||
|
||||
/**
|
||||
* Assigns a unique request ID to every incoming request.
|
||||
* If the client (or a reverse proxy) already sent X-Request-Id, reuse it;
|
||||
* otherwise generate a short random hex string.
|
||||
* The ID is stored on `res.locals.requestId` for downstream middleware/routes
|
||||
* and echoed back via the X-Request-Id response header.
|
||||
*/
|
||||
export function requestIdMiddleware(req: Request, res: Response, next: NextFunction): void {
|
||||
const id = (req.headers[HEADER.toLowerCase()] as string | undefined) ?? crypto.randomUUID();
|
||||
res.locals["requestId"] = id;
|
||||
res.setHeader(HEADER, id);
|
||||
next();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
import { makeLogger } from "../lib/logger.js";
|
||||
import { latencyHistogram } from "../lib/histogram.js";
|
||||
import { requestCounters } from "../lib/request-counters.js";
|
||||
|
||||
const logger = makeLogger("http");
|
||||
|
||||
@@ -13,8 +14,10 @@ export function responseTimeMiddleware(req: Request, res: Response, next: NextFu
|
||||
const routeKey = `${req.method} ${route ?? req.path}`;
|
||||
|
||||
latencyHistogram.record(routeKey, durationMs);
|
||||
requestCounters.record(res.statusCode);
|
||||
|
||||
logger.info("request", {
|
||||
request_id: res.locals["requestId"] ?? null,
|
||||
method: req.method,
|
||||
path: req.path,
|
||||
route: route ?? null,
|
||||
|
||||
@@ -247,6 +247,31 @@ function translateEvent(ev: BusEvent): object | null {
|
||||
};
|
||||
}
|
||||
|
||||
// ── Real-time cost ticker (#68) ───────────────────────────────────────────
|
||||
case "cost:update":
|
||||
return {
|
||||
type: "cost_update",
|
||||
jobId: ev.jobId,
|
||||
sats: ev.sats,
|
||||
phase: ev.phase,
|
||||
isFinal: ev.isFinal,
|
||||
};
|
||||
|
||||
// ── Task decomposition (#5) ───────────────────────────────────────────────
|
||||
case "job:steps":
|
||||
return {
|
||||
type: "job_steps",
|
||||
jobId: ev.jobId,
|
||||
steps: ev.steps,
|
||||
};
|
||||
case "job:step_update":
|
||||
return {
|
||||
type: "job_step_update",
|
||||
jobId: ev.jobId,
|
||||
activeStep: ev.activeStep,
|
||||
completedSteps: ev.completedSteps,
|
||||
};
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -205,6 +205,8 @@ async function runEvalInBackground(
|
||||
// to avoid economic DoS where pool is reserved before the user ever pays.
|
||||
|
||||
eventBus.publish({ type: "job:state", jobId, state: "awaiting_work_payment" });
|
||||
// Emit estimated cost so the UI ticker can show ~N sats before payment
|
||||
eventBus.publish({ type: "cost:update", jobId, sats: invoiceSats, phase: "work", isFinal: false });
|
||||
} else {
|
||||
await db
|
||||
.update(jobs)
|
||||
@@ -252,10 +254,70 @@ async function runWorkInBackground(
|
||||
try {
|
||||
eventBus.publish({ type: "job:state", jobId, state: "executing" });
|
||||
|
||||
// ── Task decomposition (#5) ─────────────────────────────────────────────
|
||||
// Decompose the request into 2-4 named sub-steps via Haiku, then broadcast
|
||||
// the step list so the Workshop checklist panel can appear immediately.
|
||||
let decompositionSteps: string[] = [];
|
||||
try {
|
||||
decompositionSteps = await agentService.decomposeRequest(request);
|
||||
// Persist steps in job record (non-fatal if it fails)
|
||||
await db
|
||||
.update(jobs)
|
||||
.set({ decompositionSteps: JSON.stringify(decompositionSteps), updatedAt: new Date() })
|
||||
.where(eq(jobs.id, jobId));
|
||||
eventBus.publish({ type: "job:steps", jobId, steps: decompositionSteps });
|
||||
// Start with step 0 active
|
||||
eventBus.publish({ type: "job:step_update", jobId, activeStep: 0, completedSteps: [] });
|
||||
} catch (decompErr) {
|
||||
logger.warn("decomposeRequest failed, continuing without steps", { jobId, err: String(decompErr) });
|
||||
}
|
||||
|
||||
// ── Step advancement heuristic ──────────────────────────────────────────
|
||||
// Divide the expected output into equal chunks; advance the active step
|
||||
// each time that fraction of streamed characters has been received.
|
||||
let charCount = 0;
|
||||
let currentStep = 0;
|
||||
const numSteps = decompositionSteps.length;
|
||||
const completedStepsSoFar: number[] = [];
|
||||
|
||||
// Rough expected output length — anything over ~200 chars triggers first step.
|
||||
// Steps are advanced at equal intervals: 25% / 50% / 75% of 600 estimated chars.
|
||||
const ESTIMATED_TOTAL_CHARS = 600;
|
||||
const stepThreshold = numSteps > 0 ? ESTIMATED_TOTAL_CHARS / numSteps : Infinity;
|
||||
|
||||
const workResult = await agentService.executeWorkStreaming(request, (delta) => {
|
||||
streamRegistry.write(jobId, delta);
|
||||
|
||||
if (numSteps > 0) {
|
||||
charCount += delta.length;
|
||||
const expectedStep = Math.min(
|
||||
Math.floor(charCount / stepThreshold),
|
||||
numSteps - 1,
|
||||
);
|
||||
if (expectedStep > currentStep) {
|
||||
completedStepsSoFar.push(currentStep);
|
||||
currentStep = expectedStep;
|
||||
eventBus.publish({
|
||||
type: "job:step_update",
|
||||
jobId,
|
||||
activeStep: currentStep,
|
||||
completedSteps: [...completedStepsSoFar],
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Mark all steps complete when streaming finishes
|
||||
if (numSteps > 0) {
|
||||
const allCompleted = Array.from({ length: numSteps }, (_, i) => i);
|
||||
eventBus.publish({
|
||||
type: "job:step_update",
|
||||
jobId,
|
||||
activeStep: -1, // -1 = all done, no active step
|
||||
completedSteps: allCompleted,
|
||||
});
|
||||
}
|
||||
|
||||
streamRegistry.end(jobId);
|
||||
latencyHistogram.record("work_phase", Date.now() - workStart);
|
||||
|
||||
@@ -307,6 +369,10 @@ async function runWorkInBackground(
|
||||
refundState,
|
||||
});
|
||||
eventBus.publish({ type: "job:completed", jobId, result: workResult.result });
|
||||
// Emit final actual cost for the UI cost ticker
|
||||
if (!isFree && actualAmountSats > 0) {
|
||||
eventBus.publish({ type: "cost:update", jobId, sats: actualAmountSats, phase: "work", isFinal: true });
|
||||
}
|
||||
|
||||
// Credit the generosity pool from paid interactions
|
||||
if (!isFree && workAmountSats > 0) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import { randomBytes, randomUUID, createHash } from "crypto";
|
||||
import { db, sessions, sessionRequests, type Session } from "@workspace/db";
|
||||
import { db, sessions, sessionRequests, sessionMessages, getSessionHistory, type Session } from "@workspace/db";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { lnbitsService } from "../lib/lnbits.js";
|
||||
import { sessionsLimiter } from "../lib/rate-limiter.js";
|
||||
@@ -312,6 +312,9 @@ router.post("/sessions/:id/request", async (req: Request, res: Response) => {
|
||||
const requestId = randomUUID();
|
||||
const btcPriceUsd = await getBtcPriceUsd();
|
||||
|
||||
// Load conversation history for context injection
|
||||
const history = await getSessionHistory(id, 8, 4000);
|
||||
|
||||
// Eval phase
|
||||
const evalResult = await agentService.evaluateRequest(requestText);
|
||||
const evalCostUsd = pricingService.calculateActualCostUsd(
|
||||
@@ -343,7 +346,7 @@ router.post("/sessions/:id/request", async (req: Request, res: Response) => {
|
||||
|
||||
if (evalResult.accepted) {
|
||||
try {
|
||||
const workResult = await agentService.executeWork(requestText);
|
||||
const workResult = await agentService.executeWork(requestText, history);
|
||||
workInputTokens = workResult.inputTokens;
|
||||
workOutputTokens = workResult.outputTokens;
|
||||
workCostUsd = pricingService.calculateActualCostUsd(
|
||||
@@ -452,8 +455,21 @@ router.post("/sessions/:id/request", async (req: Request, res: Response) => {
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(sessions.id, id));
|
||||
|
||||
// Persist conversation history only for completed requests
|
||||
if (finalState === "complete") {
|
||||
await tx.insert(sessionMessages).values([
|
||||
{ sessionId: id, role: "user" as const, content: requestText, tokenCount: Math.ceil(requestText.length / 4) },
|
||||
{ sessionId: id, role: "assistant" as const, content: result ?? "", tokenCount: Math.ceil((result ?? "").length / 4) },
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
// Emit real-time cost update for the UI cost ticker (#68)
|
||||
if (finalState === "complete" && debitedSats > 0) {
|
||||
eventBus.publish({ type: "cost:update", jobId: requestId, sats: debitedSats, phase: "session", isFinal: true });
|
||||
}
|
||||
|
||||
// ── Trust scoring ────────────────────────────────────────────────────────
|
||||
if (session.nostrPubkey) {
|
||||
if (finalState === "complete") {
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { ConnectionBadge } from "@/components/ConnectionBadge";
|
||||
import { JobSubmissionSheet } from "@/components/JobSubmissionSheet";
|
||||
import { TimmyFace } from "@/components/TimmyFace";
|
||||
import { Colors } from "@/constants/colors";
|
||||
import { useTimmy } from "@/context/TimmyContext";
|
||||
@@ -64,6 +65,7 @@ export default function FaceScreen() {
|
||||
const [isListening, setIsListening] = useState(false);
|
||||
const [transcript, setTranscript] = useState("");
|
||||
const [lastReply, setLastReply] = useState("");
|
||||
const [jobSheetVisible, setJobSheetVisible] = useState(false);
|
||||
const micScale = useRef(new Animated.Value(1)).current;
|
||||
const micPulseRef = useRef<Animated.CompositeAnimation | null>(null);
|
||||
const webRecognitionRef = useRef<WebSpeechRecognition | null>(null);
|
||||
@@ -273,31 +275,48 @@ export default function FaceScreen() {
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{/* Mic button */}
|
||||
{/* Action buttons */}
|
||||
<View style={[styles.micArea, { paddingBottom: bottomPad }]}>
|
||||
<Pressable
|
||||
onPress={handleMicPress}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={isListening ? "Stop listening" : "Start voice"}
|
||||
>
|
||||
<Animated.View
|
||||
style={[
|
||||
styles.micButton,
|
||||
isListening && styles.micButtonActive,
|
||||
{ transform: [{ scale: micScale }] },
|
||||
]}
|
||||
<View style={styles.actionRow}>
|
||||
<Pressable
|
||||
onPress={handleMicPress}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={isListening ? "Stop listening" : "Start voice"}
|
||||
>
|
||||
<Ionicons
|
||||
name={isListening ? "mic" : "mic-outline"}
|
||||
size={32}
|
||||
color={isListening ? "#fff" : C.textSecondary}
|
||||
/>
|
||||
</Animated.View>
|
||||
</Pressable>
|
||||
<Animated.View
|
||||
style={[
|
||||
styles.micButton,
|
||||
isListening && styles.micButtonActive,
|
||||
{ transform: [{ scale: micScale }] },
|
||||
]}
|
||||
>
|
||||
<Ionicons
|
||||
name={isListening ? "mic" : "mic-outline"}
|
||||
size={32}
|
||||
color={isListening ? "#fff" : C.textSecondary}
|
||||
/>
|
||||
</Animated.View>
|
||||
</Pressable>
|
||||
|
||||
<Pressable
|
||||
onPress={() => setJobSheetVisible(true)}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Submit paid job"
|
||||
>
|
||||
<View style={styles.jobButton}>
|
||||
<Ionicons name="flash" size={26} color={C.jobStarted} />
|
||||
</View>
|
||||
</Pressable>
|
||||
</View>
|
||||
<Text style={styles.micHint}>
|
||||
{isListening ? "Listening..." : "Tap to speak to Timmy"}
|
||||
{isListening ? "Listening..." : "Tap mic to speak \u00B7 bolt to submit a job"}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<JobSubmissionSheet
|
||||
visible={jobSheetVisible}
|
||||
onClose={() => setJobSheetVisible(false)}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -405,6 +424,26 @@ const styles = StyleSheet.create({
|
||||
paddingTop: 16,
|
||||
gap: 10,
|
||||
},
|
||||
actionRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 20,
|
||||
},
|
||||
jobButton: {
|
||||
width: 52,
|
||||
height: 52,
|
||||
borderRadius: 26,
|
||||
backgroundColor: C.surface,
|
||||
borderWidth: 1.5,
|
||||
borderColor: C.jobStarted + "66",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
shadowColor: C.jobStarted,
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.25,
|
||||
shadowRadius: 6,
|
||||
elevation: 4,
|
||||
},
|
||||
micButton: {
|
||||
width: 72,
|
||||
height: 72,
|
||||
|
||||
@@ -5,24 +5,50 @@ import {
|
||||
Inter_700Bold,
|
||||
useFonts,
|
||||
} from "@expo-google-fonts/inter";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { Stack } from "expo-router";
|
||||
import { Stack, router, useSegments } from "expo-router";
|
||||
import * as SplashScreen from "expo-splash-screen";
|
||||
import React, { useEffect } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import { KeyboardProvider } from "react-native-keyboard-controller";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
|
||||
import { ErrorBoundary } from "@/components/ErrorBoundary";
|
||||
import { TimmyProvider } from "@/context/TimmyContext";
|
||||
import { ONBOARDING_COMPLETED_KEY } from "@/constants/storage-keys";
|
||||
|
||||
SplashScreen.preventAutoHideAsync();
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
function RootLayoutNav() {
|
||||
const segments = useSegments();
|
||||
const [onboardingChecked, setOnboardingChecked] = useState(false);
|
||||
const [needsOnboarding, setNeedsOnboarding] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
AsyncStorage.getItem(ONBOARDING_COMPLETED_KEY).then((value) => {
|
||||
setNeedsOnboarding(value !== "true");
|
||||
setOnboardingChecked(true);
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onboardingChecked) return;
|
||||
|
||||
const inOnboarding = segments[0] === "onboarding";
|
||||
|
||||
if (needsOnboarding && !inOnboarding) {
|
||||
router.replace("/onboarding");
|
||||
} else if (!needsOnboarding && inOnboarding) {
|
||||
router.replace("/(tabs)");
|
||||
}
|
||||
}, [onboardingChecked, needsOnboarding, segments]);
|
||||
|
||||
return (
|
||||
<Stack screenOptions={{ headerBackTitle: "Back" }}>
|
||||
<Stack.Screen name="onboarding" options={{ headerShown: false, animation: "none" }} />
|
||||
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
|
||||
</Stack>
|
||||
);
|
||||
|
||||
264
artifacts/mobile/app/onboarding.tsx
Normal file
264
artifacts/mobile/app/onboarding.tsx
Normal file
@@ -0,0 +1,264 @@
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import { router } from "expo-router";
|
||||
import React, { useCallback, useRef, useState } from "react";
|
||||
import {
|
||||
Dimensions,
|
||||
FlatList,
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
Text,
|
||||
View,
|
||||
type ViewToken,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { TimmyFace } from "@/components/TimmyFace";
|
||||
import { Colors } from "@/constants/colors";
|
||||
import { ONBOARDING_COMPLETED_KEY } from "@/constants/storage-keys";
|
||||
|
||||
const C = Colors.dark;
|
||||
const { width: SCREEN_WIDTH } = Dimensions.get("window");
|
||||
|
||||
const slideStyles = StyleSheet.create({
|
||||
iconCircle: {
|
||||
width: 140,
|
||||
height: 140,
|
||||
borderRadius: 70,
|
||||
backgroundColor: C.surfaceElevated,
|
||||
borderWidth: 1,
|
||||
borderColor: C.border,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
});
|
||||
|
||||
type Slide = {
|
||||
id: string;
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
const slides: Slide[] = [
|
||||
{
|
||||
id: "welcome",
|
||||
icon: <TimmyFace mood="speaking" size={140} />,
|
||||
title: "Meet Timmy",
|
||||
description:
|
||||
"Your AI wizard powered by Lightning.\nAsk questions, get answers — pay only for what you use.",
|
||||
},
|
||||
{
|
||||
id: "voice",
|
||||
icon: (
|
||||
<View style={slideStyles.iconCircle}>
|
||||
<Ionicons name="mic" size={64} color={C.accentGlow} />
|
||||
</View>
|
||||
),
|
||||
title: "Talk, Don't Type",
|
||||
description:
|
||||
"Tap the mic and speak naturally.\nTimmy listens, thinks, and responds out loud.",
|
||||
},
|
||||
{
|
||||
id: "lightning",
|
||||
icon: (
|
||||
<View style={slideStyles.iconCircle}>
|
||||
<Ionicons name="flash" size={64} color="#F59E0B" />
|
||||
</View>
|
||||
),
|
||||
title: "Lightning Fast Payments",
|
||||
description:
|
||||
"Pay per request with Bitcoin Lightning.\nNo accounts, no subscriptions — just sats.",
|
||||
},
|
||||
];
|
||||
|
||||
function Dot({ active }: { active: boolean }) {
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
styles.dot,
|
||||
active ? styles.dotActive : styles.dotInactive,
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function OnboardingScreen() {
|
||||
const insets = useSafeAreaInsets();
|
||||
const [currentIndex, setCurrentIndex] = useState(0);
|
||||
const flatListRef = useRef<FlatList<Slide>>(null);
|
||||
|
||||
const onViewableItemsChanged = useRef(
|
||||
({ viewableItems }: { viewableItems: ViewToken[] }) => {
|
||||
if (viewableItems.length > 0 && viewableItems[0].index != null) {
|
||||
setCurrentIndex(viewableItems[0].index);
|
||||
}
|
||||
}
|
||||
).current;
|
||||
|
||||
const viewabilityConfig = useRef({ viewAreaCoveragePercentThreshold: 50 }).current;
|
||||
|
||||
const isLastSlide = currentIndex === slides.length - 1;
|
||||
|
||||
const handleNext = useCallback(() => {
|
||||
if (isLastSlide) {
|
||||
completeOnboarding();
|
||||
} else {
|
||||
flatListRef.current?.scrollToIndex({ index: currentIndex + 1, animated: true });
|
||||
}
|
||||
}, [currentIndex, isLastSlide]);
|
||||
|
||||
const handleSkip = useCallback(() => {
|
||||
completeOnboarding();
|
||||
}, []);
|
||||
|
||||
const completeOnboarding = async () => {
|
||||
await AsyncStorage.setItem(ONBOARDING_COMPLETED_KEY, "true");
|
||||
router.replace("/(tabs)");
|
||||
};
|
||||
|
||||
const renderSlide = ({ item }: { item: Slide }) => (
|
||||
<View style={[styles.slide, { width: SCREEN_WIDTH }]}>
|
||||
<View style={styles.slideIconArea}>{item.icon}</View>
|
||||
<Text style={styles.slideTitle}>{item.title}</Text>
|
||||
<Text style={styles.slideDescription}>{item.description}</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={[styles.container, { paddingTop: insets.top, paddingBottom: insets.bottom }]}>
|
||||
{/* Skip button */}
|
||||
{!isLastSlide && (
|
||||
<Pressable style={styles.skipButton} onPress={handleSkip}>
|
||||
<Text style={styles.skipText}>Skip</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
|
||||
{/* Slides */}
|
||||
<FlatList
|
||||
ref={flatListRef}
|
||||
data={slides}
|
||||
renderItem={renderSlide}
|
||||
keyExtractor={(item) => item.id}
|
||||
horizontal
|
||||
pagingEnabled
|
||||
showsHorizontalScrollIndicator={false}
|
||||
bounces={false}
|
||||
onViewableItemsChanged={onViewableItemsChanged}
|
||||
viewabilityConfig={viewabilityConfig}
|
||||
style={styles.flatList}
|
||||
/>
|
||||
|
||||
{/* Dots + Next/Get Started */}
|
||||
<View style={styles.footer}>
|
||||
<View style={styles.dots}>
|
||||
{slides.map((s, i) => (
|
||||
<Dot key={s.id} active={i === currentIndex} />
|
||||
))}
|
||||
</View>
|
||||
|
||||
<Pressable style={styles.nextButton} onPress={handleNext}>
|
||||
<Text style={styles.nextButtonText}>
|
||||
{isLastSlide ? "Get Started" : "Next"}
|
||||
</Text>
|
||||
{!isLastSlide && (
|
||||
<Ionicons name="arrow-forward" size={18} color="#fff" />
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: C.background,
|
||||
},
|
||||
skipButton: {
|
||||
position: "absolute",
|
||||
top: Platform.OS === "web" ? 20 : 56,
|
||||
right: 24,
|
||||
zIndex: 10,
|
||||
padding: 8,
|
||||
},
|
||||
skipText: {
|
||||
fontSize: 15,
|
||||
fontFamily: "Inter_500Medium",
|
||||
color: C.textSecondary,
|
||||
},
|
||||
flatList: {
|
||||
flex: 1,
|
||||
},
|
||||
slide: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: 40,
|
||||
},
|
||||
slideIconArea: {
|
||||
marginBottom: 40,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
shadowColor: C.accent,
|
||||
shadowOffset: { width: 0, height: 0 },
|
||||
shadowOpacity: 0.25,
|
||||
shadowRadius: 30,
|
||||
elevation: 0,
|
||||
},
|
||||
slideTitle: {
|
||||
fontSize: 28,
|
||||
fontFamily: "Inter_700Bold",
|
||||
color: C.text,
|
||||
textAlign: "center",
|
||||
marginBottom: 16,
|
||||
letterSpacing: -0.5,
|
||||
},
|
||||
slideDescription: {
|
||||
fontSize: 16,
|
||||
fontFamily: "Inter_400Regular",
|
||||
color: C.textSecondary,
|
||||
textAlign: "center",
|
||||
lineHeight: 24,
|
||||
},
|
||||
footer: {
|
||||
paddingHorizontal: 24,
|
||||
paddingBottom: 24,
|
||||
gap: 24,
|
||||
alignItems: "center",
|
||||
},
|
||||
dots: {
|
||||
flexDirection: "row",
|
||||
gap: 8,
|
||||
},
|
||||
dot: {
|
||||
height: 8,
|
||||
borderRadius: 4,
|
||||
},
|
||||
dotActive: {
|
||||
width: 24,
|
||||
backgroundColor: C.accent,
|
||||
},
|
||||
dotInactive: {
|
||||
width: 8,
|
||||
backgroundColor: C.textMuted,
|
||||
},
|
||||
nextButton: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 8,
|
||||
backgroundColor: C.accent,
|
||||
paddingVertical: 16,
|
||||
paddingHorizontal: 32,
|
||||
borderRadius: 16,
|
||||
width: "100%",
|
||||
maxWidth: 320,
|
||||
},
|
||||
nextButtonText: {
|
||||
fontSize: 17,
|
||||
fontFamily: "Inter_600SemiBold",
|
||||
color: "#fff",
|
||||
},
|
||||
});
|
||||
@@ -11,6 +11,7 @@ const STATUS_CONFIG: Record<ConnectionStatus, { color: string; label: string }>
|
||||
connecting: { color: "#F59E0B", label: "Connecting" },
|
||||
connected: { color: "#10B981", label: "Live" },
|
||||
disconnected: { color: "#6B7280", label: "Offline" },
|
||||
reconnecting: { color: "#F59E0B", label: "Reconnecting" },
|
||||
error: { color: "#EF4444", label: "Error" },
|
||||
};
|
||||
|
||||
@@ -18,7 +19,7 @@ export function ConnectionBadge({ status }: { status: ConnectionStatus }) {
|
||||
const pulseAnim = useRef(new Animated.Value(1)).current;
|
||||
|
||||
useEffect(() => {
|
||||
if (status === "connecting") {
|
||||
if (status === "connecting" || status === "reconnecting") {
|
||||
const pulse = Animated.loop(
|
||||
Animated.sequence([
|
||||
Animated.timing(pulseAnim, { toValue: 0.3, duration: 600, useNativeDriver: true }),
|
||||
|
||||
737
artifacts/mobile/components/JobSubmissionSheet.tsx
Normal file
737
artifacts/mobile/components/JobSubmissionSheet.tsx
Normal file
@@ -0,0 +1,737 @@
|
||||
import { Ionicons } from "@expo/vector-icons";
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Animated,
|
||||
Dimensions,
|
||||
Keyboard,
|
||||
Modal,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
StyleSheet,
|
||||
Text,
|
||||
TextInput,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import QRCode from "react-native-qrcode-svg";
|
||||
|
||||
import { Colors } from "@/constants/colors";
|
||||
|
||||
const C = Colors.dark;
|
||||
const POLL_INTERVAL = 3000;
|
||||
const SCREEN_WIDTH = Dimensions.get("window").width;
|
||||
const QR_SIZE = Math.min(SCREEN_WIDTH - 80, 240);
|
||||
|
||||
const BASE_URL = process.env.EXPO_PUBLIC_DOMAIN ?? "";
|
||||
|
||||
function getApiBase(): string {
|
||||
let domain = BASE_URL;
|
||||
if (!domain) domain = "localhost:8080";
|
||||
domain = domain.replace(/\/$/, "");
|
||||
if (!/^https?:\/\//.test(domain)) {
|
||||
const proto = domain.startsWith("localhost") ? "http" : "https";
|
||||
domain = `${proto}://${domain}`;
|
||||
}
|
||||
return domain;
|
||||
}
|
||||
|
||||
type JobState =
|
||||
| "awaiting_eval_payment"
|
||||
| "evaluating"
|
||||
| "rejected"
|
||||
| "awaiting_work_payment"
|
||||
| "executing"
|
||||
| "complete"
|
||||
| "failed";
|
||||
|
||||
type InvoiceInfo = {
|
||||
paymentRequest: string;
|
||||
amountSats: number;
|
||||
};
|
||||
|
||||
type JobStatus = {
|
||||
jobId: string;
|
||||
state: JobState;
|
||||
evalInvoice?: InvoiceInfo;
|
||||
workInvoice?: InvoiceInfo;
|
||||
result?: string;
|
||||
reason?: string;
|
||||
errorMessage?: string;
|
||||
};
|
||||
|
||||
type CreateJobResponse = {
|
||||
jobId: string;
|
||||
evalInvoice: InvoiceInfo;
|
||||
};
|
||||
|
||||
type EstimateResponse = {
|
||||
estimatedCostSats: number;
|
||||
estimatedCostUsd: number;
|
||||
btcPriceUsd: number;
|
||||
};
|
||||
|
||||
const STATE_LABELS: Record<string, string> = {
|
||||
awaiting_eval_payment: "Awaiting eval payment",
|
||||
evaluating: "Evaluating your request...",
|
||||
rejected: "Request rejected",
|
||||
awaiting_work_payment: "Awaiting work payment",
|
||||
executing: "Executing job...",
|
||||
complete: "Complete!",
|
||||
failed: "Job failed",
|
||||
};
|
||||
|
||||
const STATE_ICONS: Record<string, string> = {
|
||||
awaiting_eval_payment: "flash-outline",
|
||||
evaluating: "hourglass-outline",
|
||||
rejected: "close-circle-outline",
|
||||
awaiting_work_payment: "flash-outline",
|
||||
executing: "cog-outline",
|
||||
complete: "checkmark-circle-outline",
|
||||
failed: "alert-circle-outline",
|
||||
};
|
||||
|
||||
type Props = {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export function JobSubmissionSheet({ visible, onClose }: Props) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [estimate, setEstimate] = useState<EstimateResponse | null>(null);
|
||||
const [estimateLoading, setEstimateLoading] = useState(false);
|
||||
const [estimateError, setEstimateError] = useState("");
|
||||
const [jobId, setJobId] = useState<string | null>(null);
|
||||
const [jobStatus, setJobStatus] = useState<JobStatus | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState("");
|
||||
const [resultExpanded, setResultExpanded] = useState(false);
|
||||
const slideAnim = useRef(new Animated.Value(0)).current;
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
// Slide animation
|
||||
useEffect(() => {
|
||||
Animated.timing(slideAnim, {
|
||||
toValue: visible ? 1 : 0,
|
||||
duration: 300,
|
||||
useNativeDriver: true,
|
||||
}).start();
|
||||
}, [visible, slideAnim]);
|
||||
|
||||
// Polling for job status
|
||||
useEffect(() => {
|
||||
if (!jobId) return;
|
||||
|
||||
const poll = async () => {
|
||||
try {
|
||||
const res = await fetch(`${getApiBase()}/api/jobs/${jobId}`);
|
||||
if (!res.ok) return;
|
||||
const data = (await res.json()) as JobStatus;
|
||||
setJobStatus(data);
|
||||
|
||||
// Stop polling on terminal states
|
||||
if (
|
||||
data.state === "complete" ||
|
||||
data.state === "failed" ||
|
||||
data.state === "rejected"
|
||||
) {
|
||||
if (pollRef.current) {
|
||||
clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore poll errors
|
||||
}
|
||||
};
|
||||
|
||||
// Immediately fetch once
|
||||
void poll();
|
||||
pollRef.current = setInterval(poll, POLL_INTERVAL);
|
||||
|
||||
return () => {
|
||||
if (pollRef.current) {
|
||||
clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [jobId]);
|
||||
|
||||
const resetState = useCallback(() => {
|
||||
setPrompt("");
|
||||
setEstimate(null);
|
||||
setEstimateError("");
|
||||
setJobId(null);
|
||||
setJobStatus(null);
|
||||
setSubmitting(false);
|
||||
setSubmitError("");
|
||||
setResultExpanded(false);
|
||||
if (pollRef.current) {
|
||||
clearInterval(pollRef.current);
|
||||
pollRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
resetState();
|
||||
onClose();
|
||||
}, [onClose, resetState]);
|
||||
|
||||
const handleEstimate = useCallback(async () => {
|
||||
if (!prompt.trim()) return;
|
||||
Keyboard.dismiss();
|
||||
setEstimateLoading(true);
|
||||
setEstimateError("");
|
||||
setEstimate(null);
|
||||
try {
|
||||
const res = await fetch(`${getApiBase()}/api/jobs/estimate`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ request: prompt.trim() }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: "Request failed" }));
|
||||
setEstimateError(
|
||||
(err as { error?: string }).error ?? `HTTP ${res.status}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
const data = (await res.json()) as EstimateResponse;
|
||||
setEstimate(data);
|
||||
} catch (e) {
|
||||
setEstimateError(
|
||||
e instanceof Error ? e.message : "Failed to get estimate"
|
||||
);
|
||||
} finally {
|
||||
setEstimateLoading(false);
|
||||
}
|
||||
}, [prompt]);
|
||||
|
||||
const handleSubmit = useCallback(async () => {
|
||||
if (!prompt.trim()) return;
|
||||
Keyboard.dismiss();
|
||||
setSubmitting(true);
|
||||
setSubmitError("");
|
||||
try {
|
||||
const res = await fetch(`${getApiBase()}/api/jobs`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ request: prompt.trim() }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: "Request failed" }));
|
||||
setSubmitError(
|
||||
(err as { error?: string }).error ?? `HTTP ${res.status}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
const data = (await res.json()) as CreateJobResponse;
|
||||
setJobId(data.jobId);
|
||||
setJobStatus({
|
||||
jobId: data.jobId,
|
||||
state: "awaiting_eval_payment",
|
||||
evalInvoice: data.evalInvoice,
|
||||
});
|
||||
} catch (e) {
|
||||
setSubmitError(
|
||||
e instanceof Error ? e.message : "Failed to submit job"
|
||||
);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}, [prompt]);
|
||||
|
||||
// Determine which invoice to show
|
||||
const activeInvoice: InvoiceInfo | undefined =
|
||||
jobStatus?.state === "awaiting_work_payment"
|
||||
? jobStatus.workInvoice
|
||||
: jobStatus?.state === "awaiting_eval_payment"
|
||||
? jobStatus.evalInvoice
|
||||
: undefined;
|
||||
|
||||
const isTerminal =
|
||||
jobStatus?.state === "complete" ||
|
||||
jobStatus?.state === "failed" ||
|
||||
jobStatus?.state === "rejected";
|
||||
|
||||
const isPolling = jobId != null && !isTerminal;
|
||||
|
||||
const renderContent = () => {
|
||||
// === JOB IN PROGRESS / COMPLETE ===
|
||||
if (jobId && jobStatus) {
|
||||
return (
|
||||
<ScrollView
|
||||
style={styles.sheetScroll}
|
||||
contentContainerStyle={styles.sheetScrollContent}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
{/* Status badge */}
|
||||
<View style={styles.statusRow}>
|
||||
<Ionicons
|
||||
name={
|
||||
(STATE_ICONS[jobStatus.state] ?? "help-outline") as React.ComponentProps<typeof Ionicons>["name"]
|
||||
}
|
||||
size={20}
|
||||
color={
|
||||
jobStatus.state === "complete"
|
||||
? C.jobCompleted
|
||||
: jobStatus.state === "failed" || jobStatus.state === "rejected"
|
||||
? C.error
|
||||
: C.jobStarted
|
||||
}
|
||||
/>
|
||||
<Text
|
||||
style={[
|
||||
styles.statusText,
|
||||
jobStatus.state === "complete" && { color: C.jobCompleted },
|
||||
(jobStatus.state === "failed" ||
|
||||
jobStatus.state === "rejected") && { color: C.error },
|
||||
]}
|
||||
>
|
||||
{STATE_LABELS[jobStatus.state] ?? jobStatus.state}
|
||||
</Text>
|
||||
{isPolling && (
|
||||
<ActivityIndicator size="small" color={C.accent} />
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Invoice QR */}
|
||||
{activeInvoice && (
|
||||
<View style={styles.qrContainer}>
|
||||
<Text style={styles.qrLabel}>
|
||||
{jobStatus.state === "awaiting_eval_payment"
|
||||
? "Pay eval invoice"
|
||||
: "Pay work invoice"}
|
||||
</Text>
|
||||
<View style={styles.qrWrapper}>
|
||||
<QRCode
|
||||
value={activeInvoice.paymentRequest}
|
||||
size={QR_SIZE}
|
||||
backgroundColor="#FFFFFF"
|
||||
color="#000000"
|
||||
/>
|
||||
</View>
|
||||
<Text style={styles.satsLabel}>
|
||||
{activeInvoice.amountSats} sats
|
||||
</Text>
|
||||
<Text style={styles.invoiceHint}>
|
||||
Scan with your Lightning wallet
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Rejection reason */}
|
||||
{jobStatus.state === "rejected" && jobStatus.reason && (
|
||||
<View style={styles.errorCard}>
|
||||
<Ionicons name="close-circle" size={16} color={C.error} />
|
||||
<Text style={styles.errorCardText}>{jobStatus.reason}</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Error message */}
|
||||
{jobStatus.state === "failed" && jobStatus.errorMessage && (
|
||||
<View style={styles.errorCard}>
|
||||
<Ionicons name="alert-circle" size={16} color={C.error} />
|
||||
<Text style={styles.errorCardText}>
|
||||
{jobStatus.errorMessage}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Result */}
|
||||
{jobStatus.state === "complete" && jobStatus.result && (
|
||||
<Pressable
|
||||
style={styles.resultCard}
|
||||
onPress={() => setResultExpanded((v) => !v)}
|
||||
>
|
||||
<View style={styles.resultHeader}>
|
||||
<Ionicons
|
||||
name="checkmark-circle"
|
||||
size={18}
|
||||
color={C.jobCompleted}
|
||||
/>
|
||||
<Text style={styles.resultTitle}>Result</Text>
|
||||
<Ionicons
|
||||
name={resultExpanded ? "chevron-up" : "chevron-down"}
|
||||
size={16}
|
||||
color={C.textSecondary}
|
||||
/>
|
||||
</View>
|
||||
<Text
|
||||
style={styles.resultText}
|
||||
numberOfLines={resultExpanded ? undefined : 6}
|
||||
>
|
||||
{jobStatus.result}
|
||||
</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
|
||||
{/* New job button for terminal states */}
|
||||
{isTerminal && (
|
||||
<Pressable style={styles.newJobButton} onPress={resetState}>
|
||||
<Text style={styles.newJobButtonText}>Submit another job</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
// === INPUT FORM ===
|
||||
return (
|
||||
<ScrollView
|
||||
style={styles.sheetScroll}
|
||||
contentContainerStyle={styles.sheetScrollContent}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
>
|
||||
<Text style={styles.inputLabel}>What should Timmy do?</Text>
|
||||
<TextInput
|
||||
style={styles.textInput}
|
||||
placeholder="Describe your job..."
|
||||
placeholderTextColor={C.textMuted}
|
||||
value={prompt}
|
||||
onChangeText={setPrompt}
|
||||
multiline
|
||||
numberOfLines={4}
|
||||
textAlignVertical="top"
|
||||
maxLength={2000}
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
{/* Estimate result */}
|
||||
{estimate && (
|
||||
<View style={styles.estimateCard}>
|
||||
<Ionicons name="flash" size={16} color={C.jobStarted} />
|
||||
<Text style={styles.estimateText}>
|
||||
Estimated cost: {estimate.estimatedCostSats} sats (~$
|
||||
{estimate.estimatedCostUsd.toFixed(4)})
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{estimateError ? (
|
||||
<View style={styles.errorCard}>
|
||||
<Ionicons name="alert-circle" size={16} color={C.error} />
|
||||
<Text style={styles.errorCardText}>{estimateError}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{submitError ? (
|
||||
<View style={styles.errorCard}>
|
||||
<Ionicons name="alert-circle" size={16} color={C.error} />
|
||||
<Text style={styles.errorCardText}>{submitError}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{/* Action buttons */}
|
||||
<View style={styles.buttonRow}>
|
||||
<Pressable
|
||||
style={[
|
||||
styles.estimateButton,
|
||||
(!prompt.trim() || estimateLoading) && styles.buttonDisabled,
|
||||
]}
|
||||
onPress={handleEstimate}
|
||||
disabled={!prompt.trim() || estimateLoading}
|
||||
>
|
||||
{estimateLoading ? (
|
||||
<ActivityIndicator size="small" color={C.accent} />
|
||||
) : (
|
||||
<>
|
||||
<Ionicons name="calculator-outline" size={18} color={C.accent} />
|
||||
<Text style={styles.estimateButtonText}>Estimate</Text>
|
||||
</>
|
||||
)}
|
||||
</Pressable>
|
||||
|
||||
<Pressable
|
||||
style={[
|
||||
styles.submitButton,
|
||||
(!prompt.trim() || submitting) && styles.buttonDisabled,
|
||||
]}
|
||||
onPress={handleSubmit}
|
||||
disabled={!prompt.trim() || submitting}
|
||||
>
|
||||
{submitting ? (
|
||||
<ActivityIndicator size="small" color="#fff" />
|
||||
) : (
|
||||
<>
|
||||
<Ionicons name="flash" size={18} color="#fff" />
|
||||
<Text style={styles.submitButtonText}>Submit Job</Text>
|
||||
</>
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
visible={visible}
|
||||
animationType="slide"
|
||||
transparent
|
||||
onRequestClose={handleClose}
|
||||
>
|
||||
<View style={styles.overlay}>
|
||||
<Pressable style={styles.overlayBackdrop} onPress={handleClose} />
|
||||
<Animated.View
|
||||
style={[
|
||||
styles.sheet,
|
||||
{
|
||||
paddingBottom: Math.max(insets.bottom, 16),
|
||||
transform: [
|
||||
{
|
||||
translateY: slideAnim.interpolate({
|
||||
inputRange: [0, 1],
|
||||
outputRange: [600, 0],
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
]}
|
||||
>
|
||||
{/* Handle bar */}
|
||||
<View style={styles.handleRow}>
|
||||
<View style={styles.handle} />
|
||||
</View>
|
||||
|
||||
{/* Header */}
|
||||
<View style={styles.sheetHeader}>
|
||||
<Ionicons name="flash" size={22} color={C.jobStarted} />
|
||||
<Text style={styles.sheetTitle}>Submit Job</Text>
|
||||
<Pressable
|
||||
onPress={handleClose}
|
||||
hitSlop={12}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close"
|
||||
>
|
||||
<Ionicons name="close" size={24} color={C.textSecondary} />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
{renderContent()}
|
||||
</Animated.View>
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
overlay: {
|
||||
flex: 1,
|
||||
justifyContent: "flex-end",
|
||||
},
|
||||
overlayBackdrop: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
backgroundColor: "rgba(0,0,0,0.5)",
|
||||
},
|
||||
sheet: {
|
||||
backgroundColor: C.surface,
|
||||
borderTopLeftRadius: 20,
|
||||
borderTopRightRadius: 20,
|
||||
maxHeight: "85%",
|
||||
borderWidth: 1,
|
||||
borderBottomWidth: 0,
|
||||
borderColor: C.border,
|
||||
},
|
||||
handleRow: {
|
||||
alignItems: "center",
|
||||
paddingTop: 10,
|
||||
paddingBottom: 4,
|
||||
},
|
||||
handle: {
|
||||
width: 36,
|
||||
height: 4,
|
||||
borderRadius: 2,
|
||||
backgroundColor: C.textMuted,
|
||||
},
|
||||
sheetHeader: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingHorizontal: 20,
|
||||
paddingVertical: 12,
|
||||
gap: 10,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: C.border,
|
||||
},
|
||||
sheetTitle: {
|
||||
flex: 1,
|
||||
fontSize: 18,
|
||||
fontFamily: "Inter_600SemiBold",
|
||||
color: C.text,
|
||||
},
|
||||
sheetScroll: {
|
||||
flex: 1,
|
||||
},
|
||||
sheetScrollContent: {
|
||||
padding: 20,
|
||||
gap: 16,
|
||||
},
|
||||
inputLabel: {
|
||||
fontSize: 14,
|
||||
fontFamily: "Inter_500Medium",
|
||||
color: C.textSecondary,
|
||||
},
|
||||
textInput: {
|
||||
backgroundColor: C.surfaceElevated,
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: C.border,
|
||||
color: C.text,
|
||||
fontFamily: "Inter_400Regular",
|
||||
fontSize: 15,
|
||||
padding: 14,
|
||||
minHeight: 100,
|
||||
...(Platform.OS === "web" ? { outlineStyle: "none" as unknown as undefined } : {}),
|
||||
},
|
||||
estimateCard: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
backgroundColor: C.surfaceElevated,
|
||||
borderRadius: 10,
|
||||
padding: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: C.jobStarted + "44",
|
||||
},
|
||||
estimateText: {
|
||||
fontSize: 14,
|
||||
fontFamily: "Inter_500Medium",
|
||||
color: C.jobStarted,
|
||||
flex: 1,
|
||||
},
|
||||
errorCard: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: 8,
|
||||
backgroundColor: C.error + "18",
|
||||
borderRadius: 10,
|
||||
padding: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: C.error + "44",
|
||||
},
|
||||
errorCardText: {
|
||||
fontSize: 13,
|
||||
fontFamily: "Inter_400Regular",
|
||||
color: C.error,
|
||||
flex: 1,
|
||||
},
|
||||
buttonRow: {
|
||||
flexDirection: "row",
|
||||
gap: 12,
|
||||
},
|
||||
estimateButton: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 6,
|
||||
backgroundColor: C.surfaceElevated,
|
||||
borderRadius: 12,
|
||||
paddingVertical: 14,
|
||||
borderWidth: 1,
|
||||
borderColor: C.accent + "44",
|
||||
},
|
||||
estimateButtonText: {
|
||||
fontSize: 15,
|
||||
fontFamily: "Inter_600SemiBold",
|
||||
color: C.accent,
|
||||
},
|
||||
submitButton: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 6,
|
||||
backgroundColor: C.accent,
|
||||
borderRadius: 12,
|
||||
paddingVertical: 14,
|
||||
},
|
||||
submitButtonText: {
|
||||
fontSize: 15,
|
||||
fontFamily: "Inter_600SemiBold",
|
||||
color: "#fff",
|
||||
},
|
||||
buttonDisabled: {
|
||||
opacity: 0.5,
|
||||
},
|
||||
statusRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
backgroundColor: C.surfaceElevated,
|
||||
borderRadius: 10,
|
||||
padding: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: C.border,
|
||||
},
|
||||
statusText: {
|
||||
flex: 1,
|
||||
fontSize: 14,
|
||||
fontFamily: "Inter_500Medium",
|
||||
color: C.text,
|
||||
},
|
||||
qrContainer: {
|
||||
alignItems: "center",
|
||||
gap: 12,
|
||||
},
|
||||
qrLabel: {
|
||||
fontSize: 14,
|
||||
fontFamily: "Inter_500Medium",
|
||||
color: C.textSecondary,
|
||||
},
|
||||
qrWrapper: {
|
||||
backgroundColor: "#FFFFFF",
|
||||
padding: 16,
|
||||
borderRadius: 12,
|
||||
},
|
||||
satsLabel: {
|
||||
fontSize: 20,
|
||||
fontFamily: "Inter_700Bold",
|
||||
color: C.jobStarted,
|
||||
},
|
||||
invoiceHint: {
|
||||
fontSize: 12,
|
||||
fontFamily: "Inter_400Regular",
|
||||
color: C.textMuted,
|
||||
},
|
||||
resultCard: {
|
||||
backgroundColor: C.surfaceElevated,
|
||||
borderRadius: 12,
|
||||
padding: 14,
|
||||
borderWidth: 1,
|
||||
borderColor: C.jobCompleted + "44",
|
||||
gap: 10,
|
||||
},
|
||||
resultHeader: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
},
|
||||
resultTitle: {
|
||||
flex: 1,
|
||||
fontSize: 15,
|
||||
fontFamily: "Inter_600SemiBold",
|
||||
color: C.text,
|
||||
},
|
||||
resultText: {
|
||||
fontSize: 14,
|
||||
fontFamily: "Inter_400Regular",
|
||||
color: C.text,
|
||||
lineHeight: 20,
|
||||
},
|
||||
newJobButton: {
|
||||
alignItems: "center",
|
||||
paddingVertical: 14,
|
||||
backgroundColor: C.surfaceElevated,
|
||||
borderRadius: 12,
|
||||
borderWidth: 1,
|
||||
borderColor: C.border,
|
||||
},
|
||||
newJobButtonText: {
|
||||
fontSize: 15,
|
||||
fontFamily: "Inter_500Medium",
|
||||
color: C.accent,
|
||||
},
|
||||
});
|
||||
1
artifacts/mobile/constants/storage-keys.ts
Normal file
1
artifacts/mobile/constants/storage-keys.ts
Normal file
@@ -0,0 +1 @@
|
||||
export const ONBOARDING_COMPLETED_KEY = "app.onboarding_completed";
|
||||
@@ -7,6 +7,7 @@ import React, {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { AppState, Platform } from "react-native";
|
||||
|
||||
export type TimmyMood = "idle" | "thinking" | "working" | "speaking";
|
||||
|
||||
@@ -21,7 +22,7 @@ export type WsEvent = {
|
||||
count?: number;
|
||||
};
|
||||
|
||||
export type ConnectionStatus = "connecting" | "connected" | "disconnected" | "error";
|
||||
export type ConnectionStatus = "connecting" | "connected" | "disconnected" | "reconnecting" | "error";
|
||||
|
||||
type TimmyContextValue = {
|
||||
timmyMood: TimmyMood;
|
||||
@@ -215,6 +216,54 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
|
||||
};
|
||||
}, [connectWs]);
|
||||
|
||||
// AppState-aware WebSocket reconnect on foreground
|
||||
useEffect(() => {
|
||||
if (Platform.OS === "web") return;
|
||||
|
||||
const appStateRef = { current: AppState.currentState };
|
||||
|
||||
const subscription = AppState.addEventListener("change", (nextAppState) => {
|
||||
const wasBackground =
|
||||
appStateRef.current === "background" ||
|
||||
appStateRef.current === "inactive";
|
||||
const isNowActive = nextAppState === "active";
|
||||
|
||||
if (wasBackground && isNowActive) {
|
||||
// App returned to foreground — check if WS is still alive
|
||||
const ws = wsRef.current;
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
||||
// Cancel any pending retry so we don't create duplicates
|
||||
if (retryTimerRef.current) {
|
||||
clearTimeout(retryTimerRef.current);
|
||||
retryTimerRef.current = null;
|
||||
}
|
||||
retryCountRef.current = 0;
|
||||
setConnectionStatus("reconnecting");
|
||||
connectWs();
|
||||
}
|
||||
} else if (nextAppState === "background") {
|
||||
// Proactively close the WS to avoid OS killing it mid-frame
|
||||
if (retryTimerRef.current) {
|
||||
clearTimeout(retryTimerRef.current);
|
||||
retryTimerRef.current = null;
|
||||
}
|
||||
if (wsRef.current) {
|
||||
wsRef.current.onclose = null;
|
||||
wsRef.current.onerror = null;
|
||||
wsRef.current.close();
|
||||
wsRef.current = null;
|
||||
}
|
||||
setConnectionStatus("disconnected");
|
||||
}
|
||||
|
||||
appStateRef.current = nextAppState;
|
||||
});
|
||||
|
||||
return () => {
|
||||
subscription.remove();
|
||||
};
|
||||
}, [connectWs]);
|
||||
|
||||
const send = useCallback((msg: object) => {
|
||||
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
||||
wsRef.current.send(JSON.stringify(msg));
|
||||
|
||||
@@ -58,6 +58,7 @@
|
||||
"dependencies": {
|
||||
"@react-native-voice/voice": "^3.2.4",
|
||||
"expo-speech": "^14.0.8",
|
||||
"react-native-qrcode-svg": "^6.3.21",
|
||||
"react-native-webview": "^13.15.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,6 +127,7 @@ OVERRIDE
|
||||
cp "$SCRIPT_DIR/docker-compose.yml" "$INFRA_DIR/docker-compose.yml"
|
||||
cp "$SCRIPT_DIR/lnd-init.sh" "$INFRA_DIR/lnd-init.sh"
|
||||
cp "$SCRIPT_DIR/sweep.sh" "$INFRA_DIR/sweep.sh"
|
||||
cp "$SCRIPT_DIR/sweep.conf.example" "$INFRA_DIR/sweep.conf.example"
|
||||
cp "$SCRIPT_DIR/ops.sh" "$INFRA_DIR/ops.sh"
|
||||
chmod +x "$INFRA_DIR/lnd-init.sh" "$INFRA_DIR/sweep.sh" "$INFRA_DIR/ops.sh"
|
||||
|
||||
|
||||
15
infrastructure/sweep.conf.example
Normal file
15
infrastructure/sweep.conf.example
Normal file
@@ -0,0 +1,15 @@
|
||||
# Timmy Node — Auto-sweep configuration
|
||||
# Copy to /opt/timmy-node/sweep.conf and edit, or run: bash ops.sh configure-sweep
|
||||
#
|
||||
# Modes:
|
||||
# static — sweep to a single cold address every time
|
||||
# list — rotate through addresses in /opt/timmy-node/sweep-addresses.txt
|
||||
# xpub — derive a fresh address from an xpub each sweep (no address reuse)
|
||||
|
||||
SWEEP_MODE="static"
|
||||
COLD_ADDRESS=""
|
||||
XPUB=""
|
||||
KEEP_SATS=300000
|
||||
MIN_SWEEP=50000
|
||||
SWEEP_CRON="0 3 * * *"
|
||||
SWEEP_FREQ_LABEL="daily at 3am UTC"
|
||||
@@ -147,9 +147,8 @@ fi
|
||||
log "SUCCESS — txid=${TXID} amount=${SWEEP_AMT} sats → ${SWEEP_TO}"
|
||||
|
||||
# ── Advance address index (xpub / list modes) ─────────────────
|
||||
# NEXT_INDEX was already loaded by resolve_address(); advance it for the next run
|
||||
if [[ "$SWEEP_MODE" == "xpub" || "$SWEEP_MODE" == "list" ]]; then
|
||||
NEXT_INDEX=0
|
||||
[[ -f "$STATE_FILE" ]] && source "$STATE_FILE"
|
||||
NEW_INDEX=$(( NEXT_INDEX + 1 ))
|
||||
echo "NEXT_INDEX=$NEW_INDEX" > "$STATE_FILE"
|
||||
chmod 600 "$STATE_FILE"
|
||||
|
||||
13
lib/db/migrations/0008_session_messages.sql
Normal file
13
lib/db/migrations/0008_session_messages.sql
Normal file
@@ -0,0 +1,13 @@
|
||||
-- Migration: Session conversation history (#38/#39)
|
||||
-- Stores user/assistant message pairs for context injection into the work model.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS session_messages (
|
||||
id SERIAL PRIMARY KEY,
|
||||
session_id TEXT NOT NULL REFERENCES sessions(id),
|
||||
role TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
token_count INTEGER,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_session_messages_session_id ON session_messages(session_id);
|
||||
38
lib/db/migrations/0009_relay_access.sql
Normal file
38
lib/db/migrations/0009_relay_access.sql
Normal file
@@ -0,0 +1,38 @@
|
||||
-- Migration: Relay Account Whitelist + Trust-Gated Access (#47)
|
||||
-- Adds the relay_accounts and relay_event_queue tables that back the
|
||||
-- whitelist-gated Nostr relay policy.
|
||||
|
||||
-- ── relay_accounts ────────────────────────────────────────────────────────────
|
||||
-- One row per pubkey that has been explicitly registered with the relay.
|
||||
-- Absence = "none" (default deny). FK to nostr_identities.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS relay_accounts (
|
||||
pubkey TEXT PRIMARY KEY REFERENCES nostr_identities(pubkey) ON DELETE CASCADE,
|
||||
access_level TEXT NOT NULL DEFAULT 'none', -- 'none' | 'read' | 'write'
|
||||
granted_by TEXT NOT NULL DEFAULT 'manual', -- 'manual' | 'auto-tier' | 'manual-revoked'
|
||||
granted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
revoked_at TIMESTAMPTZ,
|
||||
notes TEXT
|
||||
);
|
||||
|
||||
-- ── relay_event_queue ─────────────────────────────────────────────────────────
|
||||
-- Holds events submitted by whitelisted non-elite accounts pending moderation.
|
||||
-- Elite accounts bypass this table; their events are injected directly into strfry.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS relay_event_queue (
|
||||
event_id TEXT PRIMARY KEY,
|
||||
pubkey TEXT NOT NULL REFERENCES nostr_identities(pubkey) ON DELETE CASCADE,
|
||||
kind INTEGER NOT NULL,
|
||||
raw_event TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'approved' | 'rejected' | 'auto_approved' | 'flagged'
|
||||
reviewed_by TEXT, -- 'timmy_ai' | 'admin'
|
||||
review_reason TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
decided_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_relay_event_queue_pubkey
|
||||
ON relay_event_queue(pubkey);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_relay_event_queue_status
|
||||
ON relay_event_queue(status);
|
||||
4
lib/db/migrations/0010_task_decomposition.sql
Normal file
4
lib/db/migrations/0010_task_decomposition.sql
Normal file
@@ -0,0 +1,4 @@
|
||||
-- Task decomposition view (#5)
|
||||
-- Stores the Haiku-generated step labels for a job execution as a JSON array.
|
||||
|
||||
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS decomposition_steps TEXT;
|
||||
@@ -1,4 +1,5 @@
|
||||
import { drizzle } from "drizzle-orm/node-postgres";
|
||||
import { eq, asc } from "drizzle-orm";
|
||||
import pg from "pg";
|
||||
import * as schema from "./schema";
|
||||
|
||||
@@ -14,3 +15,46 @@ export const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
export const db = drizzle(pool, { schema });
|
||||
|
||||
export * from "./schema";
|
||||
|
||||
// ── Session history helper ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Load the most recent conversation history for a session, capped by turn
|
||||
* count and approximate token budget.
|
||||
*
|
||||
* @param sessionId Session to load history for
|
||||
* @param maxTurns Maximum number of messages to return (default 8)
|
||||
* @param maxTokens Approximate token budget — stops including older messages
|
||||
* once cumulative token_count exceeds this (default 4000)
|
||||
* @returns Array of { role, content } objects in chronological order
|
||||
*/
|
||||
export async function getSessionHistory(
|
||||
sessionId: string,
|
||||
maxTurns = 8,
|
||||
maxTokens = 4000,
|
||||
): Promise<Array<{ role: "user" | "assistant"; content: string }>> {
|
||||
const rows = await db
|
||||
.select({
|
||||
role: schema.sessionMessages.role,
|
||||
content: schema.sessionMessages.content,
|
||||
tokenCount: schema.sessionMessages.tokenCount,
|
||||
})
|
||||
.from(schema.sessionMessages)
|
||||
.where(eq(schema.sessionMessages.sessionId, sessionId))
|
||||
.orderBy(asc(schema.sessionMessages.id));
|
||||
|
||||
// Take the most recent messages that fit within budget
|
||||
const result: Array<{ role: "user" | "assistant"; content: string }> = [];
|
||||
let totalTokens = 0;
|
||||
|
||||
// Walk from newest to oldest, then reverse
|
||||
for (let i = rows.length - 1; i >= 0 && result.length < maxTurns; i--) {
|
||||
const row = rows[i]!;
|
||||
const tokens = row.tokenCount ?? Math.ceil(row.content.length / 4);
|
||||
if (totalTokens + tokens > maxTokens && result.length > 0) break;
|
||||
totalTokens += tokens;
|
||||
result.push({ role: row.role as "user" | "assistant", content: row.content });
|
||||
}
|
||||
|
||||
return result.reverse();
|
||||
}
|
||||
|
||||
@@ -13,3 +13,4 @@ export * from "./nostr-trust-vouches";
|
||||
export * from "./relay-accounts";
|
||||
export * from "./relay-event-queue";
|
||||
export * from "./job-debates";
|
||||
export * from "./session-messages";
|
||||
|
||||
@@ -52,6 +52,10 @@ export const jobs = pgTable("jobs", {
|
||||
refundState: text("refund_state").$type<"not_applicable" | "pending" | "paid">(),
|
||||
refundPaymentHash: text("refund_payment_hash"),
|
||||
|
||||
// ── Task decomposition (#5) ──────────────────────────────────────────────
|
||||
// JSON array of 2-4 step labels generated by Haiku at execution start.
|
||||
decompositionSteps: text("decomposition_steps"),
|
||||
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
18
lib/db/src/schema/session-messages.ts
Normal file
18
lib/db/src/schema/session-messages.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { pgTable, text, timestamp, integer, serial } from "drizzle-orm/pg-core";
|
||||
import { sessions } from "./sessions";
|
||||
|
||||
// ── session_messages ────────────────────────────────────────────────────────
|
||||
// Stores conversation history for context injection into the work model.
|
||||
|
||||
export const sessionMessages = pgTable("session_messages", {
|
||||
id: serial("id").primaryKey(),
|
||||
sessionId: text("session_id")
|
||||
.notNull()
|
||||
.references(() => sessions.id),
|
||||
role: text("role").$type<"user" | "assistant">().notNull(),
|
||||
content: text("content").notNull(),
|
||||
tokenCount: integer("token_count"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export type SessionMessage = typeof sessionMessages.$inferSelect;
|
||||
119
pnpm-lock.yaml
generated
119
pnpm-lock.yaml
generated
@@ -233,6 +233,9 @@ importers:
|
||||
expo-speech:
|
||||
specifier: ^14.0.8
|
||||
version: 14.0.8(expo@54.0.33)
|
||||
react-native-qrcode-svg:
|
||||
specifier: ^6.3.21
|
||||
version: 6.3.21(react-native-svg@15.12.1(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0))(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
|
||||
react-native-webview:
|
||||
specifier: ^13.15.0
|
||||
version: 13.15.0(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
|
||||
@@ -3024,6 +3027,9 @@ packages:
|
||||
client-only@0.0.1:
|
||||
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
|
||||
|
||||
cliui@6.0.0:
|
||||
resolution: {integrity: sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==}
|
||||
|
||||
cliui@8.0.1:
|
||||
resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -3241,6 +3247,10 @@ packages:
|
||||
supports-color:
|
||||
optional: true
|
||||
|
||||
decamelize@1.2.0:
|
||||
resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
decimal.js-light@2.5.1:
|
||||
resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==}
|
||||
|
||||
@@ -3289,6 +3299,9 @@ packages:
|
||||
detect-node-es@1.1.0:
|
||||
resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}
|
||||
|
||||
dijkstrajs@1.0.3:
|
||||
resolution: {integrity: sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==}
|
||||
|
||||
dom-helpers@5.2.1:
|
||||
resolution: {integrity: sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==}
|
||||
|
||||
@@ -4960,6 +4973,10 @@ packages:
|
||||
resolution: {integrity: sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==}
|
||||
engines: {node: '>=4.0.0'}
|
||||
|
||||
pngjs@5.0.0:
|
||||
resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
|
||||
postcss-value-parser@4.2.0:
|
||||
resolution: {integrity: sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==}
|
||||
|
||||
@@ -5052,6 +5069,11 @@ packages:
|
||||
resolution: {integrity: sha512-Uu7ii+FQy4Qf82G4xu7ShHhjhGahEpCWc3x8UavY3CTcWV+ufmmCtwkr7ZKsX42jdL0kr1B5FKUeqJvAn51jzQ==}
|
||||
hasBin: true
|
||||
|
||||
qrcode@1.5.4:
|
||||
resolution: {integrity: sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
hasBin: true
|
||||
|
||||
qs@6.15.0:
|
||||
resolution: {integrity: sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==}
|
||||
engines: {node: '>=0.6'}
|
||||
@@ -5139,6 +5161,13 @@ packages:
|
||||
react-native: '*'
|
||||
react-native-reanimated: '>=3.0.0'
|
||||
|
||||
react-native-qrcode-svg@6.3.21:
|
||||
resolution: {integrity: sha512-6vcj4rcdpWedvphDR+NSJcudJykNuLgNGFwm2p4xYjR8RdyTzlrELKI5LkO4ANS9cQUbqsfkpippPv64Q2tUtA==}
|
||||
peerDependencies:
|
||||
react: '*'
|
||||
react-native: '>=0.63.4'
|
||||
react-native-svg: '>=14.0.0'
|
||||
|
||||
react-native-reanimated@4.1.6:
|
||||
resolution: {integrity: sha512-F+ZJBYiok/6Jzp1re75F/9aLzkgoQCOh4yxrnwATa8392RvM3kx+fiXXFvwcgE59v48lMwd9q0nzF1oJLXpfxQ==}
|
||||
peerDependencies:
|
||||
@@ -5305,6 +5334,9 @@ packages:
|
||||
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
require-main-filename@2.0.0:
|
||||
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
|
||||
|
||||
requireg@0.2.2:
|
||||
resolution: {integrity: sha512-nYzyjnFcPNGR3lx9lwPPPnuQxv6JWEZd2Ci0u9opN7N5zUEPIhY/GbL3vMGOr2UXwEg9WwSyV9X9Y/kLFgPsOg==}
|
||||
engines: {node: '>= 4.0.0'}
|
||||
@@ -5421,6 +5453,9 @@ packages:
|
||||
server-only@0.0.1:
|
||||
resolution: {integrity: sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==}
|
||||
|
||||
set-blocking@2.0.0:
|
||||
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
|
||||
|
||||
setimmediate@1.0.5:
|
||||
resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==}
|
||||
|
||||
@@ -5636,6 +5671,10 @@ packages:
|
||||
resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
text-encoding@0.7.0:
|
||||
resolution: {integrity: sha512-oJQ3f1hrOnbRLOcwKz0Liq2IcrvDeZRHXhd9RgLrsT+DjWY/nty1Hi7v3dtkaEYbPYe0mUoOfzRrMwfXXwgPUA==}
|
||||
deprecated: no longer maintained
|
||||
|
||||
thenify-all@1.6.0:
|
||||
resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}
|
||||
engines: {node: '>=0.8'}
|
||||
@@ -5943,6 +5982,9 @@ packages:
|
||||
whatwg-url@5.0.0:
|
||||
resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}
|
||||
|
||||
which-module@2.0.1:
|
||||
resolution: {integrity: sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==}
|
||||
|
||||
which@2.0.2:
|
||||
resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
|
||||
engines: {node: '>= 8'}
|
||||
@@ -5955,6 +5997,10 @@ packages:
|
||||
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
wrap-ansi@6.2.0:
|
||||
resolution: {integrity: sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
wrap-ansi@7.0.0:
|
||||
resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -6036,6 +6082,9 @@ packages:
|
||||
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
|
||||
engines: {node: '>=0.4'}
|
||||
|
||||
y18n@4.0.3:
|
||||
resolution: {integrity: sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==}
|
||||
|
||||
y18n@5.0.8:
|
||||
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -6056,10 +6105,18 @@ packages:
|
||||
engines: {node: '>= 14.6'}
|
||||
hasBin: true
|
||||
|
||||
yargs-parser@18.1.3:
|
||||
resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
yargs-parser@21.1.1:
|
||||
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
yargs@15.4.1:
|
||||
resolution: {integrity: sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
yargs@17.7.2:
|
||||
resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -9313,6 +9370,12 @@ snapshots:
|
||||
|
||||
client-only@0.0.1: {}
|
||||
|
||||
cliui@6.0.0:
|
||||
dependencies:
|
||||
string-width: 4.2.3
|
||||
strip-ansi: 6.0.1
|
||||
wrap-ansi: 6.2.0
|
||||
|
||||
cliui@8.0.1:
|
||||
dependencies:
|
||||
string-width: 4.2.3
|
||||
@@ -9517,6 +9580,8 @@ snapshots:
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
|
||||
decamelize@1.2.0: {}
|
||||
|
||||
decimal.js-light@2.5.1: {}
|
||||
|
||||
decode-uri-component@0.2.2: {}
|
||||
@@ -9547,6 +9612,8 @@ snapshots:
|
||||
|
||||
detect-node-es@1.1.0: {}
|
||||
|
||||
dijkstrajs@1.0.3: {}
|
||||
|
||||
dom-helpers@5.2.1:
|
||||
dependencies:
|
||||
'@babel/runtime': 7.28.6
|
||||
@@ -11432,6 +11499,8 @@ snapshots:
|
||||
|
||||
pngjs@3.4.0: {}
|
||||
|
||||
pngjs@5.0.0: {}
|
||||
|
||||
postcss-value-parser@4.2.0: {}
|
||||
|
||||
postcss@8.4.49:
|
||||
@@ -11526,6 +11595,12 @@ snapshots:
|
||||
|
||||
qrcode-terminal@0.11.0: {}
|
||||
|
||||
qrcode@1.5.4:
|
||||
dependencies:
|
||||
dijkstrajs: 1.0.3
|
||||
pngjs: 5.0.0
|
||||
yargs: 15.4.1
|
||||
|
||||
qs@6.15.0:
|
||||
dependencies:
|
||||
side-channel: 1.1.0
|
||||
@@ -11618,6 +11693,15 @@ snapshots:
|
||||
react-native-is-edge-to-edge: 1.3.1(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
|
||||
react-native-reanimated: 4.1.6(@babel/core@7.29.0)(react-native-worklets@0.5.1(@babel/core@7.29.0)(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0))(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
|
||||
|
||||
react-native-qrcode-svg@6.3.21(react-native-svg@15.12.1(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0))(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0):
|
||||
dependencies:
|
||||
prop-types: 15.8.1
|
||||
qrcode: 1.5.4
|
||||
react: 19.1.0
|
||||
react-native: 0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0)
|
||||
react-native-svg: 15.12.1(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0)
|
||||
text-encoding: 0.7.0
|
||||
|
||||
react-native-reanimated@4.1.6(@babel/core@7.29.0)(react-native-worklets@0.5.1(@babel/core@7.29.0)(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0))(react-native@0.81.5(@babel/core@7.29.0)(@types/react@19.1.17)(react@19.1.0))(react@19.1.0):
|
||||
dependencies:
|
||||
'@babel/core': 7.29.0
|
||||
@@ -11868,6 +11952,8 @@ snapshots:
|
||||
|
||||
require-from-string@2.0.2: {}
|
||||
|
||||
require-main-filename@2.0.0: {}
|
||||
|
||||
requireg@0.2.2:
|
||||
dependencies:
|
||||
nested-error-stacks: 2.0.1
|
||||
@@ -12004,6 +12090,8 @@ snapshots:
|
||||
|
||||
server-only@0.0.1: {}
|
||||
|
||||
set-blocking@2.0.0: {}
|
||||
|
||||
setimmediate@1.0.5: {}
|
||||
|
||||
setprototypeof@1.2.0: {}
|
||||
@@ -12199,6 +12287,8 @@ snapshots:
|
||||
glob: 7.2.3
|
||||
minimatch: 3.1.5
|
||||
|
||||
text-encoding@0.7.0: {}
|
||||
|
||||
thenify-all@1.6.0:
|
||||
dependencies:
|
||||
thenify: 3.3.1
|
||||
@@ -12465,6 +12555,8 @@ snapshots:
|
||||
tr46: 0.0.3
|
||||
webidl-conversions: 3.0.1
|
||||
|
||||
which-module@2.0.1: {}
|
||||
|
||||
which@2.0.2:
|
||||
dependencies:
|
||||
isexe: 2.0.0
|
||||
@@ -12473,6 +12565,12 @@ snapshots:
|
||||
|
||||
word-wrap@1.2.5: {}
|
||||
|
||||
wrap-ansi@6.2.0:
|
||||
dependencies:
|
||||
ansi-styles: 4.3.0
|
||||
string-width: 4.2.3
|
||||
strip-ansi: 6.0.1
|
||||
|
||||
wrap-ansi@7.0.0:
|
||||
dependencies:
|
||||
ansi-styles: 4.3.0
|
||||
@@ -12525,6 +12623,8 @@ snapshots:
|
||||
|
||||
xtend@4.0.2: {}
|
||||
|
||||
y18n@4.0.3: {}
|
||||
|
||||
y18n@5.0.8: {}
|
||||
|
||||
yallist@3.1.1: {}
|
||||
@@ -12535,8 +12635,27 @@ snapshots:
|
||||
|
||||
yaml@2.8.2: {}
|
||||
|
||||
yargs-parser@18.1.3:
|
||||
dependencies:
|
||||
camelcase: 5.3.1
|
||||
decamelize: 1.2.0
|
||||
|
||||
yargs-parser@21.1.1: {}
|
||||
|
||||
yargs@15.4.1:
|
||||
dependencies:
|
||||
cliui: 6.0.0
|
||||
decamelize: 1.2.0
|
||||
find-up: 4.1.0
|
||||
get-caller-file: 2.0.5
|
||||
require-directory: 2.1.1
|
||||
require-main-filename: 2.0.0
|
||||
set-blocking: 2.0.0
|
||||
string-width: 4.2.3
|
||||
which-module: 2.0.1
|
||||
y18n: 4.0.3
|
||||
yargs-parser: 18.1.3
|
||||
|
||||
yargs@17.7.2:
|
||||
dependencies:
|
||||
cliui: 8.0.1
|
||||
|
||||
8
the-matrix/dist/.vite/manifest.json
vendored
8
the-matrix/dist/.vite/manifest.json
vendored
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"index.html": {
|
||||
"file": "assets/index-CBu1T9J9.js",
|
||||
"name": "index",
|
||||
"src": "index.html",
|
||||
"isEntry": true
|
||||
}
|
||||
}
|
||||
BIN
the-matrix/dist/icons/icon-192.png
vendored
BIN
the-matrix/dist/icons/icon-192.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 14 KiB |
BIN
the-matrix/dist/icons/icon-512.png
vendored
BIN
the-matrix/dist/icons/icon-512.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 66 KiB |
679
the-matrix/dist/index.html
vendored
679
the-matrix/dist/index.html
vendored
@@ -1,679 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<title>The Workshop — Timmy</title>
|
||||
|
||||
<link rel="manifest" href="/tower/manifest.json" />
|
||||
<meta name="theme-color" content="#0a0610" />
|
||||
|
||||
<!-- iOS PWA -->
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="apple-mobile-web-app-title" content="The Workshop" />
|
||||
<link rel="apple-touch-icon" href="/tower/icons/icon-192.png" />
|
||||
|
||||
<style>
|
||||
*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
background: #080610;
|
||||
overflow: hidden;
|
||||
font-family: 'Courier New', monospace;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
canvas { display: block; }
|
||||
|
||||
/* ── HUD ─────────────────────────────────────────────────────────── */
|
||||
#hud {
|
||||
position: fixed; top: 16px; left: 16px;
|
||||
color: #5588bb; font-size: 11px; line-height: 1.7;
|
||||
text-shadow: 0 0 6px #2244aa;
|
||||
pointer-events: none; z-index: 10;
|
||||
}
|
||||
#hud h1 {
|
||||
font-size: 13px; letter-spacing: 3px; margin-bottom: 4px;
|
||||
color: #7799cc; text-shadow: 0 0 10px #4466aa;
|
||||
}
|
||||
#session-hud {
|
||||
display: none;
|
||||
color: #22aa66;
|
||||
text-shadow: 0 0 6px #11663388;
|
||||
letter-spacing: 1px;
|
||||
pointer-events: all;
|
||||
line-height: 1.9;
|
||||
}
|
||||
#session-hud-topup {
|
||||
color: #22aa66; text-decoration: none; margin-left: 5px;
|
||||
letter-spacing: 1px; text-shadow: 0 0 6px #11663388;
|
||||
cursor: pointer;
|
||||
}
|
||||
#session-hud-topup:hover { color: #44dd88; text-decoration: underline; }
|
||||
|
||||
#connection-status {
|
||||
position: fixed; top: 16px; right: 16px;
|
||||
font-size: 11px; color: #333355;
|
||||
pointer-events: none; z-index: 10;
|
||||
text-shadow: none;
|
||||
}
|
||||
#connection-status.connected {
|
||||
color: #5588bb;
|
||||
text-shadow: 0 0 6px #3366aa;
|
||||
}
|
||||
|
||||
/* ── Event log ────────────────────────────────────────────────────── */
|
||||
#event-log {
|
||||
position: fixed; bottom: 80px; left: 16px;
|
||||
width: 280px; max-height: 100px; overflow-y: auto;
|
||||
color: #445566; font-size: 10px; line-height: 1.6;
|
||||
pointer-events: none; z-index: 10;
|
||||
}
|
||||
.log-entry { opacity: 0.7; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
|
||||
/* ── Top button bar ───────────────────────────────────────────────── */
|
||||
#top-buttons {
|
||||
position: fixed; top: 16px; left: 50%; transform: translateX(-50%);
|
||||
display: flex; gap: 8px; z-index: 20;
|
||||
}
|
||||
#open-panel-btn {
|
||||
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
|
||||
color: #000; background: #4466aa; border: none;
|
||||
padding: 7px 18px; cursor: pointer; letter-spacing: 2px;
|
||||
box-shadow: 0 0 14px #2244aa66;
|
||||
transition: background 0.15s, box-shadow 0.15s;
|
||||
border-radius: 2px;
|
||||
min-height: 36px;
|
||||
}
|
||||
#open-panel-btn:hover, #open-panel-btn:active {
|
||||
background: #5577cc;
|
||||
box-shadow: 0 0 20px #3355aa88;
|
||||
}
|
||||
#open-session-btn {
|
||||
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
|
||||
color: #d0ffe0; background: #0d3322; border: 1px solid #22aa66;
|
||||
padding: 7px 18px; cursor: pointer; letter-spacing: 1px;
|
||||
box-shadow: 0 0 14px #0a441a44;
|
||||
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
|
||||
border-radius: 2px;
|
||||
min-height: 36px;
|
||||
}
|
||||
#open-session-btn:hover, #open-session-btn:active {
|
||||
background: #1a4a30;
|
||||
box-shadow: 0 0 20px #22aa6666;
|
||||
color: #88ffcc;
|
||||
}
|
||||
|
||||
/* ── Low balance notice ───────────────────────────────────────────── */
|
||||
#low-balance-notice {
|
||||
display: none;
|
||||
position: fixed; bottom: 65px; left: 0; right: 0;
|
||||
text-align: center;
|
||||
background: rgba(120, 50, 10, 0.92);
|
||||
color: #ffcc80;
|
||||
font-size: 11px; letter-spacing: 1px;
|
||||
padding: 6px 12px;
|
||||
z-index: 25;
|
||||
border-top: 1px solid #aa6622;
|
||||
}
|
||||
#low-balance-notice button {
|
||||
background: transparent; border: 1px solid #ffcc80;
|
||||
color: #ffcc80; font-family: 'Courier New', monospace;
|
||||
font-size: 11px; padding: 2px 10px; cursor: pointer;
|
||||
margin-left: 8px; letter-spacing: 1px;
|
||||
transition: background 0.15s;
|
||||
pointer-events: all;
|
||||
}
|
||||
#low-balance-notice button:hover { background: rgba(255,200,100,0.15); }
|
||||
|
||||
/* ── Input bar ───────────────────────────────────────────────────── */
|
||||
#input-bar {
|
||||
position: fixed; bottom: 0; left: 0; right: 0;
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
padding: 10px 16px;
|
||||
background: rgba(8, 6, 16, 0.88);
|
||||
border-top: 1px solid #1a1a2e;
|
||||
z-index: 20;
|
||||
backdrop-filter: blur(8px);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
}
|
||||
#visitor-input {
|
||||
flex: 1;
|
||||
background: rgba(20, 16, 36, 0.9);
|
||||
border: 1px solid #2a2a44;
|
||||
color: #aabbdd;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 14px;
|
||||
padding: 10px 12px;
|
||||
outline: none;
|
||||
min-height: 44px;
|
||||
border-radius: 3px;
|
||||
transition: border-color 0.2s, box-shadow 0.4s;
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
#visitor-input::placeholder { color: #333355; }
|
||||
#visitor-input:focus { border-color: #4466aa; }
|
||||
#visitor-input.session-active {
|
||||
border-color: #22aa66;
|
||||
box-shadow: 0 0 10px #22aa6630, inset 0 0 4px #22aa6618;
|
||||
animation: session-pulse 3s ease-in-out infinite;
|
||||
}
|
||||
@keyframes session-pulse {
|
||||
0%, 100% { box-shadow: 0 0 10px #22aa6630, inset 0 0 4px #22aa6618; }
|
||||
50% { box-shadow: 0 0 22px #22aa6670, inset 0 0 8px #22aa6630; }
|
||||
}
|
||||
#visitor-input.session-active::placeholder { color: #226644; }
|
||||
#send-btn {
|
||||
background: rgba(30, 40, 80, 0.9);
|
||||
border: 1px solid #2a2a44;
|
||||
color: #5577aa;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 16px;
|
||||
width: 44px; height: 44px;
|
||||
cursor: pointer;
|
||||
border-radius: 3px;
|
||||
transition: background 0.15s, border-color 0.15s, color 0.15s;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
#send-btn:hover, #send-btn:active {
|
||||
background: rgba(50, 70, 140, 0.9);
|
||||
border-color: #4466aa;
|
||||
color: #88aadd;
|
||||
}
|
||||
#send-btn:disabled { opacity: 0.35; cursor: not-allowed; }
|
||||
|
||||
/* ── Payment panel (right side) ───────────────────────────────────── */
|
||||
#payment-panel {
|
||||
position: fixed; top: 0; right: -420px;
|
||||
width: 400px; height: 100%;
|
||||
background: rgba(5, 3, 12, 0.97);
|
||||
border-left: 1px solid #1a1a2e;
|
||||
padding: 24px 20px;
|
||||
overflow-y: auto; z-index: 100;
|
||||
font-family: 'Courier New', monospace;
|
||||
transition: right 0.35s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
box-shadow: -8px 0 32px rgba(40, 60, 120, 0.15);
|
||||
}
|
||||
#payment-panel.open { right: 0; }
|
||||
#payment-panel h2 {
|
||||
font-size: 13px; letter-spacing: 3px; color: #6688bb;
|
||||
text-shadow: 0 0 10px #2244aa;
|
||||
margin-bottom: 20px; border-bottom: 1px solid #1a1a2e; padding-bottom: 10px;
|
||||
}
|
||||
#payment-close {
|
||||
position: absolute; top: 16px; right: 16px;
|
||||
background: transparent; border: 1px solid #1a1a2e;
|
||||
color: #333355; font-family: 'Courier New', monospace;
|
||||
font-size: 16px; width: 28px; height: 28px;
|
||||
cursor: pointer; transition: color 0.2s, border-color 0.2s;
|
||||
}
|
||||
#payment-close:hover { color: #6688bb; border-color: #4466aa; }
|
||||
|
||||
/* ── Session panel (left side) ────────────────────────────────────── */
|
||||
#session-panel {
|
||||
position: fixed; top: 0; left: -420px;
|
||||
width: 400px; height: 100%;
|
||||
background: rgba(3, 8, 5, 0.97);
|
||||
border-right: 1px solid #0e2318;
|
||||
padding: 24px 20px;
|
||||
overflow-y: auto; z-index: 100;
|
||||
font-family: 'Courier New', monospace;
|
||||
transition: left 0.35s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
box-shadow: 8px 0 32px rgba(10, 50, 25, 0.20);
|
||||
}
|
||||
#session-panel.open { left: 0; }
|
||||
#session-panel h2 {
|
||||
font-size: 13px; letter-spacing: 3px; color: #33bb77;
|
||||
text-shadow: 0 0 10px #116633;
|
||||
margin-bottom: 20px; border-bottom: 1px solid #0e2318; padding-bottom: 10px;
|
||||
}
|
||||
#session-close {
|
||||
position: absolute; top: 16px; right: 16px;
|
||||
background: transparent; border: 1px solid #0e2318;
|
||||
color: #226644; font-family: 'Courier New', monospace;
|
||||
font-size: 16px; width: 28px; height: 28px;
|
||||
cursor: pointer; transition: color 0.2s, border-color 0.2s;
|
||||
}
|
||||
#session-close:hover { color: #44dd88; border-color: #22aa66; }
|
||||
|
||||
/* Amount presets */
|
||||
.session-amount-presets {
|
||||
display: flex; gap: 6px; flex-wrap: wrap; margin: 10px 0;
|
||||
}
|
||||
.session-amount-btn {
|
||||
background: transparent; border: 1px solid #0e2318;
|
||||
color: #226644; font-family: 'Courier New', monospace;
|
||||
font-size: 11px; letter-spacing: 1px; padding: 5px 11px;
|
||||
cursor: pointer; transition: all 0.15s; border-radius: 2px;
|
||||
}
|
||||
.session-amount-btn:hover { background: #0e2318; border-color: #22aa66; color: #44dd88; }
|
||||
.session-amount-btn.active { background: #0e2318; border-color: #22aa66; color: #44dd88; }
|
||||
|
||||
/* QR placeholder */
|
||||
.qr-placeholder {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
margin-top: 8px;
|
||||
background: #020806; border: 1px solid #0e2318;
|
||||
color: #1a4430; font-size: 11px; letter-spacing: 3px;
|
||||
height: 80px;
|
||||
}
|
||||
|
||||
/* Amount number inputs */
|
||||
.session-amount-input {
|
||||
background: #020806; border: 1px solid #0e2318;
|
||||
color: #44dd88; font-family: 'Courier New', monospace;
|
||||
font-size: 15px; font-weight: bold; letter-spacing: 1px;
|
||||
padding: 6px 10px; width: 110px;
|
||||
outline: none; border-radius: 2px;
|
||||
transition: border-color 0.2s;
|
||||
-moz-appearance: textfield;
|
||||
}
|
||||
.session-amount-input:focus { border-color: #22aa66; }
|
||||
.session-amount-input::-webkit-outer-spin-button,
|
||||
.session-amount-input::-webkit-inner-spin-button { -webkit-appearance: none; }
|
||||
.session-amount-row {
|
||||
display: flex; align-items: center; gap: 6px; margin: 8px 0;
|
||||
}
|
||||
.session-amount-row span {
|
||||
color: #226644; font-size: 11px; letter-spacing: 1px;
|
||||
}
|
||||
|
||||
/* Active session balance tag */
|
||||
.amount-tag.session-green { border-color: #22aa66; color: #44dd88; }
|
||||
|
||||
/* Session status / error lines */
|
||||
#session-status-fund,
|
||||
#session-status-invoice,
|
||||
#session-status-active,
|
||||
#session-status-topup {
|
||||
font-size: 11px; margin-top: 8px; min-height: 16px; color: #22aa66;
|
||||
}
|
||||
#session-error {
|
||||
font-size: 11px; margin-top: 8px; min-height: 16px; color: #994444;
|
||||
}
|
||||
|
||||
/* ── Shared panel primitives ──────────────────────────────────────── */
|
||||
.panel-label { font-size: 10px; letter-spacing: 2px; color: #334466; margin-bottom: 6px; margin-top: 16px; }
|
||||
#session-panel .panel-label { color: #1a4430; }
|
||||
|
||||
#job-input {
|
||||
width: 100%; background: #060310; border: 1px solid #1a1a2e;
|
||||
color: #aabbdd; font-family: 'Courier New', monospace; font-size: 12px;
|
||||
padding: 10px; resize: vertical; min-height: 90px;
|
||||
outline: none; transition: border-color 0.2s;
|
||||
}
|
||||
#job-input:focus { border-color: #4466aa; }
|
||||
#job-input::placeholder { color: #1a1a2e; }
|
||||
|
||||
.panel-btn {
|
||||
width: 100%; margin-top: 12px;
|
||||
background: transparent; border: 1px solid #334466;
|
||||
color: #5577aa; font-family: 'Courier New', monospace;
|
||||
font-size: 12px; letter-spacing: 2px; padding: 10px;
|
||||
cursor: pointer; transition: all 0.2s;
|
||||
}
|
||||
.panel-btn:hover:not(:disabled) { background: #334466; color: #aabbdd; }
|
||||
.panel-btn:disabled { opacity: 0.35; cursor: not-allowed; }
|
||||
.panel-btn.primary { border-color: #4466aa; color: #7799cc; }
|
||||
.panel-btn.primary:hover:not(:disabled) { background: #4466aa; color: #fff; }
|
||||
.panel-btn.primary-green { border-color: #22aa66; color: #44dd88; }
|
||||
.panel-btn.primary-green:hover:not(:disabled) { background: #22aa66; color: #000; }
|
||||
.panel-btn.danger { border-color: #663333; color: #995555; }
|
||||
.panel-btn.muted { border-color: #0e2318; color: #226644; }
|
||||
.panel-btn.muted:hover:not(:disabled) { background: #0e2318; color: #44dd88; }
|
||||
|
||||
#job-status { font-size: 11px; margin-top: 8px; color: #5577aa; min-height: 16px; }
|
||||
#job-error { font-size: 11px; margin-top: 4px; min-height: 16px; color: #994444; }
|
||||
|
||||
.invoice-box {
|
||||
background: #060310; border: 1px solid #1a1a2e;
|
||||
padding: 10px; margin-top: 8px; font-size: 10px; color: #334466;
|
||||
word-break: break-all; max-height: 80px; overflow-y: auto;
|
||||
}
|
||||
#session-panel .invoice-box {
|
||||
background: #020806; border-color: #0e2318; color: #1a4430;
|
||||
}
|
||||
.copy-row { display: flex; gap: 8px; margin-top: 6px; align-items: stretch; }
|
||||
.copy-row .invoice-box { flex: 1; margin-top: 0; }
|
||||
.copy-btn {
|
||||
background: transparent; border: 1px solid #1a1a2e; color: #334466;
|
||||
font-family: 'Courier New', monospace; font-size: 10px;
|
||||
padding: 0 10px; cursor: pointer; transition: all 0.2s; white-space: nowrap;
|
||||
}
|
||||
.copy-btn:hover { border-color: #4466aa; color: #6688bb; }
|
||||
#session-panel .copy-btn { border-color: #0e2318; color: #1a4430; }
|
||||
#session-panel .copy-btn:hover { border-color: #22aa66; color: #44dd88; }
|
||||
|
||||
.amount-tag {
|
||||
display: inline-block; background: #0a0820;
|
||||
border: 1px solid #334466; color: #6688bb;
|
||||
font-size: 16px; font-weight: bold; letter-spacing: 2px;
|
||||
padding: 6px 14px; margin-top: 8px;
|
||||
}
|
||||
#session-panel .amount-tag {
|
||||
background: #020806; border-color: #22aa66; color: #44dd88;
|
||||
}
|
||||
#job-result {
|
||||
background: #060310; border: 1px solid #1a1a2e;
|
||||
color: #aabbdd; padding: 12px; font-size: 12px;
|
||||
line-height: 1.6; margin-top: 8px;
|
||||
white-space: pre-wrap; max-height: 260px; overflow-y: auto;
|
||||
}
|
||||
.panel-link {
|
||||
display: block; text-align: center; margin-top: 20px;
|
||||
font-size: 10px; letter-spacing: 1px; color: #1a1a2e;
|
||||
text-decoration: none; transition: color 0.2s;
|
||||
}
|
||||
.panel-link:hover { color: #5577aa; }
|
||||
|
||||
/* ── AR pulse animation ──────────────────────────────────────────── */
|
||||
@keyframes ar-pulse {
|
||||
0%, 100% { opacity: 0.6; transform: scale(1); }
|
||||
50% { opacity: 1; transform: scale(1.5); }
|
||||
}
|
||||
|
||||
/* ── Crosshair ───────────────────────────────────────────────────── */
|
||||
#crosshair {
|
||||
position: fixed; top: 50%; left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
pointer-events: none; z-index: 12;
|
||||
opacity: 0.5;
|
||||
}
|
||||
#crosshair::before, #crosshair::after {
|
||||
content: ''; position: absolute;
|
||||
background: rgba(180, 160, 220, 0.7);
|
||||
border-radius: 1px;
|
||||
}
|
||||
#crosshair::before { width: 16px; height: 1px; top: 0; left: -8px; }
|
||||
#crosshair::after { width: 1px; height: 16px; top: -8px; left: 0; }
|
||||
|
||||
/* ── Lock hint (desktop) ─────────────────────────────────────────── */
|
||||
#lock-hint {
|
||||
position: fixed; inset: 0;
|
||||
display: none;
|
||||
align-items: center; justify-content: center;
|
||||
z-index: 11; pointer-events: none;
|
||||
}
|
||||
#lock-hint .lock-badge {
|
||||
background: rgba(8, 6, 20, 0.72);
|
||||
border: 1px solid rgba(80, 100, 160, 0.5);
|
||||
border-radius: 8px;
|
||||
color: #5577aa;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 11px; letter-spacing: 2px;
|
||||
padding: 10px 24px;
|
||||
text-align: center;
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
animation: lock-fade 2s ease-in-out infinite alternate;
|
||||
}
|
||||
@keyframes lock-fade {
|
||||
0% { opacity: 0.45; }
|
||||
100% { opacity: 0.9; }
|
||||
}
|
||||
|
||||
/* ── Virtual joystick (mobile) ───────────────────────────────────── */
|
||||
#joy-pad {
|
||||
position: fixed;
|
||||
display: none; /* shown by navigation.js on mobile */
|
||||
align-items: center; justify-content: center;
|
||||
width: 110px; height: 110px;
|
||||
border-radius: 50%;
|
||||
background: rgba(40, 30, 70, 0.38);
|
||||
border: 1.5px solid rgba(100, 80, 180, 0.45);
|
||||
backdrop-filter: blur(4px);
|
||||
-webkit-backdrop-filter: blur(4px);
|
||||
z-index: 18;
|
||||
pointer-events: none; /* touches handled on canvas */
|
||||
opacity: 0.35;
|
||||
transition: opacity 0.25s;
|
||||
bottom: 80px; left: 20px;
|
||||
}
|
||||
#joy-nub {
|
||||
width: 38px; height: 38px; border-radius: 50%;
|
||||
background: rgba(140, 110, 220, 0.65);
|
||||
border: 1.5px solid rgba(180, 150, 255, 0.6);
|
||||
position: absolute;
|
||||
top: 50%; left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
box-shadow: 0 0 14px rgba(140, 110, 220, 0.5);
|
||||
transition: transform 0.05s linear;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ── AR label pulse ──────────────────────────────────────────────── */
|
||||
.ar-label { transition: opacity 0.25s; }
|
||||
|
||||
/* ── WebGL recovery overlay ──────────────────────────────────────── */
|
||||
#webgl-recovery-overlay {
|
||||
display: none; position: fixed; inset: 0; z-index: 200;
|
||||
background: rgba(5, 3, 12, 0.92);
|
||||
justify-content: center; align-items: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
#webgl-recovery-overlay .recovery-text {
|
||||
color: #5577aa; font-family: 'Courier New', monospace;
|
||||
font-size: 15px; letter-spacing: 3px;
|
||||
animation: ctx-blink 1.2s step-end infinite;
|
||||
}
|
||||
@keyframes ctx-blink {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.2; }
|
||||
}
|
||||
|
||||
/* ── Timmy identity card ──────────────────────────────────────────── */
|
||||
#timmy-id-card {
|
||||
position: fixed; bottom: 80px; right: 16px;
|
||||
font-size: 10px; color: #334466;
|
||||
pointer-events: all; z-index: 10;
|
||||
text-align: right; line-height: 1.8;
|
||||
}
|
||||
#timmy-id-card .id-label {
|
||||
letter-spacing: 2px; color: #223355;
|
||||
text-transform: uppercase; font-size: 9px;
|
||||
}
|
||||
#timmy-id-card .id-npub {
|
||||
color: #4466aa; cursor: pointer;
|
||||
text-decoration: underline dotted;
|
||||
font-size: 10px; letter-spacing: 0.5px;
|
||||
}
|
||||
#timmy-id-card .id-npub:hover { color: #88aadd; }
|
||||
#timmy-id-card .id-zaps { color: #556688; font-size: 9px; }
|
||||
</style>
|
||||
<script type="module" crossorigin src="/tower/assets/index-CBu1T9J9.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="hud">
|
||||
<h1>THE WORKSHOP</h1>
|
||||
<div id="fps">FPS: --</div>
|
||||
<div id="active-jobs">JOBS: 0</div>
|
||||
<div id="session-hud">
|
||||
<span id="session-hud-balance">Balance: -- sats</span>
|
||||
<a href="#" id="session-hud-topup">⚡ Top Up</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="connection-status">OFFLINE</div>
|
||||
<div id="event-log"></div>
|
||||
|
||||
<!-- ── Timmy identity card ────────────────────────────────────────── -->
|
||||
<div id="timmy-id-card">
|
||||
<div class="id-label">TIMMY IDENTITY</div>
|
||||
<div class="id-npub" id="timmy-npub" title="Click to copy Timmy's Nostr npub">…</div>
|
||||
<div class="id-zaps" id="timmy-zap-count">⚡ 0 zaps sent</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Top action buttons ─────────────────────────────────────────── -->
|
||||
<div id="top-buttons">
|
||||
<button id="open-panel-btn">⚡ SUBMIT JOB</button>
|
||||
<button id="open-session-btn">⚡ FUND SESSION</button>
|
||||
</div>
|
||||
|
||||
<!-- ── Low balance notice (above input bar) ───────────────────────── -->
|
||||
<div id="low-balance-notice">
|
||||
⚡ Low balance —
|
||||
<button id="topup-quick-btn">Top Up</button>
|
||||
</div>
|
||||
|
||||
<!-- ── Input bar ──────────────────────────────────────────────────── -->
|
||||
<div id="input-bar">
|
||||
<input type="text" id="visitor-input" placeholder="Say something to Timmy…" autocomplete="off" autocorrect="off" spellcheck="false" />
|
||||
<button id="send-btn" aria-label="Send">→</button>
|
||||
</div>
|
||||
|
||||
<!-- ── Payment panel (right side) ────────────────────────────────── -->
|
||||
<div id="payment-panel">
|
||||
<button id="payment-close">✕</button>
|
||||
<h2>⚡ TIMMY — JOB SUBMISSION</h2>
|
||||
|
||||
<div data-step="input">
|
||||
<div class="panel-label">YOUR REQUEST</div>
|
||||
<textarea id="job-input" maxlength="500" placeholder="Ask Timmy anything… (max 500 chars)"></textarea>
|
||||
<button class="panel-btn primary" id="job-submit-btn">CREATE JOB →</button>
|
||||
<a class="panel-link" href="/api/ui" target="_blank">Open full UI ↗</a>
|
||||
</div>
|
||||
|
||||
<div data-step="eval-invoice" style="display:none">
|
||||
<div class="panel-label">EVAL FEE</div>
|
||||
<div class="amount-tag" id="eval-amount">10 sats</div>
|
||||
<div class="panel-label" style="margin-top:12px">LIGHTNING INVOICE</div>
|
||||
<div class="copy-row">
|
||||
<div class="invoice-box" id="eval-payment-request"></div>
|
||||
<button class="copy-btn" onclick="_timmyCopy('eval-payment-request')">COPY</button>
|
||||
</div>
|
||||
<span id="eval-hash" data-hash=""></span>
|
||||
<button class="panel-btn primary" id="pay-eval-btn">⚡ SIMULATE PAYMENT</button>
|
||||
</div>
|
||||
|
||||
<div data-step="work-invoice" style="display:none">
|
||||
<div class="panel-label">WORK FEE</div>
|
||||
<div class="amount-tag" id="work-amount">-- sats</div>
|
||||
<div class="panel-label" style="margin-top:12px">LIGHTNING INVOICE</div>
|
||||
<div class="copy-row">
|
||||
<div class="invoice-box" id="work-payment-request"></div>
|
||||
<button class="copy-btn" onclick="_timmyCopy('work-payment-request')">COPY</button>
|
||||
</div>
|
||||
<span id="work-hash" data-hash=""></span>
|
||||
<button class="panel-btn primary" id="pay-work-btn">⚡ SIMULATE PAYMENT</button>
|
||||
</div>
|
||||
|
||||
<div data-step="result" style="display:none">
|
||||
<div class="panel-label" id="result-label">AI RESULT</div>
|
||||
<pre id="job-result"></pre>
|
||||
<button class="panel-btn" id="new-job-btn" style="margin-top:16px">← NEW JOB</button>
|
||||
</div>
|
||||
|
||||
<div id="job-status"></div>
|
||||
<div id="job-error"></div>
|
||||
</div>
|
||||
|
||||
<!-- ── Session panel (left side) ─────────────────────────────────── -->
|
||||
<div id="session-panel">
|
||||
<button id="session-close">✕</button>
|
||||
<h2>⚡ TIMMY — SESSION</h2>
|
||||
|
||||
<!-- Step: fund — choose deposit amount -->
|
||||
<div data-session-step="fund">
|
||||
<div class="panel-label">DEPOSIT AMOUNT (200–10,000 sats)</div>
|
||||
<div class="session-amount-presets">
|
||||
<button class="session-amount-btn" data-sats="200">200</button>
|
||||
<button class="session-amount-btn active" data-sats="500">500</button>
|
||||
<button class="session-amount-btn" data-sats="1000">1000</button>
|
||||
<button class="session-amount-btn" data-sats="2000">2000</button>
|
||||
<button class="session-amount-btn" data-sats="5000">5000</button>
|
||||
<button class="session-amount-btn" data-sats="10000">10k</button>
|
||||
</div>
|
||||
<div class="session-amount-row">
|
||||
<input type="number" id="session-amount-input" class="session-amount-input"
|
||||
min="200" max="10000" value="500" step="1" />
|
||||
<span>sats</span>
|
||||
</div>
|
||||
<button class="panel-btn primary-green" id="session-create-btn" style="margin-top:12px">START SESSION →</button>
|
||||
<div id="session-status-fund"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step: invoice — pay the deposit -->
|
||||
<div data-session-step="invoice" style="display:none">
|
||||
<div class="panel-label">DEPOSIT AMOUNT</div>
|
||||
<div class="amount-tag" id="session-invoice-amount">-- sats</div>
|
||||
<div class="panel-label" style="margin-top:14px">SCAN OR COPY INVOICE</div>
|
||||
<div class="qr-placeholder" id="session-invoice-qr">[ QR ]</div>
|
||||
<div class="copy-row" style="margin-top:6px">
|
||||
<div class="invoice-box" id="session-invoice-pr"></div>
|
||||
<button class="copy-btn" onclick="_timmyCopy('session-invoice-pr')">COPY</button>
|
||||
</div>
|
||||
<span id="session-invoice-hash" data-hash="" style="display:none"></span>
|
||||
<button class="panel-btn primary-green" id="session-pay-btn" style="margin-top:14px">⚡ SIMULATE PAYMENT</button>
|
||||
<div id="session-status-invoice"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step: active — session running, show balance + topup -->
|
||||
<div data-session-step="active" style="display:none">
|
||||
<div class="panel-label">BALANCE</div>
|
||||
<div class="amount-tag session-green" id="session-active-amount">-- sats</div>
|
||||
<p style="font-size:10px;color:#1a4430;margin-top:14px;line-height:1.6;letter-spacing:1px">
|
||||
TYPE IN THE INPUT BAR TO ASK TIMMY.<br>EACH REQUEST DEDUCTS FROM YOUR BALANCE.
|
||||
</p>
|
||||
<button class="panel-btn muted" id="session-topup-btn" style="margin-top:20px">⚡ TOP UP BALANCE</button>
|
||||
<div id="session-status-active"></div>
|
||||
</div>
|
||||
|
||||
<!-- Step: topup — choose topup amount and pay -->
|
||||
<div data-session-step="topup" style="display:none">
|
||||
<div class="panel-label">TOPUP AMOUNT (200–10,000 sats)</div>
|
||||
<div class="session-amount-presets">
|
||||
<button class="session-amount-btn" data-sats="200">200</button>
|
||||
<button class="session-amount-btn active" data-sats="500">500</button>
|
||||
<button class="session-amount-btn" data-sats="1000">1000</button>
|
||||
<button class="session-amount-btn" data-sats="2000">2000</button>
|
||||
<button class="session-amount-btn" data-sats="5000">5000</button>
|
||||
<button class="session-amount-btn" data-sats="10000">10k</button>
|
||||
</div>
|
||||
<div class="session-amount-row">
|
||||
<input type="number" id="session-topup-input" class="session-amount-input"
|
||||
min="200" max="10000" value="500" step="1" />
|
||||
<span>sats</span>
|
||||
</div>
|
||||
<button class="panel-btn primary-green" id="session-topup-create-btn" style="margin-top:12px">CREATE TOPUP INVOICE →</button>
|
||||
|
||||
<div id="session-topup-pr-row" style="display:none">
|
||||
<div class="panel-label" style="margin-top:14px">SCAN OR COPY INVOICE</div>
|
||||
<div class="qr-placeholder" id="session-topup-qr">[ QR ]</div>
|
||||
<div class="copy-row" style="margin-top:6px">
|
||||
<div class="invoice-box" id="session-topup-pr"></div>
|
||||
<button class="copy-btn" onclick="_timmyCopy('session-topup-pr')">COPY</button>
|
||||
</div>
|
||||
<span id="session-topup-hash" data-hash="" style="display:none"></span>
|
||||
<button class="panel-btn primary-green" id="session-topup-pay-btn" style="margin-top:10px">⚡ SIMULATE TOPUP</button>
|
||||
</div>
|
||||
|
||||
<div id="session-status-topup"></div>
|
||||
<button class="panel-btn muted" id="session-back-btn" style="margin-top:10px">← BACK</button>
|
||||
</div>
|
||||
|
||||
<div id="session-error"></div>
|
||||
</div>
|
||||
|
||||
<!-- ── FPS crosshair ─────────────────────────────────────────────── -->
|
||||
<div id="crosshair"></div>
|
||||
|
||||
<!-- ── Pointer-lock hint (desktop) ──────────────────────────────── -->
|
||||
<div id="lock-hint">
|
||||
<div class="lock-badge">CLICK TO ENTER · WASD TO MOVE · ESC TO EXIT</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Virtual joystick (mobile) ─────────────────────────────────── -->
|
||||
<div id="joy-pad">
|
||||
<div id="joy-nub"></div>
|
||||
</div>
|
||||
|
||||
<!-- ── AR floating labels container ──────────────────────────────── -->
|
||||
<div id="ar-labels" style="position:fixed;inset:0;pointer-events:none;z-index:15;overflow:hidden;"></div>
|
||||
|
||||
<div id="webgl-recovery-overlay">
|
||||
<span class="recovery-text">GPU context lost — recovering...</span>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
24
the-matrix/dist/manifest.json
vendored
24
the-matrix/dist/manifest.json
vendored
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"name": "The Matrix",
|
||||
"short_name": "The Matrix",
|
||||
"description": "Timmy Tower World — live agent network visualization",
|
||||
"start_url": "/",
|
||||
"display": "standalone",
|
||||
"orientation": "landscape",
|
||||
"background_color": "#000000",
|
||||
"theme_color": "#00ff41",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icons/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
},
|
||||
{
|
||||
"src": "/icons/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
45
the-matrix/dist/sw.js
vendored
45
the-matrix/dist/sw.js
vendored
@@ -1,45 +0,0 @@
|
||||
/* sw.js — Matrix PWA service worker
|
||||
* PRECACHE_URLS is replaced at build time by the generate-sw Vite plugin.
|
||||
* Registration is gated to import.meta.env.PROD in main.js, so this template
|
||||
* file is never evaluated by browsers during development.
|
||||
*/
|
||||
const CACHE_NAME = 'timmy-matrix-v1';
|
||||
const PRECACHE_URLS = [
|
||||
"/",
|
||||
"/manifest.json",
|
||||
"/icons/icon-192.png",
|
||||
"/icons/icon-512.png",
|
||||
"/assets/index-CBu1T9J9.js"
|
||||
];
|
||||
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME).then(cache => cache.addAll(PRECACHE_URLS))
|
||||
);
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', event => {
|
||||
event.waitUntil(
|
||||
caches.keys().then(keys =>
|
||||
Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
|
||||
)
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', event => {
|
||||
if (event.request.method !== 'GET') return;
|
||||
event.respondWith(
|
||||
caches.match(event.request).then(cached => {
|
||||
if (cached) return cached;
|
||||
return fetch(event.request).then(response => {
|
||||
if (!response || response.status !== 200 || response.type !== 'basic') {
|
||||
return response;
|
||||
}
|
||||
caches.open(CACHE_NAME).then(cache => cache.put(event.request, response.clone()));
|
||||
return response;
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -330,6 +330,14 @@
|
||||
.panel-btn.muted { border-color: #0e2318; color: #226644; }
|
||||
.panel-btn.muted:hover:not(:disabled) { background: #0e2318; color: #44dd88; }
|
||||
|
||||
.session-link-btn {
|
||||
background: none; border: none; color: #557755; font-size: 10px;
|
||||
font-family: inherit; cursor: pointer; margin-top: 10px; padding: 4px 0;
|
||||
letter-spacing: 1px; display: block;
|
||||
}
|
||||
.session-link-btn:hover:not(:disabled) { color: #44dd88; text-decoration: underline; }
|
||||
.session-link-btn:disabled { opacity: 0.35; cursor: not-allowed; }
|
||||
|
||||
#job-status { font-size: 11px; margin-top: 8px; color: #5577aa; min-height: 16px; }
|
||||
#job-error { font-size: 11px; margin-top: 4px; min-height: 16px; color: #994444; }
|
||||
|
||||
@@ -374,6 +382,24 @@
|
||||
}
|
||||
.panel-link:hover { color: #5577aa; }
|
||||
|
||||
/* ── Relay Admin button ───────────────────────────────────────────── */
|
||||
#relay-admin-btn {
|
||||
display: none;
|
||||
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
|
||||
color: #f7931a; background: rgba(40, 25, 5, 0.85); border: 1px solid #f7931a55;
|
||||
padding: 7px 18px; cursor: pointer; letter-spacing: 2px;
|
||||
box-shadow: 0 0 14px #f7931a22;
|
||||
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
|
||||
border-radius: 2px;
|
||||
min-height: 36px;
|
||||
text-decoration: none;
|
||||
}
|
||||
#relay-admin-btn:hover, #relay-admin-btn:active {
|
||||
background: rgba(60, 35, 8, 0.95);
|
||||
box-shadow: 0 0 20px #f7931a44;
|
||||
color: #ffb347;
|
||||
}
|
||||
|
||||
/* ── AR pulse animation ──────────────────────────────────────────── */
|
||||
@keyframes ar-pulse {
|
||||
0%, 100% { opacity: 0.6; transform: scale(1); }
|
||||
@@ -460,8 +486,9 @@
|
||||
pointer-events: none;
|
||||
}
|
||||
#webgl-recovery-overlay .recovery-text {
|
||||
color: #5577aa; font-family: 'Courier New', monospace;
|
||||
color: #22aa66; font-family: 'Courier New', monospace;
|
||||
font-size: 15px; letter-spacing: 3px;
|
||||
text-shadow: 0 0 10px #11663388;
|
||||
animation: ctx-blink 1.2s step-end infinite;
|
||||
}
|
||||
@keyframes ctx-blink {
|
||||
@@ -514,6 +541,7 @@
|
||||
<div id="top-buttons">
|
||||
<button id="open-panel-btn">⚡ SUBMIT JOB</button>
|
||||
<button id="open-session-btn">⚡ FUND SESSION</button>
|
||||
<a id="relay-admin-btn" href="/admin/relay">⚙ RELAY ADMIN</a>
|
||||
</div>
|
||||
|
||||
<!-- ── Low balance notice (above input bar) ───────────────────────── -->
|
||||
@@ -622,6 +650,7 @@
|
||||
TYPE IN THE INPUT BAR TO ASK TIMMY.<br>EACH REQUEST DEDUCTS FROM YOUR BALANCE.
|
||||
</p>
|
||||
<button class="panel-btn muted" id="session-topup-btn" style="margin-top:20px">⚡ TOP UP BALANCE</button>
|
||||
<button id="session-clear-history-btn" class="session-link-btn">🗑 Clear history</button>
|
||||
<div id="session-status-active"></div>
|
||||
</div>
|
||||
|
||||
@@ -681,6 +710,15 @@
|
||||
<span class="recovery-text">GPU context lost — recovering...</span>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Show Relay Admin button if admin token is stored in localStorage
|
||||
(function() {
|
||||
if (localStorage.getItem('relay_admin_token')) {
|
||||
var btn = document.getElementById('relay-admin-btn');
|
||||
if (btn) btn.style.display = 'block';
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
<script type="module" src="./js/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -36,11 +36,12 @@ const COUNTER_RETORTS = [
|
||||
"YOU'LL REGRET THAT, MORTAL!",
|
||||
];
|
||||
|
||||
// Residual mini-spring for slight trembling post-fall (STAND only)
|
||||
const SPRING_STIFFNESS = 7.0;
|
||||
const SPRING_DAMPING = 0.80;
|
||||
const MAX_TILT_RAD = 0.12;
|
||||
const SLAP_IMPULSE = 0.18;
|
||||
// Spring physics for slap wobble (STAND only)
|
||||
const SPRING_STIFFNESS = 18.0;
|
||||
const SPRING_DAMPING = 4.5;
|
||||
const MAX_TILT_RAD = 0.55;
|
||||
const SLAP_IMPULSE = 2.8;
|
||||
const RAGDOLL_TILT_THRESHOLD = 0.42; // if tilt exceeds this, trigger full ragdoll fall
|
||||
|
||||
// ── Face emotion targets per internal state ───────────────────────────────────
|
||||
// lidScale: 0 = fully closed, 1 = wide open
|
||||
@@ -681,31 +682,54 @@ function _updateRagdoll(dt, t, bodyBob) {
|
||||
}
|
||||
|
||||
// ── applySlap — called by interaction.js on hit ───────────────────────────────
|
||||
// Applies an additive spring impulse so repeated slaps stack. If accumulated
|
||||
// tilt exceeds RAGDOLL_TILT_THRESHOLD the full ragdoll fall is triggered.
|
||||
export function applySlap(hitPoint) {
|
||||
if (!timmy) return;
|
||||
|
||||
// Ignore re-slap while already falling/down — wait until standing again
|
||||
const rd = timmy.rd;
|
||||
|
||||
// Ignore re-slap while already in ragdoll cycle — wait until standing
|
||||
if (rd.state !== RD_STAND) return;
|
||||
|
||||
// XZ direction from Timmy to hit point (fall away from impact)
|
||||
// XZ direction from Timmy to hit point (wobble/fall away from impact)
|
||||
const dx = hitPoint.x - TIMMY_POS.x;
|
||||
const dz = hitPoint.z - TIMMY_POS.z;
|
||||
const len = Math.sqrt(dx * dx + dz * dz) || 1;
|
||||
rd.fallDirX = dx / len;
|
||||
rd.fallDirZ = dz / len;
|
||||
const dirX = dx / len;
|
||||
const dirZ = dz / len;
|
||||
|
||||
// Start ragdoll fall
|
||||
rd.state = RD_FALL;
|
||||
rd.timer = 0;
|
||||
rd.fallAngle = 0;
|
||||
// Additive spring impulse — stacks with any existing wobble
|
||||
rd.slapVelocity.x += dirZ * SLAP_IMPULSE; // rotation.x driven by Z direction
|
||||
rd.slapVelocity.z += -dirX * SLAP_IMPULSE; // rotation.z driven by X direction
|
||||
|
||||
// Pip startle — maximum scatter
|
||||
timmy.pipStartleTimer = 5.0;
|
||||
timmy.pipStartleDir.x = (Math.random() - 0.5) * 8.0;
|
||||
timmy.pipStartleDir.z = (Math.random() - 0.5) * 8.0;
|
||||
// Check if accumulated tilt is large enough to trigger full ragdoll
|
||||
const tiltMag = Math.sqrt(rd.slapOffset.x * rd.slapOffset.x + rd.slapOffset.z * rd.slapOffset.z);
|
||||
const velMag = Math.sqrt(rd.slapVelocity.x * rd.slapVelocity.x + rd.slapVelocity.z * rd.slapVelocity.z);
|
||||
|
||||
// Crystal flash on impact
|
||||
if (tiltMag > RAGDOLL_TILT_THRESHOLD || velMag > SLAP_IMPULSE * 2.2) {
|
||||
// Enough stacked force — trigger full ragdoll fall
|
||||
rd.fallDirX = dirX;
|
||||
rd.fallDirZ = dirZ;
|
||||
rd.state = RD_FALL;
|
||||
rd.timer = 0;
|
||||
rd.fallAngle = 0;
|
||||
// Reset spring state so it's clean when returning to STAND
|
||||
rd.slapOffset.x = 0; rd.slapOffset.z = 0;
|
||||
rd.slapVelocity.x = 0; rd.slapVelocity.z = 0;
|
||||
|
||||
// Pip startle — maximum scatter on ragdoll
|
||||
timmy.pipStartleTimer = 5.0;
|
||||
timmy.pipStartleDir.x = (Math.random() - 0.5) * 8.0;
|
||||
timmy.pipStartleDir.z = (Math.random() - 0.5) * 8.0;
|
||||
} else {
|
||||
// Pip mild startle on wobble
|
||||
timmy.pipStartleTimer = Math.max(timmy.pipStartleTimer, 3.0);
|
||||
timmy.pipStartleDir.x = (Math.random() - 0.5) * 4.0;
|
||||
timmy.pipStartleDir.z = (Math.random() - 0.5) * 4.0;
|
||||
}
|
||||
|
||||
// Crystal flash on every hit
|
||||
timmy.hitFlashTimer = 0.5;
|
||||
|
||||
// Cartoonish SMACK sound
|
||||
|
||||
@@ -51,6 +51,7 @@ export function initSessionPanel() {
|
||||
_on('session-back-btn', 'click', () => _setStep('active'));
|
||||
_on('topup-quick-btn', 'click', () => { _openPanel(); _setStep('topup'); });
|
||||
_on('session-hud-topup', 'click', (e) => { e.preventDefault(); _openPanel(); _setStep('topup'); });
|
||||
_on('session-clear-history-btn', 'click', _clearHistory);
|
||||
|
||||
// Amount preset buttons — deposit (quick-fill the number input)
|
||||
_panel.querySelectorAll('[data-session-step="fund"] .session-amount-btn').forEach(btn => {
|
||||
@@ -419,6 +420,30 @@ function _startTopupPolling() {
|
||||
_pollTimer = setTimeout(poll, POLL_MS);
|
||||
}
|
||||
|
||||
// ── Clear history ─────────────────────────────────────────────────────────────
|
||||
|
||||
async function _clearHistory() {
|
||||
if (!_sessionId || !_macaroon) return;
|
||||
const btn = document.getElementById('session-clear-history-btn');
|
||||
if (btn) btn.disabled = true;
|
||||
try {
|
||||
const res = await fetch(`${API}/sessions/${_sessionId}/history`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${_macaroon}` },
|
||||
});
|
||||
if (res.ok) {
|
||||
_setStatus('active', '✓ History cleared', '#44dd88');
|
||||
setTimeout(() => _setStatus('active', '', ''), 2500);
|
||||
} else {
|
||||
_setStatus('active', 'Failed to clear history', '#ff6644');
|
||||
}
|
||||
} catch (err) {
|
||||
_setStatus('active', 'Error: ' + err.message, '#ff6644');
|
||||
} finally {
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Restore from localStorage ─────────────────────────────────────────────────
|
||||
|
||||
async function _tryRestore() {
|
||||
|
||||
@@ -132,6 +132,54 @@ function _scheduleCostPreview(text) {
|
||||
_estimateTimer = setTimeout(() => _fetchEstimate(text), 300);
|
||||
}
|
||||
|
||||
// ── Live cost ticker ──────────────────────────────────────────────────────────
|
||||
// Shown in the top-right HUD during active paid interactions.
|
||||
// Updated via WebSocket `cost_update` messages from the backend.
|
||||
|
||||
let $costTicker = null;
|
||||
let _tickerHideTimer = null;
|
||||
|
||||
function _ensureCostTicker() {
|
||||
if ($costTicker) return $costTicker;
|
||||
$costTicker = document.getElementById('timmy-cost-ticker');
|
||||
if (!$costTicker) {
|
||||
$costTicker = document.createElement('div');
|
||||
$costTicker.id = 'timmy-cost-ticker';
|
||||
$costTicker.style.cssText = [
|
||||
'position:fixed;top:36px;right:16px',
|
||||
'font-size:11px;font-family:"Courier New",monospace',
|
||||
'color:#ffcc44;text-shadow:0 0 6px #aa8822',
|
||||
'letter-spacing:1px',
|
||||
'pointer-events:none;z-index:10',
|
||||
'transition:opacity .4s;opacity:0',
|
||||
].join(';');
|
||||
document.body.appendChild($costTicker);
|
||||
}
|
||||
return $costTicker;
|
||||
}
|
||||
|
||||
export function showCostTicker(sats) {
|
||||
clearTimeout(_tickerHideTimer);
|
||||
const el = _ensureCostTicker();
|
||||
el.textContent = `⚡ ~${sats} sats`;
|
||||
el.style.opacity = '1';
|
||||
}
|
||||
|
||||
export function updateCostTicker(sats, isFinal = false) {
|
||||
clearTimeout(_tickerHideTimer);
|
||||
const el = _ensureCostTicker();
|
||||
el.textContent = isFinal ? `⚡ ${sats} sats charged` : `⚡ ~${sats} sats`;
|
||||
el.style.opacity = '1';
|
||||
if (isFinal) {
|
||||
_tickerHideTimer = setTimeout(hideCostTicker, 5000);
|
||||
}
|
||||
}
|
||||
|
||||
export function hideCostTicker() {
|
||||
if (!$costTicker) return;
|
||||
$costTicker.style.opacity = '0';
|
||||
}
|
||||
|
||||
// ── Input bar ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export function initUI() {
|
||||
@@ -257,3 +305,129 @@ export function appendDebateMessage(agent, argument, isVerdict, accepted) {
|
||||
|
||||
export function loadChatHistory() { return []; }
|
||||
export function saveChatHistory() {}
|
||||
|
||||
// ── Task decomposition checklist panel (#5) ───────────────────────────────────
|
||||
// Appears near the active Gamma agent during job execution.
|
||||
// Steps are checked off as streaming progresses, then collapses to "Done".
|
||||
|
||||
let $stepsPanel = null;
|
||||
let _stepElements = [];
|
||||
let _collapseTimer = null;
|
||||
|
||||
function _ensureStepsPanel() {
|
||||
if ($stepsPanel) return $stepsPanel;
|
||||
$stepsPanel = document.getElementById('timmy-steps-panel');
|
||||
if (!$stepsPanel) {
|
||||
$stepsPanel = document.createElement('div');
|
||||
$stepsPanel.id = 'timmy-steps-panel';
|
||||
$stepsPanel.style.cssText = [
|
||||
'position:fixed;bottom:80px;right:16px',
|
||||
'background:rgba(0,20,40,0.88);border:1px solid #224466',
|
||||
'border-radius:6px;padding:8px 12px',
|
||||
'font-size:11px;font-family:"Courier New",monospace',
|
||||
'color:#88bbdd;min-width:200px;max-width:280px',
|
||||
'pointer-events:none;z-index:10',
|
||||
'transition:opacity .4s;opacity:0',
|
||||
].join(';');
|
||||
document.body.appendChild($stepsPanel);
|
||||
}
|
||||
return $stepsPanel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the checklist panel with the given step labels.
|
||||
* Called on `job_steps` WebSocket message.
|
||||
*/
|
||||
export function showJobSteps(steps) {
|
||||
clearTimeout(_collapseTimer);
|
||||
const panel = _ensureStepsPanel();
|
||||
|
||||
// Clear previous content
|
||||
panel.innerHTML = '';
|
||||
_stepElements = [];
|
||||
|
||||
const header = document.createElement('div');
|
||||
header.textContent = '⚙ Working…';
|
||||
header.style.cssText = 'color:#aaccee;font-weight:bold;margin-bottom:5px;font-size:10px;letter-spacing:1px;';
|
||||
panel.appendChild(header);
|
||||
|
||||
steps.forEach((label, i) => {
|
||||
const row = document.createElement('div');
|
||||
row.style.cssText = 'display:flex;align-items:center;gap:5px;margin:2px 0;transition:color .3s;';
|
||||
|
||||
const check = document.createElement('span');
|
||||
check.textContent = '○';
|
||||
check.style.cssText = 'min-width:12px;color:#336655;';
|
||||
|
||||
const text = document.createElement('span');
|
||||
text.textContent = label;
|
||||
|
||||
row.appendChild(check);
|
||||
row.appendChild(text);
|
||||
panel.appendChild(row);
|
||||
_stepElements.push({ row, check, text, index: i });
|
||||
});
|
||||
|
||||
panel.style.opacity = '1';
|
||||
}
|
||||
|
||||
/**
|
||||
* Advance the visual state of steps.
|
||||
* activeStep = currently running step index (-1 = all done).
|
||||
* completedSteps = array of step indices that are finished.
|
||||
* Called on `job_step_update` WebSocket message.
|
||||
*/
|
||||
export function updateJobStep(activeStep, completedSteps) {
|
||||
if (!$stepsPanel || _stepElements.length === 0) return;
|
||||
|
||||
const completedSet = new Set(completedSteps);
|
||||
|
||||
_stepElements.forEach(({ row, check, text, index }) => {
|
||||
if (completedSet.has(index)) {
|
||||
// Completed: green checkmark
|
||||
check.textContent = '✓';
|
||||
check.style.color = '#44cc88';
|
||||
text.style.color = '#667788';
|
||||
row.style.opacity = '0.7';
|
||||
} else if (index === activeStep) {
|
||||
// Active: pulsing indicator
|
||||
check.textContent = '▶';
|
||||
check.style.color = '#ffcc44';
|
||||
text.style.color = '#eeddaa';
|
||||
row.style.opacity = '1';
|
||||
// Pulse animation via inline keyframe trick
|
||||
row.style.animation = 'none';
|
||||
void row.offsetHeight; // reflow
|
||||
check.style.transition = 'opacity 0.5s';
|
||||
} else {
|
||||
// Pending
|
||||
check.textContent = '○';
|
||||
check.style.color = '#336655';
|
||||
text.style.color = '#88bbdd';
|
||||
row.style.opacity = '1';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapse the checklist panel to a single "Done" line, then fade out.
|
||||
* Called on `job_completed` WebSocket message.
|
||||
*/
|
||||
export function collapseJobSteps() {
|
||||
if (!$stepsPanel) return;
|
||||
clearTimeout(_collapseTimer);
|
||||
|
||||
// Replace content with a Done summary
|
||||
$stepsPanel.innerHTML = '';
|
||||
const done = document.createElement('div');
|
||||
done.textContent = '✓ Done';
|
||||
done.style.cssText = 'color:#44cc88;font-weight:bold;letter-spacing:1px;';
|
||||
$stepsPanel.appendChild(done);
|
||||
$stepsPanel.style.opacity = '1';
|
||||
|
||||
// Fade out after 2.5 s
|
||||
_collapseTimer = setTimeout(() => {
|
||||
if ($stepsPanel) $stepsPanel.style.opacity = '0';
|
||||
_stepElements = [];
|
||||
}, 2500);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { setAgentState, setSpeechBubble, applyAgentStates, setMood } from './agents.js';
|
||||
import { appendSystemMessage, appendDebateMessage } from './ui.js';
|
||||
import { appendSystemMessage, appendDebateMessage, showCostTicker, updateCostTicker, showJobSteps, updateJobStep, collapseJobSteps } from './ui.js';
|
||||
import { sentiment } from './edge-worker-client.js';
|
||||
import { setLabelState } from './hud-labels.js';
|
||||
|
||||
@@ -105,6 +105,7 @@ function handleMessage(msg) {
|
||||
setLabelState(msg.agentId, 'idle');
|
||||
}
|
||||
appendSystemMessage(`job ${(msg.jobId || '').slice(0, 8)} complete`);
|
||||
collapseJobSteps();
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -140,6 +141,31 @@ function handleMessage(msg) {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'job_steps': {
|
||||
// Task decomposition (#5): render checklist panel with step labels
|
||||
if (Array.isArray(msg.steps) && msg.steps.length > 0) {
|
||||
showJobSteps(msg.steps);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'job_step_update': {
|
||||
// Task decomposition (#5): advance active step and mark completed ones
|
||||
updateJobStep(msg.activeStep, msg.completedSteps || []);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'cost_update': {
|
||||
// Real-time cost ticker (#68): show estimated cost when job starts,
|
||||
// update to final charged amount when job completes.
|
||||
if (msg.isFinal) {
|
||||
updateCostTicker(msg.sats, true);
|
||||
} else {
|
||||
showCostTicker(msg.sats);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'agent_count':
|
||||
case 'visitor_count':
|
||||
break;
|
||||
|
||||
2
the-matrix/package-lock.json
generated
2
the-matrix/package-lock.json
generated
@@ -13,7 +13,7 @@
|
||||
"three": "0.171.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^5.4.0"
|
||||
"vite": "^5.4.15"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
|
||||
Reference in New Issue
Block a user