feat: add the multiplayer room server and client
A room is one conversation, one ssh sandbox, and one agent. Accounts create rooms; friends join through a single-use invite link and a display name; the agent speaks only through the message tool. The server is Axum and SQLite. It serves the built Nuxt client, streams room events over SSE, and runs one serialized turn loop per room with turn-level steering copied from rhema-code. The client has the chat, preview iframe, read-only file pane, xterm terminal, and presence. Preview URLs are signed wildcard hosts, and the proxy tunnels HTTP over ssh direct-tcpip. HostAgent::step remains deferred in the framework.
This commit is contained in:
1 parent
04dd63c4ca
commit
0035f4e031
69 files changed
+22501
-48
No files matched your search
@@ -0,0 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { initials } from '~/utils/format'
|
||||
import { memberColorVar } from '~/utils/member'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
name: string
|
||||
color?: string | null
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
offline?: boolean
|
||||
}>(),
|
||||
{ color: null, size: 'md', offline: false },
|
||||
)
|
||||
|
||||
const style = computed(() => ({ '--member': memberColorVar(props.color) }))
|
||||
const className = computed(() => ({
|
||||
'avatar-lg': props.size === 'lg',
|
||||
'avatar-sm': props.size === 'sm',
|
||||
'avatar-offline': props.offline,
|
||||
}))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="avatar" :class="className" :style="style" :title="name" role="img" :aria-label="name">
|
||||
{{ initials(name) }}
|
||||
</span>
|
||||
</template>
|
||||
@@ -0,0 +1,108 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, useId } from 'vue'
|
||||
import { X } from 'lucide-vue-next'
|
||||
|
||||
const props = withDefaults(defineProps<{ title: string; description?: string; wide?: boolean }>(), {
|
||||
description: '',
|
||||
wide: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const titleId = useId()
|
||||
const descId = useId()
|
||||
const panel = ref<HTMLElement | null>(null)
|
||||
let previousFocus: HTMLElement | null = null
|
||||
let previousOverflow = ''
|
||||
|
||||
function focusable(): HTMLElement[] {
|
||||
if (!panel.value) return []
|
||||
const selector = [
|
||||
'a[href]',
|
||||
'button:not([disabled])',
|
||||
'input:not([disabled]):not([type="hidden"])',
|
||||
'select:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(',')
|
||||
return Array.from(panel.value.querySelectorAll<HTMLElement>(selector)).filter(
|
||||
(element) => element.offsetParent !== null,
|
||||
)
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault()
|
||||
emit('close')
|
||||
return
|
||||
}
|
||||
if (event.key !== 'Tab') return
|
||||
const items = focusable()
|
||||
if (items.length === 0) {
|
||||
event.preventDefault()
|
||||
panel.value?.focus()
|
||||
return
|
||||
}
|
||||
const first = items[0]
|
||||
const last = items[items.length - 1]
|
||||
const active = document.activeElement as HTMLElement | null
|
||||
if (event.shiftKey) {
|
||||
if (active === first || !panel.value?.contains(active)) {
|
||||
event.preventDefault()
|
||||
last?.focus()
|
||||
}
|
||||
} else if (active === last || !panel.value?.contains(active)) {
|
||||
event.preventDefault()
|
||||
first?.focus()
|
||||
}
|
||||
}
|
||||
|
||||
function onBackdrop(event: MouseEvent) {
|
||||
if (event.target === event.currentTarget) emit('close')
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
previousFocus = document.activeElement as HTMLElement | null
|
||||
previousOverflow = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
document.addEventListener('keydown', onKeydown)
|
||||
await nextTick()
|
||||
const preferred = panel.value?.querySelector<HTMLElement>('[autofocus]')
|
||||
const items = focusable()
|
||||
;(preferred ?? items[0] ?? panel.value)?.focus()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('keydown', onKeydown)
|
||||
document.body.style.overflow = previousOverflow
|
||||
previousFocus?.focus?.()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div class="dialog-backdrop" @mousedown="onBackdrop">
|
||||
<section
|
||||
ref="panel"
|
||||
class="dialog"
|
||||
:class="{ 'dialog-wide': wide }"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-labelledby="titleId"
|
||||
:aria-describedby="description ? descId : undefined"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="dialog-head">
|
||||
<div>
|
||||
<h2 :id="titleId" class="dialog-title">{{ props.title }}</h2>
|
||||
<p v-if="description" :id="descId" class="dialog-sub">{{ description }}</p>
|
||||
</div>
|
||||
<button type="button" class="icon-btn" aria-label="Close dialog" title="Close" @click="emit('close')">
|
||||
<X :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<slot />
|
||||
</section>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,136 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, ref } from 'vue'
|
||||
import { AtSign, Send } from 'lucide-vue-next'
|
||||
import type { Message, SendMessageResponse } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
|
||||
const props = defineProps<{ roomId: string }>()
|
||||
const emit = defineEmits<{ sent: [message: Message]; typing: [active: boolean] }>()
|
||||
|
||||
const api = useApi()
|
||||
const text = ref('')
|
||||
const sending = ref(false)
|
||||
const error = ref('')
|
||||
const input = ref<HTMLTextAreaElement | null>(null)
|
||||
let typingTimer: number | null = null
|
||||
let typingActive = false
|
||||
|
||||
function resize() {
|
||||
const element = input.value
|
||||
if (!element) return
|
||||
element.style.height = 'auto'
|
||||
element.style.height = `${element.scrollHeight}px`
|
||||
}
|
||||
|
||||
function notifyTyping(active: boolean) {
|
||||
if (typingActive === active) return
|
||||
typingActive = active
|
||||
emit('typing', active)
|
||||
}
|
||||
|
||||
function onInput() {
|
||||
resize()
|
||||
notifyTyping(true)
|
||||
if (typingTimer !== null) window.clearTimeout(typingTimer)
|
||||
typingTimer = window.setTimeout(() => {
|
||||
typingTimer = null
|
||||
notifyTyping(false)
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
function insertMention() {
|
||||
const element = input.value
|
||||
const current = text.value
|
||||
const start = element?.selectionStart ?? current.length
|
||||
const end = element?.selectionEnd ?? current.length
|
||||
const before = current.slice(0, start)
|
||||
const after = current.slice(end)
|
||||
const spacer = before.length > 0 && !/\s$/.test(before) ? ' ' : ''
|
||||
const insertion = `${spacer}@rhema `
|
||||
text.value = `${before}${insertion}${after}`
|
||||
const cursor = before.length + insertion.length
|
||||
void nextTick(() => {
|
||||
element?.focus()
|
||||
element?.setSelectionRange(cursor, cursor)
|
||||
resize()
|
||||
})
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.key !== 'Enter' || event.shiftKey || event.isComposing) return
|
||||
event.preventDefault()
|
||||
void send()
|
||||
}
|
||||
|
||||
async function send() {
|
||||
const value = text.value.trim()
|
||||
if (!value || sending.value) return
|
||||
sending.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await api.post<SendMessageResponse>(`/rooms/${props.roomId}/messages`, { text: value })
|
||||
text.value = ''
|
||||
if (typingTimer !== null) {
|
||||
window.clearTimeout(typingTimer)
|
||||
typingTimer = null
|
||||
}
|
||||
notifyTyping(false)
|
||||
emit('sent', response.message)
|
||||
await nextTick()
|
||||
resize()
|
||||
input.value?.focus()
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typingTimer !== null) window.clearTimeout(typingTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="composer">
|
||||
<div class="composer-inner">
|
||||
<label class="sr-only" for="room-composer">Message the room</label>
|
||||
<textarea
|
||||
id="room-composer"
|
||||
ref="input"
|
||||
v-model="text"
|
||||
class="composer-input"
|
||||
rows="1"
|
||||
placeholder="Message the room. Use @rhema to ask the agent."
|
||||
@input="onInput"
|
||||
@keydown="onKeydown"
|
||||
/>
|
||||
<div class="composer-actions">
|
||||
<span class="composer-hint">Enter sends, Shift+Enter adds a line.</span>
|
||||
<div class="composer-buttons">
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Insert @rhema mention"
|
||||
title="Insert @rhema mention"
|
||||
@click="insertMention"
|
||||
>
|
||||
<AtSign :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-primary btn-sm"
|
||||
:disabled="!text.trim() || sending"
|
||||
aria-label="Send message"
|
||||
title="Send"
|
||||
@click="send"
|
||||
>
|
||||
<Send :size="14" aria-hidden="true" />
|
||||
{{ sending ? 'Sending' : 'Send' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="error" class="form-error composer-error" role="alert">{{ error }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { Message } from '~/types'
|
||||
import { fullTime, relativeTime } from '~/utils/format'
|
||||
import { memberColorVar } from '~/utils/member'
|
||||
|
||||
const props = defineProps<{ message: Message; color?: string | null }>()
|
||||
|
||||
const segments = computed(() => {
|
||||
const parts = props.message.text.split(/(@rhema\b)/gi)
|
||||
return parts
|
||||
.filter((part) => part.length > 0)
|
||||
.map((part) => ({ text: part, mention: /^@rhema$/i.test(part) }))
|
||||
})
|
||||
|
||||
const style = computed(() => ({ '--member': memberColorVar(props.color) }))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="message.author_kind === 'system'" class="msg msg-system">
|
||||
{{ message.text }}
|
||||
</div>
|
||||
|
||||
<div v-else-if="message.author_kind === 'agent'" class="msg msg-agent">
|
||||
<div class="msg-head">
|
||||
<span class="msg-agent-label">rhema</span>
|
||||
<span class="msg-time" :title="fullTime(message.created_at)">{{ relativeTime(message.created_at) }}</span>
|
||||
</div>
|
||||
<div class="msg-text">
|
||||
<template v-for="(segment, index) in segments" :key="index">
|
||||
<span v-if="segment.mention" class="mention">{{ segment.text }}</span>
|
||||
<template v-else>{{ segment.text }}</template>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="msg">
|
||||
<div class="msg-head">
|
||||
<span class="msg-author member-name" :style="style">{{ message.author_name }}</span>
|
||||
<span class="msg-time" :title="fullTime(message.created_at)">{{ relativeTime(message.created_at) }}</span>
|
||||
</div>
|
||||
<div class="msg-text">
|
||||
<template v-for="(segment, index) in segments" :key="index">
|
||||
<span v-if="segment.mention" class="mention">{{ segment.text }}</span>
|
||||
<template v-else>{{ segment.text }}</template>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,190 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ChevronLeft, ChevronRight, File, Folder, Link as LinkIcon } from 'lucide-vue-next'
|
||||
import type { FileContentResponse, FileEntry, FileListResponse, GitSummaryResponse } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import { formatSize } from '~/utils/format'
|
||||
|
||||
const props = defineProps<{ roomId: string; roomName: string }>()
|
||||
const api = useApi()
|
||||
|
||||
const path = ref('.')
|
||||
const entries = ref<FileEntry[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const selected = ref<FileEntry | null>(null)
|
||||
const file = ref<FileContentResponse | null>(null)
|
||||
const fileLoading = ref(false)
|
||||
const fileError = ref('')
|
||||
|
||||
const git = ref<GitSummaryResponse | null>(null)
|
||||
const gitLoading = ref(false)
|
||||
const gitError = ref('')
|
||||
|
||||
let dirRequest = 0
|
||||
let fileRequest = 0
|
||||
|
||||
const segments = computed(() => (path.value === '.' ? [] : path.value.split('/').filter(Boolean)))
|
||||
const hasParent = computed(() => segments.value.length > 0)
|
||||
|
||||
const lineNumbers = computed(() => {
|
||||
const content = file.value?.content ?? ''
|
||||
const count = content === '' ? 1 : content.replace(/\n$/, '').split('\n').length
|
||||
return Array.from({ length: count }, (_, index) => index + 1).join('\n')
|
||||
})
|
||||
|
||||
function crumbPath(index: number) {
|
||||
return segments.value.slice(0, index + 1).join('/')
|
||||
}
|
||||
|
||||
async function loadDir(target: string) {
|
||||
const request = ++dirRequest
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await api.get<FileListResponse>(`/rooms/${props.roomId}/files`, { path: target })
|
||||
if (request !== dirRequest) return
|
||||
path.value = response.path
|
||||
entries.value = response.entries
|
||||
} catch (err) {
|
||||
if (request !== dirRequest) return
|
||||
entries.value = []
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
if (request === dirRequest) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function openFile(entry: FileEntry) {
|
||||
const request = ++fileRequest
|
||||
selected.value = entry
|
||||
file.value = null
|
||||
fileError.value = ''
|
||||
fileLoading.value = true
|
||||
try {
|
||||
const response = await api.get<FileContentResponse>(`/rooms/${props.roomId}/file`, { path: entry.path })
|
||||
if (request !== fileRequest) return
|
||||
file.value = response
|
||||
} catch (err) {
|
||||
if (request !== fileRequest) return
|
||||
fileError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
if (request === fileRequest) fileLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openEntry(entry: FileEntry) {
|
||||
if (entry.kind === 'dir') {
|
||||
selected.value = null
|
||||
file.value = null
|
||||
fileError.value = ''
|
||||
void loadDir(entry.path)
|
||||
} else {
|
||||
void openFile(entry)
|
||||
}
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
const parent = segments.value.slice(0, -1).join('/')
|
||||
void loadDir(parent)
|
||||
}
|
||||
|
||||
async function loadGit() {
|
||||
gitLoading.value = true
|
||||
gitError.value = ''
|
||||
try {
|
||||
git.value = await api.get<GitSummaryResponse>(`/rooms/${props.roomId}/git`)
|
||||
} catch (err) {
|
||||
gitError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
gitLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadDir('')
|
||||
void loadGit()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="files-pane">
|
||||
<div class="files">
|
||||
<div class="files-browser">
|
||||
<div class="crumbs">
|
||||
<button v-if="hasParent" type="button" class="crumb-back" @click="goBack">
|
||||
<ChevronLeft :size="12" aria-hidden="true" />
|
||||
Back
|
||||
</button>
|
||||
<div class="crumbs-row">
|
||||
<button type="button" class="crumb" @click="loadDir('')">Workspace</button>
|
||||
<template v-for="(segment, index) in segments" :key="crumbPath(index)">
|
||||
<ChevronRight :size="12" class="faint" aria-hidden="true" />
|
||||
<button type="button" class="crumb" @click="loadDir(crumbPath(index))">
|
||||
{{ segment }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="file-list">
|
||||
<p v-if="loading" class="meta pane-pad">Loading files.</p>
|
||||
<p v-else-if="error" class="form-error pane-pad">{{ error }}</p>
|
||||
<p v-else-if="entries.length === 0" class="empty pane-pad">This folder is empty.</p>
|
||||
<template v-else>
|
||||
<button
|
||||
v-for="entry in entries"
|
||||
:key="entry.path"
|
||||
type="button"
|
||||
class="file-row"
|
||||
:class="{ active: selected?.path === entry.path }"
|
||||
:title="entry.path"
|
||||
@click="openEntry(entry)"
|
||||
>
|
||||
<Folder v-if="entry.kind === 'dir'" :size="14" aria-hidden="true" />
|
||||
<LinkIcon v-else-if="entry.kind === 'link'" :size="14" aria-hidden="true" />
|
||||
<File v-else :size="14" aria-hidden="true" />
|
||||
<span class="file-row-name">{{ entry.name }}</span>
|
||||
<span v-if="entry.kind === 'file'" class="file-row-size">{{ formatSize(entry.size) }}</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="files-viewer">
|
||||
<template v-if="selected">
|
||||
<div class="viewer-head">
|
||||
<span class="viewer-path" :title="selected.path">{{ selected.path }}</span>
|
||||
<span v-if="file" class="file-row-size">{{ formatSize(file.size) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="viewer-scroll">
|
||||
<p v-if="fileLoading" class="meta pane-pad-3">Reading file.</p>
|
||||
<p v-else-if="fileError" class="form-error pane-pad-3">{{ fileError }}</p>
|
||||
<p v-else-if="file?.binary" class="meta pane-pad-3">Binary file. Preview is not available.</p>
|
||||
<p v-else-if="file && file.content === ''" class="meta pane-pad-3">This file is empty.</p>
|
||||
<template v-else-if="file">
|
||||
<pre class="gutter" aria-hidden="true">{{ lineNumbers }}</pre>
|
||||
<pre class="viewer-code">{{ file.content }}</pre>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<p v-if="file?.truncated" class="meta viewer-note">
|
||||
Showing the first 400 KB.
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<p v-else class="empty pane-pad-3">Select a file to read.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details class="git-strip">
|
||||
<summary>Git status</summary>
|
||||
<p v-if="gitLoading" class="meta pane-note">Reading git status.</p>
|
||||
<p v-else-if="gitError" class="form-error pane-note">{{ gitError }}</p>
|
||||
<pre v-else-if="git?.text">{{ git.text }}</pre>
|
||||
<p v-else class="meta pane-note">No git output.</p>
|
||||
</details>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import { Check, Copy } from 'lucide-vue-next'
|
||||
import type { Invite } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import { formatDate } from '~/utils/format'
|
||||
import BaseDialog from '~/components/BaseDialog.vue'
|
||||
|
||||
const props = defineProps<{ roomId: string; roomName: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const api = useApi()
|
||||
const invite = ref<Invite | null>(null)
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
const copied = ref(false)
|
||||
const linkInput = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const inviteUrl = computed(() => invite.value?.url ?? '')
|
||||
|
||||
async function create() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
invite.value = await api.post<Invite>(`/rooms/${props.roomId}/invites`)
|
||||
await nextTick()
|
||||
linkInput.value?.focus()
|
||||
linkInput.value?.select()
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
if (!inviteUrl.value) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(inviteUrl.value)
|
||||
copied.value = true
|
||||
window.setTimeout(() => {
|
||||
copied.value = false
|
||||
}, 1800)
|
||||
} catch {
|
||||
error.value = 'The clipboard is not available. Select the link and copy it by hand.'
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(create)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BaseDialog title="Invite people" @close="emit('close')">
|
||||
<p v-if="loading" class="meta">Creating the link.</p>
|
||||
<p v-else-if="error && !invite" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div v-if="invite" class="form">
|
||||
<div class="field">
|
||||
<label class="field-label" for="invite-url">Invite link</label>
|
||||
<div class="key-line">
|
||||
<input id="invite-url" ref="linkInput" class="input mono" :value="inviteUrl" readonly autofocus>
|
||||
<button type="button" class="btn" aria-label="Copy invite link" title="Copy invite link" @click="copy">
|
||||
<component :is="copied ? Check : Copy" :size="14" aria-hidden="true" />
|
||||
{{ copied ? 'Copied' : 'Copy' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="form-note">
|
||||
Anyone with this link can join {{ roomName }}. It works once and expires {{ formatDate(invite.expires_at) }}.
|
||||
</p>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
</div>
|
||||
|
||||
<div class="dialog-actions">
|
||||
<button type="button" class="btn" @click="emit('close')">Done</button>
|
||||
</div>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,190 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import type {
|
||||
CreateRoomBody,
|
||||
CreateRoomResponse,
|
||||
ProviderConfig,
|
||||
ProviderListResponse,
|
||||
SandboxListResponse,
|
||||
SandboxTarget,
|
||||
} from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import BaseDialog from '~/components/BaseDialog.vue'
|
||||
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const api = useApi()
|
||||
const router = useRouter()
|
||||
const rooms = useRooms()
|
||||
|
||||
const providers = ref<ProviderConfig[]>([])
|
||||
const targets = ref<SandboxTarget[]>([])
|
||||
const loading = ref(true)
|
||||
const loadError = ref('')
|
||||
|
||||
const name = ref('')
|
||||
const providerId = ref('')
|
||||
const targetId = ref('')
|
||||
const workspace = ref('')
|
||||
const repoUrl = ref('')
|
||||
const model = ref('')
|
||||
|
||||
const submitting = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const canSubmit = computed(
|
||||
() => !loading.value && !submitting.value && !!name.value.trim() && !!providerId.value && !!targetId.value,
|
||||
)
|
||||
|
||||
const missing = computed(() => {
|
||||
if (loading.value) return ''
|
||||
if (providers.value.length === 0 && targets.value.length === 0) {
|
||||
return 'Add a provider and a sandbox in settings before creating a room.'
|
||||
}
|
||||
if (providers.value.length === 0) return 'Add a provider in settings before creating a room.'
|
||||
if (targets.value.length === 0) return 'Add a sandbox in settings before creating a room.'
|
||||
return ''
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const [providerList, targetList] = await Promise.all([
|
||||
api.get<ProviderListResponse>('/provider-configs'),
|
||||
api.get<SandboxListResponse>('/sandbox-targets'),
|
||||
])
|
||||
providers.value = providerList.providers
|
||||
targets.value = targetList.targets
|
||||
providerId.value = providers.value[0]?.id ?? ''
|
||||
targetId.value = targets.value[0]?.id ?? ''
|
||||
const current = providers.value.find((provider) => provider.id === providerId.value)
|
||||
model.value = current?.model ?? ''
|
||||
} catch (err) {
|
||||
loadError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
|
||||
function onProviderChange() {
|
||||
const current = providers.value.find((provider) => provider.id === providerId.value)
|
||||
if (current && !model.value.trim()) model.value = current.model
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!canSubmit.value) return
|
||||
submitting.value = true
|
||||
error.value = ''
|
||||
const body: CreateRoomBody = {
|
||||
name: name.value.trim(),
|
||||
provider_config_id: providerId.value,
|
||||
sandbox_target_id: targetId.value,
|
||||
}
|
||||
if (workspace.value.trim()) body.workspace = workspace.value.trim()
|
||||
if (repoUrl.value.trim()) body.repo_url = repoUrl.value.trim()
|
||||
if (model.value.trim()) body.model = model.value.trim()
|
||||
try {
|
||||
const response = await api.post<CreateRoomResponse>('/rooms', body)
|
||||
await rooms.refresh()
|
||||
emit('close')
|
||||
await router.push(`/room/${response.room.id}`)
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BaseDialog title="New room" description="A room has one workspace, one provider, and one shared log." @close="emit('close')">
|
||||
<p v-if="loading" class="meta">Loading providers and sandboxes.</p>
|
||||
<p v-else-if="loadError" class="form-error">{{ loadError }}</p>
|
||||
|
||||
<form class="form" @submit.prevent="submit">
|
||||
<p v-if="missing" class="form-note">
|
||||
{{ missing }}
|
||||
<NuxtLink to="/settings" @click="emit('close')">Open settings</NuxtLink>
|
||||
</p>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-name">Room name</label>
|
||||
<input
|
||||
id="new-room-name"
|
||||
v-model="name"
|
||||
class="input"
|
||||
type="text"
|
||||
maxlength="60"
|
||||
autocomplete="off"
|
||||
autofocus
|
||||
required
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-provider">Provider</label>
|
||||
<select
|
||||
id="new-room-provider"
|
||||
v-model="providerId"
|
||||
class="select"
|
||||
:disabled="providers.length === 0"
|
||||
required
|
||||
@change="onProviderChange"
|
||||
>
|
||||
<option v-for="provider in providers" :key="provider.id" :value="provider.id">
|
||||
{{ provider.name }} ({{ provider.kind }})
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-sandbox">Sandbox</label>
|
||||
<select id="new-room-sandbox" v-model="targetId" class="select" :disabled="targets.length === 0" required>
|
||||
<option v-for="target in targets" :key="target.id" :value="target.id">
|
||||
{{ target.name }} ({{ target.user_name }}@{{ target.host }}:{{ target.port }})
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-model">Model <span class="field-optional">optional</span></label>
|
||||
<input id="new-room-model" v-model="model" class="input" type="text" autocomplete="off">
|
||||
<span class="hint">Leave this as the provider model unless the room needs another one.</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-workspace">Workspace <span class="field-optional">optional</span></label>
|
||||
<input
|
||||
id="new-room-workspace"
|
||||
v-model="workspace"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
placeholder="/root/my-project"
|
||||
>
|
||||
<span class="hint">An absolute path. Without one, the server creates a directory under the sandbox workspace root.</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-repo">Repository <span class="field-optional">optional</span></label>
|
||||
<input
|
||||
id="new-room-repo"
|
||||
v-model="repoUrl"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
placeholder="https://github.com/owner/project.git"
|
||||
>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div class="dialog-actions">
|
||||
<button type="button" class="btn btn-quiet" @click="emit('close')">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary" :disabled="!canSubmit">
|
||||
{{ submitting ? 'Creating' : 'Create room' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,105 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { Maximize2, Minimize2, X } from 'lucide-vue-next'
|
||||
|
||||
const props = defineProps<{ roomId: string }>()
|
||||
|
||||
const port = ref<number | string>(3000)
|
||||
const url = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const fullscreen = ref(false)
|
||||
|
||||
async function load() {
|
||||
const value = Number(port.value)
|
||||
if (!Number.isInteger(value) || value < 1 || value > 65535) {
|
||||
error.value = 'Enter a port between 1 and 65535.'
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await fetch(`/api/rooms/${encodeURIComponent(props.roomId)}/preview?port=${value}`, {
|
||||
credentials: 'include',
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
if (response.status === 401) {
|
||||
await navigateTo('/login')
|
||||
return
|
||||
}
|
||||
const type = response.headers.get('content-type') ?? ''
|
||||
if (!type.includes('application/json')) {
|
||||
throw new Error('The server did not return a preview address.')
|
||||
}
|
||||
const body: unknown = await response.json()
|
||||
if (!response.ok) {
|
||||
const message = body && typeof body === 'object' && 'error' in body
|
||||
? String((body as { error: unknown }).error)
|
||||
: 'The preview could not be opened.'
|
||||
throw new Error(message)
|
||||
}
|
||||
if (!body || typeof body !== 'object' || typeof (body as { url?: unknown }).url !== 'string') {
|
||||
throw new Error('The server returned no preview address.')
|
||||
}
|
||||
url.value = (body as { url: string }).url
|
||||
} catch (err) {
|
||||
url.value = ''
|
||||
error.value = err instanceof Error ? err.message : 'The preview could not be opened.'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function toggleFullscreen() {
|
||||
fullscreen.value = !fullscreen.value
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="preview-wrap" :class="{ 'preview-full': fullscreen }">
|
||||
<div class="preview-bar">
|
||||
<label class="sr-only" for="preview-port">Port</label>
|
||||
<input
|
||||
id="preview-port"
|
||||
v-model.number="port"
|
||||
class="input port-field"
|
||||
type="number"
|
||||
min="1"
|
||||
max="65535"
|
||||
aria-label="Preview port"
|
||||
>
|
||||
<button type="button" class="btn btn-sm" :disabled="loading" @click="load">
|
||||
{{ loading ? 'Opening' : url ? 'Reload' : 'Go' }}
|
||||
</button>
|
||||
<div class="room-topbar-spacer" />
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
:aria-label="fullscreen ? 'Exit full screen preview' : 'Full screen preview'"
|
||||
:title="fullscreen ? 'Exit full screen' : 'Full screen'"
|
||||
@click="toggleFullscreen"
|
||||
>
|
||||
<component :is="fullscreen ? Minimize2 : Maximize2" :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
v-if="fullscreen"
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Close full screen preview"
|
||||
title="Close full screen preview"
|
||||
@click="fullscreen = false"
|
||||
>
|
||||
<X :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="preview-message form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div v-if="url" class="preview-frame-wrap">
|
||||
<iframe class="preview-frame" :src="url" :title="`Preview on port ${port}`" />
|
||||
</div>
|
||||
<p v-else-if="!error" class="preview-message">
|
||||
Enter the port the room serves and choose Go.
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { Eye, FolderTree, PanelRightClose, Terminal } from 'lucide-vue-next'
|
||||
|
||||
type Tab = 'terminal' | 'preview' | 'files'
|
||||
|
||||
defineProps<{ roomId: string; roomName: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const tab = ref<Tab>('files')
|
||||
const tabs: Array<{ id: Tab; label: string; icon: typeof Terminal }> = [
|
||||
{ id: 'terminal', label: 'Terminal', icon: Terminal },
|
||||
{ id: 'preview', label: 'Preview', icon: Eye },
|
||||
{ id: 'files', label: 'Files', icon: FolderTree },
|
||||
]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="right-pane right-pane-overlay" aria-label="Workspace panes">
|
||||
<div class="pane-head">
|
||||
<div class="pane-tabs" role="tablist" aria-label="Workspace panels">
|
||||
<button
|
||||
v-for="item in tabs"
|
||||
:key="item.id"
|
||||
type="button"
|
||||
class="pane-tab"
|
||||
:class="{ active: tab === item.id }"
|
||||
role="tab"
|
||||
:id="`pane-tab-${item.id}`"
|
||||
:aria-selected="tab === item.id"
|
||||
aria-controls="pane-panel"
|
||||
@click="tab = item.id"
|
||||
>
|
||||
<component :is="item.icon" :size="14" aria-hidden="true" />
|
||||
{{ item.label }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Close side pane"
|
||||
title="Close side pane"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<PanelRightClose :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="pane-panel" class="pane-body" role="tabpanel" :aria-labelledby="`pane-tab-${tab}`">
|
||||
<FilesPane v-if="tab === 'files'" :room-id="roomId" :room-name="roomName" />
|
||||
<TerminalPane v-else-if="tab === 'terminal'" :room-id="roomId" />
|
||||
<PreviewPane v-else :room-id="roomId" />
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
@@ -0,0 +1,151 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import type {
|
||||
ProviderConfig,
|
||||
ProviderListResponse,
|
||||
Room,
|
||||
UpdateRoomBody,
|
||||
UpdateRoomResponse,
|
||||
} from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import BaseDialog from '~/components/BaseDialog.vue'
|
||||
|
||||
const props = defineProps<{ room: Room }>()
|
||||
const emit = defineEmits<{ close: []; updated: [room: Room]; archived: [] }>()
|
||||
|
||||
const api = useApi()
|
||||
|
||||
const providers = ref<ProviderConfig[]>([])
|
||||
const loadingProviders = ref(true)
|
||||
const providersError = ref('')
|
||||
|
||||
const name = ref(props.room.name)
|
||||
const providerId = ref(props.room.provider_config_id ?? '')
|
||||
const model = ref(props.room.model ?? '')
|
||||
const maxSteps = ref<number | string>(props.room.max_turn_steps)
|
||||
|
||||
const saving = ref(false)
|
||||
const error = ref('')
|
||||
const archiving = ref(false)
|
||||
const confirmingArchive = ref(false)
|
||||
const archiveError = ref('')
|
||||
|
||||
const canSave = computed(() => !saving.value && name.value.trim().length > 0)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const list = await api.get<ProviderListResponse>('/provider-configs')
|
||||
providers.value = list.providers
|
||||
} catch (err) {
|
||||
providersError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loadingProviders.value = false
|
||||
}
|
||||
})
|
||||
|
||||
async function save() {
|
||||
if (!canSave.value) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
const body: UpdateRoomBody = {
|
||||
name: name.value.trim(),
|
||||
max_turn_steps: Math.min(500, Math.max(1, Math.round(Number(maxSteps.value) || 1))),
|
||||
}
|
||||
if (providerId.value) body.provider_config_id = providerId.value
|
||||
if (model.value.trim()) body.model = model.value.trim()
|
||||
try {
|
||||
const response = await api.patch<UpdateRoomResponse>(`/rooms/${props.room.id}`, body)
|
||||
emit('updated', response.room)
|
||||
emit('close')
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function archive() {
|
||||
if (archiving.value) return
|
||||
archiving.value = true
|
||||
archiveError.value = ''
|
||||
try {
|
||||
await api.del(`/rooms/${props.room.id}`)
|
||||
emit('archived')
|
||||
emit('close')
|
||||
} catch (err) {
|
||||
archiveError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
archiving.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BaseDialog title="Room settings" @close="emit('close')">
|
||||
<form class="form" @submit.prevent="save">
|
||||
<div class="field">
|
||||
<label class="field-label" for="room-settings-name">Name</label>
|
||||
<input id="room-settings-name" v-model="name" class="input" type="text" maxlength="60" autofocus required>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="room-settings-provider">Provider</label>
|
||||
<select id="room-settings-provider" v-model="providerId" class="select" :disabled="loadingProviders">
|
||||
<option v-if="!room.provider_config_id" value="" disabled>No provider selected</option>
|
||||
<option v-for="provider in providers" :key="provider.id" :value="provider.id">
|
||||
{{ provider.name }} ({{ provider.kind }})
|
||||
</option>
|
||||
</select>
|
||||
<span v-if="loadingProviders" class="hint">Loading providers.</span>
|
||||
<span v-else-if="providersError" class="form-error">{{ providersError }}</span>
|
||||
<span v-else-if="providers.length === 0" class="hint">
|
||||
No providers yet. <NuxtLink to="/settings">Add one in settings</NuxtLink>.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="room-settings-model">Model</label>
|
||||
<input id="room-settings-model" v-model="model" class="input" type="text" spellcheck="false">
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="room-settings-steps">Max turn steps</label>
|
||||
<input id="room-settings-steps" v-model.number="maxSteps" class="input" type="number" min="1" max="500" required>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div class="dialog-actions">
|
||||
<button type="button" class="btn btn-quiet" @click="emit('close')">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary" :disabled="!canSave">
|
||||
{{ saving ? 'Saving' : 'Save changes' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="section archive-section">
|
||||
<h3 class="panel-title">Archive</h3>
|
||||
<p class="hint">
|
||||
Archiving hides the room and stops its sandbox. The log and files stay on disk.
|
||||
</p>
|
||||
<p v-if="archiveError" class="form-error" role="alert">{{ archiveError }}</p>
|
||||
<div v-if="confirmingArchive" class="confirm-line mt-2">
|
||||
<span>Archive {{ room.name }}?</span>
|
||||
<button type="button" class="btn btn-sm btn-quiet" :disabled="archiving" @click="confirmingArchive = false">
|
||||
Cancel
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-danger" :disabled="archiving" @click="archive">
|
||||
{{ archiving ? 'Archiving' : 'Archive room' }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="btn btn-danger mt-2"
|
||||
@click="confirmingArchive = true"
|
||||
>
|
||||
Archive room
|
||||
</button>
|
||||
</div>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { PanelRight, PanelRightClose, Settings, UserPlus } from 'lucide-vue-next'
|
||||
import type { Member } from '~/types'
|
||||
|
||||
const props = defineProps<{
|
||||
roomName: string
|
||||
members: Member[]
|
||||
onlineIds: string[]
|
||||
isOwner: boolean
|
||||
paneOpen: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ invite: []; togglePane: []; settings: [] }>()
|
||||
|
||||
const online = computed(() => new Set(props.onlineIds))
|
||||
const visible = computed(() => props.members.slice(0, 5))
|
||||
const extra = computed(() => props.members.slice(5))
|
||||
const extraTitle = computed(() => extra.value.map((member) => member.display_name).join(', '))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="room-topbar">
|
||||
<h1 class="room-name">{{ roomName }}</h1>
|
||||
|
||||
<div class="room-topbar-spacer" />
|
||||
|
||||
<div class="presence">
|
||||
<div class="presence-avatars" aria-label="Room members">
|
||||
<AppAvatar
|
||||
v-for="member in visible"
|
||||
:key="member.id"
|
||||
:name="member.display_name"
|
||||
:color="member.color"
|
||||
:offline="!online.has(member.id)"
|
||||
size="sm"
|
||||
/>
|
||||
<span v-if="extra.length > 0" class="small muted" :title="extraTitle">+{{ extra.length }}</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Invite people"
|
||||
title="Invite people"
|
||||
@click="emit('invite')"
|
||||
>
|
||||
<UserPlus :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
:aria-label="paneOpen ? 'Close side pane' : 'Open side pane'"
|
||||
:title="paneOpen ? 'Close side pane' : 'Open side pane'"
|
||||
@click="emit('togglePane')"
|
||||
>
|
||||
<component :is="paneOpen ? PanelRightClose : PanelRight" :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
v-if="isOwner"
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Room settings"
|
||||
title="Room settings"
|
||||
@click="emit('settings')"
|
||||
>
|
||||
<Settings :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
@@ -0,0 +1,249 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import '@xterm/xterm/css/xterm.css'
|
||||
import type { FitAddon as FitAddonInstance } from '@xterm/addon-fit'
|
||||
import type { Terminal as TerminalInstance } from '@xterm/xterm'
|
||||
|
||||
const props = defineProps<{ roomId: string }>()
|
||||
|
||||
type Status = 'connecting' | 'connected' | 'disconnected'
|
||||
|
||||
const host = ref<HTMLElement | null>(null)
|
||||
const status = ref<Status>('connecting')
|
||||
const detail = ref('')
|
||||
const exitCode = ref<number | null>(null)
|
||||
|
||||
let term: TerminalInstance | null = null
|
||||
let fit: FitAddonInstance | null = null
|
||||
let socket: WebSocket | null = null
|
||||
let observer: ResizeObserver | null = null
|
||||
let resizeFrame = 0
|
||||
let disposed = false
|
||||
|
||||
function token(name: string): string {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(name).trim()
|
||||
}
|
||||
|
||||
function terminalTheme() {
|
||||
return {
|
||||
background: token('--surface-2'),
|
||||
foreground: token('--text'),
|
||||
cursor: token('--accent'),
|
||||
cursorAccent: token('--surface-2'),
|
||||
selectionBackground: token('--accent-soft'),
|
||||
black: token('--ansi-black'),
|
||||
red: token('--ansi-red'),
|
||||
green: token('--ansi-green'),
|
||||
yellow: token('--ansi-yellow'),
|
||||
blue: token('--ansi-blue'),
|
||||
magenta: token('--ansi-magenta'),
|
||||
cyan: token('--ansi-cyan'),
|
||||
white: token('--ansi-white'),
|
||||
brightBlack: token('--ansi-bright-black'),
|
||||
brightRed: token('--ansi-bright-red'),
|
||||
brightGreen: token('--ansi-bright-green'),
|
||||
brightYellow: token('--ansi-bright-yellow'),
|
||||
brightBlue: token('--ansi-bright-blue'),
|
||||
brightMagenta: token('--ansi-bright-magenta'),
|
||||
brightCyan: token('--ansi-bright-cyan'),
|
||||
brightWhite: token('--ansi-bright-white'),
|
||||
}
|
||||
}
|
||||
|
||||
function sendResize() {
|
||||
if (!term || !socket || socket.readyState !== WebSocket.OPEN) return
|
||||
socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
||||
}
|
||||
|
||||
function fitTerminal() {
|
||||
if (!fit) return
|
||||
try {
|
||||
fit.fit()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
sendResize()
|
||||
}
|
||||
|
||||
function scheduleFit() {
|
||||
if (typeof window === 'undefined') return
|
||||
if (resizeFrame) window.cancelAnimationFrame(resizeFrame)
|
||||
resizeFrame = window.requestAnimationFrame(() => {
|
||||
resizeFrame = 0
|
||||
fitTerminal()
|
||||
})
|
||||
}
|
||||
|
||||
function closeSocket() {
|
||||
if (!socket) return
|
||||
socket.onopen = null
|
||||
socket.onmessage = null
|
||||
socket.onerror = null
|
||||
socket.onclose = null
|
||||
try {
|
||||
socket.close()
|
||||
} catch {
|
||||
// Already closed.
|
||||
}
|
||||
socket = null
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (disposed) return
|
||||
closeSocket()
|
||||
term?.reset()
|
||||
status.value = 'connecting'
|
||||
detail.value = ''
|
||||
exitCode.value = null
|
||||
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const url = `${protocol}//${window.location.host}/api/rooms/${encodeURIComponent(props.roomId)}/terminal`
|
||||
const next = new WebSocket(url)
|
||||
next.binaryType = 'arraybuffer'
|
||||
socket = next
|
||||
|
||||
next.onopen = () => {
|
||||
if (socket !== next) return
|
||||
scheduleFit()
|
||||
}
|
||||
|
||||
next.onmessage = (event) => {
|
||||
if (socket !== next) return
|
||||
if (typeof event.data === 'string') {
|
||||
try {
|
||||
const message: unknown = JSON.parse(event.data)
|
||||
if (!message || typeof message !== 'object') return
|
||||
const type = 'type' in message ? message.type : null
|
||||
if (type === 'ready') {
|
||||
status.value = 'connected'
|
||||
detail.value = ''
|
||||
sendResize()
|
||||
term?.focus()
|
||||
} else if (type === 'error') {
|
||||
status.value = 'disconnected'
|
||||
detail.value = typeof (message as { message?: unknown }).message === 'string'
|
||||
? String((message as { message: unknown }).message)
|
||||
: 'The terminal reported an error.'
|
||||
} else if (type === 'exit') {
|
||||
status.value = 'disconnected'
|
||||
const code = (message as { code?: unknown }).code
|
||||
exitCode.value = typeof code === 'number' ? code : null
|
||||
}
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (event.data instanceof ArrayBuffer) {
|
||||
term?.write(new Uint8Array(event.data))
|
||||
} else if (event.data instanceof Blob) {
|
||||
void event.data.arrayBuffer().then((buffer) => term?.write(new Uint8Array(buffer)))
|
||||
}
|
||||
}
|
||||
|
||||
next.onerror = () => {
|
||||
if (socket !== next) return
|
||||
if (status.value !== 'disconnected') {
|
||||
status.value = 'disconnected'
|
||||
detail.value = 'The connection failed.'
|
||||
}
|
||||
}
|
||||
|
||||
next.onclose = () => {
|
||||
if (socket !== next) return
|
||||
socket = null
|
||||
if (status.value !== 'disconnected') {
|
||||
status.value = 'disconnected'
|
||||
detail.value = 'The connection closed.'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function reconnect() {
|
||||
connect()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await nextTick()
|
||||
const [{ Terminal }, { FitAddon }] = await Promise.all([
|
||||
import('@xterm/xterm'),
|
||||
import('@xterm/addon-fit'),
|
||||
])
|
||||
if (!host.value) return
|
||||
|
||||
term = new Terminal({
|
||||
convertEol: false,
|
||||
cursorBlink: true,
|
||||
fontFamily: getComputedStyle(document.documentElement).getPropertyValue('--font-mono').trim(),
|
||||
fontSize: Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--fs-code')) || 13,
|
||||
scrollback: 3000,
|
||||
theme: terminalTheme(),
|
||||
})
|
||||
fit = new FitAddon()
|
||||
term.loadAddon(fit)
|
||||
term.open(host.value)
|
||||
term.onData((data) => {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) return
|
||||
socket.send(new TextEncoder().encode(data))
|
||||
})
|
||||
|
||||
observer = new ResizeObserver(() => {
|
||||
scheduleFit()
|
||||
})
|
||||
observer.observe(host.value)
|
||||
|
||||
term.focus()
|
||||
scheduleFit()
|
||||
connect()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
if (observer) {
|
||||
observer.disconnect()
|
||||
observer = null
|
||||
}
|
||||
if (resizeFrame) {
|
||||
window.cancelAnimationFrame(resizeFrame)
|
||||
resizeFrame = 0
|
||||
}
|
||||
closeSocket()
|
||||
term?.dispose()
|
||||
term = null
|
||||
fit = null
|
||||
})
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (status.value === 'connected') return 'Connected'
|
||||
if (status.value === 'connecting') return 'Connecting'
|
||||
return 'Disconnected'
|
||||
})
|
||||
|
||||
function focusTerminal() {
|
||||
term?.focus()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="terminal-wrap">
|
||||
<div class="terminal-bar">
|
||||
<span class="terminal-status">
|
||||
{{ statusText }}
|
||||
<template v-if="exitCode !== null">, exit {{ exitCode }}</template>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm"
|
||||
:disabled="status === 'connecting'"
|
||||
aria-label="Reconnect terminal"
|
||||
title="Reconnect terminal"
|
||||
@click="reconnect"
|
||||
>
|
||||
Reconnect
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="detail" class="form-error pane-pad">{{ detail }}</p>
|
||||
<div ref="host" class="terminal-host" @click="focusTerminal" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,121 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { ToolActivity, TurnActivity } from '~/types'
|
||||
import { formatCost } from '~/utils/format'
|
||||
|
||||
const props = defineProps<{ activity: TurnActivity }>()
|
||||
|
||||
const stateLabel = computed(() => {
|
||||
switch (props.activity.status) {
|
||||
case 'running':
|
||||
return 'is working'
|
||||
case 'error':
|
||||
return 'failed'
|
||||
case 'interrupted':
|
||||
return 'stopped'
|
||||
case 'step_limit':
|
||||
return 'hit the step limit'
|
||||
case 'max_tokens':
|
||||
return 'hit the token limit'
|
||||
default:
|
||||
return 'finished'
|
||||
}
|
||||
})
|
||||
|
||||
const usageText = computed(() => {
|
||||
const usage = props.activity.usage
|
||||
if (!usage) return ''
|
||||
const parts = [
|
||||
`${usage.input_tokens.toLocaleString()} in`,
|
||||
`${usage.output_tokens.toLocaleString()} out`,
|
||||
]
|
||||
if (usage.cached_input_tokens > 0) parts.push(`${usage.cached_input_tokens.toLocaleString()} cached`)
|
||||
const cost = formatCost(usage.cost_usd)
|
||||
if (cost) parts.push(cost)
|
||||
return parts.join(', ')
|
||||
})
|
||||
|
||||
function parseArgs(raw: string): Record<string, unknown> | null {
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed.startsWith('{')) return null
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(trimmed)
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function toolSummary(tool: ToolActivity): string {
|
||||
if (!tool.args.trim()) return ''
|
||||
const parsed = parseArgs(tool.args)
|
||||
let summary = tool.args.trim()
|
||||
if (parsed) {
|
||||
summary = JSON.stringify(parsed)
|
||||
for (const key of ['command', 'cmd', 'path', 'file_path', 'pattern', 'url', 'query']) {
|
||||
const value = parsed[key]
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
summary = value.trim()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return summary.length > 240 ? `${summary.slice(0, 240)}...` : summary
|
||||
}
|
||||
|
||||
function outputText(tool: ToolActivity): string {
|
||||
return tool.content ?? tool.output
|
||||
}
|
||||
|
||||
function toolLabel(tool: ToolActivity): string {
|
||||
return tool.name || 'tool'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="activity">
|
||||
<div class="activity-head">
|
||||
<div class="row">
|
||||
<span class="activity-label">rhema</span>
|
||||
<span class="activity-steps">{{ stateLabel }}</span>
|
||||
</div>
|
||||
<span v-if="activity.steps > 0" class="activity-state">
|
||||
{{ activity.steps }} {{ activity.steps === 1 ? 'step' : 'steps' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<details v-if="activity.thinking" class="activity-draft">
|
||||
<summary>thinking</summary>
|
||||
<div>{{ activity.thinking }}</div>
|
||||
</details>
|
||||
|
||||
<details v-if="activity.text" class="activity-draft">
|
||||
<summary>draft</summary>
|
||||
<div>{{ activity.text }}</div>
|
||||
</details>
|
||||
|
||||
<div v-for="tool in activity.tools" :key="tool.call_id" class="tool">
|
||||
<div class="tool-head">
|
||||
<span class="tool-name">{{ toolLabel(tool) }}</span>
|
||||
<span v-if="tool.isError" class="tool-state tool-error">failed</span>
|
||||
<span v-else-if="tool.done && tool.code !== null" class="tool-state">exit {{ tool.code }}</span>
|
||||
<span v-else-if="!tool.done" class="tool-state">running</span>
|
||||
<span v-else class="tool-state">done</span>
|
||||
</div>
|
||||
<div v-if="toolSummary(tool)" class="tool-args">{{ toolSummary(tool) }}</div>
|
||||
<details v-if="tool.done && outputText(tool)">
|
||||
<summary>output</summary>
|
||||
<pre class="code-block tool-output">{{ outputText(tool) }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div v-if="activity.status === 'error' && activity.error" class="activity-error">{{ activity.error }}</div>
|
||||
|
||||
<div v-if="usageText" class="activity-foot">
|
||||
<span>{{ usageText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
Reference in new issue
Block a user