feat(demo): P2.7 Vite React two-pane realtime demo + dev token endpoint (P2 complete)
apps/message-demo: Alice creates a thread, Bob joins; live two-way chat, typing, read receipts (useMessages now exposes reads[]). Dev-only /v1/dev/token endpoint (gated by IIOS_DEV_TOKENS) so the browser can auth. .env autoloaded (dotenv). Realtime smoke script passes end-to-end (message + unread + receipt). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>IIOS P2 — Message Demo</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
{
|
||||||
|
"name": "message-demo",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@insignia/iios-kernel-client": "workspace:*",
|
||||||
|
"@insignia/iios-message-web": "workspace:*",
|
||||||
|
"react": "^19.0.0",
|
||||||
|
"react-dom": "^19.0.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "^19.0.0",
|
||||||
|
"@types/react-dom": "^19.0.0",
|
||||||
|
"@vitejs/plugin-react": "^4.3.4",
|
||||||
|
"typescript": "^5.7.3",
|
||||||
|
"vite": "^6.0.7"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { MessageProvider, useThread, useMessages } from '@insignia/iios-message-web';
|
||||||
|
|
||||||
|
const SERVICE = 'http://localhost:3200';
|
||||||
|
const APP_ID = 'portal-demo';
|
||||||
|
|
||||||
|
async function devToken(userId: string, name: string): Promise<string> {
|
||||||
|
const r = await fetch(`${SERVICE}/v1/dev/token`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify({ appId: APP_ID, userId, name }),
|
||||||
|
});
|
||||||
|
if (!r.ok) throw new Error(`devToken ${r.status} (is the service running with IIOS_DEV_TOKENS=1?)`);
|
||||||
|
return ((await r.json()) as { token: string }).token;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChatInner({
|
||||||
|
label,
|
||||||
|
threadId,
|
||||||
|
onCreated,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
threadId: string | null;
|
||||||
|
onCreated?: (id: string) => void;
|
||||||
|
}) {
|
||||||
|
const { open } = useThread();
|
||||||
|
const [tid, setTid] = useState<string | null>(threadId);
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (threadId) {
|
||||||
|
setTid(threadId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (onCreated) {
|
||||||
|
void open().then((id) => {
|
||||||
|
setTid(id);
|
||||||
|
onCreated(id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [threadId]);
|
||||||
|
|
||||||
|
const { messages, send, typing, typingUsers, markRead, reads } = useMessages(tid);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ flex: 1, border: '1px solid #ccc', borderRadius: 8, padding: 12, margin: 8, fontFamily: 'sans-serif' }}>
|
||||||
|
<h3 style={{ marginTop: 0 }}>{label}</h3>
|
||||||
|
<div style={{ color: '#888', fontSize: 12 }}>thread: {tid ?? '…'}</div>
|
||||||
|
<div style={{ height: 240, overflow: 'auto', background: '#fafafa', padding: 8, margin: '8px 0' }}>
|
||||||
|
{messages.map((m) => (
|
||||||
|
<div key={m.id} style={{ padding: '2px 0' }}>
|
||||||
|
<b>{m.senderActorId.slice(0, 6)}:</b> {m.content} {reads.includes(m.id) ? '✓✓' : ''}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{typingUsers.length > 0 && <em style={{ color: '#888' }}>{typingUsers.join(', ')} typing…</em>}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
value={text}
|
||||||
|
placeholder="type a message + Enter"
|
||||||
|
style={{ width: '100%', padding: 6 }}
|
||||||
|
onChange={(e) => {
|
||||||
|
setText(e.target.value);
|
||||||
|
typing();
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' && text.trim()) {
|
||||||
|
void send(text.trim());
|
||||||
|
setText('');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
style={{ marginTop: 8 }}
|
||||||
|
onClick={() => {
|
||||||
|
const last = messages.at(-1);
|
||||||
|
if (last) void markRead(last.id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
mark last read
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Pane(props: { token: string | null; label: string; threadId: string | null; onCreated?: (id: string) => void }) {
|
||||||
|
if (!props.token) return <div style={{ flex: 1, margin: 8 }}>loading {props.label}…</div>;
|
||||||
|
return (
|
||||||
|
<MessageProvider serviceUrl={SERVICE} token={props.token}>
|
||||||
|
<ChatInner label={props.label} threadId={props.threadId} onCreated={props.onCreated} />
|
||||||
|
</MessageProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function App() {
|
||||||
|
const [alice, setAlice] = useState<string | null>(null);
|
||||||
|
const [bob, setBob] = useState<string | null>(null);
|
||||||
|
const [threadId, setThreadId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void devToken('alice', 'Alice').then(setAlice);
|
||||||
|
void devToken('bob', 'Bob').then(setBob);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ padding: 16 }}>
|
||||||
|
<h2 style={{ fontFamily: 'sans-serif' }}>IIOS P2 — realtime demo (Alice ↔ Bob)</h2>
|
||||||
|
<p style={{ fontFamily: 'sans-serif', color: '#666' }}>
|
||||||
|
Type in either pane — it appears live in the other. ✓✓ = read receipt.
|
||||||
|
</p>
|
||||||
|
<div style={{ display: 'flex' }}>
|
||||||
|
<Pane token={alice} label="Alice (creates thread)" threadId={null} onCreated={setThreadId} />
|
||||||
|
<Pane token={bob} label="Bob (joins)" threadId={threadId} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
import { App } from './App';
|
||||||
|
|
||||||
|
const el = document.getElementById('root');
|
||||||
|
if (el) createRoot(el).render(<App />);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../tsconfig.base.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"lib": ["ES2022", "DOM"],
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"types": ["react", "react-dom"],
|
||||||
|
"noEmit": true
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "src/**/*.tsx"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
server: { port: 5173 },
|
||||||
|
});
|
||||||
@@ -55,10 +55,12 @@ export function useMessages(threadId: string | null): {
|
|||||||
markRead: (interactionId: string) => Promise<void>;
|
markRead: (interactionId: string) => Promise<void>;
|
||||||
typing: () => void;
|
typing: () => void;
|
||||||
typingUsers: string[];
|
typingUsers: string[];
|
||||||
|
reads: string[];
|
||||||
} {
|
} {
|
||||||
const socket = useSocket();
|
const socket = useSocket();
|
||||||
const [messages, setMessages] = useState<Message[]>([]);
|
const [messages, setMessages] = useState<Message[]>([]);
|
||||||
const [typingUsers, setTypingUsers] = useState<string[]>([]);
|
const [typingUsers, setTypingUsers] = useState<string[]>([]);
|
||||||
|
const [reads, setReads] = useState<string[]>([]);
|
||||||
const seen = useRef<Set<string>>(new Set());
|
const seen = useRef<Set<string>>(new Set());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -80,10 +82,14 @@ export function useMessages(threadId: string | null): {
|
|||||||
setTypingUsers((u) => (u.includes(e.userId) ? u : [...u, e.userId]));
|
setTypingUsers((u) => (u.includes(e.userId) ? u : [...u, e.userId]));
|
||||||
setTimeout(() => setTypingUsers((u) => u.filter((x) => x !== e.userId)), 2500);
|
setTimeout(() => setTypingUsers((u) => u.filter((x) => x !== e.userId)), 2500);
|
||||||
});
|
});
|
||||||
|
const offReceipt = socket.on('receipt', (e) => {
|
||||||
|
if (e.kind === 'READ') setReads((r) => (r.includes(e.interactionId) ? r : [...r, e.interactionId]));
|
||||||
|
});
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
offMessage();
|
offMessage();
|
||||||
offTyping();
|
offTyping();
|
||||||
|
offReceipt();
|
||||||
};
|
};
|
||||||
}, [socket, threadId]);
|
}, [socket, threadId]);
|
||||||
|
|
||||||
@@ -97,5 +103,5 @@ export function useMessages(threadId: string | null): {
|
|||||||
if (threadId) socket.typing(threadId);
|
if (threadId) socket.typing(threadId);
|
||||||
};
|
};
|
||||||
|
|
||||||
return { messages, send, markRead, typing, typingUsers };
|
return { messages, send, markRead, typing, typingUsers, reads };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
"socket.io": "^4.8.3",
|
"socket.io": "^4.8.3",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.15.1",
|
"class-validator": "^0.15.1",
|
||||||
|
"dotenv": "^16.4.7",
|
||||||
"jsonwebtoken": "^9.0.3",
|
"jsonwebtoken": "^9.0.3",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.2"
|
"rxjs": "^7.8.2"
|
||||||
@@ -34,6 +35,7 @@
|
|||||||
"@types/jsonwebtoken": "^9.0.10",
|
"@types/jsonwebtoken": "^9.0.10",
|
||||||
"@types/node": "^26.0.1",
|
"@types/node": "^26.0.1",
|
||||||
"prisma": "^6.2.1",
|
"prisma": "^6.2.1",
|
||||||
|
"socket.io-client": "^4.8.3",
|
||||||
"typescript": "^5.7.3"
|
"typescript": "^5.7.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
// P2 realtime smoke: two socket.io clients (Alice, Bob) on one thread.
|
||||||
|
// Requires the service running with IIOS_DEV_TOKENS=1 + APP_SECRETS set.
|
||||||
|
// Run: node scripts/smoke-realtime.mjs
|
||||||
|
import 'dotenv/config';
|
||||||
|
import { io } from 'socket.io-client';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
const SERVICE = process.env.SMOKE_URL ?? 'http://localhost:3200';
|
||||||
|
const APP_ID = 'portal-demo';
|
||||||
|
const SECRET = JSON.parse(process.env.APP_SECRETS ?? '{"portal-demo":"dev-secret"}')[APP_ID];
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
const sign = (userId) =>
|
||||||
|
jwt.sign({ sub: userId, name: userId, appId: APP_ID, orgId: `org_${APP_ID}` }, SECRET, {
|
||||||
|
algorithm: 'HS256',
|
||||||
|
expiresIn: '1h',
|
||||||
|
});
|
||||||
|
|
||||||
|
const connect = (userId) =>
|
||||||
|
io(`${SERVICE}/message`, { auth: { token: sign(userId) }, transports: ['websocket'], forceNew: true });
|
||||||
|
|
||||||
|
const once = (socket, event) => new Promise((res) => socket.once(event, res));
|
||||||
|
const assert = (cond, msg) => {
|
||||||
|
if (!cond) {
|
||||||
|
console.error('✗', msg);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
console.log('✓', msg);
|
||||||
|
};
|
||||||
|
|
||||||
|
async function unread(threadId, userId) {
|
||||||
|
const handle = await prisma.iiosSourceHandle.findFirst({ where: { externalId: userId } });
|
||||||
|
if (!handle) return 0;
|
||||||
|
const actor = await prisma.iiosActorRef.findFirst({ where: { sourceHandleId: handle.id } });
|
||||||
|
if (!actor) return 0;
|
||||||
|
const c = await prisma.iiosUnreadCounter.findUnique({
|
||||||
|
where: { threadId_actorId: { threadId, actorId: actor.id } },
|
||||||
|
});
|
||||||
|
return c?.unreadCount ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const alice = connect('alice');
|
||||||
|
const bob = connect('bob');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Alice creates a thread; Bob joins it.
|
||||||
|
const opened = await alice.emitWithAck('open_thread', {});
|
||||||
|
const threadId = opened.threadId;
|
||||||
|
assert(!!threadId, `Alice created thread ${threadId}`);
|
||||||
|
await bob.emitWithAck('open_thread', { threadId });
|
||||||
|
|
||||||
|
// Alice sends; Bob should receive it live.
|
||||||
|
const bobGetsMessage = once(bob, 'message');
|
||||||
|
const sent = await alice.emitWithAck('send_message', { threadId, content: 'hi bob' });
|
||||||
|
const received = await bobGetsMessage;
|
||||||
|
assert(received.content === 'hi bob', `Bob received "${received.content}" in realtime`);
|
||||||
|
assert((await unread(threadId, 'bob')) === 1, "Bob's unread = 1");
|
||||||
|
|
||||||
|
// Bob reads; Alice should get the receipt; Bob's unread resets.
|
||||||
|
const aliceGetsReceipt = once(alice, 'receipt');
|
||||||
|
await bob.emitWithAck('read', { threadId, interactionId: sent.id });
|
||||||
|
const receipt = await aliceGetsReceipt;
|
||||||
|
assert(receipt.kind === 'READ' && receipt.interactionId === sent.id, 'Alice received READ receipt');
|
||||||
|
assert((await unread(threadId, 'bob')) === 0, "Bob's unread reset to 0");
|
||||||
|
|
||||||
|
console.log('\nP2 realtime smoke: PASS');
|
||||||
|
} finally {
|
||||||
|
alice.close();
|
||||||
|
bob.close();
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
process.exit(0);
|
||||||
@@ -6,9 +6,10 @@ import { OutboxModule } from './outbox/outbox.module';
|
|||||||
import { ThreadsModule } from './threads/threads.module';
|
import { ThreadsModule } from './threads/threads.module';
|
||||||
import { MessageModule } from './messaging/message.module';
|
import { MessageModule } from './messaging/message.module';
|
||||||
import { HealthController } from './health.controller';
|
import { HealthController } from './health.controller';
|
||||||
|
import { DevController } from './dev/dev.controller';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [PrismaModule, PlatformModule, InteractionsModule, OutboxModule, ThreadsModule, MessageModule],
|
imports: [PrismaModule, PlatformModule, InteractionsModule, OutboxModule, ThreadsModule, MessageModule],
|
||||||
controllers: [HealthController],
|
controllers: [HealthController, DevController],
|
||||||
})
|
})
|
||||||
export class AppModule {}
|
export class AppModule {}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { BadRequestException, Body, Controller, ForbiddenException, Post } from '@nestjs/common';
|
||||||
|
import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dev-only helper: mints an HS256 token a host app would normally sign, so the
|
||||||
|
* browser demo can authenticate. Gated by IIOS_DEV_TOKENS=1 — never enable in
|
||||||
|
* production (the host app signs its own tokens there).
|
||||||
|
*/
|
||||||
|
@Controller('v1/dev')
|
||||||
|
export class DevController {
|
||||||
|
@Post('token')
|
||||||
|
token(@Body() body: { appId: string; userId: string; name?: string; orgId?: string }): { token: string } {
|
||||||
|
if (process.env.IIOS_DEV_TOKENS !== '1') throw new ForbiddenException('dev tokens disabled');
|
||||||
|
let secrets: Record<string, string>;
|
||||||
|
try {
|
||||||
|
secrets = JSON.parse(process.env.APP_SECRETS ?? '{}');
|
||||||
|
} catch {
|
||||||
|
secrets = {};
|
||||||
|
}
|
||||||
|
const secret = secrets[body.appId];
|
||||||
|
if (!secret) throw new BadRequestException(`unknown app: ${body.appId}`);
|
||||||
|
const token = jwt.sign(
|
||||||
|
{ sub: body.userId, name: body.name ?? body.userId, appId: body.appId, orgId: body.orgId ?? `org_${body.appId}` },
|
||||||
|
secret,
|
||||||
|
{ algorithm: 'HS256', expiresIn: '2h' },
|
||||||
|
);
|
||||||
|
return { token };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import 'dotenv/config';
|
||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { ValidationPipe } from '@nestjs/common';
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
|||||||
Generated
+669
-1
File diff suppressed because it is too large
Load Diff
@@ -1,2 +1,3 @@
|
|||||||
packages:
|
packages:
|
||||||
- "packages/*"
|
- "packages/*"
|
||||||
|
- "apps/*"
|
||||||
|
|||||||
Reference in New Issue
Block a user