ci / checks (push) Successful in 54s
ci / test (push) Successful in 58s
ci / chart (push) Successful in 5s
ci / web (push) Successful in 21s
ci / docker (push) Successful in 11s
ci / publish-edge-image (push) Successful in 10s
ci / publish-edge-chart (push) Successful in 3s
The invite dialog was reachable only from the invite button, and who was in the room showed only as avatars in the top bar. Selecting an avatar, the member count, or the People button now opens one dialog: a scrollable member list with the invite link below it. The owner removes a member from the row after a confirmation, and the top bar drops them without reloading the room. The server already refuses to remove the owner. Invite link creation is unchanged.
928 lines
27 KiB
Vue
928 lines
27 KiB
Vue
<script setup lang="ts">
|
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
|
import type {
|
|
DeltaData,
|
|
Envelope,
|
|
Member,
|
|
Message,
|
|
MessagePage,
|
|
NoticeData,
|
|
PresencePeer,
|
|
PreviewTarget,
|
|
Room,
|
|
RoomDetailResponse,
|
|
StepStartData,
|
|
TimelineEntry,
|
|
ToolArgsData,
|
|
ToolOutputData,
|
|
ToolResultData,
|
|
ToolStartData,
|
|
TurnActivity,
|
|
TurnEndData,
|
|
TurnStartData,
|
|
UsageEventData,
|
|
} from '~/types'
|
|
import { apiErrorMessage } from '~/utils/errors'
|
|
|
|
definePageMeta({ key: (route) => route.fullPath })
|
|
|
|
const route = useRoute()
|
|
const api = useApi()
|
|
const { session } = useSession()
|
|
const rooms = useRooms()
|
|
|
|
const roomId = computed(() => String(route.params.id ?? ''))
|
|
|
|
const detail = ref<RoomDetailResponse | null>(null)
|
|
const detailLoading = ref(true)
|
|
const detailError = ref('')
|
|
|
|
const previewTarget = ref<PreviewTarget | null>(null)
|
|
const messages = ref<Message[]>([])
|
|
const notices = ref<Array<{ seq: number; level: string; text: string }>>([])
|
|
const activities = ref<TurnActivity[]>([])
|
|
const messagesLoading = ref(true)
|
|
const messagesError = ref('')
|
|
const hasMore = ref(false)
|
|
const loadingOlder = ref(false)
|
|
|
|
const chatScroll = ref<HTMLElement | null>(null)
|
|
const chatInner = ref<HTMLElement | null>(null)
|
|
const stick = ref(true)
|
|
const newMessages = ref(0)
|
|
|
|
const streamState = ref<'connecting' | 'live' | 'disconnected'>('connecting')
|
|
const streamError = ref('')
|
|
const peers = ref<PresencePeer[]>([])
|
|
const onlineIds = ref<string[]>([])
|
|
const typingActive = ref(false)
|
|
|
|
const paneOpen = ref(typeof window === 'undefined' ? true : !window.matchMedia('(max-width: 1099px)').matches)
|
|
const peopleOpen = ref(false)
|
|
const settingsOpen = ref(false)
|
|
|
|
const PANE_WIDTH_KEY = 'together.pane-width'
|
|
const DEFAULT_PANE_PERCENT = 44
|
|
const PANE_MIN_WIDTH = 380
|
|
const CHAT_MIN_WIDTH = 420
|
|
const DIVIDER_WIDTH = 8
|
|
|
|
const roomBody = ref<HTMLElement | null>(null)
|
|
const paneWidth = ref<number | null>(null)
|
|
const paneBodyWidth = ref(0)
|
|
let paneBodyObserver: ResizeObserver | null = null
|
|
|
|
type PaneDrag = {
|
|
pointerId: number
|
|
startX: number
|
|
startWidth: number
|
|
moved: boolean
|
|
}
|
|
|
|
let paneDrag: PaneDrag | null = null
|
|
|
|
const seenMessages = new Set<number>()
|
|
const seenNotices = new Set<number>()
|
|
let lastDurable = 0
|
|
let disposed = false
|
|
|
|
let eventController: AbortController | null = null
|
|
let eventGeneration = 0
|
|
let retryIndex = 0
|
|
let reconnectTimer: number | null = null
|
|
|
|
let chatObserver: ResizeObserver | null = null
|
|
let suspendAutoScroll = false
|
|
|
|
let presenceSocket: WebSocket | null = null
|
|
let presenceTimer: number | null = null
|
|
let presenceRetry = 0
|
|
|
|
const DURABLE_KINDS = new Set(['message', 'notice', 'turn_start', 'turn_end', 'tool_result', 'preview'])
|
|
const BACKOFF = [1000, 2000, 5000, 10000]
|
|
|
|
useHead({
|
|
title: computed(() => `${detail.value?.room.name ?? 'Room'} · Rhema Together`),
|
|
})
|
|
|
|
const isOwner = computed(
|
|
() => !!detail.value && detail.value.room.owner_id === session.value.user?.id,
|
|
)
|
|
|
|
const memberById = computed(() => {
|
|
const map = new Map<string, Member>()
|
|
for (const member of detail.value?.members ?? []) map.set(member.id, member)
|
|
return map
|
|
})
|
|
|
|
const paneMaxWidth = computed(() => {
|
|
const total = paneBodyWidth.value
|
|
if (!total) return PANE_MIN_WIDTH
|
|
return Math.max(PANE_MIN_WIDTH, total - CHAT_MIN_WIDTH - DIVIDER_WIDTH)
|
|
})
|
|
|
|
function clampPaneWidth(width: number): number {
|
|
const rounded = Math.round(width)
|
|
if (!paneBodyWidth.value) return Math.max(rounded, PANE_MIN_WIDTH)
|
|
return Math.min(Math.max(rounded, PANE_MIN_WIDTH), paneMaxWidth.value)
|
|
}
|
|
|
|
const effectivePaneWidth = computed(() => {
|
|
if (paneWidth.value === null) return null
|
|
return clampPaneWidth(paneWidth.value)
|
|
})
|
|
|
|
const paneStyle = computed<Record<string, string> | undefined>(() => {
|
|
const width = effectivePaneWidth.value
|
|
return width === null ? undefined : { '--pane-width': `${width}px` }
|
|
})
|
|
|
|
function panePercentFor(width: number): number {
|
|
const total = paneBodyWidth.value
|
|
if (!total) return DEFAULT_PANE_PERCENT
|
|
return Math.round((width / total) * 100)
|
|
}
|
|
|
|
const paneValue = computed(() => {
|
|
const total = paneBodyWidth.value
|
|
if (!total) return DEFAULT_PANE_PERCENT
|
|
const width = effectivePaneWidth.value ?? (total * DEFAULT_PANE_PERCENT) / 100
|
|
return panePercentFor(width)
|
|
})
|
|
|
|
const paneMinPercent = computed(() => (paneBodyWidth.value ? panePercentFor(PANE_MIN_WIDTH) : 25))
|
|
const paneMaxPercent = computed(() => (paneBodyWidth.value ? panePercentFor(paneMaxWidth.value) : 75))
|
|
|
|
const timeline = computed<TimelineEntry[]>(() => {
|
|
const entries: TimelineEntry[] = []
|
|
for (const message of messages.value) {
|
|
entries.push({ kind: 'message', seq: message.seq, message })
|
|
}
|
|
for (const notice of notices.value) {
|
|
entries.push({ kind: 'notice', seq: notice.seq, level: notice.level, text: notice.text })
|
|
}
|
|
for (const activity of activities.value) {
|
|
if (activity.status === 'running') continue
|
|
entries.push({ kind: 'turn', seq: activity.seq, activity })
|
|
}
|
|
return entries.sort((a, b) => a.seq - b.seq)
|
|
})
|
|
|
|
const agentWorking = computed(
|
|
() => streamState.value === 'live' && activities.value.some((activity) => activity.status === 'running'),
|
|
)
|
|
|
|
const typingText = computed(() => {
|
|
const me = detail.value?.me.id
|
|
const names = peers.value
|
|
.filter((peer) => peer.member_id !== me && peer.state?.typing === true)
|
|
.map((peer) => peer.display_name)
|
|
if (names.length === 0) return ''
|
|
if (names.length === 1) return `${names[0]} is typing...`
|
|
if (names.length === 2) return `${names[0]} and ${names[1]} are typing...`
|
|
return 'Several people are typing...'
|
|
})
|
|
|
|
function eventData<T>(envelope: Envelope): T {
|
|
return envelope.data as unknown as T
|
|
}
|
|
|
|
function findActivity(turnId: string): TurnActivity | undefined {
|
|
return activities.value.find((activity) => activity.turnId === turnId)
|
|
}
|
|
|
|
function ensureActivity(turnId: string, seq: number): TurnActivity {
|
|
const existing = findActivity(turnId)
|
|
if (existing) return existing
|
|
const created: TurnActivity = {
|
|
turnId,
|
|
seq: Number.isFinite(seq) ? seq : lastDurable,
|
|
startedAt: Date.now(),
|
|
text: '',
|
|
thinking: '',
|
|
steps: 0,
|
|
tools: [],
|
|
usage: null,
|
|
status: 'running',
|
|
error: '',
|
|
}
|
|
activities.value.push(created)
|
|
return created
|
|
}
|
|
|
|
function addMessage(message: Message, quiet = false) {
|
|
if (seenMessages.has(message.seq)) return
|
|
seenMessages.add(message.seq)
|
|
const index = messages.value.findIndex((item) => item.seq > message.seq)
|
|
if (index === -1) messages.value.push(message)
|
|
else messages.value.splice(index, 0, message)
|
|
if (!quiet) {
|
|
if (stick.value) {
|
|
void nextTick(() => {
|
|
if (stick.value) scrollToBottom()
|
|
})
|
|
} else {
|
|
newMessages.value += 1
|
|
}
|
|
}
|
|
}
|
|
|
|
function addNotice(seq: number, level: string, text: string) {
|
|
if (seenNotices.has(seq)) return
|
|
seenNotices.add(seq)
|
|
notices.value.push({ seq, level, text })
|
|
}
|
|
|
|
function handleEnvelope(envelope: Envelope) {
|
|
if (DURABLE_KINDS.has(envelope.kind)) {
|
|
lastDurable = Math.max(lastDurable, envelope.seq)
|
|
}
|
|
|
|
switch (envelope.kind) {
|
|
case 'message':
|
|
addMessage(eventData<Message>(envelope))
|
|
break
|
|
case 'preview': {
|
|
const data = eventData<PreviewTarget>(envelope)
|
|
if (data && (data.kind === 'port' || data.kind === 'static')) previewTarget.value = data
|
|
break
|
|
}
|
|
case 'notice': {
|
|
const data = eventData<NoticeData>(envelope)
|
|
addNotice(envelope.seq, data.level, data.text)
|
|
break
|
|
}
|
|
case 'turn_start': {
|
|
const data = eventData<TurnStartData>(envelope)
|
|
if (!findActivity(data.turn_id)) {
|
|
const activity = ensureActivity(data.turn_id, envelope.seq)
|
|
activity.startedAt = data.at || Date.now()
|
|
}
|
|
break
|
|
}
|
|
case 'text_delta': {
|
|
const data = eventData<DeltaData>(envelope)
|
|
ensureActivity(data.turn_id, lastDurable).text += data.delta
|
|
break
|
|
}
|
|
case 'thinking_delta': {
|
|
const data = eventData<DeltaData>(envelope)
|
|
ensureActivity(data.turn_id, lastDurable).thinking += data.delta
|
|
break
|
|
}
|
|
case 'step_start': {
|
|
const data = eventData<StepStartData>(envelope)
|
|
ensureActivity(data.turn_id, lastDurable).steps += 1
|
|
break
|
|
}
|
|
case 'tool_start': {
|
|
const data = eventData<ToolStartData>(envelope)
|
|
const activity = ensureActivity(data.turn_id, lastDurable)
|
|
if (!activity.tools.some((tool) => tool.call_id === data.call_id)) {
|
|
activity.tools.push({
|
|
call_id: data.call_id,
|
|
name: data.name,
|
|
args: '',
|
|
output: '',
|
|
content: null,
|
|
isError: null,
|
|
code: null,
|
|
done: false,
|
|
})
|
|
}
|
|
break
|
|
}
|
|
case 'tool_args': {
|
|
const data = eventData<ToolArgsData>(envelope)
|
|
const activity = ensureActivity(data.turn_id, lastDurable)
|
|
const tool = activity.tools.find((item) => item.call_id === data.call_id)
|
|
if (tool) tool.args += data.delta
|
|
break
|
|
}
|
|
case 'tool_output': {
|
|
const data = eventData<ToolOutputData>(envelope)
|
|
const activity = ensureActivity(data.turn_id, lastDurable)
|
|
const tool = activity.tools.find((item) => item.call_id === data.call_id)
|
|
if (tool) tool.output += data.chunk
|
|
break
|
|
}
|
|
case 'tool_result': {
|
|
const data = eventData<ToolResultData>(envelope)
|
|
const activity = findActivity(data.turn_id)
|
|
if (!activity) break
|
|
let tool = activity.tools.find((item) => item.call_id === data.call_id)
|
|
if (!tool) {
|
|
tool = {
|
|
call_id: data.call_id,
|
|
name: '',
|
|
args: '',
|
|
output: '',
|
|
content: null,
|
|
isError: null,
|
|
code: null,
|
|
done: false,
|
|
}
|
|
activity.tools.push(tool)
|
|
}
|
|
if (data.name) tool.name = data.name
|
|
if (data.args) tool.args = data.args
|
|
tool.content = data.content
|
|
tool.isError = data.is_error
|
|
tool.code = data.code
|
|
tool.done = true
|
|
break
|
|
}
|
|
case 'usage': {
|
|
const data = eventData<UsageEventData>(envelope)
|
|
const activity = ensureActivity(data.turn_id, lastDurable)
|
|
const usage = activity.usage ?? {
|
|
input_tokens: 0,
|
|
output_tokens: 0,
|
|
cached_input_tokens: 0,
|
|
cost_usd: null,
|
|
}
|
|
usage.input_tokens += data.input_tokens
|
|
usage.output_tokens += data.output_tokens
|
|
usage.cached_input_tokens += data.cached_input_tokens
|
|
if (data.cost_usd !== null && data.cost_usd !== undefined) {
|
|
usage.cost_usd = (usage.cost_usd ?? 0) + data.cost_usd
|
|
}
|
|
activity.usage = usage
|
|
break
|
|
}
|
|
case 'turn_end': {
|
|
const data = eventData<TurnEndData>(envelope)
|
|
const activity = findActivity(data.turn_id)
|
|
if (!activity) break
|
|
activity.status = data.status
|
|
activity.seq = envelope.seq
|
|
activity.steps = data.steps
|
|
activity.usage = data.usage
|
|
if (data.status === 'error') activity.error = data.error ?? 'The turn failed.'
|
|
break
|
|
}
|
|
default:
|
|
break
|
|
}
|
|
}
|
|
|
|
function processChunk(chunk: string) {
|
|
const dataLines = chunk
|
|
.split('\n')
|
|
.filter((line) => line.startsWith('data:'))
|
|
.map((line) => line.slice(5).replace(/^ /, ''))
|
|
if (dataLines.length === 0) return
|
|
const raw = dataLines.join('\n')
|
|
try {
|
|
const envelope = JSON.parse(raw) as Envelope
|
|
if (envelope.kind === 'lag') {
|
|
handleLag()
|
|
return
|
|
}
|
|
handleEnvelope(envelope)
|
|
scheduleStick()
|
|
} catch {
|
|
return
|
|
}
|
|
}
|
|
|
|
async function connectEvents() {
|
|
if (disposed) return
|
|
eventController?.abort()
|
|
const generation = ++eventGeneration
|
|
const controller = new AbortController()
|
|
eventController = controller
|
|
streamState.value = 'connecting'
|
|
streamError.value = ''
|
|
try {
|
|
const response = await fetch(`/api/rooms/${encodeURIComponent(roomId.value)}/events?since=${lastDurable}`, {
|
|
credentials: 'include',
|
|
headers: { Accept: 'text/event-stream' },
|
|
signal: controller.signal,
|
|
})
|
|
if (response.status === 401) {
|
|
await navigateTo('/login')
|
|
return
|
|
}
|
|
if (!response.ok || !response.body) {
|
|
if (response.status === 403 || response.status === 404) {
|
|
streamState.value = 'disconnected'
|
|
streamError.value = 'Live updates are unavailable.'
|
|
return
|
|
}
|
|
throw new Error('The live feed is unavailable.')
|
|
}
|
|
streamState.value = 'live'
|
|
retryIndex = 0
|
|
const reader = response.body.getReader()
|
|
const decoder = new TextDecoder()
|
|
let buffer = ''
|
|
while (!disposed && generation === eventGeneration) {
|
|
const { value, done } = await reader.read()
|
|
if (done) break
|
|
buffer += decoder.decode(value, { stream: true })
|
|
let boundary = buffer.indexOf('\n\n')
|
|
while (boundary !== -1) {
|
|
const chunk = buffer.slice(0, boundary)
|
|
buffer = buffer.slice(boundary + 2)
|
|
processChunk(chunk)
|
|
boundary = buffer.indexOf('\n\n')
|
|
}
|
|
}
|
|
if (generation !== eventGeneration || disposed) return
|
|
throw new Error('The live feed closed.')
|
|
} catch {
|
|
if (controller.signal.aborted || generation !== eventGeneration || disposed) return
|
|
streamState.value = 'disconnected'
|
|
scheduleReconnect()
|
|
}
|
|
}
|
|
|
|
function scheduleReconnect() {
|
|
if (disposed || reconnectTimer !== null) return
|
|
const delay = BACKOFF[Math.min(retryIndex, BACKOFF.length - 1)] ?? 1000
|
|
retryIndex += 1
|
|
reconnectTimer = window.setTimeout(() => {
|
|
reconnectTimer = null
|
|
void connectEvents()
|
|
}, delay)
|
|
}
|
|
|
|
function handleLag() {
|
|
eventController?.abort()
|
|
streamState.value = 'disconnected'
|
|
void refetchNewest()
|
|
scheduleReconnect()
|
|
}
|
|
|
|
async function refetchNewest() {
|
|
try {
|
|
const page = await api.get<MessagePage>(`/rooms/${roomId.value}/messages`, { limit: 60 })
|
|
for (const message of page.messages) addMessage(message, true)
|
|
} catch {
|
|
// The next reconnect brings the durable backlog.
|
|
}
|
|
}
|
|
|
|
function connectPresence() {
|
|
if (disposed) return
|
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
const socket = new WebSocket(`${protocol}//${window.location.host}/api/rooms/${encodeURIComponent(roomId.value)}/presence`)
|
|
presenceSocket = socket
|
|
|
|
socket.onopen = () => {
|
|
presenceRetry = 0
|
|
if (typingActive.value) sendPresenceState(true)
|
|
}
|
|
|
|
socket.onmessage = (event) => {
|
|
if (typeof event.data !== 'string') return
|
|
try {
|
|
const parsed = JSON.parse(event.data) as unknown
|
|
if (!parsed || typeof parsed !== 'object') return
|
|
if ((parsed as { type?: unknown }).type !== 'presence') return
|
|
const list = (parsed as { peers?: unknown }).peers
|
|
if (!Array.isArray(list)) return
|
|
peers.value = list as PresencePeer[]
|
|
onlineIds.value = peers.value.map((peer) => peer.member_id)
|
|
} catch {
|
|
return
|
|
}
|
|
}
|
|
|
|
socket.onclose = () => {
|
|
if (presenceSocket !== socket || disposed) return
|
|
presenceSocket = null
|
|
if (presenceTimer !== null) return
|
|
const delay = BACKOFF[Math.min(presenceRetry, BACKOFF.length - 1)] ?? 1000
|
|
presenceRetry += 1
|
|
presenceTimer = window.setTimeout(() => {
|
|
presenceTimer = null
|
|
connectPresence()
|
|
}, delay)
|
|
}
|
|
|
|
socket.onerror = () => {
|
|
socket.close()
|
|
}
|
|
}
|
|
|
|
function sendPresenceState(typing: boolean) {
|
|
if (!presenceSocket || presenceSocket.readyState !== WebSocket.OPEN) return
|
|
presenceSocket.send(JSON.stringify({ state: { typing } }))
|
|
}
|
|
|
|
function onTyping(active: boolean) {
|
|
typingActive.value = active
|
|
sendPresenceState(active)
|
|
}
|
|
|
|
function readPaneWidth(): number | null {
|
|
try {
|
|
const stored = window.localStorage.getItem(PANE_WIDTH_KEY)
|
|
if (!stored) return null
|
|
const value = Number.parseInt(stored, 10)
|
|
return Number.isFinite(value) && value > 0 ? value : null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
function savePaneWidth(width: number) {
|
|
try {
|
|
window.localStorage.setItem(PANE_WIDTH_KEY, String(Math.round(width)))
|
|
} catch {
|
|
// A browser that refuses storage keeps the width for this visit.
|
|
}
|
|
}
|
|
|
|
function currentPaneElement(): HTMLElement | null {
|
|
return roomBody.value?.querySelector<HTMLElement>('.right-pane') ?? null
|
|
}
|
|
|
|
function onPaneResizeStart(event: PointerEvent) {
|
|
if (event.button !== 0) return
|
|
const pane = currentPaneElement()
|
|
if (!pane) return
|
|
event.preventDefault()
|
|
paneDrag = {
|
|
pointerId: event.pointerId,
|
|
startX: event.clientX,
|
|
startWidth: pane.getBoundingClientRect().width,
|
|
moved: false,
|
|
}
|
|
;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)
|
|
document.body.classList.add('pane-resizing')
|
|
}
|
|
|
|
function onPaneResizeMove(event: PointerEvent) {
|
|
if (!paneDrag || event.pointerId !== paneDrag.pointerId) return
|
|
const next = paneDrag.startWidth + paneDrag.startX - event.clientX
|
|
if (Math.abs(event.clientX - paneDrag.startX) >= 1) paneDrag.moved = true
|
|
paneWidth.value = clampPaneWidth(next)
|
|
}
|
|
|
|
function endPaneResize() {
|
|
if (!paneDrag) return
|
|
const moved = paneDrag.moved
|
|
paneDrag = null
|
|
document.body.classList.remove('pane-resizing')
|
|
if (moved && paneWidth.value !== null) savePaneWidth(paneWidth.value)
|
|
}
|
|
|
|
function onPaneResizeKey(event: KeyboardEvent) {
|
|
const pane = currentPaneElement()
|
|
const current = pane?.getBoundingClientRect().width ?? effectivePaneWidth.value ?? 0
|
|
const step = event.shiftKey ? 64 : 16
|
|
let next: number
|
|
switch (event.key) {
|
|
case 'ArrowLeft':
|
|
next = current + step
|
|
break
|
|
case 'ArrowRight':
|
|
next = current - step
|
|
break
|
|
case 'Home':
|
|
next = PANE_MIN_WIDTH
|
|
break
|
|
case 'End':
|
|
next = paneMaxWidth.value
|
|
break
|
|
default:
|
|
return
|
|
}
|
|
event.preventDefault()
|
|
const clamped = clampPaneWidth(next)
|
|
paneWidth.value = clamped
|
|
savePaneWidth(clamped)
|
|
}
|
|
|
|
function colorFor(message: Message): string | null {
|
|
if (!message.author_id) return null
|
|
return memberById.value.get(message.author_id)?.color ?? null
|
|
}
|
|
|
|
function avatarFor(message: Message): string | null {
|
|
if (!message.author_id) return null
|
|
const member = memberById.value.get(message.author_id)
|
|
if (!member?.avatar_updated_at) return null
|
|
return `/api/avatars/${member.account_id}?v=${member.avatar_updated_at}`
|
|
}
|
|
|
|
function isNearBottom(element: HTMLElement) {
|
|
return element.scrollHeight - element.scrollTop - element.clientHeight < 80
|
|
}
|
|
|
|
function scrollToBottom() {
|
|
const element = chatScroll.value
|
|
if (!element) return
|
|
element.scrollTop = element.scrollHeight
|
|
stick.value = true
|
|
newMessages.value = 0
|
|
}
|
|
|
|
function onScroll() {
|
|
const element = chatScroll.value
|
|
if (!element) return
|
|
if (isNearBottom(element)) {
|
|
stick.value = true
|
|
newMessages.value = 0
|
|
} else {
|
|
stick.value = false
|
|
}
|
|
}
|
|
|
|
let stickScheduled = false
|
|
|
|
/// Keep the newest turn card or message in view while the log grows,
|
|
/// unless the reader has scrolled away from the bottom.
|
|
function scheduleStick() {
|
|
if (!stick.value || suspendAutoScroll || stickScheduled) return
|
|
stickScheduled = true
|
|
void nextTick(() => {
|
|
stickScheduled = false
|
|
if (stick.value) scrollToBottom()
|
|
})
|
|
}
|
|
|
|
async function loadDetail() {
|
|
detailLoading.value = true
|
|
detailError.value = ''
|
|
try {
|
|
const response = await api.get<RoomDetailResponse>(`/rooms/${roomId.value}`)
|
|
detail.value = response
|
|
previewTarget.value = response.preview ?? null
|
|
if (onlineIds.value.length === 0) {
|
|
onlineIds.value = response.members.filter((member) => member.online).map((member) => member.id)
|
|
}
|
|
} catch (err) {
|
|
detailError.value = apiErrorMessage(err)
|
|
} finally {
|
|
detailLoading.value = false
|
|
}
|
|
}
|
|
|
|
async function loadMessages() {
|
|
messagesLoading.value = true
|
|
messagesError.value = ''
|
|
try {
|
|
const page = await api.get<MessagePage>(`/rooms/${roomId.value}/messages`, { limit: 60 })
|
|
for (const message of page.messages) addMessage(message, true)
|
|
hasMore.value = page.has_more
|
|
// Replay from the oldest loaded message, not the newest: the feed
|
|
// must also bring the turn_start and tool events that rebuild a
|
|
// completed turn's summary.
|
|
lastDurable = messages.value[0]?.seq ?? 0
|
|
} catch (err) {
|
|
messagesError.value = apiErrorMessage(err)
|
|
} finally {
|
|
messagesLoading.value = false
|
|
}
|
|
}
|
|
|
|
async function loadOlder() {
|
|
if (loadingOlder.value || !hasMore.value || messages.value.length === 0) return
|
|
const element = chatScroll.value
|
|
const previousHeight = element?.scrollHeight ?? 0
|
|
const previousTop = element?.scrollTop ?? 0
|
|
loadingOlder.value = true
|
|
suspendAutoScroll = true
|
|
try {
|
|
const oldest = messages.value[0]?.seq
|
|
const page = await api.get<MessagePage>(`/rooms/${roomId.value}/messages`, {
|
|
limit: 60,
|
|
before: oldest,
|
|
})
|
|
for (const message of page.messages) addMessage(message, true)
|
|
hasMore.value = page.has_more
|
|
await nextTick()
|
|
if (element) element.scrollTop = element.scrollHeight - previousHeight + previousTop
|
|
} catch (err) {
|
|
messagesError.value = apiErrorMessage(err)
|
|
} finally {
|
|
loadingOlder.value = false
|
|
await nextTick()
|
|
window.requestAnimationFrame(() => {
|
|
suspendAutoScroll = false
|
|
})
|
|
}
|
|
}
|
|
|
|
function onComposerResized() {
|
|
scheduleStick()
|
|
}
|
|
|
|
async function onSent(message: Message) {
|
|
addMessage(message, true)
|
|
stick.value = true
|
|
newMessages.value = 0
|
|
await nextTick()
|
|
scrollToBottom()
|
|
}
|
|
|
|
async function onSettingsUpdated(room: Room) {
|
|
if (detail.value) detail.value = { ...detail.value, room }
|
|
await loadDetail()
|
|
await rooms.refresh()
|
|
}
|
|
|
|
function onMemberRemoved(memberId: string) {
|
|
if (!detail.value) return
|
|
detail.value = {
|
|
...detail.value,
|
|
members: detail.value.members.filter((member) => member.id !== memberId),
|
|
}
|
|
onlineIds.value = onlineIds.value.filter((id) => id !== memberId)
|
|
}
|
|
|
|
async function onArchived() {
|
|
await rooms.refresh()
|
|
await navigateTo('/rooms', { replace: true })
|
|
}
|
|
|
|
onMounted(async () => {
|
|
paneWidth.value = readPaneWidth()
|
|
await loadDetail()
|
|
await loadMessages()
|
|
|
|
if (!detailError.value) {
|
|
await nextTick()
|
|
if (roomBody.value) {
|
|
paneBodyWidth.value = roomBody.value.clientWidth
|
|
paneBodyObserver = new ResizeObserver(() => {
|
|
paneBodyWidth.value = roomBody.value?.clientWidth ?? 0
|
|
})
|
|
paneBodyObserver.observe(roomBody.value)
|
|
}
|
|
scrollToBottom()
|
|
window.requestAnimationFrame(() => {
|
|
if (stick.value) scrollToBottom()
|
|
})
|
|
if (chatInner.value) {
|
|
chatObserver = new ResizeObserver(() => {
|
|
if (!stick.value || suspendAutoScroll) return
|
|
const element = chatScroll.value
|
|
if (element) element.scrollTop = element.scrollHeight
|
|
})
|
|
chatObserver.observe(chatInner.value)
|
|
}
|
|
void connectEvents()
|
|
connectPresence()
|
|
}
|
|
})
|
|
|
|
onBeforeUnmount(() => {
|
|
disposed = true
|
|
eventGeneration += 1
|
|
paneBodyObserver?.disconnect()
|
|
paneBodyObserver = null
|
|
document.body.classList.remove('pane-resizing')
|
|
chatObserver?.disconnect()
|
|
chatObserver = null
|
|
eventController?.abort()
|
|
eventController = null
|
|
if (reconnectTimer !== null) window.clearTimeout(reconnectTimer)
|
|
if (presenceTimer !== null) window.clearTimeout(presenceTimer)
|
|
presenceSocket?.close()
|
|
presenceSocket = null
|
|
})
|
|
</script>
|
|
|
|
<template>
|
|
<div v-if="detailLoading" class="page">
|
|
<p class="meta">Opening the room.</p>
|
|
</div>
|
|
|
|
<div v-else-if="detailError" class="page">
|
|
<h1 class="page-title">Room</h1>
|
|
<p class="form-error" role="alert">{{ detailError }}</p>
|
|
<p class="mt-4"><NuxtLink to="/rooms">Back to rooms</NuxtLink></p>
|
|
</div>
|
|
|
|
<div v-else-if="detail" class="room-shell">
|
|
<RoomTopBar
|
|
:room-name="detail.room.name"
|
|
:members="detail.members"
|
|
:online-ids="onlineIds"
|
|
:is-owner="isOwner"
|
|
:pane-open="paneOpen"
|
|
@people="peopleOpen = true"
|
|
@settings="settingsOpen = true"
|
|
@toggle-pane="paneOpen = !paneOpen"
|
|
/>
|
|
|
|
<div ref="roomBody" class="room-body" :style="paneStyle">
|
|
<div class="chat-column">
|
|
<div class="chat-area">
|
|
<div ref="chatScroll" class="chat-scroll" @scroll="onScroll">
|
|
<div ref="chatInner" class="chat-inner">
|
|
<button
|
|
v-if="hasMore"
|
|
type="button"
|
|
class="btn btn-sm btn-quiet chat-start"
|
|
:disabled="loadingOlder"
|
|
@click="loadOlder"
|
|
>
|
|
{{ loadingOlder ? 'Loading older messages' : 'Load older messages' }}
|
|
</button>
|
|
|
|
<p v-if="messagesError" class="form-error" role="alert">{{ messagesError }}</p>
|
|
<p v-if="messagesLoading && timeline.length === 0" class="meta">Loading the log.</p>
|
|
|
|
<p v-if="!messagesLoading && !messagesError && timeline.length === 0" class="empty">
|
|
No messages yet. Ask @rhema to start.
|
|
</p>
|
|
|
|
<template v-for="(entry, index) in timeline" :key="`${entry.kind}-${entry.seq}-${index}`">
|
|
<ChatMessage
|
|
v-if="entry.kind === 'message'"
|
|
:message="entry.message"
|
|
:color="colorFor(entry.message)"
|
|
:avatar="avatarFor(entry.message)"
|
|
/>
|
|
<p
|
|
v-else-if="entry.kind === 'notice'"
|
|
class="msg msg-system"
|
|
:class="{ 'msg-system-danger': entry.level === 'error' }"
|
|
>
|
|
{{ entry.text }}
|
|
</p>
|
|
<TurnActivityView v-else :activity="entry.activity" />
|
|
</template>
|
|
</div>
|
|
</div>
|
|
|
|
<button
|
|
v-if="newMessages > 0"
|
|
type="button"
|
|
class="btn btn-sm new-messages"
|
|
@click="scrollToBottom"
|
|
>
|
|
{{ newMessages }} new {{ newMessages === 1 ? 'message' : 'messages' }}
|
|
</button>
|
|
</div>
|
|
|
|
<div class="room-status" aria-live="polite">
|
|
<p v-if="streamError" class="room-status-line room-status-error">{{ streamError }}</p>
|
|
<p v-else-if="streamState === 'disconnected'" class="room-status-line">
|
|
Reconnecting to live updates.
|
|
</p>
|
|
<p v-if="agentWorking" class="room-status-line">Rhema is working...</p>
|
|
<p v-if="typingText" class="room-status-line">{{ typingText }}</p>
|
|
</div>
|
|
|
|
<ChatComposer
|
|
:room-id="roomId"
|
|
@sent="onSent"
|
|
@typing="onTyping"
|
|
@resized="onComposerResized"
|
|
/>
|
|
</div>
|
|
|
|
<div
|
|
v-if="paneOpen"
|
|
class="pane-resizer"
|
|
role="separator"
|
|
aria-orientation="vertical"
|
|
aria-label="Resize conversation and workspace panes"
|
|
:aria-valuemin="paneMinPercent"
|
|
:aria-valuemax="paneMaxPercent"
|
|
:aria-valuenow="paneValue"
|
|
:aria-valuetext="`${paneValue} percent`"
|
|
title="Drag to resize. Arrow keys also work."
|
|
tabindex="0"
|
|
@pointerdown="onPaneResizeStart"
|
|
@pointermove="onPaneResizeMove"
|
|
@pointerup="endPaneResize"
|
|
@pointercancel="endPaneResize"
|
|
@lostpointercapture="endPaneResize"
|
|
@keydown="onPaneResizeKey"
|
|
></div>
|
|
|
|
<RightPane
|
|
v-if="paneOpen"
|
|
:room-id="detail.room.id"
|
|
:room-name="detail.room.name"
|
|
:preview="previewTarget"
|
|
@close="paneOpen = false"
|
|
/>
|
|
</div>
|
|
|
|
<PeopleDialog
|
|
v-if="peopleOpen"
|
|
:room-id="detail.room.id"
|
|
:room-name="detail.room.name"
|
|
@close="peopleOpen = false"
|
|
@removed="onMemberRemoved"
|
|
/>
|
|
|
|
<RoomSettingsDialog
|
|
v-if="settingsOpen && isOwner"
|
|
:room="detail.room"
|
|
@close="settingsOpen = false"
|
|
@updated="onSettingsUpdated"
|
|
@archived="onArchived"
|
|
/>
|
|
</div>
|
|
</template>
|