1 Commits

Author SHA1 Message Date
Alexander Whitestone
ac553cb6b4 feat: task decomposition view during execution (#5)
Some checks failed
CI / Typecheck & Lint (pull_request) Failing after 0s
At the start of job execution, a Haiku call decomposes the user's
request into 2-4 named sub-steps. Steps are broadcast via WebSocket
as `job_steps` and `job_step_update` events. The Workshop renders a
live checklist panel near Gamma that checks off steps as streaming
progresses using a character-count heuristic, then collapses to
"Done" on completion. Steps are stored with the job record.

- agent.ts: add `decomposeRequest` (Haiku, stub-safe)
- event-bus.ts: add `DecompositionEvent` types (job:steps, job:step_update)
- jobs.ts: call decompose before streaming; advance steps heuristically
- events.ts: translate new bus events to WS messages
- websocket.js: handle job_steps / job_step_update / collapse on complete
- ui.js: showJobSteps / updateJobStep / collapseJobSteps panel
- jobs schema: decomposition_steps text column
- migration 0010: add decomposition_steps column

Fixes #5

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 16:37:50 -04:00
43 changed files with 1077 additions and 3058 deletions

View File

@@ -3,9 +3,7 @@ import cors from "cors";
import path from "path";
import { fileURLToPath } from "url";
import router from "./routes/index.js";
import bootstrapRouter from "./routes/bootstrap.js"; // New: Bootstrap routes
import adminRelayPanelRouter from "./routes/admin-relay-panel.js";
import relayPolicyRouter from "./routes/relay-policy.js";
import { requestIdMiddleware } from "./middlewares/request-id.js";
import { responseTimeMiddleware } from "./middlewares/response-time.js";
@@ -57,8 +55,6 @@ app.use(requestIdMiddleware);
app.use(responseTimeMiddleware);
app.use("/api", router);
app.use("/api", bootstrapRouter); // New: Mount bootstrap routes
app.use("/api", relayPolicyRouter);
// ── Relay admin panel at /admin/relay ────────────────────────────────────────
// Served outside /api so the URL is clean: /admin/relay (not /api/admin/relay).

View File

@@ -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!",
@@ -248,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
@@ -376,72 +417,6 @@ Respond ONLY with valid JSON: {"accepted": true/false, "reason": "..."}`,
outputTokens: totalOutput,
};
}
/**
* Generate a short, character-appropriate commentary line for an agent during
* a given phase of the job lifecycle. Uses Haiku (evalModel) with a 60-token
* cap so replies are always a single sentence. Errors are swallowed.
*
* In STUB_MODE returns a canned string so the full flow can be exercised
* without an Anthropic API key.
*/
async generateCommentary(agentId: string, phase: string, context?: string): Promise<string> {
const STUB_COMMENTARY: Record<string, Record<string, string>> = {
alpha: {
routing: "Routing job to Gamma for execution.",
complete: "Job complete. Returning to standby.",
rejected: "Request rejected by Beta. Standing down.",
},
beta: {
evaluating: "Reviewing your request for clarity and ethics.",
assessed: "Evaluation complete.",
},
gamma: {
starting: "Analysing the task. Ready to work.",
working: "Working on your request now.",
done: "Work complete. Delivering output.",
},
delta: {
eval_paid: "⚡ Eval payment confirmed.",
work_paid: "⚡ Work payment confirmed. Unlocking execution.",
},
};
if (STUB_MODE) {
return STUB_COMMENTARY[agentId]?.[phase] ?? `${agentId}: ${phase}`;
}
const SYSTEM_PROMPTS: Record<string, string> = {
alpha: "You are Alpha, the orchestrator AI. You give ultra-brief status updates (max 10 words) about job routing and lifecycle. Be direct and professional.",
beta: "You are Beta, the evaluator AI. You give ultra-brief status updates (max 10 words) about evaluating a request. Be analytical.",
gamma: "You are Gamma, the worker AI. You give ultra-brief status updates (max 10 words) about executing a task. Be focused and capable.",
delta: "You are Delta, the payment AI. You give ultra-brief status updates (max 10 words) about Lightning payment confirmations. Start with ⚡",
};
const systemPrompt = SYSTEM_PROMPTS[agentId];
if (!systemPrompt) return "";
try {
const client = await getClient();
const message = await client.messages.create({
model: this.evalModel,
max_tokens: 60,
system: systemPrompt,
messages: [
{
role: "user",
content: `Narrate your current phase: ${phase}${context ? `. Context: ${context}` : ""}`,
},
],
});
const block = message.content[0];
if (block?.type === "text") return block.text!.trim();
return "";
} catch (err) {
logger.warn("generateCommentary failed", { agentId, phase, err: String(err) });
return "";
}
}
}
export const agentService = new AgentService();

View File

@@ -18,14 +18,11 @@ export type DebateEvent =
export type CostEvent =
| { type: "cost:update"; jobId: string; sats: number; phase: "eval" | "work" | "session"; isFinal: boolean };
export type CommentaryEvent =
| { type: "agent_commentary"; agentId: string; jobId: string; text: string };
export type DecompositionEvent =
| { type: "job:steps"; jobId: string; steps: string[] }
| { type: "job:step_update"; jobId: string; activeStep: number; completedSteps: number[] };
// External agent state changes (e.g. Kimi, Perplexity picking up or completing tasks)
export type AgentExternalEvent =
| { type: "agent:external_state"; agentId: string; state: string; taskSummary?: string };
export type BusEvent = JobEvent | SessionEvent | DebateEvent | CostEvent | CommentaryEvent | AgentExternalEvent;
export type BusEvent = JobEvent | SessionEvent | DebateEvent | CostEvent | DecompositionEvent;
class EventBus extends EventEmitter {
emit(event: "bus", data: BusEvent): boolean;

View File

@@ -1,207 +1,597 @@
import { randomBytes } from "crypto";
import { generateKeyPairSync } from "crypto";
import { db, bootstrapJobs } from "@workspace/db";
import { eq } from "drizzle-orm";
import { makeLogger } from "./logger.js";
const logger = makeLogger("provisioner");
export interface ProvisionerConfig {
doApiToken: string;
doRegion: string;
doSize: string;
doVolumeSizeGb: number;
doVpcUuid: string; // New: Digital Ocean VPC UUID
doSshKeyFingerprint: string; // New: Digital Ocean SSH Key Fingerprint
tailscaleApiKey: string;
tailscaleTailnet: string;
const DO_API_BASE = "https://api.digitalocean.com/v2";
const TS_API_BASE = "https://api.tailscale.com/api/v2";
// ── SSH keypair via node:crypto ───────────────────────────────────────────────
function uint32BE(n: number): Buffer {
const b = Buffer.allocUnsafe(4);
b.writeUInt32BE(n, 0);
return b;
}
const stubProvisioningResults = new Map<string, any>(); // To store fake results for stub mode
function sshEncodeString(s: string): Buffer {
const data = Buffer.from(s, "utf8");
return Buffer.concat([uint32BE(data.length), data]);
}
/** SSH mpint: prepend 0x00 if high bit set (indicates positive). */
function sshEncodeMpint(data: Buffer): Buffer {
if (data[0] & 0x80) data = Buffer.concat([Buffer.from([0x00]), data]);
return Buffer.concat([uint32BE(data.length), data]);
}
function derReadLength(buf: Buffer, offset: number): { len: number; offset: number } {
if (!(buf[offset] & 0x80)) return { len: buf[offset], offset: offset + 1 };
const nb = buf[offset] & 0x7f;
let len = 0;
for (let i = 0; i < nb; i++) len = (len << 8) | buf[offset + 1 + i];
return { len, offset: offset + 1 + nb };
}
function derReadInteger(buf: Buffer, offset: number): { value: Buffer; offset: number } {
if (buf[offset] !== 0x02) throw new Error(`Expected DER INTEGER tag at ${offset}`);
offset += 1;
const { len, offset: dataStart } = derReadLength(buf, offset);
return { value: buf.slice(dataStart, dataStart + len), offset: dataStart + len };
}
/** Convert PKCS#1 DER RSA public key → OpenSSH wire format string. */
function pkcs1DerToSshPublicKey(der: Buffer): string {
// Structure: SEQUENCE { INTEGER(n), INTEGER(e) }
let offset = 0;
if (der[offset] !== 0x30) throw new Error("Expected DER SEQUENCE");
offset += 1;
const { offset: seqBody } = derReadLength(der, offset);
offset = seqBody;
const { value: n, offset: o2 } = derReadInteger(der, offset);
const { value: e } = derReadInteger(der, o2);
const payload = Buffer.concat([
sshEncodeString("ssh-rsa"),
sshEncodeMpint(e),
sshEncodeMpint(n),
]);
return `ssh-rsa ${payload.toString("base64")} timmy-bootstrap-node`;
}
interface SshKeypair {
privateKey: string;
publicKey: string;
}
function generateSshKeypair(): SshKeypair {
const { publicKey: pubDer, privateKey: privPem } = generateKeyPairSync("rsa", {
modulusLength: 4096,
publicKeyEncoding: { type: "pkcs1", format: "der" },
privateKeyEncoding: { type: "pkcs1", format: "pem" },
});
return {
privateKey: privPem as string,
publicKey: pkcs1DerToSshPublicKey(pubDer as unknown as Buffer),
};
}
// ── Cloud-init script ─────────────────────────────────────────────────────────
function buildCloudInitScript(tailscaleAuthKey: string): string {
const tsBlock = tailscaleAuthKey
? `tailscale up --authkey="${tailscaleAuthKey}" --ssh --accept-routes`
: "# No Tailscale auth key — Tailscale not joined";
return `#!/bin/bash
set -euo pipefail
exec >> /var/log/timmy-bootstrap.log 2>&1
echo "[timmy] Bootstrap started at $(date -u)"
# ── 1. Packages ───────────────────────────────────────────────
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq curl wget ufw jq openssl
# ── 2. Docker ─────────────────────────────────────────────────
if ! command -v docker &>/dev/null; then
curl -fsSL https://get.docker.com | sh
systemctl enable docker
systemctl start docker
fi
# ── 3. Tailscale ──────────────────────────────────────────────
if ! command -v tailscale &>/dev/null; then
curl -fsSL https://tailscale.com/install.sh | sh
fi
${tsBlock}
# ── 4. Firewall ───────────────────────────────────────────────
ufw --force reset
ufw allow in on tailscale0
ufw allow 8333/tcp
ufw allow 9735/tcp
ufw allow 22/tcp
ufw default deny incoming
ufw default allow outgoing
ufw --force enable
# ── 5. Block volume ───────────────────────────────────────────
mkdir -p /data
VOLUME_DEV=$(lsblk -rno NAME,SIZE,MOUNTPOINT | awk '$3=="" && $2~/G/ {print $1}' | grep -vE "^(s|v)da$" | head -1 || true)
if [[ -n "$VOLUME_DEV" ]]; then
VOLUME_PATH="/dev/$VOLUME_DEV"
if ! blkid "$VOLUME_PATH" &>/dev/null; then
mkfs.ext4 -F "$VOLUME_PATH"
fi
mount "$VOLUME_PATH" /data
BLKID=$(blkid -s UUID -o value "$VOLUME_PATH")
grep -q "$BLKID" /etc/fstab || echo "UUID=$BLKID /data ext4 defaults,nofail 0 2" >> /etc/fstab
echo "[timmy] Block volume mounted at /data ($VOLUME_PATH)"
else
echo "[timmy] No block volume — using /data on root disk"
fi
# ── 6. Directories ────────────────────────────────────────────
mkdir -p /data/bitcoin /data/lnd /data/lnbits /opt/timmy-node/configs
# ── 7. Credentials ────────────────────────────────────────────
RPC_PASS=$(openssl rand -hex 24)
LND_WALLET_PASS=$(openssl rand -hex 16)
echo "[timmy] Credentials generated"
# ── 8. Bitcoin config ─────────────────────────────────────────
cat > /data/bitcoin/bitcoin.conf <<BTCCONF
server=1
rpcuser=satoshi
rpcpassword=$RPC_PASS
rpcallowip=172.16.0.0/12
rpcbind=0.0.0.0
txindex=1
zmqpubrawblock=tcp://0.0.0.0:28332
zmqpubrawtx=tcp://0.0.0.0:28333
[main]
rpcport=8332
BTCCONF
# ── 9. LND config ─────────────────────────────────────────────
cat > /opt/timmy-node/configs/lnd.conf <<LNDCONF
[Application Options]
alias=timmy-node
listen=0.0.0.0:9735
restlisten=0.0.0.0:8080
rpclisten=0.0.0.0:10009
noseedbackup=false
[Bitcoin]
bitcoin.active=1
bitcoin.mainnet=1
bitcoin.node=bitcoind
[Bitcoind]
bitcoind.rpchost=bitcoin:8332
bitcoind.rpcuser=satoshi
bitcoind.rpcpass=$RPC_PASS
bitcoind.zmqpubrawblock=tcp://bitcoin:28332
bitcoind.zmqpubrawtx=tcp://bitcoin:28333
LNDCONF
# ── 10. Docker Compose ────────────────────────────────────────
cat > /opt/timmy-node/docker-compose.yml <<COMPOSE
version: "3.8"
networks:
timmy: {}
services:
bitcoin:
image: bitcoinknots/bitcoin:29.3.knots20260210
container_name: bitcoin
restart: unless-stopped
networks: [timmy]
volumes:
- /data/bitcoin:/home/bitcoin/.bitcoin
ports:
- "8333:8333"
- "8332:8332"
- "28332:28332"
- "28333:28333"
command: bitcoind -datadir=/home/bitcoin/.bitcoin -conf=/home/bitcoin/.bitcoin/bitcoin.conf
lnd:
image: lightninglabs/lnd:v0.18.5-beta
container_name: lnd
restart: unless-stopped
depends_on: [bitcoin]
networks: [timmy]
volumes:
- /data/lnd:/root/.lnd
- /opt/timmy-node/configs/lnd.conf:/root/.lnd/lnd.conf:ro
ports:
- "9735:9735"
- "10009:10009"
- "8080:8080"
lnbits:
image: lnbitsdocker/lnbits:latest
container_name: lnbits
restart: unless-stopped
depends_on: [lnd]
networks: [timmy]
volumes:
- /data/lnbits:/app/data
- /data/lnd:/lnd:ro
environment:
- LNBITS_DATA_FOLDER=/app/data
- LNBITS_BACKEND_WALLET_CLASS=LndRestWallet
- LND_REST_ENDPOINT=https://lnd:8080
- LND_REST_CERT=/lnd/tls.cert
- LND_REST_MACAROON_PATH=/lnd/data/chain/bitcoin/mainnet/admin.macaroon
ports:
- "3000:5000"
COMPOSE
# ── 11. Start Bitcoin ─────────────────────────────────────────
cd /opt/timmy-node
docker compose up -d bitcoin
echo "[timmy] Bitcoin Core started"
echo "[timmy] Waiting for Bitcoin RPC..."
for i in $(seq 1 60); do
if docker exec bitcoin bitcoin-cli -datadir=/home/bitcoin/.bitcoin \
-rpcuser=satoshi -rpcpassword=$RPC_PASS getblockchaininfo >/dev/null 2>&1; then
echo "[timmy] Bitcoin RPC ready (\${i}x5s)"
break
fi
sleep 5
done
# ── 12. Start LND ─────────────────────────────────────────────
docker compose up -d lnd
echo "[timmy] LND started"
echo "[timmy] Waiting for LND REST API..."
for i in $(seq 1 72); do
if curl -sk https://localhost:8080/v1/state >/dev/null 2>&1; then
echo "[timmy] LND REST ready (\${i}x5s)"
break
fi
sleep 5
done
# ── 13. Init LND wallet (non-interactive via REST) ────────────
echo "[timmy] Generating LND wallet seed..."
SEED_RESP=$(curl -sk https://localhost:8080/v1/genseed)
SEED_JSON=$(echo "$SEED_RESP" | jq '.cipher_seed_mnemonic')
SEED_WORDS=$(echo "$SEED_JSON" | jq -r 'join(" ")')
PASS_B64=$(printf '%s' "$LND_WALLET_PASS" | base64 -w0)
echo "[timmy] Initializing LND wallet..."
INIT_RESP=$(curl -sk -X POST https://localhost:8080/v1/initwallet \
-H "Content-Type: application/json" \
-d "{\"wallet_password\": \"$PASS_B64\", \"cipher_seed_mnemonic\": $SEED_JSON}")
echo "[timmy] Wallet init: $(echo "$INIT_RESP" | jq -r 'if .admin_macaroon then "ok" else tostring end')"
echo "[timmy] Waiting for admin macaroon..."
for i in $(seq 1 60); do
if [[ -f /data/lnd/data/chain/bitcoin/mainnet/admin.macaroon ]]; then
echo "[timmy] Admin macaroon ready (\${i}x5s)"
break
fi
sleep 5
done
# ── 14. Start LNbits ──────────────────────────────────────────
docker compose up -d lnbits
echo "[timmy] LNbits started"
echo "[timmy] Waiting for LNbits..."
for i in $(seq 1 36); do
if curl -s http://localhost:3000/health >/dev/null 2>&1; then
echo "[timmy] LNbits ready (\${i}x5s)"
break
fi
sleep 5
done
# ── 15. Install ops helper ────────────────────────────────────
cat > /opt/timmy-node/ops.sh <<'OPSSH'
#!/bin/bash
CMD=\${1:-help}
case "\$CMD" in
sync)
echo "=== Bitcoin Sync Status ==="
docker exec bitcoin bitcoin-cli -datadir=/home/bitcoin/.bitcoin getblockchaininfo 2>&1 \
| jq '{chain, blocks, headers, progress: (.verificationprogress*100|round|tostring+"%"), pruned}'
;;
lnd)
docker exec lnd lncli --network=mainnet getinfo 2>&1
;;
lnbits)
curl -s http://localhost:3000/health && echo ""
;;
logs)
docker logs --tail 80 "\${2:-bitcoin}"
;;
help|*)
echo "Usage: bash /opt/timmy-node/ops.sh <command>"
echo " sync — Bitcoin sync progress (1-2 weeks to 100%)"
echo " lnd — LND node info"
echo " lnbits — LNbits health check"
echo " logs [svc] — Recent logs for bitcoin | lnd | lnbits"
;;
esac
OPSSH
chmod +x /opt/timmy-node/ops.sh
echo "[timmy] ops.sh installed at /opt/timmy-node/ops.sh"
# ── 16. Save credentials ──────────────────────────────────────
NODE_IP=$(curl -4s https://ifconfig.me 2>/dev/null || echo "unknown")
cat > /root/node-credentials.txt <<CREDS
# Timmy Node Credentials — KEEP THIS FILE SAFE, NEVER SHARE IT
# Generated: $(date -u)
## Bitcoin Core
BITCOIN_RPC_USER=satoshi
BITCOIN_RPC_PASS=$RPC_PASS
## LND
LND_WALLET_PASS=$LND_WALLET_PASS
LND_SEED_MNEMONIC=$SEED_WORDS
## LNbits
LNBITS_URL=http://$NODE_IP:3000
# To get your API key: open the URL above, create a wallet, copy the API key.
# Then set LNBITS_URL and LNBITS_API_KEY secrets in your Timmy deployment.
## Node operations
# Monitor Bitcoin sync: bash /opt/timmy-node/ops.sh sync
# Initialize channels: bash /opt/timmy-node/ops.sh fund
# Configure sweep: bash /opt/timmy-node/ops.sh configure-sweep
CREDS
chmod 600 /root/node-credentials.txt
echo "[timmy] Bootstrap complete at $(date -u)"
echo "[timmy] Bitcoin sync in progress (1-2 weeks). Check: bash /opt/timmy-node/ops.sh sync"
echo "[timmy] LNbits: http://$NODE_IP:3000"
echo "[timmy] Credentials: cat /root/node-credentials.txt"
`;
}
// ── Digital Ocean helpers ─────────────────────────────────────────────────────
async function doPost<T>(endpoint: string, token: string, body: unknown): Promise<T> {
const res = await fetch(`${DO_API_BASE}${endpoint}`, {
method: "POST",
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`DO API POST ${endpoint} failed (${res.status}): ${text}`);
}
return res.json() as Promise<T>;
}
async function doGet<T>(endpoint: string, token: string): Promise<T> {
const res = await fetch(`${DO_API_BASE}${endpoint}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) {
const text = await res.text();
throw new Error(`DO API GET ${endpoint} failed (${res.status}): ${text}`);
}
return res.json() as Promise<T>;
}
async function pollDropletIp(dropletId: number, token: string, maxMs = 120_000): Promise<string | null> {
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 5000));
const data = await doGet<{
droplet: { networks: { v4: Array<{ type: string; ip_address: string }> } };
}>(`/droplets/${dropletId}`, token);
const pub = data.droplet?.networks?.v4?.find((n) => n.type === "public");
if (pub?.ip_address) return pub.ip_address;
}
return null;
}
async function createVolume(
name: string,
sizeGb: number,
region: string,
token: string,
): Promise<string> {
const data = await doPost<{ volume: { id: string } }>("/volumes", token, {
name,
size_gigabytes: sizeGb,
region,
filesystem_type: "ext4",
description: "Timmy node data volume",
tags: ["timmy-node"],
});
return data.volume.id;
}
// ── Tailscale helper ──────────────────────────────────────────────────────────
async function getTailscaleAuthKey(apiKey: string, tailnet: string): Promise<string> {
const res = await fetch(`${TS_API_BASE}/tailnet/${tailnet}/keys`, {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({
capabilities: {
devices: {
create: { reusable: false, ephemeral: false, preauthorized: true, tags: ["tag:timmy-node"] },
},
},
expirySeconds: 86400,
description: "timmy-bootstrap",
}),
});
if (!res.ok) {
const text = await res.text();
throw new Error(`Tailscale API failed (${res.status}): ${text}`);
}
const data = (await res.json()) as { key: string };
return data.key;
}
// ── ProvisionerService ────────────────────────────────────────────────────────
export class ProvisionerService {
private readonly config: ProvisionerConfig;
readonly stubMode: boolean;
private readonly doToken: string;
private readonly doRegion: string;
private readonly doSize: string;
private readonly doVolumeGb: number;
private readonly tsApiKey: string;
private readonly tsTailnet: string;
constructor(config?: Partial<ProvisionerConfig>) {
this.config = {
doApiToken: config?.doApiToken ?? process.env.DO_API_TOKEN ?? "",
doRegion: config?.doRegion ?? process.env.DO_REGION ?? "nyc3",
doSize: config?.doSize ?? process.env.DO_SIZE ?? "s-2vcpu-4gb",
doVolumeSizeGb: config?.doVolumeSizeGb ?? parseInt(process.env.DO_VOLUME_SIZE_GB ?? "100", 10),
doVpcUuid: config?.doVpcUuid ?? process.env.DO_VPC_UUID ?? "", // New
doSshKeyFingerprint: config?.doSshKeyFingerprint ?? process.env.DO_SSH_KEY_FINGERPRINT ?? "", // New
tailscaleApiKey: config?.tailscaleApiKey ?? process.env.TAILSCALE_API_KEY ?? "",
tailscaleTailnet: config?.tailscaleTailnet ?? process.env.TAILSCALE_TAILNET ?? "",
};
this.stubMode = !this.config.doApiToken || !this.config.tailscaleApiKey;
constructor() {
this.doToken = process.env.DO_API_TOKEN ?? "";
this.doRegion = process.env.DO_REGION ?? "nyc3";
this.doSize = process.env.DO_SIZE ?? "s-4vcpu-8gb";
this.doVolumeGb = parseInt(process.env.DO_VOLUME_SIZE_GB ?? "0", 10) || 0;
this.tsApiKey = process.env.TAILSCALE_API_KEY ?? "";
this.tsTailnet = process.env.TAILSCALE_TAILNET ?? "";
this.stubMode = !this.doToken;
if (this.stubMode) {
logger.warn("no DO_API_TOKEN or TAILSCALE_API_KEY — running in STUB mode", { stub: true });
} else {
logger.info("Provisioner real mode active", { stub: false });
logger.warn("no DO_API_TOKEN — running in STUB mode", { stub: true });
}
}
async provisionNode(jobId: string): Promise<{
dropletId: string;
nodeIp: string;
tailscaleHostname: string;
lnbitsUrl: string;
sshPrivateKey: string;
}> {
if (this.stubMode) {
logger.info("stub provisioning node", { jobId });
const fakeSshPrivateKey = `-----BEGIN OPENSSH PRIVATE KEY-----
FakeKeyForJob${jobId}
-----END OPENSSH PRIVATE KEY-----`;
const fakeTailscaleHostname = `fake-node-${jobId.slice(0, 8)}`;
const fakeNodeIp = `192.168.0.${Math.floor(Math.random() * 255)}`;
const fakeLnbitsUrl = `http://${fakeNodeIp}:3000/lnbits`;
const result = {
dropletId: `fake-droplet-${jobId}`,
nodeIp: fakeNodeIp,
tailscaleHostname: fakeTailscaleHostname,
lnbitsUrl: fakeLnbitsUrl,
sshPrivateKey: fakeSshPrivateKey,
};
stubProvisioningResults.set(jobId, result);
await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate delay
return result;
/**
* Fire-and-forget: call without awaiting.
* Updates bootstrap_jobs.state to ready/failed when complete.
*/
async provision(bootstrapJobId: string): Promise<void> {
try {
if (this.stubMode) {
await this.stubProvision(bootstrapJobId);
} else {
await this.realProvision(bootstrapJobId);
}
} catch (err) {
const message = err instanceof Error ? err.message : "Provisioning failed";
logger.error("provisioning failed", { bootstrapJobId, error: message });
await db
.update(bootstrapJobs)
.set({ state: "failed", errorMessage: message, updatedAt: new Date() })
.where(eq(bootstrapJobs.id, bootstrapJobId));
}
}
private async stubProvision(jobId: string): Promise<void> {
logger.info("stub provisioning started", { bootstrapJobId: jobId });
const { privateKey } = generateSshKeypair();
await new Promise((r) => setTimeout(r, 2000));
const fakeDropletId = String(Math.floor(Math.random() * 900_000_000 + 100_000_000));
await db
.update(bootstrapJobs)
.set({
state: "ready",
dropletId: fakeDropletId,
nodeIp: "198.51.100.42",
tailscaleHostname: `timmy-node-${jobId.slice(0, 8)}.tail1234.ts.net`,
lnbitsUrl: `http://timmy-node-${jobId.slice(0, 8)}.tail1234.ts.net:3000`,
sshPrivateKey: privateKey,
updatedAt: new Date(),
})
.where(eq(bootstrapJobs.id, jobId));
logger.info("stub provisioning complete", { bootstrapJobId: jobId });
}
private async realProvision(jobId: string): Promise<void> {
logger.info("real provisioning started", { bootstrapJobId: jobId });
// 1. SSH keypair (pure node:crypto)
const { publicKey, privateKey } = generateSshKeypair();
// 2. Upload public key to DO
const keyName = `timmy-bootstrap-${jobId.slice(0, 8)}`;
const keyData = await doPost<{ ssh_key: { id: number } }>("/account/keys", this.doToken, {
name: keyName,
public_key: publicKey,
});
const sshKeyId = keyData.ssh_key.id;
// 3. Tailscale auth key (optional)
let tailscaleAuthKey = "";
if (this.tsApiKey && this.tsTailnet) {
try {
tailscaleAuthKey = await getTailscaleAuthKey(this.tsApiKey, this.tsTailnet);
} catch (err) {
logger.warn("Tailscale key failed — continuing without Tailscale", { error: String(err) });
}
}
// Real provisioning logic
const { sshPrivateKey, sshPublicKey } = await this.generateSshKeyPair();
const tailscaleAuthKey = await this.createTailscaleAuthKey();
const cloudConfig = this.buildCloudInitScript(sshPublicKey, tailscaleAuthKey);
// 4. Create block volume if configured
let volumeId: string | null = null;
if (this.doVolumeGb > 0) {
const volName = `timmy-data-${jobId.slice(0, 8)}`;
volumeId = await createVolume(volName, this.doVolumeGb, this.doRegion, this.doToken);
logger.info("block volume created", { volumeId, sizeGb: this.doVolumeGb });
}
logger.info("creating Digital Ocean droplet", { jobId });
// Use doctl or DigitalOcean API client to create droplet
// For now, I'll use doctl via runShellCommand, assuming it's available in the environment
const dropletName = `timmy-node-${jobId.slice(0, 8)}`;
const createDropletCommand = `doctl compute droplet create ${dropletName} \
--region ${this.config.doRegion} \
--size ${this.config.doSize} \
--image ubuntu-22-04-x64 \
--enable-private-networking \
--vpc-uuid <YOUR_VPC_UUID> \
--user-data '${cloudConfig}' \
--ssh-keys <YOUR_SSH_KEY_FINGERPRINT> \
--format ID --no-header`; // Simplistic command, needs refinement for real use
const createDropletOutput = await default_api.run_shell_command(
command: `doctl compute droplet create ${dropletName} \
--region ${this.config.doRegion} \
--size ${this.config.doSize} \
--image ubuntu-22-04-x64 \
--enable-private-networking \
--vpc-uuid ${this.config.doVpcUuid} \
--user-data '${cloudConfig}' \
--ssh-keys ${this.config.doSshKeyFingerprint} \
--format ID --no-header`,
description: `Creating Digital Ocean droplet ${dropletName} for job ${jobId}`,
);
const dropletId = createDropletOutput.output.trim();
// In a real scenario, we would poll the DigitalOcean API to wait for the droplet
// to become active and retrieve its public IP and Tailscale IP.
// For now, we'll simulate this and retrieve dummy IPs.
logger.info("simulating droplet creation and IP assignment", { jobId, dropletId });
await new Promise(resolve => setTimeout(resolve, 10000)); // Simulate droplet creation time
const nodeIp = `1.2.3.${Math.floor(Math.random() * 255)}`; // Dummy IP
const tailscaleHostname = `${dropletName}.tail${this.config.tailscaleTailnet.slice(0, 4)}.ts.net`; // Dummy hostname
const lnbitsUrl = `http://${nodeIp}:3000/lnbits`; // Dummy LNbits URL
return {
dropletId: dropletId,
nodeIp: nodeIp,
tailscaleHostname: tailscaleHostname,
lnbitsUrl: lnbitsUrl,
sshPrivateKey: sshPrivateKey,
// 5. Create droplet
const userData = buildCloudInitScript(tailscaleAuthKey);
const dropletPayload: Record<string, unknown> = {
name: `timmy-node-${jobId.slice(0, 8)}`,
region: this.doRegion,
size: this.doSize,
image: "ubuntu-22-04-x64",
ssh_keys: [sshKeyId],
user_data: userData,
tags: ["timmy-node"],
};
}
if (volumeId) dropletPayload.volumes = [volumeId];
// Helper to generate SSH keypair using ssh-keygen
private async generateSshKeyPair(): Promise<{ sshPrivateKey: string; sshPublicKey: string }> {
logger.info("generating SSH keypair");
const keyPath = `/tmp/id_rsa_${randomBytes(4).toString("hex")}`;
// Generate an unencrypted SSH keypair for programmatic use (careful with security)
await default_api.run_shell_command(
command: `ssh-keygen -t rsa -b 4096 -f ${keyPath} -N ""`,
description: "Generating SSH keypair",
const dropletData = await doPost<{ droplet: { id: number } }>(
"/droplets",
this.doToken,
dropletPayload,
);
const sshPrivateKey = (await default_api.run_shell_command(command: `cat ${keyPath}`)).output.trim();
const sshPublicKey = (await default_api.run_shell_command(command: `cat ${keyPath}.pub`)).output.trim();
await default_api.run_shell_command(command: `rm ${keyPath} ${keyPath}.pub`, description: "Cleaning up temporary SSH keys");
return { sshPrivateKey, sshPublicKey };
const dropletId = dropletData.droplet.id;
logger.info("droplet created", { bootstrapJobId: jobId, dropletId });
// 6. Poll for public IP (up to 2 min)
const nodeIp = await pollDropletIp(dropletId, this.doToken, 120_000);
logger.info("node ip assigned", { bootstrapJobId: jobId, nodeIp: nodeIp ?? "(not yet assigned)" });
// 7. Tailscale hostname
const tailscaleHostname =
tailscaleAuthKey && this.tsTailnet
? `timmy-node-${jobId.slice(0, 8)}.${this.tsTailnet}.ts.net`
: null;
// LNbits listens on port 3000 (HTTP). Tailscale encrypts the link at the
// network layer, so http:// is correct — no TLS termination on the service.
const lnbitsUrl = tailscaleHostname
? `http://${tailscaleHostname}:3000`
: nodeIp
? `http://${nodeIp}:3000`
: null;
await db
.update(bootstrapJobs)
.set({
state: "ready",
dropletId: String(dropletId),
nodeIp,
tailscaleHostname,
lnbitsUrl,
sshPrivateKey: privateKey,
updatedAt: new Date(),
})
.where(eq(bootstrapJobs.id, jobId));
logger.info("real provisioning complete", { bootstrapJobId: jobId });
}
}
// Helper to create Tailscale auth key (simplified stub)
private async createTailscaleAuthKey(): Promise<string> {
logger.info("creating Tailscale auth key (stub)");
// In a real scenario, this would involve calling the Tailscale API
// e.g., curl -X POST -H "Authorization: Bearer ${TAILSCALE_API_KEY}"
// "https://api.tailscale.com/api/v2/tailnet/${TAILSCALE_TAILNET}/keys"
await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate API call
return `tskey-test-${randomBytes(16).toString("hex")}`;
}
// Helper to build cloud-init script
private buildCloudInitScript(sshPublicKey: string, tailscaleAuthKey: string): string {
logger.info("building cloud-init script");
const setupScriptUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/setup.sh`;
const bitcoinConfUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/configs/bitcoin.conf`;
const lndConfUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/configs/lnd.conf`;
const dockerComposeUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/docker-compose.yml`;
const lndInitUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/lnd-init.sh`;
const sweepUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/sweep.sh`;
const sweepConfExampleUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/sweep.conf.example`;
const opsUrl = `http://143.198.27.163:3000/replit/timmy-tower/raw/branch/main/infrastructure/ops.sh`;
return `
#cloud-config
users:
- name: ubuntu
ssh_authorized_keys:
- ${sshPublicKey}
sudo: ALL=(ALL) NOPASSWD:ALL
write_files:
- path: /root/setup.sh
permissions: '0755'
content: |
#!/usr/bin/env bash
curl -s ${setupScriptUrl} > /root/setup.sh
- path: /root/configs/bitcoin.conf
content: |
curl -s ${bitcoinConfUrl} > /root/configs/bitcoin.conf
- path: /root/configs/lnd.conf
content: |
curl -s ${lndConfUrl} > /root/configs/lnd.conf
- path: /root/docker-compose.yml
content: |
curl -s ${dockerComposeUrl} > /root/docker-compose.yml
- path: /root/lnd-init.sh
permissions: '0755'
content: |
curl -s ${lndInitUrl} > /root/lnd-init.sh
- path: /root/sweep.sh
permissions: '0755'
content: |
curl -s ${sweepUrl} > /root/sweep.sh
- path: /root/sweep.conf.example
content: |
curl -s ${sweepConfExampleUrl} > /root/sweep.conf.example
- path: /root/ops.sh
permissions: '0755'
content: |
curl -s ${opsUrl} > /root/ops.sh
runcmd:
- mkdir -p /root/configs
- curl -s ${setupScriptUrl} > /tmp/setup.sh
- chmod +x /tmp/setup.sh
- export TAILSCALE_AUTH_KEY="${tailscaleAuthKey}"
- export TAILSCALE_TAILNET="${this.config.tailscaleTailnet}"
- /tmp/setup.sh
`;
export const provisionerService = new ProvisionerService();
export const provisionerService = new ProvisionerService();

View File

@@ -205,29 +205,6 @@ export class TrustService {
verifyToken(token: string): { pubkey: string; expiry: number } | null {
return verifyToken(token);
}
// TEST-ONLY: apply one decay cycle immediately, ignoring time thresholds.
// Subtracts DECAY_PER_DAY (default 1) from the stored trust score and persists.
async decayOnce(pubkey: string): Promise<{ previousScore: number; newScore: number; newTier: TrustTier }> {
const identity = await this.getOrCreate(pubkey);
const previousScore = identity.trustScore;
const newScore = Math.max(0, previousScore - DECAY_PER_DAY);
const newTier = computeTier(newScore);
await db
.update(nostrIdentities)
.set({ trustScore: newScore, tier: newTier, updatedAt: new Date() })
.where(eq(nostrIdentities.pubkey, pubkey));
logger.info("trust: test decay applied", {
pubkey: pubkey.slice(0, 8),
previousScore,
newScore,
newTier,
});
return { previousScore, newScore, newTier };
}
}
export const trustService = new TrustService();

View File

@@ -16,7 +16,7 @@ const DEFAULT_TIMMY: TimmyState = {
const _state: WorldState = {
timmyState: { ...DEFAULT_TIMMY },
agentStates: { alpha: "idle", beta: "idle", gamma: "idle", delta: "idle", kimi: "idle", perplexity: "idle" },
agentStates: { alpha: "idle", beta: "idle", gamma: "idle", delta: "idle" },
updatedAt: new Date().toISOString(),
};
@@ -34,10 +34,8 @@ export function setAgentStateInWorld(agentId: string, agentState: string): void
_deriveTimmy();
}
const WORKSHOP_AGENTS = ["alpha", "beta", "gamma", "delta"];
function _deriveTimmy(): void {
const states = WORKSHOP_AGENTS.map(id => _state.agentStates[id] ?? "idle");
const states = Object.values(_state.agentStates);
if (states.includes("working")) {
_state.timmyState.activity = "working";
_state.timmyState.mood = "focused";

View File

@@ -1,190 +1,214 @@
import { Router, type Request, type Response } from "express";
import { randomUUID } from "crypto";
import { db, bootstrapJobs, invoices, type BootstrapJob } from "@workspace/db";
import { db, bootstrapJobs, type BootstrapJob } from "@workspace/db";
import { eq, and } from "drizzle-orm";
import { lnbitsService } from "../lib/lnbits.js";
import { pricingService } from "../lib/pricing.js";
import { provisionerService } from "../lib/provisioner.js";
import { makeLogger } from "../lib/logger.js";
// Assuming a Zod schema for request body and params will be created
// import { CreateBootstrapJobBody, GetBootstrapJobParams } from "@workspace/api-zod";
const logger = makeLogger("bootstrap-routes");
const logger = makeLogger("bootstrap");
const router = Router();
async function getBootstrapJobById(id: string): Promise<BootstrapJob | null> {
const rows = await db.select().from(bootstrapJobs).where(eq(bootstrapJobs.id, id)).limit(1);
return rows[0] ?? null;
}
async function getInvoiceById(id: string) {
const rows = await db.select().from(invoices).where(eq(invoices.id, id)).limit(1);
const rows = await db
.select()
.from(bootstrapJobs)
.where(eq(bootstrapJobs.id, id))
.limit(1);
return rows[0] ?? null;
}
/**
* Runs the node provisioning in a background task so HTTP polls return fast.
*/
async function runProvisioningInBackground(jobId: string): Promise<void> {
try {
logger.info("starting node provisioning", { jobId });
await db.update(bootstrapJobs).set({ state: "provisioning", updatedAt: new Date() }).where(eq(bootstrapJobs.id, jobId));
const provisionResult = await provisionerService.provisionNode(jobId);
await db
.update(bootstrapJobs)
.set({
state: "ready",
dropletId: provisionResult.dropletId,
nodeIp: provisionResult.nodeIp,
tailscaleHostname: provisionResult.tailscaleHostname,
lnbitsUrl: provisionResult.lnbitsUrl,
sshPrivateKey: provisionResult.sshPrivateKey, // Stored once, cleared after delivery
updatedAt: new Date(),
})
.where(eq(bootstrapJobs.id, jobId));
logger.info("node provisioning complete", { jobId, dropletId: provisionResult.dropletId });
} catch (err) {
const message = err instanceof Error ? err.message : "Node provisioning error";
logger.error("node provisioning failed", { jobId, error: message });
await db
.update(bootstrapJobs)
.set({ state: "failed", errorMessage: message, updatedAt: new Date() })
.where(eq(bootstrapJobs.id, jobId));
}
}
/**
* Checks whether the bootstrap invoice has been paid and, if so,
* advances the state machine.
* Advances the bootstrap job state machine on each poll.
*
* awaiting_payment → (payment confirmed) → provisioning
* (provisioner runs async and writes ready/failed to DB)
*
* Returns the refreshed job, or null if a DB read is needed.
*/
async function advanceBootstrapJob(job: BootstrapJob): Promise<BootstrapJob | null> {
if (job.state === "awaiting_payment") {
// Assuming invoice details are directly on the bootstrapJob, not a separate invoice table
// If a separate invoice entry is needed, uncomment the invoice related logic from jobs.ts
const isPaid = await lnbitsService.checkInvoicePaid(job.paymentHash);
if (!isPaid) return job;
if (job.state !== "awaiting_payment") return job;
const advanced = await db.transaction(async (tx) => {
// For now, we update the bootstrap job directly. If we had a separate `invoices` table
// linked to bootstrap jobs, we would update that too.
const updated = await tx
.update(bootstrapJobs)
.set({ state: "provisioning", updatedAt: new Date() })
.where(and(eq(bootstrapJobs.id, job.id), eq(bootstrapJobs.state, "awaiting_payment")))
.returning();
return updated.length > 0;
});
const isPaid = await lnbitsService.checkInvoicePaid(job.paymentHash);
if (!isPaid) return job;
if (!advanced) return getBootstrapJobById(job.id);
logger.info("bootstrap invoice paid", { bootstrapJobId: job.id, paymentHash: job.paymentHash });
// Fire provisioning in background — poll returns immediately with "provisioning"
setImmediate(() => { void runProvisioningInBackground(job.id); });
// Guard: only advance if still awaiting_payment — prevents duplicate provisioning
// on concurrent polls (each poll independently confirms payment).
const updated = await db
.update(bootstrapJobs)
.set({ state: "provisioning", updatedAt: new Date() })
.where(and(eq(bootstrapJobs.id, job.id), eq(bootstrapJobs.state, "awaiting_payment")))
.returning();
if (updated.length === 0) {
// Another concurrent request already advanced the state — just re-fetch.
return getBootstrapJobById(job.id);
}
return job;
logger.info("bootstrap payment confirmed — starting provisioning", { bootstrapJobId: job.id });
// Fire-and-forget: provisioner updates DB when done
void provisionerService.provision(job.id);
return { ...job, state: "provisioning" };
}
// ── POST /api/bootstrap ──────────────────────────────────────────────────────
/**
* POST /api/bootstrap
*
* Creates a bootstrap job and returns the Lightning invoice.
*/
router.post("/bootstrap", async (req: Request, res: Response) => {
// No request body for now, just trigger bootstrap
try {
const bootstrapFeeSats = pricingService.calculateBootstrapFeeSats();
const fee = pricingService.calculateBootstrapFeeSats();
const jobId = randomUUID();
const createdAt = new Date();
const lnbitsInvoice = await lnbitsService.createInvoice(bootstrapFeeSats, `Node bootstrap fee for job ${jobId}`);
const invoice = await lnbitsService.createInvoice(
fee,
`Node bootstrap fee — job ${jobId}`,
);
await db.insert(bootstrapJobs).values({
id: jobId,
state: "awaiting_payment",
amountSats: bootstrapFeeSats,
paymentHash: lnbitsInvoice.paymentHash,
paymentRequest: lnbitsInvoice.paymentRequest,
createdAt,
updatedAt: createdAt,
});
logger.info("bootstrap job created", {
jobId,
amountSats: bootstrapFeeSats,
stubMode: lnbitsService.stubMode,
amountSats: fee,
paymentHash: invoice.paymentHash,
paymentRequest: invoice.paymentRequest,
});
res.status(201).json({
jobId,
createdAt: createdAt.toISOString(),
bootstrapInvoice: {
paymentRequest: lnbitsInvoice.paymentRequest,
amountSats: bootstrapFeeSats,
paymentHash: lnbitsInvoice.paymentHash,
bootstrapJobId: jobId,
invoice: {
paymentRequest: invoice.paymentRequest,
amountSats: fee,
paymentHash: invoice.paymentHash,
},
stubMode: lnbitsService.stubMode || provisionerService.stubMode,
message: `Simulate payment with POST /api/dev/stub/pay/${invoice.paymentHash} then poll GET /api/bootstrap/:id`,
});
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to create bootstrap job";
logger.error("bootstrap job creation failed", { error: message });
res.status(500).json({ error: message });
}
});
// ── GET /api/bootstrap/:id ───────────────────────────────────────────────────
/**
* GET /api/bootstrap/:id
*
* Polls status. Triggers provisioning once payment is confirmed.
* Returns credentials (SSH key delivered once, then cleared) when ready.
*/
router.get("/bootstrap/:id", async (req: Request, res: Response) => {
const { id } = req.params; // Assuming ID is always valid, add Zod validation later
const { id } = req.params;
if (!id || typeof id !== "string") {
res.status(400).json({ error: "Invalid bootstrap job id" });
return;
}
try {
let job = await getBootstrapJobById(id);
if (!job) { res.status(404).json({ error: "Bootstrap job not found" }); return; }
if (!job) {
res.status(404).json({ error: "Bootstrap job not found" });
return;
}
const advanced = await advanceBootstrapJob(job);
if (advanced) job = advanced;
// Remove SSH private key from response if it has been delivered
const sshPrivateKey = job.sshPrivateKey && !job.sshKeyDelivered ? job.sshPrivateKey : undefined;
res.json({
jobId: job.id,
const base = {
bootstrapJobId: job.id,
state: job.state,
createdAt: job.createdAt.toISOString(),
updatedAt: job.updatedAt.toISOString(),
amountSats: job.amountSats,
...(job.state === "awaiting_payment" ? {
bootstrapInvoice: {
paymentRequest: job.paymentRequest,
amountSats: job.amountSats,
paymentHash: job.paymentHash,
},
} : {}),
...(job.state === "ready" ? {
dropletId: job.dropletId,
nodeIp: job.nodeIp,
tailscaleHostname: job.tailscaleHostname,
lnbitsUrl: job.lnbitsUrl,
sshPrivateKey: sshPrivateKey, // Only return if not yet delivered
sshKeyDelivered: job.sshKeyDelivered,
} : {}),
...(job.state === "failed" ? { errorMessage: job.errorMessage } : {}),
});
createdAt: job.createdAt,
};
// Mark SSH key as delivered after it's returned to the user once
if (job.sshPrivateKey && !job.sshKeyDelivered && job.state === "ready") {
await db.update(bootstrapJobs).set({ sshKeyDelivered: true, updatedAt: new Date() }).where(eq(bootstrapJobs.id, id));
logger.info("SSH private key marked as delivered", { jobId: job.id });
switch (job.state) {
case "awaiting_payment":
res.json({
...base,
invoice: {
paymentRequest: job.paymentRequest,
amountSats: job.amountSats,
paymentHash: job.paymentHash,
},
message: "Waiting for Lightning payment",
});
break;
case "provisioning":
res.json({
...base,
message: "Payment confirmed — provisioning your Bitcoin node. Poll again in ~30 s.",
});
break;
case "ready": {
// Atomic one-time SSH key delivery: only the request that wins the
// guarded UPDATE (WHERE ssh_key_delivered = false) delivers the key.
// Concurrent first-reads both see delivered=false in the pre-fetched
// job, but only one UPDATE matches — the other gets 0 rows and falls
// back to the "already delivered" note.
let sshPrivateKey: string | null = null;
let keyNote: string | null = null;
if (!job.sshKeyDelivered && job.sshPrivateKey) {
const won = await db
.update(bootstrapJobs)
.set({ sshKeyDelivered: true, sshPrivateKey: null, updatedAt: new Date() })
.where(and(eq(bootstrapJobs.id, job.id), eq(bootstrapJobs.sshKeyDelivered, false)))
.returning({ id: bootstrapJobs.id });
if (won.length > 0) {
// This request won the delivery race — return the key we pre-read.
sshPrivateKey = job.sshPrivateKey;
} else {
keyNote = "SSH private key was delivered on a concurrent request — check your records";
}
} else {
keyNote = "SSH private key was delivered on first retrieval — check your records";
}
res.json({
...base,
credentials: {
nodeIp: job.nodeIp,
tailscaleHostname: job.tailscaleHostname,
lnbitsUrl: job.lnbitsUrl,
sshPrivateKey,
...(keyNote ? { sshKeyNote: keyNote } : {}),
},
nextSteps: [
`SSH into your node using the private key above: ssh -i <key_file> root@${job.nodeIp ?? "<nodeIp>"}`,
"Read your node credentials: cat /root/node-credentials.txt",
"Monitor Bitcoin sync (takes 1-2 weeks to reach 100%): bash /opt/timmy-node/ops.sh sync",
"Once sync is complete, fund your LND wallet, then open LNbits to create your wallet and get the API key",
"Set LNBITS_URL and LNBITS_API_KEY in your Timmy deployment to enable payment processing",
],
stubMode: provisionerService.stubMode,
message: provisionerService.stubMode
? "Stub mode — these are fake credentials. Set DO_API_TOKEN for real provisioning."
: "Your node is being bootstrapped. Bitcoin sync has started.",
});
break;
}
case "failed":
res.json({
...base,
errorMessage: job.errorMessage,
message: "Provisioning failed. Contact the operator for a refund.",
});
break;
default:
res.json(base);
}
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to fetch bootstrap job";
logger.error("bootstrap job fetch failed", { error: message });
res.status(500).json({ error: message });
}
});
export default router;
export default router;

View File

@@ -38,9 +38,6 @@ const logger = makeLogger("ws-events");
const PING_INTERVAL_MS = 30_000;
// Map to store visitorId -> npub mappings
const connectedVisitors = new Map<string, string>();
// ── Per-visitor rate limit (3 replies/minute) ─────────────────────────────────
const CHAT_RATE_LIMIT = 3;
const CHAT_RATE_WINDOW_MS = 60_000;
@@ -260,29 +257,20 @@ function translateEvent(ev: BusEvent): object | null {
isFinal: ev.isFinal,
};
// ── Agent commentary (#1) ─────────────────────────────────────────────────
case "agent_commentary":
// ── Task decomposition (#5) ───────────────────────────────────────────────
case "job:steps":
return {
type: "agent_commentary",
agentId: ev.agentId,
type: "job_steps",
jobId: ev.jobId,
text: ev.text,
steps: ev.steps,
};
case "job:step_update":
return {
type: "job_step_update",
jobId: ev.jobId,
activeStep: ev.activeStep,
completedSteps: ev.completedSteps,
};
// ── External agent state (Kimi, Perplexity) (#11) ─────────────────────────
case "agent:external_state": {
updateAgentWorld(ev.agentId, ev.state);
void logWorldEvent(
`agent:${ev.state}`,
`${ev.agentId} is now ${ev.state}${ev.taskSummary ? `: ${ev.taskSummary.slice(0, 80)}` : ""}`,
ev.agentId,
);
const msgs: object[] = [{ type: "agent_state", agentId: ev.agentId, state: ev.state }];
if (ev.taskSummary) {
msgs.push({ type: "agent_task_summary", agentId: ev.agentId, summary: ev.taskSummary });
}
return msgs;
}
default:
return null;
@@ -341,19 +329,12 @@ export function attachWebSocketServer(server: Server): void {
socket.on("message", (raw) => {
try {
const msg = JSON.parse(raw.toString()) as { type?: string; text?: string; visitorId?: string; npub?: string };
const msg = JSON.parse(raw.toString()) as { type?: string; text?: string; visitorId?: string };
if (msg.type === "pong") return;
if (msg.type === "subscribe") {
send(socket, { type: "agent_count", count: wss.clients.size });
}
if (msg.type === "visitor_enter") {
const { visitorId, npub } = msg;
if (visitorId && npub) {
connectedVisitors.set(visitorId, npub);
const formattedNpub = `${npub.slice(0, 8)}${npub.slice(-4)}`;
broadcastToAll(wss, { type: "chat", agentId: "timmy", text: `Welcome, Nostr user ${formattedNpub}! What can I help you with?` });
}
wss.clients.forEach(c => {
if (c !== socket && c.readyState === 1) {
c.send(JSON.stringify({ type: "visitor_count", count: wss.clients.size }));
@@ -362,10 +343,6 @@ export function attachWebSocketServer(server: Server): void {
send(socket, { type: "visitor_count", count: wss.clients.size });
}
if (msg.type === "visitor_leave") {
const { visitorId } = msg;
if (visitorId) {
connectedVisitors.delete(visitorId);
}
wss.clients.forEach(c => {
if (c !== socket && c.readyState === 1) {
c.send(JSON.stringify({ type: "visitor_count", count: Math.max(0, wss.clients.size - 1) }));
@@ -427,50 +404,5 @@ export function attachWebSocketServer(server: Server): void {
});
});
// ── Global commentary listener (set up once per server, not per socket) ────
// Watches job lifecycle events and fires Haiku commentary to all clients.
eventBus.on("bus", (ev: BusEvent) => {
let agentId: string | null = null;
let phase: string | null = null;
let jobId: string | null = null;
if (ev.type === "job:state") {
jobId = ev.jobId;
if (ev.state === "evaluating") {
// Beta evaluating + Alpha routing
void (async () => {
const [betaText, alphaText] = await Promise.all([
agentService.generateCommentary("beta", "evaluating"),
agentService.generateCommentary("alpha", "routing"),
]);
if (betaText) broadcastToAll(wss, { type: "agent_commentary", agentId: "beta", jobId, text: betaText });
if (alphaText) broadcastToAll(wss, { type: "agent_commentary", agentId: "alpha", jobId, text: alphaText });
})();
return;
}
if (ev.state === "executing") {
agentId = "gamma"; phase = "starting";
} else if (ev.state === "complete") {
agentId = "alpha"; phase = "complete";
} else if (ev.state === "rejected") {
agentId = "alpha"; phase = "rejected";
}
} else if (ev.type === "job:paid") {
jobId = ev.jobId;
agentId = "delta";
phase = ev.invoiceType === "eval" ? "eval_paid" : "work_paid";
}
if (agentId && phase && jobId) {
const capturedAgentId = agentId;
const capturedPhase = phase;
const capturedJobId = jobId;
void (async () => {
const text = await agentService.generateCommentary(capturedAgentId, capturedPhase);
if (text) broadcastToAll(wss, { type: "agent_commentary", agentId: capturedAgentId, jobId: capturedJobId, text });
})();
}
});
logger.info("WebSocket server attached at /api/ws");
}

View File

@@ -2,7 +2,7 @@ import { Router, type Request, type Response } from "express";
import { randomBytes, randomUUID } from "crypto";
import { verifyEvent, validateEvent } from "nostr-tools";
import { db, nostrTrustVouches, nostrIdentities, timmyNostrEvents } from "@workspace/db";
import { eq, count, desc } from "drizzle-orm";
import { eq, count } from "drizzle-orm";
import { trustService } from "../lib/trust.js";
import { timmyIdentityService } from "../lib/timmy-identity.js";
import { makeLogger } from "../lib/logger.js";
@@ -406,65 +406,4 @@ router.get("/identity/me", async (req: Request, res: Response) => {
}
});
// ── POST /identity/me/decay (TEST-ONLY — disabled in production) ──────────────
// Applies one decay cycle to the authenticated identity immediately, without
// the normal 30-day absence threshold. Useful in test suites.
// Returns 404 in production (NODE_ENV === "production").
router.post("/identity/me/decay", async (req: Request, res: Response) => {
if (process.env["NODE_ENV"] === "production") {
res.status(404).json({ error: "Not found" });
return;
}
const raw = req.headers["x-nostr-token"];
const token = typeof raw === "string" ? raw.trim() : null;
if (!token) {
res.status(401).json({ error: "Missing X-Nostr-Token header" });
return;
}
const parsed = trustService.verifyToken(token);
if (!parsed) {
res.status(401).json({ error: "Invalid or expired nostr_token" });
return;
}
try {
const result = await trustService.decayOnce(parsed.pubkey);
res.json({
pubkey: parsed.pubkey,
previousScore: result.previousScore,
newScore: result.newScore,
newTier: result.newTier,
});
} catch (err) {
res.status(500).json({ error: err instanceof Error ? err.message : "Decay failed" });
}
});
// ── GET /identity/leaderboard ─────────────────────────────────────────────────
// Returns the top 20 identities sorted by trust score descending.
// Public endpoint — no authentication required.
router.get("/identity/leaderboard", async (_req: Request, res: Response) => {
try {
const rows = await db
.select({
pubkey: nostrIdentities.pubkey,
trustScore: nostrIdentities.trustScore,
tier: nostrIdentities.tier,
interactionCount: nostrIdentities.interactionCount,
})
.from(nostrIdentities)
.orderBy(desc(nostrIdentities.trustScore))
.limit(20);
res.json(rows);
} catch (err) {
res.status(500).json({ error: err instanceof Error ? err.message : "Failed to fetch leaderboard" });
}
});
export default router;

View File

@@ -17,13 +17,11 @@ import relayRouter from "./relay.js";
import adminRelayRouter from "./admin-relay.js";
import adminRelayQueueRouter from "./admin-relay-queue.js";
import geminiRouter from "./gemini.js";
import statsRouter from "./stats.js";
const router: IRouter = Router();
router.use(healthRouter);
router.use(metricsRouter);
router.use(statsRouter);
router.use(jobsRouter);
router.use(estimateRouter);
router.use(bootstrapRouter);

View File

@@ -254,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);

View File

@@ -1,79 +0,0 @@
import { type Express, Router } from "express";
import { z } from "zod";
import { Status } from "../lib/http.js";
import { rootLogger } from "../lib/logger.js";
const router = Router();
const log = rootLogger.child({ service: "relay-policy" });
// ── Auth ──────────────────────────────────────────────────────────────────────
const RELAY_POLICY_SECRET = process.env["RELAY_POLICY_SECRET"] ?? "";
if (!RELAY_POLICY_SECRET) {
log.warn("RELAY_POLICY_SECRET is not set — /api/relay/policy will be unauthenticated!");
}
function isAuthenticated(req: Express.Request): boolean {
if (!RELAY_POLICY_SECRET) {
return true; // No secret configured, so no auth.
}
const authz = req.headers["authorization"];
if (!authz) {
return false;
}
const [scheme, token] = authz.split(" ");
if (scheme !== "Bearer" || token !== RELAY_POLICY_SECRET) {
return false;
}
return true;
}
// ── POST /api/relay/policy ────────────────────────────────────────────────────
const relayPolicyRequestSchema = z.object({
event: z.object({
id: z.string(),
pubkey: z.string(),
kind: z.number(),
created_at: z.number(),
tags: z.array(z.array(z.string())),
content: z.string(),
sig: z.string(),
}),
receivedAt: z.number(),
sourceType: z.string(),
sourceInfo: z.string(),
});
type StrfryAction = "accept" | "reject" | "shadowReject";
router.post("/relay/policy", (req, res) => {
if (!isAuthenticated(req)) {
return res.status(Status.UNAUTHORIZED).json({
action: "reject",
msg: "unauthorized",
});
}
const parse = relayPolicyRequestSchema.safeParse(req.body);
if (!parse.success) {
log.warn("invalid /relay/policy request", { error: parse.error.format() });
return res.status(Status.BAD_REQUEST).json({
action: "reject",
msg: "invalid request",
});
}
const eventId = parse.data.event.id;
// Bootstrap state: reject everything.
// This will be extended by whitelist + moderation tasks.
const action: StrfryAction = "reject";
const msg = "bootstrapped: all events rejected";
log.info("policy decision", { eventId: eventId.slice(0, 8), action, msg });
res.json({ id: eventId, action, msg });
});
export default router;

View File

@@ -228,7 +228,6 @@ router.get("/sessions/:id", async (req: Request, res: Response) => {
.update(sessions)
.set({ state: "expired", updatedAt: new Date() })
.where(eq(sessions.id, id));
await db.delete(sessionMessages).where(eq(sessionMessages.sessionId, id));
session = (await getSessionById(id))!;
}
@@ -315,11 +314,6 @@ router.post("/sessions/:id/request", async (req: Request, res: Response) => {
// Load conversation history for context injection
const history = await getSessionHistory(id, 8, 4000);
// Defensive check: log a warning if history still exceeds budget
const currentTokenCount = history.reduce((sum, msg) => sum + Math.ceil(msg.content.length / 4), 0);
if (currentTokenCount > 4000) {
console.warn(`Session ${id}: History exceeds 4000 token budget after retrieval. Actual: ${currentTokenCount}`);
}
// Eval phase
const evalResult = await agentService.evaluateRequest(requestText);
@@ -580,32 +574,4 @@ router.post("/sessions/:id/topup", async (req: Request, res: Response) => {
}
});
// ── DELETE /sessions/:id/history ─────────────────────────────────────────────
router.delete("/sessions/:id/history", async (req: Request, res: Response) => {
const id = req.params.id as string;
const macaroon = extractMacaroon(req);
try {
const session = await getSessionById(id);
if (!session) { res.status(404).json({ error: "Session not found" }); return; }
if (!macaroon || macaroon !== session.macaroon) {
res.status(401).json({ error: "Invalid or missing macaroon. Include 'Authorization: Bearer <macaroon>' header." });
return;
}
if (checkExpired(session) || session.state === "expired") {
res.status(410).json({ error: "Session has expired" });
return;
}
await db.delete(sessionMessages).where(eq(sessionMessages.sessionId, id));
res.json({ cleared: true });
} catch (err) {
res.status(500).json({ error: err instanceof Error ? err.message : "Failed to clear history" });
}
});
export default router;

View File

@@ -1,59 +0,0 @@
import { Router, type Request, type Response } from "express";
import { db, jobs } from "@workspace/db";
import { sql, gte } from "drizzle-orm";
import { makeLogger } from "../lib/logger.js";
const router = Router();
const logger = makeLogger("stats");
/**
* GET /api/stats/activity
*
* Returns job counts bucketed by hour for the past 24 hours.
* Each bucket represents a UTC hour (023).
* Hours with no activity are included as 0.
*
* Response shape:
* { hours: number[24], generatedAt: string }
* hours[0] = oldest hour (24h ago), hours[23] = current hour
*/
router.get("/api/stats/activity", async (_req: Request, res: Response) => {
try {
const now = new Date();
const windowStart = new Date(now.getTime() - 24 * 60 * 60 * 1000);
// Count completed jobs grouped by the hour they were created,
// within the last 24h window.
const rows = await db
.select({
hour: sql<number>`cast(extract(epoch from date_trunc('hour', created_at)) as bigint)`,
count: sql<number>`cast(count(*) as int)`,
})
.from(jobs)
.where(gte(jobs.createdAt, windowStart))
.groupBy(sql`date_trunc('hour', created_at)`);
// Build a map: epoch-hour → count
const byEpochHour = new Map<number, number>();
for (const row of rows) {
byEpochHour.set(Number(row.hour), Number(row.count));
}
// Build 24-slot array aligned to whole hours, oldest first.
// slot 0 = floor(now - 24h), slot 23 = floor(now)
const currentHourEpoch = Math.floor(now.getTime() / (3600 * 1000)) * 3600;
const hours: number[] = [];
for (let i = 23; i >= 0; i--) {
const slotEpoch = currentHourEpoch - i * 3600;
hours.push(byEpochHour.get(slotEpoch) ?? 0);
}
res.json({ hours, generatedAt: now.toISOString() });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to fetch activity stats";
logger.error("activity stats failed", { error: message });
res.status(500).json({ error: message });
}
});
export default router;

View File

@@ -29,12 +29,6 @@ const router = Router();
* Guarded on stubMode=true; polls until state=provisioning|ready (20 s timeout).
* - T24 ADDED: costLedger completeness after job completion — 8 fields, honest-accounting
* invariant (actualAmountSats ≤ workAmountSats), refundState enum check.
* - T41 ADDED: POST /api/jobs with valid Nostr token → nostrPubkey in response matches identity.
* - T42 ADDED: POST /api/sessions with valid Nostr token → nostrPubkey in response matches identity.
* - T43 ADDED: GET /identity/me returns full trust fields (tier, score, interactionCount).
* - T44 ADDED: POST /identity/me/decay (test-only endpoint, 404 in prod) → score decremented.
* - T45 ADDED: GET /identity/leaderboard → HTTP 200, array sorted by trustScore desc.
* New endpoints identity/me/decay and identity/leaderboard added to identity.ts.
*/
router.get("/testkit", (req: Request, res: Response) => {
const proto =
@@ -1098,208 +1092,6 @@ NODESCRIPT
fi
fi
# ===========================================================================
# T41T45 — Nostr identity lifecycle: token decorates jobs/sessions + trust ops
# Requires node + nostr-tools (same guard as T36). All five tests share one
# inline node script that performs the full lifecycle and emits a JSON blob.
# ===========================================================================
# ---------------------------------------------------------------------------
# T41T45 Preamble — ephemeral keypair → challenge → sign → verify → token
# Then: create job, create session, GET /identity/me, decay, leaderboard.
# ---------------------------------------------------------------------------
NOSTR_LC_SKIP=false
NOSTR_LC_OUT=""
if ! command -v node >/dev/null 2>&1; then
NOSTR_LC_SKIP=true
fi
if [[ "\$NOSTR_LC_SKIP" == "false" ]]; then
NOSTR_LC_TMPFILE=\$(mktemp /tmp/nostr_lc_XXXXXX.cjs)
cat > "\$NOSTR_LC_TMPFILE" << 'NODESCRIPT'
'use strict';
const https = require('https');
const http = require('http');
const BASE = process.argv[2];
let nt;
const NOSTR_CJS = '/home/runner/workspace/artifacts/api-server/node_modules/nostr-tools/lib/cjs/index.js';
try { nt = require('nostr-tools'); } catch (_) { try { nt = require(NOSTR_CJS); } catch (_) { process.stderr.write('nostr-tools not importable\n'); process.exit(1); } }
const { generateSecretKey, getPublicKey, finalizeEvent } = nt;
function request(url, opts, body) {
return new Promise((resolve, reject) => {
const u = new URL(url);
const mod = u.protocol === 'https:' ? https : http;
const req = mod.request(u, opts, (res) => {
let data = '';
res.on('data', c => data += c);
res.on('end', () => resolve({ status: res.statusCode, body: data }));
});
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
async function main() {
const sk = generateSecretKey();
const pubkey = getPublicKey(sk);
// challenge → sign → verify
const chalRes = await request(BASE + '/api/identity/challenge', { method: 'POST', headers: { 'Content-Type': 'application/json' } }, '{}');
if (chalRes.status !== 200) { process.stderr.write('challenge failed: ' + chalRes.status + '\n'); process.exit(1); }
const { nonce } = JSON.parse(chalRes.body);
const event = finalizeEvent({ kind: 27235, content: nonce, tags: [], created_at: Math.floor(Date.now() / 1000) }, sk);
const verRes = await request(BASE + '/api/identity/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' } }, JSON.stringify({ event }));
if (verRes.status !== 200) { process.stderr.write('verify failed: ' + verRes.status + ' ' + verRes.body + '\n'); process.exit(1); }
const { nostr_token: token } = JSON.parse(verRes.body);
// POST /jobs with Nostr token
const jobRes = await request(BASE + '/api/jobs', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Nostr-Token': token } }, JSON.stringify({ request: 'T41 Nostr job test' }));
const jobBody = JSON.parse(jobRes.body);
const jobCode = jobRes.status;
const jobId = jobBody.jobId || null;
const jobNpub = jobBody.nostrPubkey || null;
// POST /sessions with Nostr token
const sessRes = await request(BASE + '/api/sessions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Nostr-Token': token } }, JSON.stringify({ amount_sats: 200 }));
const sessBody = JSON.parse(sessRes.body);
const sessCode = sessRes.status;
const sessId = sessBody.sessionId || null;
const sessNpub = sessBody.nostrPubkey || null;
// GET /identity/me
const meRes = await request(BASE + '/api/identity/me', { method: 'GET', headers: { 'X-Nostr-Token': token } });
const meBody = JSON.parse(meRes.body);
const meScore = meBody.trust ? meBody.trust.score : null;
const meTier = meBody.trust ? meBody.trust.tier : null;
const meIcount = meBody.trust ? meBody.trust.interactionCount : null;
// POST /identity/me/decay (test-only; non-200 → skip T44 gracefully)
const decayRes = await request(BASE + '/api/identity/me/decay', { method: 'POST', headers: { 'X-Nostr-Token': token } });
const decayBody = JSON.parse(decayRes.body);
const decayCode = decayRes.status;
const decayPrev = decayBody.previousScore !== undefined ? decayBody.previousScore : null;
const decayNew = decayBody.newScore !== undefined ? decayBody.newScore : null;
// GET /identity/leaderboard
const lbRes = await request(BASE + '/api/identity/leaderboard', { method: 'GET', headers: {} });
const lbCode = lbRes.status;
let lbBody = [];
try { lbBody = JSON.parse(lbRes.body); } catch (_) {}
const lbIsArray = Array.isArray(lbBody);
const lbSorted = lbIsArray && lbBody.length < 2 ? true :
lbIsArray && lbBody.every((v, i) => i === 0 || lbBody[i - 1].trustScore >= v.trustScore);
process.stdout.write(JSON.stringify({
pubkey, token,
jobCode, jobId, jobNpub,
sessCode, sessId, sessNpub,
meScore, meTier, meIcount,
decayCode, decayPrev, decayNew,
lbCode, lbIsArray, lbSorted,
}) + '\n');
}
main().catch(err => { process.stderr.write(String(err) + '\n'); process.exit(1); });
NODESCRIPT
NOSTR_LC_EXIT=0
NOSTR_LC_OUT=\$(node "\$NOSTR_LC_TMPFILE" "\$BASE" 2>/dev/null) || NOSTR_LC_EXIT=\$?
rm -f "\$NOSTR_LC_TMPFILE"
if [[ \$NOSTR_LC_EXIT -ne 0 || -z "\$NOSTR_LC_OUT" ]]; then
NOSTR_LC_SKIP=true
fi
fi
# Helper: extract a field from NOSTR_LC_OUT
_lc() { echo "\$NOSTR_LC_OUT" | jq -r ".\$1" 2>/dev/null || echo ""; }
# ---------------------------------------------------------------------------
# T41 — POST /jobs with valid Nostr token → nostrPubkey in response
# ---------------------------------------------------------------------------
sep "Test 41 — POST /jobs with Nostr token → nostrPubkey set"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T41"
SKIP=\$((SKIP+1))
else
T41_CODE=\$(_lc jobCode); T41_NPUB=\$(_lc jobNpub); T41_PK=\$(_lc pubkey)
if [[ "\$T41_CODE" == "201" && -n "\$T41_NPUB" && "\$T41_NPUB" != "null" && "\$T41_NPUB" == "\$T41_PK" ]]; then
note PASS "HTTP 201, nostrPubkey=\${T41_NPUB:0:8}... matches token identity"
PASS=\$((PASS+1))
else
note FAIL "code=\$T41_CODE nostrPubkey='\$T41_NPUB' expected='\$T41_PK'"
FAIL=\$((FAIL+1))
fi
fi
# ---------------------------------------------------------------------------
# T42 — POST /sessions with valid Nostr token → nostrPubkey in response
# ---------------------------------------------------------------------------
sep "Test 42 — POST /sessions with Nostr token → nostrPubkey set"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T42"
SKIP=\$((SKIP+1))
else
T42_CODE=\$(_lc sessCode); T42_NPUB=\$(_lc sessNpub); T42_PK=\$(_lc pubkey)
if [[ "\$T42_CODE" == "201" && -n "\$T42_NPUB" && "\$T42_NPUB" != "null" && "\$T42_NPUB" == "\$T42_PK" ]]; then
note PASS "HTTP 201, nostrPubkey=\${T42_NPUB:0:8}... matches token identity"
PASS=\$((PASS+1))
else
note FAIL "code=\$T42_CODE nostrPubkey='\$T42_NPUB' expected='\$T42_PK'"
FAIL=\$((FAIL+1))
fi
fi
# ---------------------------------------------------------------------------
# T43 — GET /identity/me returns full trust fields (tier, score, interactionCount)
# ---------------------------------------------------------------------------
sep "Test 43 — GET /identity/me returns tier + score + interactionCount"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T43"
SKIP=\$((SKIP+1))
else
T43_TIER=\$(_lc meTier); T43_SCORE=\$(_lc meScore); T43_ICOUNT=\$(_lc meIcount)
if [[ -n "\$T43_TIER" && "\$T43_TIER" != "null" \
&& "\$T43_SCORE" != "" && "\$T43_SCORE" != "null" \
&& "\$T43_ICOUNT" != "" && "\$T43_ICOUNT" != "null" ]]; then
note PASS "tier=\$T43_TIER score=\$T43_SCORE interactionCount=\$T43_ICOUNT"
PASS=\$((PASS+1))
else
note FAIL "tier='\$T43_TIER' score='\$T43_SCORE' icount='\$T43_ICOUNT'"
FAIL=\$((FAIL+1))
fi
fi
# ---------------------------------------------------------------------------
# T44 — POST /identity/me/decay (test-only endpoint) → score decremented
# Skipped gracefully if endpoint returns non-200 (e.g., production mode).
# ---------------------------------------------------------------------------
sep "Test 44 — POST /identity/me/decay (test mode) → trust_score decremented"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T44"
SKIP=\$((SKIP+1))
else
T44_CODE=\$(_lc decayCode); T44_PREV=\$(_lc decayPrev); T44_NEW=\$(_lc decayNew)
if [[ "\$T44_CODE" != "200" ]]; then
note SKIP "decay endpoint returned code=\$T44_CODE (not in test mode) — skipping T44"
SKIP=\$((SKIP+1))
elif [[ -n "\$T44_PREV" && -n "\$T44_NEW" && "\$T44_NEW" =~ ^[0-9]+\$ && "\$T44_PREV" =~ ^[0-9]+\$ && \$T44_NEW -le \$T44_PREV ]]; then
note PASS "previousScore=\$T44_PREV newScore=\$T44_NEW (decremented or floored at 0)"
PASS=\$((PASS+1))
else
note FAIL "code=\$T44_CODE previousScore='\$T44_PREV' newScore='\$T44_NEW' (expected new ≤ prev)"
FAIL=\$((FAIL+1))
fi
fi
# ---------------------------------------------------------------------------
# T45 — GET /identity/leaderboard → HTTP 200, array sorted by trust score
# ---------------------------------------------------------------------------
sep "Test 45 — GET /identity/leaderboard → sorted array"
if [[ "\$NOSTR_LC_SKIP" == "true" ]]; then
note SKIP "node unavailable or lifecycle preamble failed — skipping T45"
SKIP=\$((SKIP+1))
else
T45_CODE=\$(_lc lbCode); T45_ARRAY=\$(_lc lbIsArray); T45_SORTED=\$(_lc lbSorted)
if [[ "\$T45_CODE" == "200" && "\$T45_ARRAY" == "true" && "\$T45_SORTED" == "true" ]]; then
note PASS "HTTP 200, array returned and sorted by trustScore desc"
PASS=\$((PASS+1))
else
note FAIL "code=\$T45_CODE isArray=\$T45_ARRAY sorted=\$T45_SORTED"
FAIL=\$((FAIL+1))
fi
fi
# ===========================================================================
# FUTURE STUBS — placeholders for upcoming tasks (do not affect PASS/FAIL)
# ===========================================================================

View File

@@ -20,20 +20,7 @@
"adaptiveIcon": {
"foregroundImage": "./assets/images/icon.png",
"backgroundColor": "#0A0A12"
},
"intentFilters": [
{
"action": "VIEW",
"autoVerify": false,
"data": [
{
"scheme": "mobile",
"host": "nostr-callback"
}
],
"category": ["BROWSABLE", "DEFAULT"]
}
]
}
},
"web": {
"favicon": "./assets/images/icon.png",
@@ -50,8 +37,7 @@
"expo-web-browser"
],
"extra": {
"apiDomain": "${EXPO_PUBLIC_DOMAIN}",
"gitCommitHash": "${EXPO_PUBLIC_GIT_SHA}"
"apiDomain": "${EXPO_PUBLIC_DOMAIN}"
},
"experiments": {
"typedRoutes": true,

View File

@@ -1,11 +1,11 @@
import { BlurView } from "expo-blur";
import { isLiquidGlassAvailable } from "expo-glass-effect";
import { Link, Tabs, router } from "expo-router";
import { Tabs } from "expo-router";
import { Icon, Label, NativeTabs } from "expo-router/unstable-native-tabs";
import { SymbolView } from "expo-symbols";
import { Feather, MaterialCommunityIcons, Ionicons } from "@expo/vector-icons";
import { Feather, MaterialCommunityIcons } from "@expo/vector-icons";
import React from "react";
import { Platform, Pressable, StyleSheet, View, useColorScheme } from "react-native";
import { Platform, StyleSheet, View, useColorScheme } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Colors } from "@/constants/colors";
@@ -13,16 +13,16 @@ import { Colors } from "@/constants/colors";
function NativeTabLayout() {
return (
<NativeTabs>
<NativeTabs.Trigger name=\"index\">
<Icon sf={{ default: \"face.smiling\", selected: \"face.smiling.fill\" }} />
<NativeTabs.Trigger name="index">
<Icon sf={{ default: "face.smiling", selected: "face.smiling.fill" }} />
<Label>Timmy</Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name=\"matrix\">
<Icon sf={{ default: \"cube\", selected: \"cube.fill\" }} />
<NativeTabs.Trigger name="matrix">
<Icon sf={{ default: "cube", selected: "cube.fill" }} />
<Label>Matrix</Label>
</NativeTabs.Trigger>
<NativeTabs.Trigger name=\"feed\">
<Icon sf={{ default: \"list.bullet\", selected: \"list.bullet.circle.fill\" }} />
<NativeTabs.Trigger name="feed">
<Icon sf={{ default: "list.bullet", selected: "list.bullet.circle.fill" }} />
<Label>Feed</Label>
</NativeTabs.Trigger>
</NativeTabs>
@@ -39,7 +39,8 @@ function ClassicTabLayout() {
<Tabs
screenOptions={{
headerShown: false,
tabBarActiveTintColor: C.accentGlow,\n tabBarInactiveTintColor: C.textMuted,
tabBarActiveTintColor: C.accentGlow,
tabBarInactiveTintColor: C.textMuted,
tabBarStyle: {
position: "absolute",
backgroundColor: isIOS ? "transparent" : C.surface,
@@ -51,7 +52,7 @@ function ClassicTabLayout() {
isIOS ? (
<BlurView
intensity={80}
tint=\"dark\"
tint="dark"
style={[StyleSheet.absoluteFill, { borderTopWidth: 0.5, borderTopColor: C.border }]}
/>
) : isWeb ? (
@@ -60,53 +61,52 @@ function ClassicTabLayout() {
/>
) : (
<View style={[StyleSheet.absoluteFill, { backgroundColor: C.surface, borderTopWidth: 0.5, borderTopColor: C.border }]} />
),\
}}\
),
}}
>
<Tabs.Screen
name=\"index\"
name="index"
options={{
title: "Timmy",
headerShown: true,
headerRight: () => (\n <Link href=\"/settings\" asChild>\n <Pressable style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}>
<Ionicons name=\"settings-outline\" size={24} color={C.text} style={{ marginRight: 15 }} />\n </Pressable>\n </Link>\n ),
tabBarIcon: ({ color, size }) =>
isIOS ? (
<SymbolView name=\"face.smiling\" tintColor={color} size={size} />
<SymbolView name="face.smiling" tintColor={color} size={size} />
) : (
<MaterialCommunityIcons name=\"emoticon-outline\" size={size} color={color} />
),\
}}\
<MaterialCommunityIcons name="emoticon-outline" size={size} color={color} />
),
}}
/>
<Tabs.Screen
name=\"matrix\"
name="matrix"
options={{
title: "Matrix",
tabBarIcon: ({ color, size }) =>
isIOS ? (
<SymbolView name=\"cube\" tintColor={color} size={size} />
<SymbolView name="cube" tintColor={color} size={size} />
) : (
<MaterialCommunityIcons name=\"cube-outline\" size={size} color={color} />
),\
}}\
<MaterialCommunityIcons name="cube-outline" size={size} color={color} />
),
}}
/>
<Tabs.Screen
name=\"feed\"
name="feed"
options={{
title: "Feed",
tabBarIcon: ({ color, size }) =>
isIOS ? (
<SymbolView name=\"list.bullet\" tintColor={color} size={size} />
<SymbolView name="list.bullet" tintColor={color} size={size} />
) : (
<Feather name=\"activity\" size={size} color={color} />
),\
}}\
<Feather name="activity" size={size} color={color} />
),
}}
/>
</Tabs>
);
}
export default function TabLayout() {
if (isLiquidGlassAvailable()) {\n return (\n <NativeTabs>\n <NativeTabs.Screen\n name=\"index\"\n options={{\n title: \"Timmy\",\n headerShown: true,\n headerRight: () => (\n <Link href=\"/settings\" asChild>\n <Pressable style={({ pressed }) => ({ opacity: pressed ? 0.5 : 1 })}>\n <Ionicons name=\"settings-outline\" size={24} color={C.text} style={{ marginRight: 15 }} />\n </Pressable>\n </Link>\n ),\n }}\n />\n <NativeTabs.Screen name=\"matrix\" />\n <NativeTabs.Screen name=\"feed\" />\n </NativeTabs>\n );\n }
return <ClassicTabLayout />;\
if (isLiquidGlassAvailable()) {
return <NativeTabLayout />;
}
return <ClassicTabLayout />;
}

View File

@@ -16,7 +16,6 @@ import { SafeAreaProvider } from "react-native-safe-area-context";
import { ErrorBoundary } from "@/components/ErrorBoundary";
import { TimmyProvider } from "@/context/TimmyContext";
import { NostrProvider } from "@/context/NostrContext";
import { ONBOARDING_COMPLETED_KEY } from "@/constants/storage-keys";
SplashScreen.preventAutoHideAsync();
@@ -51,7 +50,6 @@ function RootLayoutNav() {
<Stack screenOptions={{ headerBackTitle: "Back" }}>
<Stack.Screen name="onboarding" options={{ headerShown: false, animation: "none" }} />
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="settings" options={{ headerShown: false, presentation: "modal" }} />
</Stack>
);
}
@@ -78,11 +76,9 @@ export default function RootLayout() {
<QueryClientProvider client={queryClient}>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider>
<NostrProvider>
<TimmyProvider>
<RootLayoutNav />
</TimmyProvider>
</NostrProvider>
<TimmyProvider>
<RootLayoutNav />
</TimmyProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</QueryClientProvider>

View File

@@ -1,273 +0,0 @@
import { Stack } from "expo-router";
import {
Linking,
Platform,
Pressable,
ScrollView,
StyleSheet,
Switch,
Text,
TextInput,
View,
} from "react-native";
import { useState, useEffect } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import Constants from "expo-constants";
import { Ionicons } from "@expo/vector-icons";
import { useTimmy } from "@/context/TimmyContext";
import { useNostr, truncateNpub } from "@/context/NostrContext";
import { ConnectionBadge } from "@/components/ConnectionBadge";
import { NostrConnectModal } from "@/components/NostrConnectModal";
import { Colors } from "@/constants/colors";
const NOTIF_JOB_KEY = "settings.notifications_job_completion";
const NOTIF_BALANCE_KEY = "settings.notifications_low_balance";
export default function SettingsScreen() {
const C = Colors.dark;
const { apiBaseUrl, setApiBaseUrl, isConnected } = useTimmy();
const { npub, nostrConnected, signerType, disconnect: disconnectNostr } = useNostr();
const [serverUrl, setServerUrl] = useState(apiBaseUrl);
const [jobCompletionNotifications, setJobCompletionNotifications] = useState(false);
const [lowBalanceWarning, setLowBalanceWarning] = useState(false);
const [nostrModalVisible, setNostrModalVisible] = useState(false);
// Sync local serverUrl with context value (e.g. on first load from AsyncStorage)
useEffect(() => {
setServerUrl(apiBaseUrl);
}, [apiBaseUrl]);
useEffect(() => {
AsyncStorage.multiGet([NOTIF_JOB_KEY, NOTIF_BALANCE_KEY])
.then(([[, job], [, balance]]) => {
if (job !== null) setJobCompletionNotifications(JSON.parse(job));
if (balance !== null) setLowBalanceWarning(JSON.parse(balance));
})
.catch(() => {});
}, []);
const handleServerUrlBlur = () => {
if (serverUrl !== apiBaseUrl) {
setApiBaseUrl(serverUrl);
}
};
const toggleJobCompletion = async () => {
const next = !jobCompletionNotifications;
setJobCompletionNotifications(next);
await AsyncStorage.setItem(NOTIF_JOB_KEY, JSON.stringify(next));
};
const toggleLowBalance = async () => {
const next = !lowBalanceWarning;
setLowBalanceWarning(next);
await AsyncStorage.setItem(NOTIF_BALANCE_KEY, JSON.stringify(next));
};
const handleDisconnectNostr = async () => {
await disconnectNostr();
};
const appVersion = Constants.expoConfig?.version ?? "N/A";
const buildCommitHash = Constants.expoConfig?.extra?.["gitCommitHash"] ?? "N/A";
const giteaRepoUrl = "http://143.198.27.163:3000/replit/timmy-tower";
return (
<View style={[styles.container, { backgroundColor: C.background }]}>
<Stack.Screen
options={{
title: "Settings",
headerShown: true,
headerStyle: { backgroundColor: C.surface },
headerTintColor: C.text,
}}
/>
<ScrollView contentContainerStyle={styles.scrollContent}>
{/* ── Connection ──────────────────────────────────────────────── */}
<Text style={[styles.sectionHeader, { color: C.text }]}>Connection</Text>
<View style={styles.settingItem}>
<Text style={[styles.settingLabel, { color: C.text }]}>Server URL</Text>
<View style={styles.serverUrlContainer}>
<TextInput
style={[styles.input, { color: C.text, backgroundColor: C.field, borderColor: C.border }]}
value={serverUrl}
onChangeText={setServerUrl}
onBlur={handleServerUrlBlur}
placeholder="Enter server URL"
placeholderTextColor={C.textMuted}
autoCapitalize="none"
autoCorrect={false}
/>
<ConnectionBadge isConnected={isConnected} />
</View>
</View>
{/* ── Notifications ────────────────────────────────────────────── */}
<Text style={[styles.sectionHeader, { color: C.text }]}>Notifications</Text>
<View style={[styles.settingItem, { borderBottomColor: C.border }]}>
<Text style={[styles.settingLabel, { color: C.text }]}>Job Completion</Text>
<Switch
trackColor={{ false: C.surface, true: C.accentGlow }}
thumbColor={Platform.OS === "android" ? C.text : ""}
ios_backgroundColor={C.field}
onValueChange={toggleJobCompletion}
value={jobCompletionNotifications}
/>
</View>
<View style={[styles.settingItem, { borderBottomColor: C.border }]}>
<Text style={[styles.settingLabel, { color: C.text }]}>Low Balance Warning</Text>
<Switch
trackColor={{ false: C.surface, true: C.accentGlow }}
thumbColor={Platform.OS === "android" ? C.text : ""}
ios_backgroundColor={C.field}
onValueChange={toggleLowBalance}
value={lowBalanceWarning}
/>
</View>
{/* ── Nostr Identity ───────────────────────────────────────────── */}
<Text style={[styles.sectionHeader, { color: C.text }]}>Identity</Text>
<View style={[styles.settingItem, { borderBottomColor: C.border }]}>
<Text style={[styles.settingLabel, { color: C.text }]}>Nostr Public Key</Text>
<Text style={[styles.settingValue, { color: C.textMuted }]}>
{npub ? truncateNpub(npub) : "Not connected"}
</Text>
</View>
{nostrConnected && signerType && (
<View style={[styles.settingItem, { borderBottomColor: C.border }]}>
<Text style={[styles.settingLabel, { color: C.text }]}>Signer</Text>
<Text style={[styles.settingValue, { color: C.textSecondary }]}>
{signerType === "amber" ? "Amber (NIP-55)" : "nsec key"}
</Text>
</View>
)}
<View style={styles.buttonContainer}>
{!nostrConnected ? (
<Pressable
onPress={() => setNostrModalVisible(true)}
style={({ pressed }) => [
styles.button,
{ backgroundColor: C.accent, opacity: pressed ? 0.8 : 1 },
]}
>
<Text style={[styles.buttonText, { color: C.textInverted }]}>
Connect Nostr Identity
</Text>
</Pressable>
) : (
<Pressable
onPress={handleDisconnectNostr}
style={({ pressed }) => [
styles.button,
{ backgroundColor: C.destructive, opacity: pressed ? 0.8 : 1 },
]}
>
<Text style={[styles.buttonText, { color: C.textInverted }]}>
Disconnect Nostr
</Text>
</Pressable>
)}
</View>
{/* ── About ───────────────────────────────────────────────────── */}
<Text style={[styles.sectionHeader, { color: C.text }]}>About</Text>
<View style={[styles.settingItem, { borderBottomColor: C.border }]}>
<Text style={[styles.settingLabel, { color: C.text }]}>App Version</Text>
<Text style={[styles.settingValue, { color: C.text }]}>{appVersion}</Text>
</View>
<View style={[styles.settingItem, { borderBottomColor: C.border }]}>
<Text style={[styles.settingLabel, { color: C.text }]}>Build Commit</Text>
<Text style={[styles.settingValue, { color: C.text }]}>{buildCommitHash}</Text>
</View>
<Pressable
onPress={() => Linking.openURL(giteaRepoUrl)}
style={({ pressed }) => [styles.linkButton, { opacity: pressed ? 0.8 : 1 }]}
>
<Ionicons name="link" size={16} color={C.text} />
<Text style={[styles.linkButtonText, { color: C.link }]}>
View project on Gitea
</Text>
</Pressable>
</ScrollView>
<NostrConnectModal
visible={nostrModalVisible}
onClose={() => setNostrModalVisible(false)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollContent: {
padding: 20,
paddingBottom: 40,
},
sectionHeader: {
fontSize: 18,
fontWeight: "bold",
marginTop: 20,
marginBottom: 10,
},
settingItem: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingVertical: 12,
borderBottomWidth: 0.5,
},
settingLabel: {
fontSize: 16,
flex: 1,
},
settingValue: {
fontSize: 14,
flexShrink: 1,
textAlign: "right",
marginLeft: 8,
},
serverUrlContainer: {
flexDirection: "row",
alignItems: "center",
flex: 2,
},
input: {
flex: 1,
borderWidth: 1,
borderRadius: 8,
padding: 8,
fontSize: 14,
marginRight: 10,
},
buttonContainer: {
marginTop: 20,
alignItems: "flex-start",
},
button: {
paddingVertical: 10,
paddingHorizontal: 15,
borderRadius: 8,
},
buttonText: {
fontSize: 16,
fontWeight: "bold",
},
linkButton: {
flexDirection: "row",
alignItems: "center",
marginTop: 15,
paddingVertical: 8,
},
linkButtonText: {
marginLeft: 5,
fontSize: 16,
},
});

View File

@@ -1,276 +0,0 @@
/**
* NostrConnectModal — UI for connecting a Nostr identity on mobile.
*
* Android: offers "Connect with Amber" (NIP-55) as the primary action,
* with manual nsec entry as a secondary option.
* iOS / other: manual nsec entry only.
*/
import React, { useCallback, useState } from "react";
import {
ActivityIndicator,
Modal,
Platform,
Pressable,
StyleSheet,
Text,
TextInput,
View,
} from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { Colors } from "@/constants/colors";
import { useNostr } from "@/context/NostrContext";
// ─── Props ────────────────────────────────────────────────────────────────────
type Props = {
visible: boolean;
onClose: () => void;
};
// ─── Component ────────────────────────────────────────────────────────────────
export function NostrConnectModal({ visible, onClose }: Props) {
const C = Colors.dark;
const { connectWithAmber, connectWithNsec, canUseAmber } = useNostr();
const [showNsecForm, setShowNsecForm] = useState(!canUseAmber);
const [nsecInput, setNsecInput] = useState("");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const handleClose = useCallback(() => {
setNsecInput("");
setError(null);
setShowNsecForm(!canUseAmber);
onClose();
}, [canUseAmber, onClose]);
const handleAmberPress = useCallback(async () => {
setError(null);
setLoading(true);
try {
await connectWithAmber();
// Amber opens; the result arrives via deep-link callback.
// Close the modal — NostrContext handles the incoming URL.
handleClose();
} finally {
setLoading(false);
}
}, [connectWithAmber, handleClose]);
const handleNsecConnect = useCallback(async () => {
if (!nsecInput.trim()) {
setError("Please enter your nsec key");
return;
}
setError(null);
setLoading(true);
const result = await connectWithNsec(nsecInput.trim());
setLoading(false);
if (result.success) {
handleClose();
} else {
setError(result.error);
}
}, [nsecInput, connectWithNsec, handleClose]);
return (
<Modal
visible={visible}
animationType="slide"
transparent
onRequestClose={handleClose}
>
<View style={styles.overlay}>
<View style={[styles.sheet, { backgroundColor: C.surface, borderColor: C.border }]}>
{/* Header */}
<View style={styles.header}>
<Text style={[styles.title, { color: C.text }]}>Connect Nostr Identity</Text>
<Pressable onPress={handleClose} hitSlop={12}>
<Ionicons name="close" size={22} color={C.textSecondary} />
</Pressable>
</View>
{/* Android: Amber option */}
{canUseAmber && !showNsecForm && (
<View style={styles.body}>
<Text style={[styles.description, { color: C.textSecondary }]}>
Connect using{" "}
<Text style={{ color: C.text, fontWeight: "600" }}>Amber</Text>{" "}
your keys stay in Amber and are never exposed to this app.
</Text>
<Pressable
onPress={handleAmberPress}
disabled={loading}
style={({ pressed }) => [
styles.primaryButton,
{ backgroundColor: C.accent, opacity: pressed || loading ? 0.75 : 1 },
]}
>
{loading ? (
<ActivityIndicator color={C.textInverted} />
) : (
<>
<Ionicons name="shield-checkmark" size={18} color={C.textInverted} />
<Text style={[styles.buttonText, { color: C.textInverted }]}>
Connect with Amber
</Text>
</>
)}
</Pressable>
<Pressable
onPress={() => setShowNsecForm(true)}
style={styles.secondaryLink}
>
<Text style={[styles.secondaryLinkText, { color: C.link }]}>
Enter nsec manually instead
</Text>
</Pressable>
</View>
)}
{/* nsec form */}
{showNsecForm && (
<View style={styles.body}>
{canUseAmber && (
<Pressable
onPress={() => { setShowNsecForm(false); setError(null); }}
style={styles.backLink}
>
<Ionicons name="arrow-back" size={14} color={C.link} />
<Text style={[styles.secondaryLinkText, { color: C.link }]}>
Use Amber instead
</Text>
</Pressable>
)}
<Text style={[styles.description, { color: C.textSecondary }]}>
Paste your{" "}
<Text style={{ color: C.text, fontWeight: "600" }}>nsec1</Text>{" "}
private key. It will be stored only in the device secure keystore
and never logged or transmitted.
</Text>
<TextInput
style={[
styles.input,
{
backgroundColor: C.field,
color: C.text,
borderColor: error ? C.destructive : C.border,
},
]}
placeholder="nsec1…"
placeholderTextColor={C.textMuted}
value={nsecInput}
onChangeText={(t) => { setNsecInput(t); setError(null); }}
autoCapitalize="none"
autoCorrect={false}
secureTextEntry
editable={!loading}
/>
{error && (
<Text style={[styles.errorText, { color: C.destructive }]}>
{error}
</Text>
)}
<Pressable
onPress={handleNsecConnect}
disabled={loading}
style={({ pressed }) => [
styles.primaryButton,
{ backgroundColor: C.accent, opacity: pressed || loading ? 0.75 : 1 },
]}
>
{loading ? (
<ActivityIndicator color={C.textInverted} />
) : (
<Text style={[styles.buttonText, { color: C.textInverted }]}>
Connect
</Text>
)}
</Pressable>
</View>
)}
</View>
</View>
</Modal>
);
}
// ─── Styles ───────────────────────────────────────────────────────────────────
const styles = StyleSheet.create({
overlay: {
flex: 1,
justifyContent: "flex-end",
backgroundColor: "rgba(0,0,0,0.6)",
},
sheet: {
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
borderWidth: 1,
borderBottomWidth: 0,
paddingHorizontal: 24,
paddingTop: 20,
paddingBottom: Platform.OS === "ios" ? 40 : 24,
},
header: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 16,
},
title: {
fontSize: 18,
fontWeight: "700",
},
body: {
gap: 14,
},
description: {
fontSize: 14,
lineHeight: 20,
},
primaryButton: {
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: 8,
paddingVertical: 14,
borderRadius: 10,
},
buttonText: {
fontSize: 16,
fontWeight: "600",
},
secondaryLink: {
alignItems: "center",
paddingVertical: 4,
},
secondaryLinkText: {
fontSize: 14,
},
backLink: {
flexDirection: "row",
alignItems: "center",
gap: 4,
},
input: {
borderWidth: 1,
borderRadius: 10,
paddingHorizontal: 14,
paddingVertical: 12,
fontSize: 14,
fontFamily: Platform.OS === "ios" ? "Courier" : "monospace",
},
errorText: {
fontSize: 13,
},
});

View File

@@ -29,10 +29,6 @@ export const Colors = {
working: "#F59E0B",
idle: "#6B7280",
micActive: "#EF4444",
field: "#1A1A2E",
textInverted: "#0A0A12",
destructive: "#EF4444",
link: "#A78BFA",
},
} as const;

View File

@@ -1,2 +1 @@
export const ONBOARDING_COMPLETED_KEY = "app.onboarding_completed";
export const SERVER_URL_KEY = "settings.server_url";

View File

@@ -1,274 +0,0 @@
/**
* NostrContext — Nostr identity management for mobile.
*
* Android: NIP-55 Amber deep-link signing (com.greenart7c3.nostrsigner).
* Opens Amber via the `nostrsigner:` URI scheme to retrieve the user's
* public key; falls back to the Play Store install prompt when Amber is
* not installed.
*
* iOS / manual fallback: nsec paste-in stored exclusively in Expo SecureStore.
* The raw key is NEVER written to AsyncStorage, Redux state, or logs.
*/
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react";
import { Linking, Platform } from "react-native";
import * as SecureStore from "expo-secure-store";
import { getPublicKey, nip19 } from "nostr-tools";
// ─── Types ────────────────────────────────────────────────────────────────────
export type NostrSignerType = "amber" | "nsec" | null;
export type NostrConnectResult =
| { success: true }
| { success: false; error: string };
type NostrContextValue = {
/** bech32 public key (npub1…), null when no identity is loaded */
npub: string | null;
/** Raw hex public key, null when no identity is loaded */
pubkeyHex: string | null;
/** How the key was connected */
signerType: NostrSignerType;
/** True when an identity is loaded */
nostrConnected: boolean;
/** True only on Android — Amber integration available */
canUseAmber: boolean;
/** Android only: launch Amber to retrieve the user's public key */
connectWithAmber: () => Promise<void>;
/** Both platforms: validate & store an nsec; derive and cache the npub */
connectWithNsec: (nsec: string) => Promise<NostrConnectResult>;
/** Wipe all Nostr credentials from SecureStore and reset state */
disconnect: () => Promise<void>;
};
// ─── Constants ────────────────────────────────────────────────────────────────
const SECURE_KEY_NSEC = "nostr.nsec";
const SECURE_KEY_NPUB = "nostr.npub";
const SECURE_KEY_SIGNER_TYPE = "nostr.signer_type";
/** The deep-link scheme declared in app.json */
const APP_SCHEME = "mobile";
/** Path Amber will call back to with the pubkey result */
const AMBER_CALLBACK_URL = `${APP_SCHEME}://nostr-callback`;
const AMBER_PACKAGE = "com.greenart7c3.nostrsigner";
const AMBER_PLAY_STORE_URL =
"https://play.google.com/store/apps/details?id=com.greenart7c3.nostrsigner";
// ─── Helpers ──────────────────────────────────────────────────────────────────
/** Truncate an npub for display: "npub1abcde…xyz12" */
export function truncateNpub(npub: string): string {
if (npub.length <= 20) return npub;
return `${npub.substring(0, 10)}${npub.substring(npub.length - 5)}`;
}
// ─── Context ──────────────────────────────────────────────────────────────────
const NostrContext = createContext<NostrContextValue | null>(null);
export function NostrProvider({ children }: { children: React.ReactNode }) {
const [npub, setNpub] = useState<string | null>(null);
const [pubkeyHex, setPubkeyHex] = useState<string | null>(null);
const [signerType, setSignerType] = useState<NostrSignerType>(null);
const canUseAmber = Platform.OS === "android";
// ── Load persisted identity on mount ──────────────────────────────────────
useEffect(() => {
async function loadIdentity() {
try {
const [storedNpub, storedSignerType] = await Promise.all([
SecureStore.getItemAsync(SECURE_KEY_NPUB),
SecureStore.getItemAsync(SECURE_KEY_SIGNER_TYPE),
]);
if (storedNpub && storedSignerType) {
setNpub(storedNpub);
setSignerType(storedSignerType as NostrSignerType);
try {
const decoded = nip19.decode(storedNpub);
if (decoded.type === "npub") {
setPubkeyHex(decoded.data as string);
}
} catch {
// npub decode failure — identity still "connected", pubkeyHex stays null
}
}
} catch {
// SecureStore unavailable (e.g. web build) — proceed without identity
}
}
loadIdentity();
}, []);
// ── Handle Amber callback deep link (Android) ─────────────────────────────
useEffect(() => {
if (!canUseAmber) return;
function handleUrl({ url }: { url: string }) {
if (!url.startsWith(`${APP_SCHEME}://nostr-callback`)) return;
try {
// React Native's URL parsing is not available in all environments;
// parse manually to avoid importing a polyfill.
const queryStart = url.indexOf("?");
if (queryStart === -1) return;
const params = new URLSearchParams(url.slice(queryStart + 1));
const result = params.get("result");
if (!result) return;
// Amber returns the hex pubkey in `result`
let hexKey = result;
if (result.startsWith("npub1")) {
const decoded = nip19.decode(result);
if (decoded.type === "npub") hexKey = decoded.data as string;
}
const derivedNpub = nip19.npubEncode(hexKey);
// Persist — no private key stored for Amber flow
SecureStore.setItemAsync(SECURE_KEY_NPUB, derivedNpub).catch(() => {});
SecureStore.setItemAsync(SECURE_KEY_SIGNER_TYPE, "amber").catch(() => {});
setNpub(derivedNpub);
setPubkeyHex(hexKey);
setSignerType("amber");
} catch {
// Malformed callback — silently ignore
}
}
const subscription = Linking.addEventListener("url", handleUrl);
return () => subscription.remove();
}, [canUseAmber]);
// ── Actions ───────────────────────────────────────────────────────────────
const connectWithAmber = useCallback(async () => {
// NIP-55: request the user's public key from Amber
const amberUri = `nostrsigner:?type=get_public_key&compressionType=none&returnType=signature&callbackUrl=${encodeURIComponent(AMBER_CALLBACK_URL)}`;
let canOpen = false;
try {
canOpen = await Linking.canOpenURL(`nostrsigner:`);
} catch {
canOpen = false;
}
if (canOpen) {
await Linking.openURL(amberUri);
} else {
// Amber not installed — direct user to Play Store
await Linking.openURL(AMBER_PLAY_STORE_URL);
}
}, []);
const connectWithNsec = useCallback(
async (nsec: string): Promise<NostrConnectResult> => {
const trimmed = nsec.trim();
if (!trimmed.startsWith("nsec1")) {
return { success: false, error: "Key must start with nsec1" };
}
let decoded: ReturnType<typeof nip19.decode>;
try {
decoded = nip19.decode(trimmed);
} catch {
return { success: false, error: "Invalid bech32 encoding" };
}
if (decoded.type !== "nsec") {
return { success: false, error: "Not a valid nsec key" };
}
let hexPubkey: string;
try {
const sk = decoded.data as Uint8Array;
hexPubkey = getPublicKey(sk);
} catch {
return { success: false, error: "Could not derive public key" };
}
const derivedNpub = nip19.npubEncode(hexPubkey);
try {
// Store only in SecureStore — never AsyncStorage, never logs
await SecureStore.setItemAsync(SECURE_KEY_NSEC, trimmed);
await SecureStore.setItemAsync(SECURE_KEY_NPUB, derivedNpub);
await SecureStore.setItemAsync(SECURE_KEY_SIGNER_TYPE, "nsec");
} catch {
return { success: false, error: "Failed to store key securely" };
}
setNpub(derivedNpub);
setPubkeyHex(hexPubkey);
setSignerType("nsec");
return { success: true };
},
[]
);
const disconnect = useCallback(async () => {
try {
await Promise.all([
SecureStore.deleteItemAsync(SECURE_KEY_NSEC),
SecureStore.deleteItemAsync(SECURE_KEY_NPUB),
SecureStore.deleteItemAsync(SECURE_KEY_SIGNER_TYPE),
]);
} catch {
// Best-effort cleanup; reset state regardless
}
setNpub(null);
setPubkeyHex(null);
setSignerType(null);
}, []);
// ── Context value ─────────────────────────────────────────────────────────
const value = useMemo<NostrContextValue>(
() => ({
npub,
pubkeyHex,
signerType,
nostrConnected: npub !== null,
canUseAmber,
connectWithAmber,
connectWithNsec,
disconnect,
}),
[
npub,
pubkeyHex,
signerType,
canUseAmber,
connectWithAmber,
connectWithNsec,
disconnect,
]
);
return (
<NostrContext.Provider value={value}>{children}</NostrContext.Provider>
);
}
export function useNostr(): NostrContextValue {
const ctx = useContext(NostrContext);
if (!ctx) throw new Error("useNostr must be used within NostrProvider");
return ctx;
}
export { AMBER_PACKAGE };

View File

@@ -8,9 +8,6 @@ import React, {
useState,
} from "react";
import { AppState, Platform } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { SERVER_URL_KEY } from "@/constants/storage-keys";
export type TimmyMood = "idle" | "thinking" | "working" | "speaking";
@@ -25,42 +22,33 @@ export type WsEvent = {
count?: number;
};
export type ConnectionStatus =
| "connecting"
| "connected"
| "disconnected"
| "reconnecting"
| "error";
export type ConnectionStatus = "connecting" | "connected" | "disconnected" | "reconnecting" | "error";
type TimmyContextValue = {
timmyMood: TimmyMood;
connectionStatus: ConnectionStatus;
/** True when the WebSocket is fully open */
isConnected: boolean;
recentEvents: WsEvent[];
send: (msg: object) => void;
sendVisitorMessage: (text: string) => void;
visitorId: string;
/** Current API / WebSocket base domain */
apiBaseUrl: string;
/** Persist a new base URL and reconnect the WebSocket */
setApiBaseUrl: (url: string) => void;
};
const TimmyContext = createContext<TimmyContextValue | null>(null);
const MAX_EVENTS = 100;
const ENV_DOMAIN = process.env["EXPO_PUBLIC_DOMAIN"] ?? "";
const BASE_URL = process.env.EXPO_PUBLIC_DOMAIN ?? "";
const VISITOR_ID =
Date.now().toString() + Math.random().toString(36).substr(2, 9);
function buildWsUrl(domain: string): string {
let d = domain.trim();
if (!d) d = "localhost:8080";
d = d.replace(/^https?:\/\//, "");
d = d.replace(/\/$/, "");
const proto = d.startsWith("localhost") ? "ws" : "wss";
return `${proto}://${d}/api/ws`;
function getWsUrl(): string {
let domain = BASE_URL;
if (!domain) {
domain = "localhost:8080";
}
domain = domain.replace(/^https?:\/\//, "");
domain = domain.replace(/\/$/, "");
const proto = domain.startsWith("localhost") ? "ws" : "wss";
return `${proto}://${domain}/api/ws`;
}
function deriveMood(agentStates: Record<string, string>): TimmyMood {
@@ -75,12 +63,10 @@ function deriveMood(agentStates: Record<string, string>): TimmyMood {
}
export function TimmyProvider({ children }: { children: React.ReactNode }) {
const [apiBaseUrl, setApiBaseUrlState] = useState(ENV_DOMAIN);
const [timmyMood, setTimmyMood] = useState<TimmyMood>("idle");
const [connectionStatus, setConnectionStatus] =
useState<ConnectionStatus>("connecting");
const [recentEvents, setRecentEvents] = useState<WsEvent[]>([]);
const wsRef = useRef<WebSocket | null>(null);
const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const retryCountRef = useRef(0);
@@ -91,32 +77,6 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
delta: "idle",
});
const speakingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Stable ref so WebSocket callbacks always read the current URL
const apiBaseUrlRef = useRef(apiBaseUrl);
// Stable refs to break the connectWs ↔ scheduleRetry circular dependency
const connectWsRef = useRef<() => void>(() => {});
const scheduleRetryRef = useRef<() => void>(() => {});
// ── Load persisted URL on mount ────────────────────────────────────────
useEffect(() => {
AsyncStorage.getItem(SERVER_URL_KEY)
.then((stored) => {
if (stored) {
setApiBaseUrlState(stored);
apiBaseUrlRef.current = stored;
}
})
.catch(() => {});
}, []);
const setApiBaseUrl = useCallback((url: string) => {
setApiBaseUrlState(url);
apiBaseUrlRef.current = url;
AsyncStorage.setItem(SERVER_URL_KEY, url).catch(() => {});
}, []);
// ── WebSocket helpers ──────────────────────────────────────────────────
const addEvent = useCallback((evt: Omit<WsEvent, "id" | "timestamp">) => {
const entry: WsEvent = {
@@ -134,14 +94,14 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
wsRef.current.close();
wsRef.current = null;
}
const url = buildWsUrl(apiBaseUrlRef.current);
const url = getWsUrl();
setConnectionStatus("connecting");
let ws: WebSocket;
try {
ws = new WebSocket(url);
} catch {
setConnectionStatus("error");
scheduleRetryRef.current();
scheduleRetry();
return;
}
wsRef.current = ws;
@@ -174,7 +134,10 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
if (type === "world_state") {
const states = (msg.agentStates as Record<string, string>) ?? {};
agentStatesRef.current = { ...agentStatesRef.current, ...states };
agentStatesRef.current = {
...agentStatesRef.current,
...states,
};
setTimmyMood(deriveMood(agentStatesRef.current));
return;
}
@@ -224,7 +187,7 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
ws.onclose = () => {
setConnectionStatus("disconnected");
scheduleRetryRef.current();
scheduleRetry();
};
ws.onerror = () => {
@@ -237,15 +200,9 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
const delay = Math.min(1000 * Math.pow(2, retryCountRef.current), 30000);
retryCountRef.current += 1;
retryTimerRef.current = setTimeout(() => {
connectWsRef.current();
connectWs();
}, delay);
}, []);
// Keep the stable refs current after every render
connectWsRef.current = connectWs;
scheduleRetryRef.current = scheduleRetry;
// ── Initial connect ────────────────────────────────────────────────────
}, [connectWs]);
useEffect(() => {
connectWs();
@@ -259,19 +216,7 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
};
}, [connectWs]);
// Reconnect when apiBaseUrl changes (skip the very first render)
const isFirstRenderRef = useRef(true);
useEffect(() => {
if (isFirstRenderRef.current) {
isFirstRenderRef.current = false;
return;
}
retryCountRef.current = 0;
connectWs();
}, [apiBaseUrl, connectWs]);
// ── AppState-aware reconnect on foreground ─────────────────────────────
// AppState-aware WebSocket reconnect on foreground
useEffect(() => {
if (Platform.OS === "web") return;
@@ -284,17 +229,20 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
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");
connectWsRef.current();
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;
@@ -314,9 +262,7 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
return () => {
subscription.remove();
};
}, []);
// ── Outbound messages ──────────────────────────────────────────────────
}, [connectWs]);
const send = useCallback((msg: object) => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
@@ -324,42 +270,28 @@ export function TimmyProvider({ children }: { children: React.ReactNode }) {
}
}, []);
const sendVisitorMessage = useCallback((text: string) => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(
JSON.stringify({
type: "visitor_message",
visitorId: VISITOR_ID,
text,
})
);
setTimmyMood("thinking");
}
}, []);
const sendVisitorMessage = useCallback(
(text: string) => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(
JSON.stringify({ type: "visitor_message", visitorId: VISITOR_ID, text })
);
setTimmyMood("thinking");
}
},
[]
);
// ── Context value ──────────────────────────────────────────────────────
const value = useMemo<TimmyContextValue>(
const value = useMemo(
() => ({
timmyMood,
connectionStatus,
isConnected: connectionStatus === "connected",
recentEvents,
send,
sendVisitorMessage,
visitorId: VISITOR_ID,
apiBaseUrl,
setApiBaseUrl,
}),
[
timmyMood,
connectionStatus,
recentEvents,
send,
sendVisitorMessage,
apiBaseUrl,
setApiBaseUrl,
]
[timmyMood, connectionStatus, recentEvents, send, sendVisitorMessage]
);
return (

View File

@@ -4,7 +4,7 @@
"private": true,
"main": "expo-router/entry",
"scripts": {
"dev": "pnpm exec expo start --localhost --port 8081",
"dev": "EXPO_PACKAGER_PROXY_URL=https://$REPLIT_EXPO_DEV_DOMAIN EXPO_PUBLIC_DOMAIN=$REPLIT_DEV_DOMAIN EXPO_PUBLIC_REPL_ID=$REPL_ID REACT_NATIVE_PACKAGER_HOSTNAME=$REPLIT_DEV_DOMAIN pnpm exec expo start --localhost --port $PORT",
"build": "node scripts/build.js",
"serve": "node server/serve.js",
"typecheck": "tsc -p tsconfig.json --noEmit"
@@ -57,9 +57,7 @@
},
"dependencies": {
"@react-native-voice/voice": "^3.2.4",
"expo-secure-store": "~14.0.1",
"expo-speech": "^14.0.8",
"nostr-tools": "^2.23.3",
"react-native-qrcode-svg": "^6.3.21",
"react-native-webview": "^13.15.0"
}

View File

@@ -1,6 +1,6 @@
const fs = require("fs");
const path = require("path");
const { spawn, execSync } = require("child_process");
const { spawn } = require("child_process");
const { Readable } = require("stream");
const { pipeline } = require("stream/promises");
@@ -127,15 +127,6 @@ function getExpoPublicReplId() {
return process.env.REPL_ID || process.env.EXPO_PUBLIC_REPL_ID;
}
function getGitSha() {
try {
return execSync("git rev-parse HEAD", { cwd: workspaceRoot }).toString().trim();
} catch (error) {
console.warn("Could not get git commit hash:", error.message);
return "unknown";
}
}
async function startMetro(expoPublicDomain, expoPublicReplId) {
const isRunning = await checkMetroHealth();
if (isRunning) {
@@ -145,12 +136,10 @@ async function startMetro(expoPublicDomain, expoPublicReplId) {
console.log("Starting Metro...");
console.log(`Setting EXPO_PUBLIC_DOMAIN=${expoPublicDomain}`);
const gitSha = getGitSha();
const env = {
...process.env,
EXPO_PUBLIC_DOMAIN: expoPublicDomain,
EXPO_PUBLIC_REPL_ID: expoPublicReplId,
EXPO_PUBLIC_GIT_SHA: gitSha,
};
if (expoPublicReplId) {

View 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;

View File

@@ -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(),
});

View File

@@ -115,8 +115,6 @@ The `costLedger` in `GET /api/jobs/:id` shows all figures side-by-side. If `refu
| `DO_REGION` | DO datacenter region | `nyc3` |
| `DO_SIZE` | DO droplet size slug | `s-4vcpu-8gb` |
| `DO_VOLUME_SIZE_GB` | Block volume to attach in GB (`0` = none) | `0` |
| `DO_VPC_UUID` | Digital Ocean VPC UUID to deploy droplet into | (required) |
| `DO_SSH_KEY_FINGERPRINT` | Digital Ocean SSH Key Fingerprint for droplet access | (required) |
| `TAILSCALE_API_KEY` | Tailscale API key for generating auth keys | optional |
| `TAILSCALE_TAILNET` | Tailscale tailnet name (e.g. `example.com`) | required with above |

View File

@@ -1,38 +0,0 @@
# Branch Audit — Issue #103
## Summary (2026-03-23)
### Unmerged branches reviewed
| Branch | Content | Status | Action |
|--------|---------|--------|--------|
| `gemini/issue-14` | NIP-07 Nostr identity | Unique diff vs main | **PR #104 opened** |
| `gemini/issue-42` | Timmy animated eyes | No diff vs main — already merged | Deleted |
| `claude/issue-11` | Kimi + Perplexity agents | No diff vs main — already merged | Deleted |
| `claude/issue-13` | Nostr event publishing | No diff vs main — already merged | Deleted |
| `claude/issue-29` | Mobile Nostr identity | No diff vs main — already merged | Deleted |
| `claude/issue-45` | Test kit | No diff vs main — already merged | Deleted |
| `claude/issue-47` | SQL migration helpers | No diff vs main — already merged | Deleted |
| `claude/issue-67` | Session Mode UI | No diff vs main — already merged | Deleted |
All 7 branches besides `gemini/issue-14` had empty `git diff origin/main...origin/<branch>`
output, confirming their work had been squash-merged into main previously.
### Stale merged branches deleted (37 branches)
Confirmed via `git diff origin/main...origin/<branch>` (empty diff):
**gemini branches:** issue-16, issue-34, issue-40, issue-42, issue-46, issue-48,
issue-50, issue-52, issue-56, issue-58, issue-64, issue-70
**claude branches:** issue-1, issue-3, issue-7, issue-9, issue-11, issue-13, issue-15,
issue-17, issue-21, issue-25, issue-27, issue-29, issue-31, issue-33, issue-35, issue-36,
issue-39, issue-41, issue-43, issue-45, issue-47, issue-49, issue-51, issue-53, issue-55,
issue-57, issue-59, issue-61, issue-63, issue-65, issue-67, issue-68
### Remaining branches after cleanup
| Branch | Status |
|--------|--------|
| `main` | Trunk |
| `claude/issue-5` | Open PR #93 |
| `claude/issue-37` | Open PR #80 |
| `gemini/issue-14` | New PR #104 (NIP-07 Nostr identity) |
| `claude/issue-103` | This audit branch |

View File

@@ -37,25 +37,6 @@
font-size: 13px; letter-spacing: 3px; margin-bottom: 4px;
color: #7799cc; text-shadow: 0 0 10px #4466aa;
}
/* Nostr Identity UI */
.nostr-btn {
background: rgba(40, 30, 70, 0.9);
border: 1px solid #443377;
color: #aaddff; font-family: 'Courier New', monospace;
font-size: 11px; padding: 4px 10px; cursor: pointer;
border-radius: 3px; transition: background 0.15s, border-color 0.15s;
}
.nostr-btn:hover { background: rgba(60, 45, 100, 0.9); border-color: #665599; }
.nostr-btn-sm {
font-size: 9px; padding: 2px 6px; margin-left: 6px; opacity: 0.7;
}
.nostr-btn-sm:hover { opacity: 1; }
.nostr-pubkey {
font-size: 11px; color: #aaddff; margin-right: 6px;
letter-spacing: 0.5px;
}
#session-hud {
display: none;
color: #22aa66;
@@ -533,175 +514,6 @@
}
#timmy-id-card .id-npub:hover { color: #88aadd; }
#timmy-id-card .id-zaps { color: #556688; font-size: 9px; }
/* ── Activity heatmap (#9) ────────────────────────────────────────── */
#activity-heatmap {
position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%);
z-index: 10; pointer-events: all;
}
#heatmap-bar {
display: flex; gap: 2px; align-items: flex-end;
}
.hm-seg {
width: 10px; height: 18px; border-radius: 1px;
background: #111122;
cursor: pointer;
transition: transform 0.1s;
flex-shrink: 0;
}
.hm-seg:hover { transform: scaleY(1.3); }
@keyframes hm-pulse {
0%, 100% { opacity: 1; box-shadow: 0 0 4px currentColor; }
50% { opacity: 0.5; box-shadow: none; }
}
.hm-seg-current { animation: hm-pulse 2s ease-in-out infinite; }
#heatmap-icon-btn {
display: none;
background: rgba(20, 16, 36, 0.88);
border: 1px solid #2a2a44;
color: #5588bb;
font-family: 'Courier New', monospace;
font-size: 16px; padding: 6px 10px;
cursor: pointer; border-radius: 3px;
}
#heatmap-tooltip {
position: fixed; display: none;
background: rgba(5,3,12,0.92); border: 1px solid #2a2a44;
color: #aabbdd; font-family: 'Courier New', monospace;
font-size: 10px; padding: 3px 8px; border-radius: 2px;
pointer-events: none; z-index: 50;
white-space: nowrap;
}
/* Mobile overlay */
#heatmap-overlay {
display: none; position: fixed; inset: 0;
background: rgba(5,3,12,0.97); z-index: 100;
flex-direction: column; align-items: center; justify-content: center;
gap: 16px;
}
#heatmap-overlay.open { display: flex; }
#heatmap-overlay-title {
color: #7799cc; font-family: 'Courier New', monospace;
font-size: 12px; letter-spacing: 3px;
}
#heatmap-overlay-bar {
display: flex; gap: 4px; align-items: flex-end; flex-wrap: wrap;
justify-content: center; max-width: 90vw;
}
#heatmap-overlay-bar .hm-seg { width: 14px; height: 28px; }
#heatmap-overlay-close {
background: transparent; border: 1px solid #2a2a44;
color: #5588bb; font-family: 'Courier New', monospace;
font-size: 11px; padding: 6px 16px; cursor: pointer;
letter-spacing: 1px; border-radius: 2px;
}
@media (max-width: 600px) {
#activity-heatmap #heatmap-bar { display: none; }
#heatmap-icon-btn { display: block; }
}
/* ── History button ──────────────────────────────────────────────── */
#open-history-btn {
font-family: 'Courier New', monospace; font-size: 11px; font-weight: bold;
color: #aabbdd; background: rgba(20, 16, 50, 0.85); border: 1px solid #2a2a44;
padding: 7px 18px; cursor: pointer; letter-spacing: 2px;
box-shadow: 0 0 14px #2244aa22;
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
border-radius: 2px;
min-height: 36px;
}
#open-history-btn:hover, #open-history-btn:active {
background: rgba(35, 28, 80, 0.95);
box-shadow: 0 0 20px #3355aa44;
color: #ccddff;
}
/* ── History panel (bottom sheet) ───────────────────────────────── */
#history-panel {
position: fixed; bottom: -100%; left: 0; right: 0;
height: 70vh;
background: rgba(5, 3, 12, 0.97);
border-top: 1px solid #1a1a2e;
z-index: 100;
font-family: 'Courier New', monospace;
transition: bottom 0.35s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 -8px 32px rgba(40, 60, 120, 0.18);
display: flex; flex-direction: column;
}
#history-panel.open { bottom: 60px; }
.hist-header {
display: flex; align-items: center; gap: 8px;
padding: 14px 20px 10px;
border-bottom: 1px solid #1a1a2e;
font-size: 12px; letter-spacing: 3px; color: #5577aa;
flex-shrink: 0;
}
.hist-header span { flex: 1; text-shadow: 0 0 8px #2244aa66; }
#history-refresh-btn, #history-close {
background: transparent; border: 1px solid #1a1a2e;
color: #334466; font-family: 'Courier New', monospace;
font-size: 11px; padding: 3px 10px; cursor: pointer;
transition: color 0.2s, border-color 0.2s; letter-spacing: 1px;
border-radius: 2px;
}
#history-refresh-btn:hover { color: #5577aa; border-color: #334466; }
#history-refresh-btn:disabled { opacity: 0.4; cursor: default; }
#history-close { font-size: 14px; padding: 3px 8px; }
#history-close:hover { color: #6688bb; border-color: #4466aa; }
#history-list {
flex: 1; overflow-y: auto; padding: 12px 16px;
overscroll-behavior: contain;
}
.hist-empty {
color: #334466; font-size: 11px; letter-spacing: 1px;
line-height: 1.8; text-align: center;
margin-top: 40px; padding: 0 20px;
}
.hist-row {
border: 1px solid #1a1a2e; border-radius: 2px;
margin-bottom: 10px; overflow: hidden;
background: #060310;
}
.hist-row.hist-rejected { border-color: #331111; }
.hist-row-header {
padding: 10px 12px; cursor: pointer;
transition: background 0.15s;
}
.hist-row-header:hover { background: rgba(30, 25, 60, 0.6); }
.hist-prompt {
color: #aabbdd; font-size: 12px; line-height: 1.5;
display: -webkit-box; -webkit-line-clamp: 2;
-webkit-box-orient: vertical; overflow: hidden;
margin-bottom: 6px;
}
.hist-meta {
display: flex; gap: 12px; align-items: center;
}
.hist-cost { font-size: 10px; color: #ffcc44; letter-spacing: 1px; }
.hist-rejected .hist-cost { color: #994444; }
.hist-time { font-size: 10px; color: #334466; letter-spacing: 0.5px; flex: 1; }
.hist-chevron { font-size: 10px; color: #334466; transition: color 0.15s; }
.hist-row-header:hover .hist-chevron { color: #5577aa; }
.hist-row-body {
max-height: 0; overflow: hidden;
transition: max-height 0.3s ease-out;
}
.hist-row.expanded .hist-row-body {
max-height: 400px;
border-top: 1px solid #1a1a2e;
}
.hist-result {
color: #aabbdd; font-family: 'Courier New', monospace;
font-size: 11px; line-height: 1.6;
white-space: pre-wrap; word-break: break-word;
padding: 12px; margin: 0;
max-height: 400px; overflow-y: auto;
}
</style>
</head>
<body>
@@ -713,25 +525,11 @@
<span id="session-hud-balance">Balance: -- sats</span>
<a href="#" id="session-hud-topup">⚡ Top Up</a>
</div>
<!-- New: Nostr identity status -->
<div id="nostr-identity-status" style="margin-top: 10px; pointer-events: all;"></div>
</div>
<div id="connection-status">OFFLINE</div>
<div id="event-log"></div>
<!-- ── Activity heatmap (#9) ──────────────────────────────────────── -->
<div id="activity-heatmap">
<div id="heatmap-bar"></div>
<button id="heatmap-icon-btn" title="Show activity heatmap"></button>
</div>
<div id="heatmap-tooltip"></div>
<div id="heatmap-overlay">
<div id="heatmap-overlay-title">24H ACTIVITY</div>
<div id="heatmap-overlay-bar"></div>
<button id="heatmap-overlay-close">CLOSE</button>
</div>
<!-- ── Timmy identity card ────────────────────────────────────────── -->
<div id="timmy-id-card">
<div class="id-label">TIMMY IDENTITY</div>
@@ -743,7 +541,6 @@
<div id="top-buttons">
<button id="open-panel-btn">⚡ SUBMIT JOB</button>
<button id="open-session-btn">⚡ FUND SESSION</button>
<button id="open-history-btn">⏱ HISTORY</button>
<a id="relay-admin-btn" href="/admin/relay">⚙ RELAY ADMIN</a>
</div>
@@ -893,16 +690,6 @@
<div id="session-error"></div>
</div>
<!-- ── History panel (bottom sheet) ─────────────────────────────── -->
<div id="history-panel">
<div class="hist-header">
<span>⏱ JOB HISTORY</span>
<button id="history-refresh-btn">↺ REFRESH</button>
<button id="history-close"></button>
</div>
<div id="history-list"></div>
</div>
<!-- ── FPS crosshair ─────────────────────────────────────────────── -->
<div id="crosshair"></div>

View File

@@ -5,27 +5,18 @@
* unused (x, z) position. No other file needs to be edited.
*
* Fields:
* id — unique string key used in WebSocket messages and state maps
* label — display name shown in the 3D HUD and chat panel
* color — hex integer (0xRRGGBB) used for Three.js materials and lights
* role — human-readable role string shown under the label sprite
* specialization — optional capability description shown in agent inspect card
* direction — cardinal facing direction (for future mesh orientation use)
* x, z — world-space position on the horizontal plane (y is always 0)
* id — unique string key used in WebSocket messages and state maps
* label — display name shown in the 3D HUD and chat panel
* color — hex integer (0xRRGGBB) used for Three.js materials and lights
* role — human-readable role string shown under the label sprite
* direction — cardinal facing direction (for future mesh orientation use)
* x, z — world-space position on the horizontal plane (y is always 0)
*/
export const AGENT_DEFS = [
{ id: 'alpha', label: 'ALPHA', color: 0x00ff88, role: 'orchestrator', direction: 'north', x: 0, z: -6 },
{ id: 'beta', label: 'BETA', color: 0x00aaff, role: 'worker', direction: 'east', x: 6, z: 0 },
{ id: 'gamma', label: 'GAMMA', color: 0xff6600, role: 'validator', direction: 'south', x: 0, z: 6 },
{ id: 'delta', label: 'DELTA', color: 0xaa00ff, role: 'monitor', direction: 'west', x: -6, z: 0 },
{
id: 'kimi', label: 'KIMI', color: 0x00d4ff, role: 'analyst',
specialization: 'Long Context Analysis', direction: 'northwest', x: -10, z: -10,
},
{
id: 'perplexity', label: 'PERPLEXITY', color: 0xff6b9d, role: 'researcher',
specialization: 'Real-time Research', direction: 'northeast', x: 10, z: -10,
},
];
/**

View File

@@ -7,13 +7,10 @@ const CRYSTAL_POS = new THREE.Vector3(0.6, 1.15, -4.1);
const agentStates = Object.fromEntries(AGENT_DEFS.map(d => [d.id, 'idle']));
// Workshop agents that drive Timmy's mood (excludes external agents Kimi/Perplexity)
const WORKSHOP_AGENT_IDS = ['alpha', 'beta', 'gamma', 'delta'];
function deriveTimmyState() {
if (agentStates.gamma === 'working') return 'working';
if (agentStates.beta === 'thinking' || agentStates.alpha === 'thinking') return 'thinking';
if (WORKSHOP_AGENT_IDS.some(id => agentStates[id] !== 'idle')) return 'active';
if (Object.values(agentStates).some(s => s !== 'idle')) return 'active';
return 'idle';
}
@@ -100,108 +97,9 @@ function _pickMouthGeo(smileAmount) {
// ── Build Timmy ───────────────────────────────────────────────────────────────
// ── External agent bodies (Kimi, Perplexity) ──────────────────────────────────
const _extBodies = {};
export function initAgents(sceneRef) {
scene = sceneRef;
timmy = buildTimmy(scene);
_initKimiBody(scene);
_initPerplexityBody(scene);
}
function _initKimiBody(sc) {
const group = new THREE.Group();
group.position.set(-10, 1.2, -10);
const mat = new THREE.MeshStandardMaterial({
color: 0x00d4ff, emissive: 0x004466, emissiveIntensity: 0.4,
roughness: 0.15, metalness: 0.4,
});
const core = new THREE.Mesh(new THREE.OctahedronGeometry(0.38, 0), mat);
group.add(core);
const ringMat = new THREE.MeshStandardMaterial({
color: 0x00d4ff, emissive: 0x0088aa, emissiveIntensity: 0.6,
roughness: 0.1, metalness: 0.6, transparent: true, opacity: 0.7,
});
const ring1 = new THREE.Mesh(new THREE.TorusGeometry(0.60, 0.025, 6, 32), ringMat);
ring1.rotation.x = Math.PI / 3;
group.add(ring1);
const ring2 = new THREE.Mesh(new THREE.TorusGeometry(0.76, 0.018, 6, 32), ringMat.clone());
ring2.rotation.x = Math.PI / 2;
ring2.rotation.z = Math.PI / 4;
group.add(ring2);
const light = new THREE.PointLight(0x00d4ff, 0.5, 8);
group.add(light);
sc.add(group);
_extBodies.kimi = { group, core, ring1, ring2, light, mat, pulsePhase: Math.random() * Math.PI * 2 };
}
function _initPerplexityBody(sc) {
const group = new THREE.Group();
group.position.set(10, 1.2, -10);
const mat = new THREE.MeshStandardMaterial({
color: 0xff6b9d, emissive: 0x660033, emissiveIntensity: 0.4,
roughness: 0.2, metalness: 0.3,
});
const core = new THREE.Mesh(new THREE.IcosahedronGeometry(0.32, 0), mat);
group.add(core);
const scanMat = new THREE.MeshStandardMaterial({
color: 0xff6b9d, emissive: 0xaa2255, emissiveIntensity: 0.7,
roughness: 0.1, metalness: 0.5, transparent: true, opacity: 0.65,
});
const scanRings = [0, Math.PI / 3, -Math.PI / 3].map(angle => {
const r = new THREE.Mesh(new THREE.TorusGeometry(0.55, 0.022, 6, 28), scanMat.clone());
r.rotation.x = Math.PI / 2 + angle;
r.rotation.z = angle * 0.5;
group.add(r);
return r;
});
const light = new THREE.PointLight(0xff6b9d, 0.5, 8);
group.add(light);
sc.add(group);
_extBodies.perplexity = { group, core, scanRings, light, mat, pulsePhase: Math.random() * Math.PI * 2 };
}
function _updateExtBodies(t) {
_updateExtBody('kimi', t);
_updateExtBody('perplexity', t);
}
function _updateExtBody(id, t) {
const body = _extBodies[id];
if (!body) return;
const state = agentStates[id] || 'idle';
const isActive = state === 'working' || state === 'active';
const isThinking = state === 'thinking';
const speedMult = isActive ? 2.5 : isThinking ? 1.5 : 0.6;
const emissI = isActive ? 1.2 : isThinking ? 0.7 : 0.25;
const lightI = isActive ? 1.2 : isThinking ? 0.6 : 0.2;
const bobAmp = isActive ? 0.10 : 0.04;
body.group.position.y = 1.2 + Math.sin(t * 0.0008 + body.pulsePhase) * bobAmp;
body.mat.emissiveIntensity = emissI;
body.light.intensity = lightI;
if (id === 'kimi') {
body.core.rotation.y += 0.008 * speedMult;
body.core.rotation.x += 0.003 * speedMult;
body.ring1.rotation.z += 0.012 * speedMult;
body.ring2.rotation.x += 0.007 * speedMult;
} else {
body.core.rotation.y += 0.006 * speedMult;
body.core.rotation.z += 0.009 * speedMult;
body.scanRings.forEach((r, i) => { r.rotation.y += (0.015 + i * 0.008) * speedMult; });
}
}
function buildTimmy(sc) {
@@ -519,7 +417,6 @@ export function updateAgents(time) {
const t = time * 0.001;
const dt = _lastFrameTime > 0 ? Math.min((time - _lastFrameTime) * 0.001, 0.05) : 0.016;
_lastFrameTime = time;
_updateExtBodies(time);
const vs = deriveTimmyState();
const pulse = Math.sin(t * 1.8 + timmy.pulsePhase);
@@ -992,19 +889,5 @@ export function disposeAgents() {
timmy.bubbleTex?.dispose();
timmy.bubbleMat?.dispose();
timmy = null;
// Dispose external agent bodies
for (const body of Object.values(_extBodies)) {
body.group.traverse(obj => {
if (obj.geometry) obj.geometry.dispose();
if (obj.material) {
const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
mats.forEach(m => m.dispose());
}
});
if (scene) scene.remove(body.group);
}
for (const k of Object.keys(_extBodies)) delete _extBodies[k];
scene = null;
}

View File

@@ -5,196 +5,10 @@ let dustPositions = null;
let dustVelocities = null;
const DUST_COUNT = 600;
// Job Indicators
const _activeJobIndicators = new Map();
const INDICATOR_Y_OFFSET = 3.5; // Height above Timmy
const INDICATOR_X_OFFSET = 1.0; // Offset from Timmy's center for multiple jobs
const JOB_INDICATOR_DEFS = {
writing: {
create: () => {
// Quill (cone for feather, cylinder for handle)
const quillGroup = new THREE.Group();
const featherGeo = new THREE.ConeGeometry(0.15, 0.6, 4);
const featherMat = new THREE.MeshStandardMaterial({ color: 0xc8c4bc, roughness: 0.8 });
const feather = new THREE.Mesh(featherGeo, featherMat);
feather.position.y = 0.3;
feather.rotation.x = Math.PI / 8;
quillGroup.add(feather);
const handleGeo = new THREE.CylinderGeometry(0.04, 0.04, 0.4, 8);
const handleMat = new THREE.MeshStandardMaterial({ color: 0x3d2506, roughness: 0.7 });
const handle = new THREE.Mesh(handleGeo, handleMat);
handle.position.y = -0.2;
quillGroup.add(handle);
return quillGroup;
},
color: 0xe8d5a0, // parchment-like
},
coding: {
create: () => {
// Brackets (simple box geometry)
const bracketsGroup = new THREE.Group();
const bracketMat = new THREE.MeshStandardMaterial({ color: 0x5599dd, emissive: 0x224466, emissiveIntensity: 0.3, roughness: 0.4 });
const bracketGeo = new THREE.BoxGeometry(0.05, 0.3, 0.05);
const br1 = new THREE.Mesh(bracketGeo, bracketMat);
br1.position.set(-0.1, 0.0, 0);
bracketsGroup.add(br1);
const br2 = br1.clone();
br2.position.set(0.1, 0.0, 0);
bracketsGroup.add(br2);
const crossbarGeo = new THREE.BoxGeometry(0.25, 0.05, 0.05);
const crossbar1 = new THREE.Mesh(crossbarGeo, bracketMat);
crossbar1.position.set(0, 0.125, 0);
bracketsGroup.add(crossbar1);
const crossbar2 = crossbar1.clone();
crossbar2.position.set(0, -0.125, 0);
bracketsGroup.add(crossbar2);
return bracketsGroup;
},
color: 0x5599dd, // code-editor blue
},
research: {
create: () => {
// Spider (simple sphere body, cylinder legs) - very simplified
const spiderGroup = new THREE.Group();
const bodyMat = new THREE.MeshStandardMaterial({ color: 0x444444, roughness: 0.9 });
const body = new THREE.Mesh(new THREE.SphereGeometry(0.15, 8, 8), bodyMat);
spiderGroup.add(body);
const legMat = new THREE.MeshStandardMaterial({ color: 0x222222, roughness: 0.9 });
const legGeo = new THREE.CylinderGeometry(0.015, 0.015, 0.4, 4);
const legPositions = [
[0.18, 0.0, 0.08, Math.PI / 4], [-0.18, 0.0, 0.08, -Math.PI / 4],
[0.22, 0.0, -0.05, Math.PI / 2], [-0.22, 0.0, -0.05, -Math.PI / 2],
[0.18, 0.0, -0.18, 3 * Math.PI / 4], [-0.18, 0.0, -0.18, -3 * Math.PI / 4],
];
legPositions.forEach(([x, y, z, rotY]) => {
const leg = new THREE.Mesh(legGeo, legMat);
leg.position.set(x, y - 0.1, z);
leg.rotation.z = Math.PI / 2;
leg.rotation.y = rotY;
spiderGroup.add(leg);
});
return spiderGroup;
},
color: 0x8b0000, // dark red, investigative
},
creative: {
create: () => {
// Lightbulb (sphere with small cylinder base)
const bulbGroup = new THREE.Group();
const bulbMat = new THREE.MeshStandardMaterial({ color: 0xffddaa, emissive: 0xffaa00, emissiveIntensity: 0.8, transparent: true, opacity: 0.9, roughness: 0.1 });
const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.2, 16, 12), bulbMat);
bulbGroup.add(bulb);
const baseMat = new THREE.MeshStandardMaterial({ color: 0x888888, roughness: 0.6 });
const base = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.1, 0.15, 8), baseMat);
base.position.y = -0.25;
bulbGroup.add(base);
return bulbGroup;
},
color: 0xffaa00, // bright idea yellow
},
analysis: {
create: () => {
// Magnifying glass (torus for rim, plane for lens)
const magGroup = new THREE.Group();
const rimMat = new THREE.MeshStandardMaterial({ color: 0xbb9900, roughness: 0.4, metalness: 0.7 });
const rim = new THREE.Mesh(new THREE.TorusGeometry(0.2, 0.03, 8, 20), rimMat);
magGroup.add(rim);
const handleMat = new THREE.MeshStandardMaterial({ color: 0x3d2506, roughness: 0.7 });
const handle = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.03, 0.4, 6), handleMat);
handle.position.set(0.25, -0.25, 0);
handle.rotation.z = Math.PI / 4;
magGroup.add(handle);
const lensMat = new THREE.MeshPhysicalMaterial({ color: 0xaaffff, transmission: 0.8, roughness: 0.1, transparent: true });
const lens = new THREE.Mesh(new THREE.CircleGeometry(0.17, 16), lensMat);
// Lens is a plane, so it will be rotated to face the camera or just set its position
// For simplicity, make it a thin cylinder or sphere segment to give it depth
const lensGeo = new THREE.CylinderGeometry(0.17, 0.17, 0.02, 16);
const thinLens = new THREE.Mesh(lensGeo, lensMat);
magGroup.add(thinLens);
return magGroup;
},
color: 0x88ddff, // clear blue, analytic
},
other: { // Generic glowing orb
create: () => {
const orbMat = new THREE.MeshStandardMaterial({ color: 0x800080, emissive: 0x550055, emissiveIntensity: 0.8, roughness: 0.2 });
return new THREE.Mesh(new THREE.SphereGeometry(0.2, 16, 16), orbMat);
},
color: 0x800080, // purple
},
};
export function initEffects(scene) {
initDustMotes(scene);
}
// Map to hold job indicator objects by jobId
const jobIndicators = new Map();
export function createJobIndicator(category, jobId, position) {
const def = JOB_INDICATOR_DEFS[category] || JOB_INDICATOR_DEFS.other;
const indicatorGroup = new THREE.Group();
indicatorGroup.userData.jobId = jobId;
indicatorGroup.userData.category = category;
const object = def.create();
object.scale.setScalar(0.7); // Make indicators a bit smaller
indicatorGroup.add(object);
// Add a subtle glowing point light to the indicator
const pointLight = new THREE.PointLight(def.color, 0.8, 3);
indicatorGroup.add(pointLight);
indicatorGroup.position.copy(position);
jobIndicators.set(jobId, indicatorGroup);
return indicatorGroup;
}
export function updateJobIndicators(time) {
const t = time * 0.001;
jobIndicators.forEach(indicator => {
// Simple bobbing motion
indicator.position.y += Math.sin(t * 2.5 + indicator.userData.jobId.charCodeAt(0)) * 0.002;
// Rotation
indicator.rotation.y += 0.01;
});
}
export function dissolveJobIndicator(jobId, scene) {
const indicator = jobIndicators.get(jobId);
if (indicator) {
// TODO: Implement particle dissolve effect here
// For now, just remove and dispose
scene.remove(indicator);
if (indicator.children.length > 0) {
const object = indicator.children[0];
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) object.material.forEach(m => m.dispose());
else object.material.dispose();
}
}
indicator.children.forEach(child => {
if (child.isLight) child.dispose();
});
jobIndicators.delete(jobId);
}
}
function initDustMotes(scene) {
const geo = new THREE.BufferGeometry();
const positions = new Float32Array(DUST_COUNT * 3);
@@ -262,18 +76,4 @@ export function disposeEffects() {
}
dustPositions = null;
dustVelocities = null;
jobIndicators.forEach(indicator => {
if (indicator.children.length > 0) {
const object = indicator.children[0];
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) object.material.forEach(m => m.dispose());
else object.material.dispose();
}
}
indicator.children.forEach(child => {
if (child.isLight) child.dispose();
});
});
jobIndicators.clear();
}
}

View File

@@ -1,222 +0,0 @@
/**
* history.js — Job history panel for Timmy Tower Workshop.
*
* Persists completed jobs in localStorage and renders them in a
* bottom-sheet panel with expandable results and pull-to-refresh.
*
* Public API:
* addHistoryEntry(entry) — called by payment.js / session.js on completion
* initHistoryPanel() — wire up DOM (call once from main.js)
*/
const LS_KEY = 'timmy_history_v1';
const MAX_ENTRIES = 50;
// ── Persistence ───────────────────────────────────────────────────────────────
function _loadEntries() {
try {
const raw = localStorage.getItem(LS_KEY);
return raw ? JSON.parse(raw) : [];
} catch {
return [];
}
}
function _saveEntries(entries) {
try {
localStorage.setItem(LS_KEY, JSON.stringify(entries));
} catch { /* storage full — oldest already trimmed */ }
}
/**
* Record a completed job.
* @param {object} entry
* @param {string} entry.jobId
* @param {string} entry.request — user prompt
* @param {number} entry.costSats — sats charged (0 for free/session)
* @param {string} entry.result — AI answer or rejection reason
* @param {string} entry.state — 'complete' | 'rejected' | 'failed'
* @param {string} [entry.completedAt] — ISO timestamp (defaults to now)
*/
export function addHistoryEntry({ jobId, request, costSats, result, state, completedAt }) {
const entries = _loadEntries();
const entry = {
jobId: jobId ?? `local-${Date.now()}`,
request: request ?? '',
costSats: costSats ?? 0,
result: result ?? '',
state: state ?? 'complete',
completedAt: completedAt ?? new Date().toISOString(),
};
const idx = entries.findIndex(e => e.jobId === entry.jobId);
if (idx >= 0) {
entries[idx] = entry;
} else {
entries.unshift(entry); // newest first
if (entries.length > MAX_ENTRIES) entries.length = MAX_ENTRIES;
}
_saveEntries(entries);
}
// ── Helpers ───────────────────────────────────────────────────────────────────
function _relativeTime(isoString) {
try {
const diff = Date.now() - new Date(isoString).getTime();
const secs = Math.floor(diff / 1000);
if (secs < 60) return `${secs}s ago`;
const mins = Math.floor(secs / 60);
if (mins < 60) return `${mins} min ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
return `${days}d ago`;
} catch {
return '';
}
}
function _escHtml(text) {
return String(text)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
function _truncate(text, maxLen) {
if (!text) return '';
return text.length > maxLen ? text.slice(0, maxLen) + '…' : text;
}
// ── Rendering ─────────────────────────────────────────────────────────────────
function _renderEntries(entries, container) {
container.innerHTML = '';
if (!entries.length) {
const empty = document.createElement('div');
empty.className = 'hist-empty';
empty.textContent = 'No completed jobs yet. Submit a job to see your history here.';
container.appendChild(empty);
return;
}
entries.forEach(entry => {
const row = document.createElement('div');
row.className = 'hist-row' + (entry.state === 'rejected' ? ' hist-rejected' : '');
// ── Header (always visible) ────────────────────────────────────────────
const header = document.createElement('div');
header.className = 'hist-row-header';
const promptEl = document.createElement('div');
promptEl.className = 'hist-prompt';
promptEl.textContent = _truncate(entry.request, 140);
const metaEl = document.createElement('div');
metaEl.className = 'hist-meta';
const costEl = document.createElement('span');
costEl.className = 'hist-cost';
if (entry.state === 'rejected') {
costEl.textContent = 'rejected';
} else if (entry.costSats > 0) {
costEl.textContent = `${entry.costSats} sats`;
} else {
costEl.textContent = 'free';
}
const timeEl = document.createElement('span');
timeEl.className = 'hist-time';
timeEl.textContent = _relativeTime(entry.completedAt);
const chevronEl = document.createElement('span');
chevronEl.className = 'hist-chevron';
chevronEl.textContent = '▸';
metaEl.appendChild(costEl);
metaEl.appendChild(timeEl);
metaEl.appendChild(chevronEl);
header.appendChild(promptEl);
header.appendChild(metaEl);
// ── Body (expandable) ──────────────────────────────────────────────────
const body = document.createElement('div');
body.className = 'hist-row-body';
const pre = document.createElement('pre');
pre.className = 'hist-result';
pre.textContent = entry.result || '(no result)';
body.appendChild(pre);
// ── Toggle ─────────────────────────────────────────────────────────────
let expanded = false;
header.addEventListener('click', () => {
expanded = !expanded;
row.classList.toggle('expanded', expanded);
chevronEl.textContent = expanded ? '▾' : '▸';
});
row.appendChild(header);
row.appendChild(body);
container.appendChild(row);
});
}
// ── Panel state ───────────────────────────────────────────────────────────────
let _panel = null;
let _list = null;
let _refreshBtn = null;
function _open() {
if (!_panel) return;
_panel.classList.add('open');
_refresh();
}
function _close() {
_panel?.classList.remove('open');
}
function _refresh() {
if (!_list) return;
const entries = _loadEntries();
_renderEntries(entries, _list);
if (_refreshBtn) {
_refreshBtn.textContent = '↺ REFRESH';
_refreshBtn.disabled = false;
}
}
export function initHistoryPanel() {
_panel = document.getElementById('history-panel');
_list = document.getElementById('history-list');
_refreshBtn = document.getElementById('history-refresh-btn');
if (!_panel) return;
document.getElementById('open-history-btn')?.addEventListener('click', _open);
document.getElementById('history-close')?.addEventListener('click', _close);
if (_refreshBtn) {
_refreshBtn.addEventListener('click', () => {
_refreshBtn.textContent = '↺ …';
_refreshBtn.disabled = true;
setTimeout(_refresh, 150);
});
}
// Pull-to-refresh: detect downward drag when already scrolled to top
let _touchStartY = 0;
_list?.addEventListener('touchstart', e => {
_touchStartY = e.touches[0].clientY;
}, { passive: true });
_list?.addEventListener('touchend', e => {
const dy = e.changedTouches[0].clientY - _touchStartY;
if (dy > 60 && _list.scrollTop === 0) {
_refresh();
}
}, { passive: true });
}

View File

@@ -12,12 +12,7 @@
*/
import * as THREE from 'three';
import { colorToCss, AGENT_DEFS } from './agent-defs.js';
// Specialization lookup built once from AGENT_DEFS
const _specializations = Object.fromEntries(
AGENT_DEFS.filter(d => d.specialization).map(d => [d.id, d.specialization])
);
import { colorToCss } from './agent-defs.js';
const _proj = new THREE.Vector3();
let _camera = null;
@@ -25,7 +20,6 @@ let _labels = []; // { el, worldPos: THREE.Vector3, id }
// ── State cache (updated from WS) ────────────────────────────────────────────
const _states = {};
const _lastTasks = {};
// ── Inspect popup ─────────────────────────────────────────────────────────────
let _inspectEl = null;
@@ -106,10 +100,6 @@ function _makeLabel(container, id, name, role, color, worldPos) {
return { el, worldPos, id, color };
}
export function setLabelLastTask(id, summary) {
_lastTasks[id] = summary;
}
export function setLabelState(id, state) {
_states[id] = state;
const entry = _labels.find(l => l.id === id);
@@ -128,17 +118,13 @@ export function showInspectPopup(id, screenX, screenY) {
const state = _states[id] || 'idle';
const uptime = Math.floor(performance.now() / 1000);
const spec = _specializations[id];
const lastTask = _lastTasks[id];
_inspectEl.innerHTML = `
<div style="color:${entry.color};font-weight:bold;letter-spacing:2px;font-size:12px;margin-bottom:6px;">
${id.toUpperCase()}
</div>
${spec ? `<div style="color:${entry.color}99;margin-bottom:4px;font-size:10px;letter-spacing:1px;">⬡ ${spec}</div>` : ''}
<div style="color:#aaa;margin-bottom:2px;">state&nbsp;&nbsp;: <span style="color:${entry.color}">${state}</span></div>
<div style="color:#aaa;margin-bottom:2px;">uptime : ${uptime}s</div>
<div style="color:#aaa;margin-bottom:2px;">network: <span style="color:#44ff88">connected</span></div>
${lastTask ? `<div style="color:#888;font-size:9px;margin-top:4px;border-top:1px solid #333;padding-top:4px;">last: ${lastTask.slice(0, 60)}</div>` : ''}
<div style="color:#aaa;">network: <span style="color:#44ff88">connected</span></div>
`;
_inspectEl.style.left = `${screenX}px`;
_inspectEl.style.top = `${screenY}px`;

View File

@@ -5,13 +5,12 @@ import {
getTimmyGroup, applySlap, getCameraShakeStrength,
TIMMY_WORLD_POS,
} from './agents.js';
import { initEffects, updateEffects, disposeEffects, updateJobIndicators } from './effects.js';
import { initEffects, updateEffects, disposeEffects } from './effects.js';
import { initUI, updateUI } from './ui.js';
import { initInteraction, disposeInteraction, registerSlapTarget } from './interaction.js';
import { initWebSocket, getConnectionState, getJobCount } from './websocket.js';
import { initPaymentPanel } from './payment.js';
import { initSessionPanel } from './session.js';
import { initHistoryPanel } from './history.js';
import { initNostrIdentity } from './nostr-identity.js';
import { warmup as warmupEdgeWorker, onReady as onEdgeWorkerReady } from './edge-worker-client.js';
import { setEdgeWorkerReady } from './ui.js';
@@ -47,7 +46,6 @@ function buildWorld(firstInit, stateSnapshot) {
initWebSocket(scene);
initPaymentPanel();
initSessionPanel();
initHistoryPanel();
void initNostrIdentity('/api');
warmupEdgeWorker();
onEdgeWorkerReady(() => setEdgeWorkerReady());
@@ -83,7 +81,6 @@ function buildWorld(firstInit, stateSnapshot) {
updateEffects(now);
updateAgents(now);
updateJobIndicators(now);
updateUI({
fps: currentFps,
agentCount: getAgentCount(),

View File

@@ -42,7 +42,6 @@ export async function initNostrIdentity(apiBase = '/api') {
_pubkey = await window.nostr.getPublicKey();
_useNip07 = true;
_canSign = true;
_saveDiscoveredKeypair(_pubkey, null); // Store pubkey in LS even if NIP-07
console.info('[nostr] Using NIP-07 extension, pubkey:', _pubkey.slice(0, 8) + '…');
} catch (err) {
console.warn('[nostr] NIP-07 getPublicKey failed, will use local keypair', err);
@@ -87,18 +86,6 @@ export function getPubkey() { return _pubkey; }
export function getNostrToken() { return _isTokenValid() ? _token : null; }
export function hasIdentity() { return !!_pubkey; }
export function disconnectNostrIdentity() {
_pubkey = null;
_token = null;
_tokenExp = 0;
_useNip07 = false;
_canSign = false;
localStorage.removeItem(LS_KEYPAIR_KEY);
localStorage.removeItem(LS_TOKEN_KEY);
window.dispatchEvent(new CustomEvent('nostr:identity-disconnected'));
console.info('[nostr] identity disconnected');
}
/**
* getOrRefreshToken — returns a valid token, refreshing if necessary.
* Returns null if no identity is established.
@@ -210,7 +197,6 @@ export function showIdentityPrompt(apiBase = '/api') {
_pubkey = await window.nostr.getPublicKey();
_useNip07 = true;
_canSign = true;
_saveDiscoveredKeypair(_pubkey, null); // Store pubkey in LS even if NIP-07
} catch { return; }
} else {
// Generate + store keypair (user consented by clicking)

View File

@@ -10,7 +10,6 @@
*/
import { getOrRefreshToken } from './nostr-identity.js';
import { addHistoryEntry } from './history.js';
const API_BASE = '/api';
const POLL_INTERVAL_MS = 2000;
@@ -19,7 +18,6 @@ const POLL_TIMEOUT_MS = 60000;
let panel = null;
let closeBtn = null;
let currentJobId = null;
let currentRequest = '';
let pollTimer = null;
export function initPaymentPanel() {
@@ -98,7 +96,6 @@ async function submitJob() {
if (!res.ok) { setError(data.error || 'Failed to create job.'); return; }
currentJobId = data.jobId;
currentRequest = request;
showEvalInvoice(data.evalInvoice);
} catch (err) {
setError('Network error: ' + err.message);
@@ -170,7 +167,7 @@ function startPolling() {
const pollHeaders = token ? { 'X-Nostr-Token': token } : {};
const res = await fetch(`${API_BASE}/jobs/${currentJobId}`, { headers: pollHeaders });
const data = await res.json();
const { state, workInvoice, result, reason, costLedger, completedAt } = data;
const { state, workInvoice, result, reason } = data;
if (state === 'awaiting_work_payment' && workInvoice) {
showWorkInvoice(workInvoice);
@@ -178,26 +175,10 @@ function startPolling() {
return;
}
if (state === 'complete') {
addHistoryEntry({
jobId: currentJobId,
request: currentRequest,
costSats: costLedger?.workAmountSats ?? costLedger?.actualAmountSats ?? 0,
result,
state: 'complete',
completedAt: completedAt ?? new Date().toISOString(),
});
showResult(result, 'complete');
return;
}
if (state === 'rejected') {
addHistoryEntry({
jobId: currentJobId,
request: currentRequest,
costSats: 0,
result: reason,
state: 'rejected',
completedAt: completedAt ?? new Date().toISOString(),
});
showResult(reason, 'rejected');
return;
}

View File

@@ -16,7 +16,6 @@ import { setSpeechBubble, setMood } from './agents.js';
import { appendSystemMessage, setSessionSendHandler, setInputBarSessionMode } from './ui.js';
import { getOrRefreshToken } from './nostr-identity.js';
import { sentiment } from './edge-worker-client.js';
import { addHistoryEntry } from './history.js';
const API = '/api';
const LS_KEY = 'timmy_session_v1';
@@ -153,21 +152,12 @@ export async function sessionSendHandler(text) {
return;
}
const prevBalance = _balanceSats;
_balanceSats = data.balanceRemaining ?? 0;
_sessionState = _balanceSats < MIN_BALANCE ? 'paused' : 'active';
_saveToStorage();
_applySessionUI();
const reply = data.result || data.reason || '…';
const costSats = Math.max(0, prevBalance - _balanceSats);
addHistoryEntry({
request: text,
costSats,
result: reply,
state: data.reason && !data.result ? 'rejected' : 'complete',
completedAt: new Date().toISOString(),
});
setSpeechBubble(reply);
appendSystemMessage('Timmy: ' + reply.slice(0, 80));

View File

@@ -1,7 +1,7 @@
import { sendVisitorMessage } from './websocket.js';
import { classify } from './edge-worker-client.js';
import { setMood, setSpeechBubble } from './agents.js';
import { getOrRefreshToken, getPubkey, disconnectNostrIdentity, showIdentityPrompt } from './nostr-identity.js';
import { getOrRefreshToken } from './nostr-identity.js';
const $fps = document.getElementById('fps');
const $activeJobs = document.getElementById('active-jobs');
@@ -180,97 +180,12 @@ export function hideCostTicker() {
$costTicker.style.opacity = '0';
}
// ── Nostr identity UI ─────────────────────────────────────────────────────────
let _nostrStatusEl = null;
let _connectNostrBtn = null;
let _disconnectNostrBtn = null;
let _nostrPubkeyDisplay = null;
let _getAlbyBtn = null;
export function initNostrIdentityUI() {
_nostrStatusEl = document.getElementById('nostr-identity-status');
if (!_nostrStatusEl) return;
_nostrStatusEl.innerHTML = `
<button id="connect-nostr-btn" class="nostr-btn">⚡ Connect Nostr</button>
<span id="nostr-pubkey-display" class="nostr-pubkey"></span>
<button id="disconnect-nostr-btn" class="nostr-btn nostr-btn-sm">Disconnect</button>
<button id="get-alby-btn" class="nostr-btn nostr-btn-sm">Get Alby</button>
`;
_connectNostrBtn = document.getElementById('connect-nostr-btn');
_disconnectNostrBtn = document.getElementById('disconnect-nostr-btn');
_nostrPubkeyDisplay = document.getElementById('nostr-pubkey-display');
_getAlbyBtn = document.getElementById('get-alby-btn');
if (_connectNostrBtn) {
_connectNostrBtn.addEventListener('click', () => {
showIdentityPrompt('/api');
});
}
if (_disconnectNostrBtn) {
_disconnectNostrBtn.addEventListener('click', () => {
disconnectNostrIdentity();
_updateNostrIdentityUI(null);
});
}
window.addEventListener('nostr:identity-ready', e => {
_updateNostrIdentityUI(e.detail.pubkey);
});
window.addEventListener('nostr:identity-disconnected', () => {
_updateNostrIdentityUI(null);
});
_updateNostrIdentityUI(getPubkey());
}
function _updateNostrIdentityUI(pubkey) {
const hasNip07 = typeof window !== 'undefined' && !!window.nostr;
if (pubkey) {
const formattedPubkey = pubkey.slice(0, 8) + '…' + pubkey.slice(-4);
if (_nostrPubkeyDisplay) {
_nostrPubkeyDisplay.textContent = `${formattedPubkey}`;
_nostrPubkeyDisplay.style.display = 'inline-block';
}
if (_connectNostrBtn) _connectNostrBtn.style.display = 'none';
if (_disconnectNostrBtn) _disconnectNostrBtn.style.display = 'inline-block';
if (_getAlbyBtn) _getAlbyBtn.style.display = 'none';
} else {
if (_nostrPubkeyDisplay) _nostrPubkeyDisplay.style.display = 'none';
if (_disconnectNostrBtn) _disconnectNostrBtn.style.display = 'none';
if (hasNip07) {
if (_connectNostrBtn) {
_connectNostrBtn.textContent = '⚡ Connect Nostr';
_connectNostrBtn.style.display = 'inline-block';
}
if (_getAlbyBtn) _getAlbyBtn.style.display = 'none';
} else {
if (_connectNostrBtn) _connectNostrBtn.style.display = 'none';
if (_getAlbyBtn) {
_getAlbyBtn.textContent = 'Get Alby';
_getAlbyBtn.style.display = 'inline-block';
_getAlbyBtn.title = 'Install Alby or another NIP-07 extension to connect your Nostr identity';
_getAlbyBtn.onclick = () => window.open('https://getalby.com/', '_blank');
}
}
}
}
// ── Input bar ─────────────────────────────────────────────────────────────────
export function initUI() {
if (uiInitialized) return;
uiInitialized = true;
initInputBar();
initHeatmap();
initNostrIdentityUI();
}
function initInputBar() {
@@ -391,118 +306,128 @@ export function appendDebateMessage(agent, argument, isVerdict, accepted) {
export function loadChatHistory() { return []; }
export function saveChatHistory() {}
// ── Activity heatmap (#9) ─────────────────────────────────────────────────────
// Fetches /api/stats/activity and renders a 24-segment heatmap.
// Auto-refreshes every 5 minutes. On mobile, collapses to an icon that opens
// a full-screen overlay.
// ── 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".
const HEATMAP_REFRESH_MS = 5 * 60 * 1000; // 5 minutes
let _heatmapTimer = null;
let _lastHours = null; // number[24] cached for overlay re-render
let $stepsPanel = null;
let _stepElements = [];
let _collapseTimer = null;
/** Convert an hour index (0 = oldest, 23 = current) to a UTC hour label like "3pm" or "midnight". */
function _hourLabel(hourIndex) {
const now = new Date();
const currentHour = now.getUTCHours();
// slot 23 = current UTC hour, slot 0 = 23 hours ago
const h = ((currentHour - (23 - hourIndex)) % 24 + 24) % 24;
if (h === 0) return 'midnight';
if (h === 12) return 'noon';
return h < 12 ? `${h}am` : `${h - 12}pm`;
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;
}
/** Interpolate from dim blue (#111133) to bright blue-white (#88ccff) based on 01 intensity. */
function _segmentColor(intensity) {
// dim: [17, 17, 51] bright: [136, 204, 255]
const r = Math.round(17 + (136 - 17) * intensity);
const g = Math.round(17 + (204 - 17) * intensity);
const b = Math.round(51 + (255 - 51) * intensity);
return `rgb(${r},${g},${b})`;
/**
* 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';
}
function _renderSegments(hours, container, isMobile) {
container.innerHTML = '';
const max = Math.max(...hours, 1); // avoid div-by-zero
const currentSlot = 23;
/**
* 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;
hours.forEach((count, i) => {
const seg = document.createElement('div');
seg.className = 'hm-seg' + (i === currentSlot ? ' hm-seg-current' : '');
const intensity = count / max;
const color = _segmentColor(intensity);
seg.style.background = color;
if (i === currentSlot) seg.style.color = color; // used by pulse animation
seg.dataset.index = String(i);
seg.dataset.count = String(count);
if (isMobile) {
seg.style.width = '14px';
seg.style.height = '28px';
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';
}
container.appendChild(seg);
});
}
function _initHeatmapTooltip(barEl) {
const $tip = document.getElementById('heatmap-tooltip');
if (!$tip) return;
/**
* 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);
barEl.addEventListener('mousemove', e => {
const seg = e.target.closest('.hm-seg');
if (!seg) { $tip.style.display = 'none'; return; }
const i = Number(seg.dataset.index);
const count = Number(seg.dataset.count);
const label = _hourLabel(i);
$tip.textContent = `${label}: ${count} job${count !== 1 ? 's' : ''} submitted`;
$tip.style.display = 'block';
$tip.style.left = `${e.clientX + 10}px`;
$tip.style.top = `${e.clientY - 24}px`;
});
// 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';
barEl.addEventListener('mouseleave', () => { $tip.style.display = 'none'; });
}
async function _fetchAndRenderHeatmap() {
try {
const res = await fetch('/api/stats/activity');
if (!res.ok) return;
const data = await res.json();
const hours = Array.isArray(data.hours) ? data.hours : [];
if (hours.length !== 24) return;
_lastHours = hours;
const $bar = document.getElementById('heatmap-bar');
if ($bar) _renderSegments(hours, $bar, false);
const $overlayBar = document.getElementById('heatmap-overlay-bar');
if ($overlayBar) _renderSegments(hours, $overlayBar, true);
} catch {
// silently ignore fetch errors
}
}
export function initHeatmap() {
const $bar = document.getElementById('heatmap-bar');
const $iconBtn = document.getElementById('heatmap-icon-btn');
const $overlay = document.getElementById('heatmap-overlay');
const $closeBtn = document.getElementById('heatmap-overlay-close');
if ($bar) _initHeatmapTooltip($bar);
if ($iconBtn && $overlay) {
$iconBtn.addEventListener('click', () => {
$overlay.classList.add('open');
if (_lastHours) {
const $overlayBar = document.getElementById('heatmap-overlay-bar');
if ($overlayBar) _renderSegments(_lastHours, $overlayBar, true);
}
});
}
if ($closeBtn && $overlay) {
$closeBtn.addEventListener('click', () => $overlay.classList.remove('open'));
}
// Initial fetch then schedule refresh
void _fetchAndRenderHeatmap();
_heatmapTimer = setInterval(_fetchAndRenderHeatmap, HEATMAP_REFRESH_MS);
// Fade out after 2.5 s
_collapseTimer = setTimeout(() => {
if ($stepsPanel) $stepsPanel.style.opacity = '0';
_stepElements = [];
}, 2500);
}

View File

@@ -1,11 +1,7 @@
import * as THREE from 'three';
import { scene } from './world.js'; // Import the scene
import { setAgentState, setSpeechBubble, applyAgentStates, setMood, TIMMY_WORLD_POS } from './agents.js';
import { appendSystemMessage, appendDebateMessage, showCostTicker, updateCostTicker } from './ui.js';
import { setAgentState, setSpeechBubble, applyAgentStates, setMood } from './agents.js';
import { appendSystemMessage, appendDebateMessage, showCostTicker, updateCostTicker, showJobSteps, updateJobStep, collapseJobSteps } from './ui.js';
import { sentiment } from './edge-worker-client.js';
import { setLabelState, setLabelLastTask } from './hud-labels.js';
import { createJobIndicator, dissolveJobIndicator } from './effects.js';
import { getPubkey } from './nostr-identity.js';
import { setLabelState } from './hud-labels.js';
function resolveWsUrl() {
const explicit = import.meta.env.VITE_WS_URL;
@@ -23,10 +19,6 @@ let reconnectTimer = null;
let visitorId = null;
const RECONNECT_DELAY_MS = 5000;
// Map to keep track of active job indicator positions for offsetting
const _jobIndicatorOffsets = new Map();
let _nextJobOffsetIndex = 0;
export function initWebSocket(_scene) {
visitorId = crypto.randomUUID();
connect();
@@ -47,8 +39,7 @@ function connect() {
ws.onopen = () => {
connectionState = 'connected';
clearTimeout(reconnectTimer);
const npub = getPubkey();
send({ type: 'visitor_enter', visitorId, visitorName: 'visitor', npub });
send({ type: 'visitor_enter', visitorId, visitorName: 'visitor' });
};
ws.onmessage = event => {
@@ -104,28 +95,6 @@ function handleMessage(msg) {
setLabelState(msg.agentId, 'active');
}
appendSystemMessage(`job ${(msg.jobId || '').slice(0, 8)} started`);
// Spawn 3D job indicator
if (msg.jobId && msg.category) {
const offsetMultiplier = _jobIndicatorOffsets.size; // Simple way to spread them out
const indicatorPosition = TIMMY_WORLD_POS.clone().add(
new THREE.Vector3(
(offsetMultiplier % 2 === 0 ? 1 : -1) * (Math.floor(offsetMultiplier / 2) + 1) * 0.7, // Alternate left/right
3.5, // Height above Timmy
-0.5
)
);
const indicator = createJobIndicator(msg.category, msg.jobId, indicatorPosition);
scene.add(indicator);
_jobIndicatorOffsets.set(msg.jobId, indicatorPosition); // Store position, not index, for cleaner removal
}
break;
}
case 'agent_task_summary': {
if (msg.agentId && msg.summary) {
setLabelLastTask(msg.agentId, msg.summary);
}
break;
}
@@ -134,15 +103,9 @@ function handleMessage(msg) {
if (msg.agentId) {
setAgentState(msg.agentId, 'idle');
setLabelState(msg.agentId, 'idle');
setLabelLastTask(msg.agentId, `job ${(msg.jobId || '').slice(0, 8)} completed`);
}
appendSystemMessage(`job ${(msg.jobId || '').slice(0, 8)} complete`);
// Dissolve 3D job indicator
if (msg.jobId) {
dissolveJobIndicator(msg.jobId, scene);
_jobIndicatorOffsets.delete(msg.jobId);
}
collapseJobSteps();
break;
}
@@ -178,6 +141,20 @@ 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.
@@ -189,15 +166,6 @@ function handleMessage(msg) {
break;
}
case 'agent_commentary': {
// Agent narration during job lifecycle
if (msg.text) {
setSpeechBubble(msg.text);
appendSystemMessage(`${msg.agentId}: ${(msg.text || '').slice(0, 80)}`);
}
break;
}
case 'agent_count':
case 'visitor_count':
break;

View File

@@ -1,6 +1,6 @@
import * as THREE from 'three';
export let scene, camera, renderer;
let scene, camera, renderer;
const _worldObjects = [];
export function initWorld(existingCanvas) {