diff --git a/.claude/skills/setup/SKILL.md b/.claude/skills/setup/SKILL.md index f150c38..5428a92 100644 --- a/.claude/skills/setup/SKILL.md +++ b/.claude/skills/setup/SKILL.md @@ -56,7 +56,7 @@ Codex 관련 선택 설정은 **별도 서비스 파일이 아니라 같은 `.en ```bash # 같은 .env 또는 서비스 Environment=에 추가 가능 -CODEX_MODEL=gpt-5.4 +CODEX_MODEL=gpt-5.5 CODEX_EFFORT=xhigh OPENAI_API_KEY=... ``` diff --git a/.env.example b/.env.example index 23e11f6..19c98a3 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,7 @@ DISCORD_ARBITER_BOT_TOKEN= # Arbiter bot # --- Agent type configuration --- OWNER_AGENT_TYPE=codex # codex | claude-code REVIEWER_AGENT_TYPE=claude-code # claude-code | codex +# ARBITER_AGENT_TYPE=codex # optional: codex | claude-code # --- API keys --- CLAUDE_CODE_OAUTH_TOKENS= # Canonical comma-separated Claude Code OAuth tokens (use one value for single-account too) @@ -23,18 +24,31 @@ GROQ_API_KEY= # Voice transcription (Groq Whisper, free: ASSISTANT_NAME=claude # Trigger name (@claude) # --- Claude model --- -CLAUDE_MODEL=claude-opus-4-6 # Claude model +CLAUDE_MODEL=claude-opus-4-8 # Claude model CLAUDE_EFFORT=high # Claude effort level CLAUDE_THINKING=adaptive # Claude thinking mode # --- Codex model --- -CODEX_MODEL=gpt-5.4 # Codex model +CODEX_MODEL=gpt-5.5 # Codex model CODEX_EFFORT=xhigh # Codex reasoning effort +# Codex fast mode / goals: dashboard Settings → Codex, or ~/.codex/config.toml: +# [features] +# fast_mode = true +# goals = true # /goal — opt-in, default OFF on Codex 0.133+ # --- Usage dashboard --- STATUS_CHANNEL_ID= # Discord channel ID for live status updates # STATUS_SHOW_ROOMS=true # Show room status in dashboard # STATUS_SHOW_ROOM_DETAILS=false # Show detailed room info +# WEB_DASHBOARD_ENABLED=false # Local dashboard server +# WEB_DASHBOARD_HOST=127.0.0.1 # Keep localhost unless using VPN/tunnel +# WEB_DASHBOARD_PORT=8734 +# WEB_DASHBOARD_TOKEN= # Optional bearer token for /api/* when exposing to phone clients + +# --- Discord image attachments --- +# Extra local directories that agents may attach from. Keep this narrow: +# prefer screenshot/output folders over /home. Comma or path-delimiter separated. +# EJCLAW_ATTACHMENT_ALLOWED_DIRS=~/Pictures/Screenshots,~/Downloads/ejclaw-images # --- Codex warm-up (optional, disabled by default) --- # Sends a tiny real Codex prompt only when both 5h and 7d usage are 0%, so @@ -64,16 +78,16 @@ STATUS_CHANNEL_ID= # Discord channel ID for live status updat # --- Per-role model overrides (paired rooms) --- # Override global CLAUDE_MODEL/CODEX_MODEL per role. # Model is injected based on each role's agent type (claude-code → CLAUDE_MODEL, codex → CODEX_MODEL). -# OWNER_MODEL=gpt-5.4 # Owner model override +# OWNER_MODEL=gpt-5.5 # Owner model override # OWNER_EFFORT=xhigh # Owner effort override # OWNER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true) # -# REVIEWER_MODEL=claude-opus-4-6 # Reviewer model override +# REVIEWER_MODEL=claude-opus-4-8 # Reviewer model override # REVIEWER_EFFORT=high # Reviewer effort override # REVIEWER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true) # -# ARBITER_MODEL=claude-sonnet-4-6 # Arbiter model override -# ARBITER_EFFORT=high # Arbiter effort override +# ARBITER_MODEL=gpt-5.5 # Arbiter model override when ARBITER_AGENT_TYPE=codex +# ARBITER_EFFORT=xhigh # Arbiter effort override # ARBITER_FALLBACK_ENABLED=true # Fall back to codex on Claude failure (default: true) # --- Mixture of Agents (MoA) --- @@ -82,11 +96,13 @@ STATUS_CHANNEL_ID= # Discord channel ID for live status updat # The SDK arbiter (subscription-based, no extra cost) aggregates all perspectives. # MOA_ENABLED=true # MOA_REF_MODELS=kimi,glm # Comma-separated reference model names -# MOA_KIMI_MODEL=kimi-k2.5 # Kimi model +# MOA_KIMI_MODEL=kimi-k2.6 # Kimi model # MOA_KIMI_BASE_URL=https://api.kimi.com/coding # Kimi API endpoint +# MOA_KIMI_API_FORMAT=anthropic # Kimi Code API format # MOA_KIMI_API_KEY=sk-kimi-xxx # Kimi API key -# MOA_GLM_MODEL=glm-4-plus # GLM model -# MOA_GLM_BASE_URL=https://open.bigmodel.cn/api/paas/v4 # GLM API endpoint +# MOA_GLM_MODEL=glm-5.1 # GLM model +# MOA_GLM_BASE_URL=https://open.bigmodel.cn/api/anthropic # GLM API endpoint +# MOA_GLM_API_FORMAT=anthropic # GLM Anthropic-compatible API # MOA_GLM_API_KEY=xxx # GLM API key # --- Advanced --- diff --git a/.gitignore b/.gitignore index b6eeabb..910a619 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,10 @@ node_modules/ # Build output dist/ runners/*/dist/ +apps/android/.gradle/ +apps/android/build/ +apps/android/app/build/ +apps/android/local.properties # Local data & auth store/ @@ -35,6 +39,7 @@ tmp/ backups/ dist-backups/ .deploy-backups/ +recovery/ cache/ runners/*/node_modules/ runners/codex-runner-backups/ diff --git a/README.md b/README.md index 55cf0ba..34b1658 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # EJClaw ![Version](https://img.shields.io/badge/version-0.2.3-blue) -![Claude Agent SDK](https://img.shields.io/badge/Claude_Agent_SDK-0.2.101-blueviolet) -![Codex SDK](https://img.shields.io/badge/Codex_SDK-0.120.0-green) +![Claude Agent SDK](https://img.shields.io/badge/Claude_Agent_SDK-0.2.126-blueviolet) +![Codex SDK](https://img.shields.io/badge/Codex_SDK-0.133.0-green) ![Bun](https://img.shields.io/badge/Bun-1.3+-f9f1e1?logo=bun&logoColor=black) ![Discord](https://img.shields.io/badge/Discord-Tribunal-5865F2?logo=discord&logoColor=white) @@ -115,6 +115,11 @@ Discord ──► SQLite (WAL) ──► GroupQueue ──┬──► Owner (ho - Codex CLI - Discord 봇 토큰 3개(owner / reviewer / arbiter) +현재 runner 번들 기준 버전: + +- Claude Agent SDK: `@anthropic-ai/claude-agent-sdk@0.2.126` +- Codex SDK/CLI: `@openai/codex@0.133.0` + ### 설치 ```bash diff --git a/apps/android/.gitignore b/apps/android/.gitignore new file mode 100644 index 0000000..bf9b3aa --- /dev/null +++ b/apps/android/.gitignore @@ -0,0 +1,11 @@ +.gradle/ +build/ +local.properties +*.apk +*.ap_ +*.aab +*.iml +.idea/ +.cxx/ +captures/ +app/build/ diff --git a/apps/android/README.md b/apps/android/README.md new file mode 100644 index 0000000..8277b94 --- /dev/null +++ b/apps/android/README.md @@ -0,0 +1,54 @@ +# EJClaw Android + +Personal Android companion for EJClaw. This is a thin client: EJClaw still runs +on the existing Bun service, and the Android app talks to the dashboard API. + +## Build + +```bash +cd apps/android +cp local.properties.example local.properties +./gradlew assembleDebug +``` + +The debug APK is written to: + +```text +apps/android/app/build/outputs/apk/debug/app-debug.apk +``` + +Install with: + +```bash +adb install -r apps/android/app/build/outputs/apk/debug/app-debug.apk +``` + +## Runtime Setup + +- Keep EJClaw behind Tailscale, VPN, SSH tunnel, or localhost forwarding. +- Base URL defaults to `http://100.101.210.95:8734`. +- If `WEB_DASHBOARD_TOKEN` is enabled on the server, paste the same token into + the app. It sends `Authorization: Bearer `. + +## Current MVP + +- Connect to `/api/health`. +- Load rooms from `/api/rooms-timeline`. +- Open a room timeline from `/api/rooms/:jid/timeline`. +- Send text through `/api/rooms/:jid/messages`. +- Keep the Ray-Ban Display integration isolated behind `DisplaySurface`. + +## Meta DAT + +The default APK does not link the Meta DAT SDK yet. Meta's Android DAT SDK is +distributed through GitHub Packages and needs Developer Preview access, a +GitHub package token, and a Wearables Developer Center application id. + +The integration point is already present: + +```text +app/src/main/java/com/ejclaw/android/display/ +``` + +After DAT access is ready, replace `MetaDatDisplaySurface` with SDK calls and +keep `NoopDisplaySurface` for phone-only testing. diff --git a/apps/android/app/build.gradle.kts b/apps/android/app/build.gradle.kts new file mode 100644 index 0000000..4fd992b --- /dev/null +++ b/apps/android/app/build.gradle.kts @@ -0,0 +1,26 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "com.ejclaw.android" + compileSdk = 36 + + defaultConfig { + applicationId = "com.ejclaw.android" + minSdk = 26 + targetSdk = 36 + versionCode = 1 + versionName = "0.1.0" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + } +} + +kotlin { + jvmToolchain(21) +} diff --git a/apps/android/app/src/main/AndroidManifest.xml b/apps/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..a8e9362 --- /dev/null +++ b/apps/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + diff --git a/apps/android/app/src/main/java/com/ejclaw/android/MainActivity.kt b/apps/android/app/src/main/java/com/ejclaw/android/MainActivity.kt new file mode 100644 index 0000000..35c53c2 --- /dev/null +++ b/apps/android/app/src/main/java/com/ejclaw/android/MainActivity.kt @@ -0,0 +1,166 @@ +package com.ejclaw.android + +import android.app.Activity +import android.os.Bundle +import android.widget.Toast +import com.ejclaw.android.api.EJClawApi +import com.ejclaw.android.display.DisplayBridge +import com.ejclaw.android.model.RoomActivity +import com.ejclaw.android.model.RoomSummary +import com.ejclaw.android.ui.EJClawView +import java.util.concurrent.Executors + +class MainActivity : Activity() { + private val executor = Executors.newSingleThreadExecutor() + private val displayBridge = DisplayBridge() + private lateinit var view: EJClawView + private var api: EJClawApi? = null + private var selectedRoom: RoomSummary? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + view = EJClawView(this) + setContentView(view.root) + loadPrefs() + bindActions() + } + + override fun onDestroy() { + executor.shutdownNow() + super.onDestroy() + } + + private fun bindActions() { + view.connectButton.setOnClickListener { connectAndLoadRooms() } + view.refreshButton.setOnClickListener { loadRooms() } + view.sendButton.setOnClickListener { sendMessage() } + view.roomsList.setOnItemClickListener { _, _, position, _ -> + selectedRoom = view.roomsAdapter.getItem(position) + selectedRoom?.let { loadRoom(it) } + } + } + + private fun loadPrefs() { + val prefs = getPreferences(MODE_PRIVATE) + view.baseUrlInput.setText(prefs.getString("baseUrl", "http://100.101.210.95:8734")) + view.tokenInput.setText(prefs.getString("token", "")) + view.nicknameInput.setText(prefs.getString("nickname", "android")) + } + + private fun savePrefs() { + getPreferences(MODE_PRIVATE).edit() + .putString("baseUrl", view.baseUrlInput.text.toString().trim()) + .putString("token", view.tokenInput.text.toString()) + .putString("nickname", view.nicknameInput.text.toString().trim()) + .apply() + } + + private fun connectAndLoadRooms() { + savePrefs() + api = EJClawApi( + view.baseUrlInput.text.toString(), + view.tokenInput.text.toString(), + ) + runNetwork("Connecting") { + requireNotNull(api).health() + requireNotNull(api).rooms() + }.onSuccess { rooms -> + view.statusView.text = "Connected: ${rooms.size} rooms" + replaceRooms(rooms) + } + } + + private fun loadRooms() { + runNetwork("Loading rooms") { + requireNotNull(api ?: createApi()).rooms() + }.onSuccess { rooms -> + view.statusView.text = "Loaded: ${rooms.size} rooms" + replaceRooms(rooms) + } + } + + private fun loadRoom(room: RoomSummary) { + runNetwork("Loading ${room.name}") { + requireNotNull(api ?: createApi()).roomTimeline(room.jid) + }.onSuccess { activity -> + renderRoom(activity) + displayBridge.updateRoom(activity.summary.name, activity.summary.status, null) + displayBridge.showLatest(activity.summary.name, activity.summary.latestText) + } + } + + private fun sendMessage() { + val room = selectedRoom ?: return toast("Select a room first") + val text = view.messageInput.text.toString().trim() + if (text.isBlank()) return + runNetwork("Sending") { + requireNotNull(api ?: createApi()).sendRoomMessage( + room.jid, + text, + view.nicknameInput.text.toString(), + ) + requireNotNull(api).roomTimeline(room.jid) + }.onSuccess { activity -> + view.messageInput.setText("") + renderRoom(activity) + } + } + + private fun createApi(): EJClawApi { + savePrefs() + val next = EJClawApi(view.baseUrlInput.text.toString(), view.tokenInput.text.toString()) + api = next + return next + } + + private fun replaceRooms(rooms: List) { + view.roomsAdapter.clear() + view.roomsAdapter.addAll(rooms) + view.roomsAdapter.notifyDataSetChanged() + } + + private fun renderRoom(activity: RoomActivity) { + val lines = activity.messages.takeLast(40).joinToString("\n\n") { message -> + val marker = if (message.fromMe) "me" else message.senderName.ifBlank { "agent" } + "[$marker] ${message.content}" + } + view.threadView.text = lines.ifBlank { "No messages" } + view.statusView.text = "${activity.summary.name}: ${activity.summary.status}" + } + + private fun runNetwork(label: String, block: () -> T): PendingUi { + view.statusView.text = label + val pending = PendingUi() + executor.execute { + try { + val result = block() + runOnUiThread { pending.succeed(result) } + } catch (error: Throwable) { + runOnUiThread { + view.statusView.text = "Error: ${error.message}" + toast(error.message ?: "Request failed") + } + } + } + return pending + } + + private fun toast(message: String) { + Toast.makeText(this, message, Toast.LENGTH_SHORT).show() + } +} + +private class PendingUi { + private var callback: ((T) -> Unit)? = null + private var result: T? = null + + fun onSuccess(next: (T) -> Unit) { + callback = next + result?.let(next) + } + + fun succeed(value: T) { + result = value + callback?.invoke(value) + } +} diff --git a/apps/android/app/src/main/java/com/ejclaw/android/api/EJClawApi.kt b/apps/android/app/src/main/java/com/ejclaw/android/api/EJClawApi.kt new file mode 100644 index 0000000..ff4f241 --- /dev/null +++ b/apps/android/app/src/main/java/com/ejclaw/android/api/EJClawApi.kt @@ -0,0 +1,104 @@ +package com.ejclaw.android.api + +import com.ejclaw.android.model.RoomActivity +import com.ejclaw.android.model.RoomMessage +import com.ejclaw.android.model.RoomSummary +import java.io.BufferedReader +import java.io.InputStreamReader +import java.net.HttpURLConnection +import java.net.URL +import java.util.UUID +import org.json.JSONObject + +class EJClawApi( + baseUrl: String, + private val token: String, +) { + private val baseUrl = baseUrl.trim().trimEnd('/') + + fun health(): Boolean { + val payload = request("GET", "/api/health") + return JSONObject(payload).optBoolean("ok", false) + } + + fun rooms(): List { + val payload = request("GET", "/api/rooms-timeline") + val root = JSONObject(payload) + return root.keys().asSequence().mapNotNull { key -> + root.optJSONObject(key)?.let { parseRoomSummary(it) } + }.sortedBy { it.name.lowercase() }.toList() + } + + fun roomTimeline(jid: String): RoomActivity { + val payload = request("GET", "/api/rooms/${encode(jid)}/timeline") + val room = JSONObject(payload) + val messages = room.optJSONArray("messages") ?: return RoomActivity(parseRoomSummary(room), emptyList()) + return RoomActivity( + parseRoomSummary(room), + (0 until messages.length()).mapNotNull { index -> + messages.optJSONObject(index)?.let { message -> + RoomMessage( + senderName = message.optString("senderName", message.optString("sender", "")), + content = message.optString("content", ""), + timestamp = message.optString("timestamp", ""), + fromMe = message.optBoolean("isFromMe", false), + ) + } + }, + ) + } + + fun sendRoomMessage(jid: String, text: String, nickname: String): Boolean { + val body = JSONObject() + .put("requestId", UUID.randomUUID().toString()) + .put("text", text) + .put("nickname", nickname.ifBlank { "android" }) + val payload = request("POST", "/api/rooms/${encode(jid)}/messages", body.toString()) + return JSONObject(payload).optBoolean("ok", false) + } + + private fun parseRoomSummary(room: JSONObject): RoomSummary { + val messages = room.optJSONArray("messages") + val latest = if (messages != null && messages.length() > 0) { + messages.optJSONObject(messages.length() - 1)?.optString("content", "") ?: "" + } else { + "" + } + return RoomSummary( + jid = room.optString("jid"), + name = room.optString("name", room.optString("jid")), + status = room.optString("status", "unknown"), + latestText = latest.take(120), + ) + } + + private fun request(method: String, path: String, body: String? = null): String { + val connection = URL("$baseUrl$path").openConnection() as HttpURLConnection + connection.requestMethod = method + connection.connectTimeout = 8_000 + connection.readTimeout = 12_000 + connection.setRequestProperty("Accept", "application/json") + if (token.isNotBlank()) connection.setRequestProperty("Authorization", "Bearer $token") + if (body != null) { + val bytes = body.toByteArray(Charsets.UTF_8) + connection.doOutput = true + connection.setRequestProperty("Content-Type", "application/json") + connection.setRequestProperty("Content-Length", bytes.size.toString()) + connection.outputStream.use { it.write(bytes) } + } + val status = connection.responseCode + val stream = if (status in 200..299) connection.inputStream else connection.errorStream + val response = stream?.use { + BufferedReader(InputStreamReader(it, Charsets.UTF_8)).readText() + } ?: "" + connection.disconnect() + if (status !in 200..299) { + val message = response.ifBlank { "HTTP $status" } + throw IllegalStateException(message) + } + return response + } + + private fun encode(value: String): String = + java.net.URLEncoder.encode(value, Charsets.UTF_8.name()).replace("+", "%20") +} diff --git a/apps/android/app/src/main/java/com/ejclaw/android/display/DisplayBridge.kt b/apps/android/app/src/main/java/com/ejclaw/android/display/DisplayBridge.kt new file mode 100644 index 0000000..ad23939 --- /dev/null +++ b/apps/android/app/src/main/java/com/ejclaw/android/display/DisplayBridge.kt @@ -0,0 +1,13 @@ +package com.ejclaw.android.display + +class DisplayBridge( + private val surface: DisplaySurface = NoopDisplaySurface(), +) { + fun updateRoom(roomName: String, status: String, progress: String?) { + surface.showStatus(roomName, status, progress) + } + + fun showLatest(roomName: String, text: String) { + if (text.isNotBlank()) surface.showMessage(roomName, text) + } +} diff --git a/apps/android/app/src/main/java/com/ejclaw/android/display/DisplaySurface.kt b/apps/android/app/src/main/java/com/ejclaw/android/display/DisplaySurface.kt new file mode 100644 index 0000000..d6f3f33 --- /dev/null +++ b/apps/android/app/src/main/java/com/ejclaw/android/display/DisplaySurface.kt @@ -0,0 +1,6 @@ +package com.ejclaw.android.display + +interface DisplaySurface { + fun showStatus(roomName: String, state: String, progress: String?) + fun showMessage(roomName: String, text: String) +} diff --git a/apps/android/app/src/main/java/com/ejclaw/android/display/MetaDatDisplaySurface.kt b/apps/android/app/src/main/java/com/ejclaw/android/display/MetaDatDisplaySurface.kt new file mode 100644 index 0000000..45fba5e --- /dev/null +++ b/apps/android/app/src/main/java/com/ejclaw/android/display/MetaDatDisplaySurface.kt @@ -0,0 +1,15 @@ +package com.ejclaw.android.display + +/** + * Meta DAT integration point. + * + * Keep this class dependency-free until the Wearables Developer Center project, + * GitHub Packages token, and DAT application id are available. The phone app can + * validate EJClaw connectivity through NoopDisplaySurface first, then this class + * can be swapped to call the Meta SDK. + */ +class MetaDatDisplaySurface : DisplaySurface { + override fun showStatus(roomName: String, state: String, progress: String?) = Unit + + override fun showMessage(roomName: String, text: String) = Unit +} diff --git a/apps/android/app/src/main/java/com/ejclaw/android/display/NoopDisplaySurface.kt b/apps/android/app/src/main/java/com/ejclaw/android/display/NoopDisplaySurface.kt new file mode 100644 index 0000000..9dc4271 --- /dev/null +++ b/apps/android/app/src/main/java/com/ejclaw/android/display/NoopDisplaySurface.kt @@ -0,0 +1,16 @@ +package com.ejclaw.android.display + +class NoopDisplaySurface : DisplaySurface { + var lastStatus: String = "" + private set + var lastMessage: String = "" + private set + + override fun showStatus(roomName: String, state: String, progress: String?) { + lastStatus = listOfNotNull(roomName, state, progress).joinToString(" / ") + } + + override fun showMessage(roomName: String, text: String) { + lastMessage = "$roomName: $text" + } +} diff --git a/apps/android/app/src/main/java/com/ejclaw/android/model/Models.kt b/apps/android/app/src/main/java/com/ejclaw/android/model/Models.kt new file mode 100644 index 0000000..cc27f99 --- /dev/null +++ b/apps/android/app/src/main/java/com/ejclaw/android/model/Models.kt @@ -0,0 +1,25 @@ +package com.ejclaw.android.model + +data class RoomSummary( + val jid: String, + val name: String, + val status: String, + val latestText: String, +) { + override fun toString(): String { + val suffix = if (latestText.isBlank()) "" else "\n$latestText" + return "$name [$status]$suffix" + } +} + +data class RoomMessage( + val senderName: String, + val content: String, + val timestamp: String, + val fromMe: Boolean, +) + +data class RoomActivity( + val summary: RoomSummary, + val messages: List, +) diff --git a/apps/android/app/src/main/java/com/ejclaw/android/ui/EJClawView.kt b/apps/android/app/src/main/java/com/ejclaw/android/ui/EJClawView.kt new file mode 100644 index 0000000..13c77c7 --- /dev/null +++ b/apps/android/app/src/main/java/com/ejclaw/android/ui/EJClawView.kt @@ -0,0 +1,80 @@ +package com.ejclaw.android.ui + +import android.app.Activity +import android.graphics.Typeface +import android.text.InputType +import android.view.View +import android.widget.ArrayAdapter +import android.widget.Button +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.ListView +import android.widget.ScrollView +import android.widget.TextView +import com.ejclaw.android.model.RoomSummary + +class EJClawView( + activity: Activity, +) { + val baseUrlInput = EditText(activity) + val tokenInput = EditText(activity) + val nicknameInput = EditText(activity) + val connectButton = Button(activity) + val refreshButton = Button(activity) + val sendButton = Button(activity) + val messageInput = EditText(activity) + val statusView = TextView(activity) + val threadView = TextView(activity) + val roomsAdapter = ArrayAdapter(activity, android.R.layout.simple_list_item_1) + val roomsList = ListView(activity) + val root: View + + init { + baseUrlInput.hint = "http://100.101.210.95:8734" + baseUrlInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI + tokenInput.hint = "WEB_DASHBOARD_TOKEN" + tokenInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + nicknameInput.hint = "nickname" + nicknameInput.inputType = InputType.TYPE_CLASS_TEXT + messageInput.hint = "message" + messageInput.minLines = 2 + + connectButton.text = "Connect" + refreshButton.text = "Refresh" + sendButton.text = "Send" + statusView.text = "Disconnected" + threadView.text = "Select a room" + threadView.setTypeface(Typeface.MONOSPACE) + roomsList.adapter = roomsAdapter + + val controls = LinearLayout(activity).apply { + orientation = LinearLayout.VERTICAL + setPadding(24, 24, 24, 12) + addView(baseUrlInput) + addView(tokenInput) + addView(nicknameInput) + addView(LinearLayout(activity).apply { + orientation = LinearLayout.HORIZONTAL + addView(connectButton, LinearLayout.LayoutParams(0, -2, 1f)) + addView(refreshButton, LinearLayout.LayoutParams(0, -2, 1f)) + }) + addView(statusView) + } + val scroll = ScrollView(activity).apply { + addView(threadView) + } + val sendRow = LinearLayout(activity).apply { + orientation = LinearLayout.HORIZONTAL + addView(messageInput, LinearLayout.LayoutParams(0, -2, 1f)) + addView(sendButton) + } + + root = LinearLayout(activity).apply { + orientation = LinearLayout.VERTICAL + addView(controls) + addView(roomsList, LinearLayout.LayoutParams(-1, 0, 1f)) + addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f)) + addView(sendRow) + } + } +} diff --git a/apps/android/app/src/main/res/values/strings.xml b/apps/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..f74f311 --- /dev/null +++ b/apps/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + EJClaw + diff --git a/apps/android/app/src/main/res/values/styles.xml b/apps/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..77f9795 --- /dev/null +++ b/apps/android/app/src/main/res/values/styles.xml @@ -0,0 +1,7 @@ + + + diff --git a/apps/android/app/src/main/res/xml/network_security_config.xml b/apps/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..fef849a --- /dev/null +++ b/apps/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,6 @@ + + + + 100.101.210.95 + + diff --git a/apps/android/build.gradle.kts b/apps/android/build.gradle.kts new file mode 100644 index 0000000..e2572a7 --- /dev/null +++ b/apps/android/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.13.0" apply false + id("org.jetbrains.kotlin.android") version "2.2.21" apply false +} diff --git a/apps/android/gradle.properties b/apps/android/gradle.properties new file mode 100644 index 0000000..bae9034 --- /dev/null +++ b/apps/android/gradle.properties @@ -0,0 +1,3 @@ +android.useAndroidX=true +android.nonTransitiveRClass=true +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 diff --git a/apps/android/gradle/wrapper/gradle-wrapper.jar b/apps/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/apps/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/apps/android/gradle/wrapper/gradle-wrapper.properties b/apps/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..d4081da --- /dev/null +++ b/apps/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/apps/android/gradlew b/apps/android/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/apps/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/apps/android/gradlew.bat b/apps/android/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/apps/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/apps/android/local.properties.example b/apps/android/local.properties.example new file mode 100644 index 0000000..e45563e --- /dev/null +++ b/apps/android/local.properties.example @@ -0,0 +1,7 @@ +## Copy to local.properties when building outside Android Studio. +## Do not commit local.properties. +sdk.dir=/home/ejclaw/android-sdk + +## Optional later, when enabling Meta Wearables DAT dependencies. +## github_token=ghp_xxx +## meta_dat_application_id=your_meta_wearables_application_id diff --git a/apps/android/settings.gradle.kts b/apps/android/settings.gradle.kts new file mode 100644 index 0000000..4ac0ad0 --- /dev/null +++ b/apps/android/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "EJClawAndroid" +include(":app") diff --git a/apps/dashboard/index.html b/apps/dashboard/index.html index 434ca72..3fdc00b 100644 --- a/apps/dashboard/index.html +++ b/apps/dashboard/index.html @@ -1,9 +1,19 @@ - + - - EJClaw Dashboard + + + + + + + + + EJClaw Ops
diff --git a/apps/dashboard/public/icons/icon-192.png b/apps/dashboard/public/icons/icon-192.png new file mode 100644 index 0000000..90ed779 Binary files /dev/null and b/apps/dashboard/public/icons/icon-192.png differ diff --git a/apps/dashboard/public/icons/icon-192.svg b/apps/dashboard/public/icons/icon-192.svg new file mode 100644 index 0000000..7ac3f43 --- /dev/null +++ b/apps/dashboard/public/icons/icon-192.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/apps/dashboard/public/icons/icon-512.png b/apps/dashboard/public/icons/icon-512.png new file mode 100644 index 0000000..9c4c78a Binary files /dev/null and b/apps/dashboard/public/icons/icon-512.png differ diff --git a/apps/dashboard/public/icons/icon-512.svg b/apps/dashboard/public/icons/icon-512.svg new file mode 100644 index 0000000..7594125 --- /dev/null +++ b/apps/dashboard/public/icons/icon-512.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/apps/dashboard/public/manifest.webmanifest b/apps/dashboard/public/manifest.webmanifest new file mode 100644 index 0000000..3c78ff5 --- /dev/null +++ b/apps/dashboard/public/manifest.webmanifest @@ -0,0 +1,27 @@ +{ + "name": "EJClaw Ops", + "short_name": "EJClaw", + "description": "EJClaw operations console", + "start_url": "/", + "scope": "/", + "display": "standalone", + "display_override": ["window-controls-overlay", "standalone", "browser"], + "background_color": "#f3efe4", + "theme_color": "#2b3726", + "orientation": "portrait-primary", + "categories": ["productivity", "utilities"], + "icons": [ + { + "src": "/icons/icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any maskable" + }, + { + "src": "/icons/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any maskable" + } + ] +} diff --git a/apps/dashboard/public/offline.html b/apps/dashboard/public/offline.html new file mode 100644 index 0000000..f71f86a --- /dev/null +++ b/apps/dashboard/public/offline.html @@ -0,0 +1,87 @@ + + + + + + + EJClaw Offline + + + +
+ EJClaw +

Offline

+

네트워크가 복구되면 대시보드를 다시 불러옵니다.

+ +
+ + diff --git a/apps/dashboard/public/sw.js b/apps/dashboard/public/sw.js new file mode 100644 index 0000000..ec1b737 --- /dev/null +++ b/apps/dashboard/public/sw.js @@ -0,0 +1,78 @@ +const CACHE_NAME = 'ejclaw-dashboard-v1'; +const PRECACHE_URLS = [ + '/', + '/index.html', + '/offline.html', + '/manifest.webmanifest', + '/icons/icon-192.png', + '/icons/icon-512.png', + '/icons/icon-192.svg', + '/icons/icon-512.svg', +]; + +self.addEventListener('install', (event) => { + event.waitUntil( + caches + .open(CACHE_NAME) + .then((cache) => cache.addAll(PRECACHE_URLS)) + .then(() => self.skipWaiting()), + ); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches + .keys() + .then((keys) => + Promise.all( + keys + .filter((key) => key !== CACHE_NAME) + .map((key) => caches.delete(key)), + ), + ) + .then(() => self.clients.claim()), + ); +}); + +self.addEventListener('fetch', (event) => { + const { request } = event; + const url = new URL(request.url); + + if (request.method !== 'GET' || url.origin !== self.location.origin) { + return; + } + + if (url.pathname.startsWith('/api/')) { + event.respondWith(fetch(request)); + return; + } + + if (request.mode === 'navigate') { + event.respondWith( + fetch(request) + .then((response) => { + const copy = response.clone(); + caches.open(CACHE_NAME).then((cache) => cache.put('/', copy)); + return response; + }) + .catch(() => + caches + .match('/') + .then((cached) => cached || caches.match('/offline.html')), + ), + ); + return; + } + + event.respondWith( + caches.match(request).then((cached) => { + if (cached) return cached; + return fetch(request).then((response) => { + if (!response.ok) return response; + const copy = response.clone(); + caches.open(CACHE_NAME).then((cache) => cache.put(request, copy)); + return response; + }); + }), + ); +}); diff --git a/apps/dashboard/src/App.tsx b/apps/dashboard/src/App.tsx index 7fd51b0..824178c 100644 --- a/apps/dashboard/src/App.tsx +++ b/apps/dashboard/src/App.tsx @@ -1,21 +1,41 @@ -import { useEffect, useMemo, useState, type ReactNode } from 'react'; +import { useEffect, useState } from 'react'; import { + type CreateScheduledTaskInput, + type DashboardRoomActivity, + type DashboardTaskAction, type DashboardOverview, type DashboardTask, + type UpdateScheduledTaskInput, type StatusSnapshot, + createScheduledTask, fetchDashboardData, + runServiceAction, + runScheduledTaskAction, + sendRoomMessage, + updateScheduledTask, } from './api'; import { - LOCALES, isLocale, - languageNames, localeTags, matchLocale, messages, type Locale, type Messages, } from './i18n'; +import { useSelectedRoomActivity } from './useRoomActivity'; +import { + SectionNav, + SideRail, + type DashboardFreshness, + type DashboardView, +} from './DashboardNav'; +import { formatDate, statusLabel } from './dashboardHelpers'; +import { RoomBoardV2 } from './RoomBoardV2'; +import { SettingsPanel } from './SettingsPanel'; +import { SystemStatusStrip } from './SystemStatusStrip'; +import { TaskPanel, type RoomOption, type TaskActionKey } from './TaskPanel'; +import { UsagePanel } from './UsagePanel'; import './styles.css'; interface DashboardState { @@ -24,12 +44,40 @@ interface DashboardState { tasks: DashboardTask[]; } -type UsageRow = DashboardOverview['usage']['rows'][number]; -type RiskLevel = 'ok' | 'warn' | 'critical'; -type UsageGroup = 'primary' | 'codex'; +type FreshnessLevel = DashboardFreshness; const REFRESH_INTERVAL_MS = 15_000; -const LOCALE_STORAGE_KEY = 'ejclaw.dashboard.locale'; +const LOCALE_STORAGE_KEY = 'ejclaw.dashboard.locale.v2'; +const DEFAULT_VIEW: DashboardView = 'rooms'; +const DASHBOARD_STALE_MS = 75_000; + +function makeClientRequestId(): string { + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; +} + +function isDashboardView( + value: string | null | undefined, +): value is DashboardView { + return ( + value === 'usage' || + value === 'rooms' || + value === 'scheduled' || + value === 'settings' + ); +} + +function readViewFromHash(): DashboardView { + if (typeof window === 'undefined') return DEFAULT_VIEW; + const raw = window.location.hash.replace(/^#\/?/, ''); + return isDashboardView(raw) ? raw : DEFAULT_VIEW; +} + +function normalizeDashboardHash(view: DashboardView): void { + if (typeof window === 'undefined') return; + const raw = window.location.hash.replace(/^#\/?/, ''); + if (!raw || isDashboardView(raw)) return; + window.history.replaceState(null, '', `#/${view}`); +} function readInitialLocale(): Locale { const stored = @@ -47,45 +95,70 @@ function readInitialLocale(): Locale { if (matched) return matched; } - return 'ko'; + return 'en'; } -function formatDate(value: string | null | undefined, locale: Locale): string { - if (!value) return '-'; +function persistNickname(trimmed: string): void { + if (typeof window === 'undefined') return; + if (trimmed) window.localStorage.setItem('ejclaw-nickname', trimmed); + else window.localStorage.removeItem('ejclaw-nickname'); +} + +function humanizeError(raw: string, t: Messages): string { + const lower = raw.toLowerCase(); + if (/abort|timeout|timed out/.test(lower)) return t.error.timeout; + if (/network|fetch failed|failed to fetch|networkerror|offline/.test(lower)) + return t.error.network; + const statusMatch = lower.match(/\b(\d{3})\b/); + if (statusMatch) { + const code = Number(statusMatch[1]); + if (code === 401 || code === 403) return t.error.auth; + if (code === 404) return t.error.notFound; + if (code >= 500) return t.error.server; + if (code >= 400) return t.error.unknown; + } + return raw || t.error.unknown; +} + +function senderRoleClass(value: string | null | undefined): string { + const v = (value ?? '').toLowerCase(); + if (v.includes('오너') || v.includes('owner')) return 'role-owner'; + if (v.includes('리뷰어') || v.includes('reviewer')) return 'role-reviewer'; + if (v.includes('중재자') || v.includes('arbiter')) return 'role-arbiter'; + if (v.includes('cron') || v.includes('sentry') || v.includes('webhook')) + return 'role-cron'; + return 'role-human'; +} + +function dashboardAgeMs(value: string | null | undefined): number | null { + if (!value) return null; const date = new Date(value); - if (Number.isNaN(date.getTime())) return value; - return new Intl.DateTimeFormat(localeTags[locale], { - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - }).format(date); + if (Number.isNaN(date.getTime())) return null; + return Math.max(0, Date.now() - date.getTime()); } -function formatPct(value: number): string { - if (value < 0) return '-'; - return `${Math.round(value)}%`; +function dashboardFreshness( + online: boolean, + generatedAt: string | null | undefined, +): FreshnessLevel { + if (!online) return 'offline'; + const age = dashboardAgeMs(generatedAt); + if (age !== null && age > DASHBOARD_STALE_MS) return 'stale'; + return 'fresh'; } -function usagePeak(row: UsageRow): number { - return Math.max(row.h5pct, row.d7pct); +function freshnessLabel(level: FreshnessLevel, t: Messages): string { + if (level === 'offline') return t.pwa.offline; + if (level === 'stale') return t.pwa.stale; + return t.pwa.fresh; } -function usageRiskLevel(row: UsageRow): RiskLevel { - const peak = usagePeak(row); - if (peak >= 85) return 'critical'; - if (peak >= 65) return 'warn'; - return 'ok'; -} - -function usageGroup(row: UsageRow): UsageGroup { - return row.name.toLowerCase().startsWith('codex') ? 'codex' : 'primary'; -} - -function statusLabel(status: string, t: Messages): string { - if (status in t.status) return t.status[status as keyof Messages['status']]; - return status; +function canUsePwaCore(): boolean { + return ( + typeof window !== 'undefined' && + window.isSecureContext && + 'serviceWorker' in navigator + ); } function formatDuration(value: number | null, t: Messages): string { @@ -98,53 +171,41 @@ function formatDuration(value: number | null, t: Messages): string { return `${hours}${t.units.hour} ${minutes % 60}${t.units.minute}`; } -function queueLabel( - pendingTasks: number, - pendingMessages: boolean, - t: Messages, -) { - const parts = [`${pendingTasks} ${t.units.task}`]; - if (pendingMessages) parts.push(t.units.messageShort); - return parts.join(' · '); +function formatLiveElapsed(value: number, t: Messages): string { + const seconds = Math.max(0, Math.floor(value / 1000)); + if (seconds < 60) return `${seconds}${t.units.second}`; + const minutes = Math.floor(seconds / 60); + const remSec = seconds % 60; + if (minutes < 60) + return `${minutes}${t.units.minute} ${remSec}${t.units.second}`; + const hours = Math.floor(minutes / 60); + const remMin = minutes % 60; + return `${hours}${t.units.hour} ${remMin}${t.units.minute} ${remSec}${t.units.second}`; } -function navItems(t: Messages) { - return [ - { href: '#overview', label: t.nav.health }, - { href: '#usage', label: t.nav.usage }, - { href: '#rooms', label: t.nav.rooms }, - { href: '#work', label: t.nav.scheduled }, - ]; -} +const ROOM_BOARD_FORMATTERS = { + formatDate, + formatDuration, + formatLiveElapsed, + senderRoleClass, + statusLabel, +}; -function EmptyState({ children }: { children: ReactNode }) { - return
{children}
; -} - -function LanguageSelector({ - locale, - onLocaleChange, - t, -}: { - locale: Locale; - onLocaleChange: (locale: Locale) => void; - t: Messages; -}) { - return ( - +function buildRoomOptions(snapshots: StatusSnapshot[]): RoomOption[] { + const rooms = new Map(); + for (const snapshot of snapshots) { + for (const entry of snapshot.entries) { + if (!rooms.has(entry.jid)) { + rooms.set(entry.jid, { + jid: entry.jid, + name: entry.name || entry.folder || entry.jid, + folder: entry.folder, + }); + } + } + } + return Array.from(rooms.values()).sort((a, b) => + `${a.name} ${a.folder}`.localeCompare(`${b.name} ${b.folder}`), ); } @@ -169,599 +230,67 @@ function LoadingSkeleton({ t }: { t: Messages }) { ); } -function SideRail({ - lastRefreshed, - locale, - onLocaleChange, - onRefresh, +function DashboardErrorCard({ + error, + onRetry, refreshing, t, }: { - lastRefreshed: string | null; - locale: Locale; - onLocaleChange: (locale: Locale) => void; - onRefresh: () => void; + error: string; + onRetry: () => void; refreshing: boolean; t: Messages; }) { return ( - - ); -} - -function SectionNav({ - drawerOpen, - lastRefreshed, - locale, - onCloseDrawer, - onLocaleChange, - onOpenDrawer, - refreshing, - onRefresh, - t, -}: { - drawerOpen: boolean; - lastRefreshed: string | null; - locale: Locale; - onCloseDrawer: () => void; - onLocaleChange: (locale: Locale) => void; - onOpenDrawer: () => void; - refreshing: boolean; - onRefresh: () => void; - t: Messages; -}) { - return ( - <> - - - {drawerOpen ? ( - <> - - - - -
- {t.nav.updated} - {formatDate(lastRefreshed, locale)} -
- - - ) : null} - - ); -} - -function ControlRail({ data, t }: { data: DashboardState; t: Messages }) { - const queue = data.snapshots.reduce( - (acc, snapshot) => { - for (const entry of snapshot.entries) { - acc.pendingTasks += entry.pendingTasks; - if (entry.pendingMessages) acc.pendingMessageRooms += 1; - } - return acc; - }, - { pendingTasks: 0, pendingMessageRooms: 0 }, - ); - - return ( -
-
- {t.metrics.rooms} - - {data.overview.rooms.active + data.overview.rooms.waiting}/ - {data.overview.rooms.total} - - {t.control.activeRooms} -
-
- {t.control.queue} - {queue.pendingTasks} - - {queue.pendingMessageRooms} {t.control.pendingRooms} - -
-
- {t.metrics.agents} - {data.overview.services.length} - {t.panels.heartbeat} -
-
- {t.metrics.ciWatchers} - {data.overview.tasks.watchers.active} - - {data.overview.tasks.watchers.paused} {t.status.paused} - -
); } -function ServicePanel({ - overview, - locale, - t, -}: { - overview: DashboardOverview; - locale: Locale; - t: Messages; -}) { - if (overview.services.length === 0) { - return {t.service.empty}; - } - - return ( -
- {overview.services.map((service) => ( -
-
- {service.agentType} -

{service.assistantName}

-
-
- - - {t.service.heartbeat} {formatDate(service.updatedAt, locale)} - -
-
-
-
{t.service.service}
-
{service.serviceId}
-
-
-
{t.service.rooms}
-
- {service.activeRooms}/{service.totalRooms} {t.status.active} -
-
-
-
{t.service.updated}
-
{formatDate(service.updatedAt, locale)}
-
-
-
- ))} -
- ); -} - -function RoomPanel({ - snapshots, - t, -}: { - snapshots: StatusSnapshot[]; - t: Messages; -}) { - const entries = snapshots.flatMap((snapshot) => - snapshot.entries.map((entry) => ({ - ...entry, - serviceId: snapshot.serviceId, - })), - ); - - if (entries.length === 0) { - return {t.rooms.empty}; - } - - return ( - <> -
- - - - - - - - - - - - {entries.map((entry) => ( - - - - - - - - ))} - -
{t.rooms.room}{t.rooms.service}{t.rooms.agent}{t.rooms.status}{t.rooms.queue}
- {entry.name} - - {entry.folder} · {entry.jid} - - {entry.serviceId}{entry.agentType} - - {statusLabel(entry.status, t)} - - {formatDuration(entry.elapsedMs, t)} - - {queueLabel(entry.pendingTasks, entry.pendingMessages, t)} -
-
- -
- {entries.map((entry) => ( -
-
-
- {entry.name} - {entry.folder} -
- - {statusLabel(entry.status, t)} - -
-
- - {t.rooms.queue} - - {queueLabel(entry.pendingTasks, entry.pendingMessages, t)} - - - - {t.rooms.agent} - {entry.agentType} - - - {t.rooms.service} - {entry.serviceId} - - - {t.rooms.elapsed} - {formatDuration(entry.elapsedMs, t)} - -
-

{entry.jid}

-
- ))} -
- - ); -} - -function UsageMeter({ - label, - pct, - reset, - rowName, - t, -}: { - label: string; - pct: number; - reset: string; - rowName: string; - t: Messages; -}) { - return ( -
-
- {label} - {formatPct(pct)} -
- - - {t.usage.reset} {reset || '-'} - -
- ); -} - -function UsagePanel({ - overview, - locale, - t, -}: { - overview: DashboardOverview; - locale: Locale; - t: Messages; -}) { - const rows = useMemo(() => [...overview.usage.rows], [overview.usage.rows]); - const watched = rows.filter((row) => usagePeak(row) >= 65).length; - - if (rows.length === 0) { - return {t.usage.empty}; - } - - const highest = rows[0]; - const groups = [ - { - key: 'primary' as const, - label: t.usage.groupPrimary, - rows: rows.filter((row) => usageGroup(row) === 'primary'), - }, - { - key: 'codex' as const, - label: t.usage.groupCodex, - rows: rows.filter((row) => usageGroup(row) === 'codex'), - }, - ].filter((group) => group.rows.length > 0); - - return ( -
-
-
- {t.usage.highest} - - {highest.name} · {formatPct(usagePeak(highest))} - -
-
- {t.usage.watch} - {watched} -
-
- {t.usage.updated} - {formatDate(overview.usage.fetchedAt, locale)} -
-
- -
-
- {t.usage.usage} - {t.usage.window5h} - {t.usage.window7d} -
- {groups.map((group) => ( -
-
- {group.label} -
- {group.rows.map((row) => { - const risk = usageRiskLevel(row); - return ( -
-
- {row.name} - - {t.usage.risk[risk]} - -
- - -
- ); - })} -
- ))} -
-
- ); -} - -function TaskPanel({ - tasks, - locale, - t, -}: { - tasks: DashboardTask[]; - locale: Locale; - t: Messages; -}) { - const sortedTasks = useMemo( - () => - [...tasks].sort((a, b) => { - const statusRank = { active: 0, paused: 1, completed: 2 } as const; - const rankDelta = statusRank[a.status] - statusRank[b.status]; - if (rankDelta !== 0) return rankDelta; - return (a.nextRun ?? a.createdAt).localeCompare( - b.nextRun ?? b.createdAt, - ); - }), - [tasks], - ); - - if (sortedTasks.length === 0) { - return {t.tasks.empty}; - } - - return ( - <> -
- - - - - - - - - - - - {sortedTasks.map((task) => ( - - - - - - - - ))} - -
{t.tasks.task}{t.tasks.status}{t.tasks.schedule}{t.tasks.next}{t.tasks.last}
- {task.isWatcher ? t.tasks.ciWatch : task.id} - {task.promptPreview || t.tasks.emptyPrompt} - - {task.groupFolder} · {task.promptLength} {t.units.chars} - - - - {statusLabel(task.status, t)} - - {task.suspendedUntil ? ( - - {t.tasks.until} {formatDate(task.suspendedUntil, locale)} - - ) : null} - - {task.scheduleType} · {task.scheduleValue} - {task.contextMode} - {formatDate(task.nextRun, locale)} - {formatDate(task.lastRun, locale)} - {task.lastResult ? {task.lastResult} : null} -
-
- -
- {sortedTasks.map((task) => ( -
-
-
- {task.isWatcher ? t.tasks.ciWatch : task.id} - {task.groupFolder} -
- - {statusLabel(task.status, t)} - -
-

{task.promptPreview || t.tasks.emptyPrompt}

-
- - {t.tasks.schedule} - {task.scheduleType} - - - {t.tasks.next} - {formatDate(task.nextRun, locale)} - - - {t.tasks.last} - {formatDate(task.lastRun, locale)} - - - {t.tasks.context} - {task.contextMode} - -
- {task.lastResult ? ( -

- {t.tasks.lastResult}: {task.lastResult} -

- ) : null} -
- ))} -
- - ); -} - function App() { const [data, setData] = useState(null); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); const [refreshing, setRefreshing] = useState(false); - const [lastRefreshed, setLastRefreshed] = useState(null); const [drawerOpen, setDrawerOpen] = useState(false); + const [activeView, setActiveView] = useState(readViewFromHash); const [locale, setLocale] = useState(readInitialLocale); + const [online, setOnline] = useState(() => + typeof navigator === 'undefined' ? true : navigator.onLine, + ); + const [taskActionKey, setTaskActionKey] = useState( + null, + ); + const [serviceRestarting, setServiceRestarting] = useState(false); + const [roomMessageKey, setRoomMessageKey] = useState(null); + const [selectedRoomJid, setSelectedRoomJid] = useState(null); + const { + refreshRoom: refreshRoomActivity, + roomActivity, + roomActivityLoading, + } = useSelectedRoomActivity({ + active: activeView === 'rooms', + selectedRoomJid: selectedRoomJid, + }); + const [pendingMessages, setPendingMessages] = useState< + Record> + >({}); + const [nickname, setNicknameState] = useState(() => { + if (typeof window === 'undefined') return ''; + return window.localStorage.getItem('ejclaw-nickname') ?? ''; + }); + function setNickname(next: string) { + const trimmed = next.trim().slice(0, 32); + setNicknameState(trimmed); + persistNickname(trimmed); + } const t = messages[locale]; function setDashboardLocale(nextLocale: Locale) { @@ -769,12 +298,18 @@ function App() { window.localStorage.setItem(LOCALE_STORAGE_KEY, nextLocale); } + function navigateToView(view: DashboardView) { + setActiveView(view); + if (window.location.hash !== `#/${view}`) { + window.location.hash = `/${view}`; + } + } + async function refresh(showSpinner = false) { if (showSpinner) setRefreshing(true); try { const nextData = await fetchDashboardData(); setData(nextData); - setLastRefreshed(new Date().toISOString()); setError(null); } catch (err) { setError(err instanceof Error ? err.message : String(err)); @@ -784,10 +319,207 @@ function App() { } } + async function handleTaskAction( + task: DashboardTask, + action: DashboardTaskAction, + ) { + if (action === 'cancel' && !window.confirm(t.tasks.actions.confirmCancel)) { + return; + } + + const actionKey: TaskActionKey = `${task.id}:${action}`; + setTaskActionKey(actionKey); + try { + await runScheduledTaskAction(task.id, action); + await refresh(false); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setTaskActionKey(null); + } + } + + async function handleTaskCreate(input: CreateScheduledTaskInput) { + setTaskActionKey('create'); + try { + await createScheduledTask({ ...input, requestId: makeClientRequestId() }); + await refresh(false); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setTaskActionKey(null); + } + } + + async function handleTaskUpdate( + task: DashboardTask, + input: UpdateScheduledTaskInput, + ) { + const actionKey: TaskActionKey = `${task.id}:edit`; + setTaskActionKey(actionKey); + try { + await updateScheduledTask(task.id, input); + await refresh(false); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setTaskActionKey(null); + } + } + + async function handleServiceRestart() { + if ( + typeof window !== 'undefined' && + !window.confirm(t.health.confirmRestart) + ) { + return; + } + + setServiceRestarting(true); + try { + await runServiceAction('stack', 'restart', { + requestId: makeClientRequestId(), + }); + await refresh(false); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setServiceRestarting(false); + } + } + + async function handleRoomMessage( + roomJid: string, + text: string, + requestId: string, + ) { + setRoomMessageKey(roomJid); + const optimisticId = `opt:${requestId}`; + const displayName = nickname || 'Web Dashboard'; + const optimisticMsg = { + id: optimisticId, + sender: 'me', + senderName: displayName, + content: text, + timestamp: new Date().toISOString(), + isFromMe: true, + isBotMessage: false, + sourceKind: 'human' as const, + }; + setPendingMessages((prev) => ({ + ...prev, + [roomJid]: [...(prev[roomJid] ?? []), optimisticMsg], + })); + try { + await sendRoomMessage(roomJid, text, requestId, nickname || null); + try { + await refreshRoomActivity(roomJid); + } catch { + /* refresh will retry on next poll */ + } + void refresh(false); + return true; + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + setPendingMessages((prev) => { + const list = prev[roomJid]; + if (!list) return prev; + const next = list.filter((m) => m.id !== optimisticId); + if (next.length === 0) { + const { [roomJid]: _drop, ...rest } = prev; + void _drop; + return rest; + } + return { ...prev, [roomJid]: next }; + }); + return false; + } finally { + setRoomMessageKey(null); + } + } + useEffect(() => { document.documentElement.lang = localeTags[locale]; }, [locale]); + useEffect(() => { + const debug = + typeof window !== 'undefined' && + /[?&]debug=1/.test(window.location.search); + document.body.classList.toggle('debug-outlines', debug); + if ( + typeof window !== 'undefined' && + /[?&]measure=1/.test(window.location.search) + ) { + const tick = () => { + const sels = [ + '.rooms-detail .room-card-v2', + '.room-card-head', + '.room-thread-section', + '.room-section.room-compose-section', + ]; + const out = sels + .map((s) => { + const el = document.querySelector(s); + if (!el) return `${s}: NOT FOUND`; + const r = el.getBoundingClientRect(); + const cs = getComputedStyle(el); + return `${s}:\n x=${Math.round(r.x)} w=${Math.round(r.width)}\n display=${cs.display} pl=${cs.paddingLeft} ml=${cs.marginLeft}`; + }) + .join('\n'); + let pre = document.getElementById('__measure'); + if (!pre) { + pre = document.createElement('pre'); + pre.id = '__measure'; + pre.style.cssText = + 'position:fixed;top:0;left:0;background:#fff;color:#000;font:11px monospace;padding:8px;z-index:99999;max-width:520px;white-space:pre;line-height:1.4;'; + document.body.appendChild(pre); + } + pre.textContent = out; + }; + const id = window.setTimeout(tick, 1500); + return () => window.clearTimeout(id); + } + return undefined; + }); + + useEffect(() => { + function handleOnline() { + setOnline(true); + } + + function handleOffline() { + setOnline(false); + } + + window.addEventListener('online', handleOnline); + window.addEventListener('offline', handleOffline); + return () => { + window.removeEventListener('online', handleOnline); + window.removeEventListener('offline', handleOffline); + }; + }, []); + + useEffect(() => { + if (!import.meta.env.PROD || !canUsePwaCore()) return; + + void navigator.serviceWorker.register('/sw.js').catch(() => { + /* ignore registration failures */ + }); + }, []); + + useEffect(() => { + function handleHashChange() { + const nextView = readViewFromHash(); + setActiveView(nextView); + normalizeDashboardHash(nextView); + } + + handleHashChange(); + window.addEventListener('hashchange', handleHashChange); + return () => window.removeEventListener('hashchange', handleHashChange); + }, []); + useEffect(() => { void refresh(); const id = window.setInterval(() => { @@ -796,6 +528,25 @@ function App() { return () => window.clearInterval(id); }, []); + useEffect(() => { + setPendingMessages((prev) => { + const next: typeof prev = {}; + let changed = false; + for (const [jid, list] of Object.entries(prev)) { + const fetched = roomActivity[jid]?.messages ?? []; + const confirmedKeys = new Set( + fetched.map((m) => `${m.senderName}${m.content}`), + ); + const remaining = list.filter( + (m) => !confirmedKeys.has(`${m.senderName}${m.content}`), + ); + if (remaining.length !== list.length) changed = true; + if (remaining.length > 0) next[jid] = remaining; + } + return changed ? next : prev; + }); + }, [roomActivity]); + useEffect(() => { if (!drawerOpen) return; @@ -811,23 +562,26 @@ function App() { return ; } + const roomOptions = data ? buildRoomOptions(data.snapshots) : []; + const freshness = dashboardFreshness(online, data?.overview.generatedAt); + return (
void refresh(true)} - refreshing={refreshing} + activeView={activeView} + data={data} + onNavigate={navigateToView} t={t} />
setDrawerOpen(false)} - onLocaleChange={setDashboardLocale} + onNavigate={navigateToView} onOpenDrawer={() => setDrawerOpen(true)} onRefresh={() => void refresh(true)} refreshing={refreshing} @@ -835,52 +589,91 @@ function App() { /> {error ? ( -
- - {t.error.api}: {error} - - -
+ void refresh(true)} + refreshing={refreshing} + t={t} + /> ) : null} {data ? ( - <> -
-
-

{t.panels.usage}

- {t.panels.usageWindow} -
- -
+
+ {activeView === 'usage' ? ( +
+
+

{t.panels.usage}

+ {t.panels.usageWindow} +
+ +
+ ) : null} - + {activeView === 'rooms' ? ( +
+
+

{t.panels.rooms}

+ {t.panels.queue} +
+ + +
+ ) : null} -
-
-

{t.panels.health}

- {t.panels.heartbeat} -
- -
+ {activeView === 'scheduled' ? ( +
+
+

{t.panels.scheduled}

+
+ + void handleTaskAction(task, action) + } + onTaskCreate={(input) => void handleTaskCreate(input)} + onTaskUpdate={(task, input) => + void handleTaskUpdate(task, input) + } + rooms={roomOptions} + taskActionKey={taskActionKey} + tasks={data.tasks} + t={t} + /> +
+ ) : null} -
-
-

{t.panels.rooms}

- {t.panels.queue} -
- -
- -
-
-

{t.panels.scheduled}

- {t.panels.promptPreviews} -
- -
- + {activeView === 'settings' ? ( +
+
+

{t.settings.title}

+
+ { + if (!serviceRestarting) void handleServiceRestart(); + }} + t={t} + /> +
+ ) : null} +
) : null}
diff --git a/apps/dashboard/src/DashboardNav.tsx b/apps/dashboard/src/DashboardNav.tsx new file mode 100644 index 0000000..fab4d2c --- /dev/null +++ b/apps/dashboard/src/DashboardNav.tsx @@ -0,0 +1,245 @@ +import { type ReactNode } from 'react'; +import { Clock, Gauge, MessageSquare, Settings } from 'lucide-react'; + +import { type DashboardOverview, type StatusSnapshot } from './api'; +import { type Messages } from './i18n'; + +export type DashboardView = 'usage' | 'rooms' | 'scheduled' | 'settings'; +export type DashboardFreshness = 'fresh' | 'stale' | 'offline'; + +interface DashboardNavData { + overview: DashboardOverview; + snapshots: StatusSnapshot[]; +} + +const NAV_ICONS: Record = { + usage: , + rooms: , + scheduled: , + settings: , +}; + +function navItems(t: Messages) { + return [ + { href: '#/rooms', label: t.nav.rooms, view: 'rooms' as const }, + { href: '#/scheduled', label: t.nav.scheduled, view: 'scheduled' as const }, + { href: '#/usage', label: t.nav.usage, view: 'usage' as const }, + { href: '#/settings', label: t.nav.settings, view: 'settings' as const }, + ]; +} + +function navStats(data: DashboardNavData | null) { + if (!data) return null; + const queue = data.snapshots.reduce( + (acc, snapshot) => { + for (const entry of snapshot.entries) { + if (entry.status === 'processing') acc.processing += 1; + } + return acc; + }, + { processing: 0 }, + ); + return { + processing: queue.processing, + }; +} + +function navBadge( + view: DashboardView, + stats: ReturnType, +): number | null { + if (view === 'rooms' && stats && stats.processing > 0) { + return stats.processing; + } + return null; +} + +function DashboardBrandLink({ + onNavigate, +}: { + onNavigate: (view: DashboardView) => void; +}) { + return ( + onNavigate('rooms')} + title="EJClaw" + > + EJ + + ); +} + +function DashboardNavLinks({ + activeView, + data, + onAfterNavigate, + onNavigate, + t, +}: { + activeView: DashboardView; + data: DashboardNavData | null; + onAfterNavigate?: () => void; + onNavigate: (view: DashboardView) => void; + t: Messages; +}) { + const stats = navStats(data); + return ( + + ); +} + +export function SideRail({ + activeView, + data, + onNavigate, + t, +}: { + activeView: DashboardView; + data: DashboardNavData | null; + onNavigate: (view: DashboardView) => void; + t: Messages; +}) { + return ( + + ); +} + +export function SectionNav({ + activeView, + data, + drawerOpen, + freshness, + freshnessText, + onCloseDrawer, + onNavigate, + onOpenDrawer, + onRefresh, + refreshing, + t, +}: { + activeView: DashboardView; + data: DashboardNavData | null; + drawerOpen: boolean; + freshness: DashboardFreshness; + freshnessText: string; + onCloseDrawer: () => void; + onNavigate: (view: DashboardView) => void; + onOpenDrawer: () => void; + onRefresh: () => void; + refreshing: boolean; + t: Messages; +}) { + const activeLabel = + navItems(t).find((item) => item.view === activeView)?.label ?? t.nav.rooms; + const showManualRefresh = freshness !== 'fresh'; + + return ( + <> + + + {drawerOpen ? ( + <> + + + + + + ) : null} + + ); +} diff --git a/apps/dashboard/src/EmptyState.tsx b/apps/dashboard/src/EmptyState.tsx new file mode 100644 index 0000000..0410bca --- /dev/null +++ b/apps/dashboard/src/EmptyState.tsx @@ -0,0 +1,5 @@ +import type { ReactNode } from 'react'; + +export function EmptyState({ children }: { children: ReactNode }) { + return
{children}
; +} diff --git a/apps/dashboard/src/GlassesApp.tsx b/apps/dashboard/src/GlassesApp.tsx new file mode 100644 index 0000000..f6b83f6 --- /dev/null +++ b/apps/dashboard/src/GlassesApp.tsx @@ -0,0 +1,207 @@ +import { useEffect, useState } from 'react'; + +import { + type DashboardInboxAction, + type DashboardOverview, + type StatusSnapshot, + fetchDashboardData, + runInboxAction, + sendRoomMessage, +} from './api'; +import { isLocale, matchLocale, type Locale } from './i18n'; +import { GlassesPanel } from './GlassesPanel'; +import './styles.css'; +import './glasses.css'; + +interface GlassesState { + overview: DashboardOverview; + snapshots: StatusSnapshot[]; +} + +type InboxItem = DashboardOverview['inbox'][number]; +type InboxActionKey = `${string}:${DashboardInboxAction}`; + +const REFRESH_INTERVAL_MS = 15_000; +const DASHBOARD_STALE_MS = 75_000; +const LOCALE_STORAGE_KEY = 'ejclaw.dashboard.locale.v2'; + +function makeClientRequestId(): string { + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; +} + +function readInitialLocale(): Locale { + const stored = + typeof window === 'undefined' + ? null + : window.localStorage.getItem(LOCALE_STORAGE_KEY); + if (isLocale(stored)) return stored; + + const languages = + typeof navigator === 'undefined' + ? [] + : [...(navigator.languages || []), navigator.language]; + for (const language of languages) { + const matched = matchLocale(language); + if (matched) return matched; + } + + return 'en'; +} + +function dashboardAgeMs(value: string | null | undefined): number | null { + if (!value) return null; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return null; + return Math.max(0, Date.now() - date.getTime()); +} + +function freshnessLabel( + online: boolean, + generatedAt: string | null | undefined, +): string { + if (!online) return 'offline'; + const age = dashboardAgeMs(generatedAt); + if (age !== null && age > DASHBOARD_STALE_MS) return 'stale'; + return 'fresh'; +} + +function readNickname(): string { + if (typeof window === 'undefined') return ''; + return window.localStorage.getItem('ejclaw-nickname') ?? ''; +} + +export function GlassesApp() { + const [data, setData] = useState(null); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(true); + const [refreshing, setRefreshing] = useState(false); + const [online, setOnline] = useState(() => + typeof navigator === 'undefined' ? true : navigator.onLine, + ); + const [locale] = useState(readInitialLocale); + const [inboxActionKey, setInboxActionKey] = useState( + null, + ); + const [roomMessageKey, setRoomMessageKey] = useState(null); + + async function refresh(showSpinner = false) { + if (showSpinner) setRefreshing(true); + try { + const nextData = await fetchDashboardData(); + setData({ + overview: nextData.overview, + snapshots: nextData.snapshots, + }); + setError(null); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + } finally { + setLoading(false); + setRefreshing(false); + } + } + + async function handleInboxAction( + item: InboxItem, + action: DashboardInboxAction, + ) { + const actionKey: InboxActionKey = `${item.id}:${action}`; + setInboxActionKey(actionKey); + try { + await runInboxAction(item.id, action, { + lastOccurredAt: item.lastOccurredAt, + requestId: makeClientRequestId(), + }); + await refresh(false); + return true; + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + return false; + } finally { + setInboxActionKey(null); + } + } + + async function handleRoomMessage( + roomJid: string, + text: string, + requestId: string, + ) { + setRoomMessageKey(roomJid); + try { + await sendRoomMessage(roomJid, text, requestId, readNickname() || null); + void refresh(false); + return true; + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + return false; + } finally { + setRoomMessageKey(null); + } + } + + useEffect(() => { + document.documentElement.lang = locale; + }, [locale]); + + useEffect(() => { + function handleOnline() { + setOnline(true); + } + + function handleOffline() { + setOnline(false); + } + + window.addEventListener('online', handleOnline); + window.addEventListener('offline', handleOffline); + return () => { + window.removeEventListener('online', handleOnline); + window.removeEventListener('offline', handleOffline); + }; + }, []); + + useEffect(() => { + void refresh(); + const id = window.setInterval(() => { + void refresh(); + }, REFRESH_INTERVAL_MS); + return () => window.clearInterval(id); + }, []); + + if (loading && !data) { + return ( +
+
+ EJClaw + Loading +
+
+ ); + } + + if (!data) { + return ( +
+

{error ?? 'Dashboard unavailable'}

+
+ ); + } + + return ( + void refresh(true)} + onSendRoomMessage={handleRoomMessage} + overview={data.overview} + refreshing={refreshing} + roomMessageKey={roomMessageKey} + snapshots={data.snapshots} + /> + ); +} diff --git a/apps/dashboard/src/GlassesPanel.test.ts b/apps/dashboard/src/GlassesPanel.test.ts new file mode 100644 index 0000000..9ebf0cd --- /dev/null +++ b/apps/dashboard/src/GlassesPanel.test.ts @@ -0,0 +1,120 @@ +import { createElement } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, it } from 'vitest'; + +import { GlassesPanel } from './GlassesPanel'; +import type { DashboardOverview, StatusSnapshot } from './api'; + +const overview: DashboardOverview = { + generatedAt: '2026-06-07T13:00:00.000Z', + services: [], + rooms: { + total: 1, + active: 1, + waiting: 0, + inactive: 0, + }, + tasks: { + total: 1, + active: 1, + paused: 0, + completed: 0, + watchers: { + active: 0, + paused: 0, + completed: 0, + }, + }, + usage: { + rows: [], + fetchedAt: null, + }, + inbox: [ + { + createdAt: '2026-06-07T12:59:30.000Z', + groupKey: 'task:review', + id: 'inbox-1', + kind: 'reviewer-request', + lastOccurredAt: '2026-06-07T12:59:30.000Z', + occurrences: 1, + occurredAt: '2026-06-07T12:59:30.000Z', + roomJid: 'dc:ops', + roomName: 'Ops', + severity: 'warn', + source: 'paired-task', + summary: 'Reviewer requested owner changes', + taskId: 'task-1', + taskStatus: 'active', + title: 'Review follow-up', + }, + ], +}; + +const snapshots: StatusSnapshot[] = [ + { + agentType: 'codex', + assistantName: 'Codex', + serviceId: 'codex-main', + updatedAt: '2026-06-07T13:00:00.000Z', + entries: [ + { + agentType: 'codex', + elapsedMs: 12000, + folder: 'ejclaw', + jid: 'dc:ops', + name: 'Ops', + pendingMessages: false, + pendingTasks: 1, + status: 'processing', + }, + ], + }, +]; + +describe('GlassesPanel', () => { + it('renders a compact display queue and voice input surface', () => { + const html = renderToStaticMarkup( + createElement(GlassesPanel, { + createRequestId: () => 'req-1', + error: null, + freshnessText: 'fresh', + inboxActionKey: null, + locale: 'ko', + onInboxAction: async () => true, + onRefresh: () => {}, + onSendRoomMessage: async () => true, + overview, + refreshing: false, + roomMessageKey: null, + snapshots, + }), + ); + + expect(html).toContain('glasses-shell'); + expect(html).toContain('Review follow-up'); + expect(html).toContain('리뷰'); + expect(html).toContain('Voice'); + }); + + it('tolerates partial status snapshot payloads while data is refreshing', () => { + const html = renderToStaticMarkup( + createElement(GlassesPanel, { + createRequestId: () => 'req-1', + error: null, + freshnessText: 'fresh', + inboxActionKey: null, + locale: 'ko', + onInboxAction: async () => true, + onRefresh: () => {}, + onSendRoomMessage: async () => true, + overview, + refreshing: false, + roomMessageKey: null, + snapshots: [{} as StatusSnapshot], + }), + ); + + expect(html).toContain('glasses-shell'); + expect(html).toContain('Review follow-up'); + }); +}); diff --git a/apps/dashboard/src/GlassesPanel.tsx b/apps/dashboard/src/GlassesPanel.tsx new file mode 100644 index 0000000..817a98a --- /dev/null +++ b/apps/dashboard/src/GlassesPanel.tsx @@ -0,0 +1,607 @@ +import { + type KeyboardEvent, + useEffect, + useMemo, + useRef, + useState, +} from 'react'; +import { Check, Inbox, Mic, RefreshCw, Send, X } from 'lucide-react'; + +import { + type DashboardInboxAction, + type DashboardOverview, + type StatusSnapshot, +} from './api'; +import { formatDate } from './dashboardHelpers'; +import type { Locale } from './i18n'; + +type InboxItem = DashboardOverview['inbox'][number]; +type GlassesMode = 'queue' | 'voice'; + +interface RoomChoice { + jid: string; + label: string; + status: StatusSnapshot['entries'][number]['status']; + pendingTasks: number; +} + +interface SpeechRecognitionResultLike { + readonly 0?: { transcript?: string }; +} + +interface SpeechRecognitionEventLike { + readonly results: ArrayLike; +} + +interface SpeechRecognitionLike { + continuous: boolean; + interimResults: boolean; + lang: string; + maxAlternatives: number; + onend: (() => void) | null; + onerror: (() => void) | null; + onresult: ((event: SpeechRecognitionEventLike) => void) | null; + start: () => void; +} + +type SpeechRecognitionConstructor = new () => SpeechRecognitionLike; + +interface SpeechWindow extends Window { + SpeechRecognition?: SpeechRecognitionConstructor; + webkitSpeechRecognition?: SpeechRecognitionConstructor; +} + +export interface GlassesPanelProps { + createRequestId: () => string; + error: string | null; + freshnessText: string; + inboxActionKey: `${string}:${DashboardInboxAction}` | null; + locale: Locale; + onInboxAction: ( + item: InboxItem, + action: DashboardInboxAction, + ) => Promise; + onRefresh: () => void; + onSendRoomMessage: ( + roomJid: string, + text: string, + requestId: string, + ) => Promise; + overview: DashboardOverview; + refreshing: boolean; + roomMessageKey: string | null; + snapshots: StatusSnapshot[]; +} + +const QUEUE_KIND_ORDER: Record = { + approval: 0, + 'reviewer-request': 1, + 'arbiter-request': 2, + 'ci-failure': 3, + mention: 4, + 'pending-room': 5, +}; + +const SEVERITY_ORDER: Record = { + error: 0, + warn: 1, + info: 2, +}; + +const SPEECH_LOCALES: Record = { + en: 'en-US', + ja: 'ja-JP', + ko: 'ko-KR', + zh: 'zh-CN', +}; + +function getSpeechRecognition(): SpeechRecognitionConstructor | null { + if (typeof window === 'undefined') return null; + const speechWindow = window as SpeechWindow; + return ( + speechWindow.SpeechRecognition ?? + speechWindow.webkitSpeechRecognition ?? + null + ); +} + +function inboxActionsFor(item: InboxItem): DashboardInboxAction[] { + if ( + item.source === 'paired-task' && + (item.kind === 'reviewer-request' || + item.kind === 'approval' || + item.kind === 'arbiter-request') + ) { + return ['run', 'decline', 'dismiss']; + } + return ['dismiss']; +} + +function actionLabel(item: InboxItem, action: DashboardInboxAction): string { + if (action === 'dismiss') return '닫기'; + if (action === 'decline') return '거절'; + if (item.kind === 'approval') return '최종화'; + if (item.kind === 'reviewer-request') return '리뷰'; + if (item.kind === 'arbiter-request') return '중재'; + return '실행'; +} + +function actionIcon(action: DashboardInboxAction) { + if (action === 'decline') return ; + if (action === 'dismiss') return ; + return ; +} + +function sortInboxItems(items: InboxItem[]): InboxItem[] { + return [...items].sort((a, b) => { + const severity = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]; + if (severity !== 0) return severity; + const kind = QUEUE_KIND_ORDER[a.kind] - QUEUE_KIND_ORDER[b.kind]; + if (kind !== 0) return kind; + return b.lastOccurredAt.localeCompare(a.lastOccurredAt); + }); +} + +function buildRoomChoices(snapshots: StatusSnapshot[]): RoomChoice[] { + const rooms = new Map(); + for (const snapshot of snapshots) { + const entries = Array.isArray(snapshot.entries) ? snapshot.entries : []; + for (const entry of entries) { + const existing = rooms.get(entry.jid); + const label = entry.name || entry.folder || entry.jid; + if (!existing) { + rooms.set(entry.jid, { + jid: entry.jid, + label, + pendingTasks: entry.pendingTasks, + status: entry.status, + }); + continue; + } + if ( + entry.status === 'processing' || + entry.pendingTasks > existing.pendingTasks + ) { + rooms.set(entry.jid, { + jid: entry.jid, + label, + pendingTasks: entry.pendingTasks, + status: entry.status, + }); + } + } + } + return [...rooms.values()].sort((a, b) => { + if (a.status === 'processing' && b.status !== 'processing') return -1; + if (b.status === 'processing' && a.status !== 'processing') return 1; + return b.pendingTasks - a.pendingTasks || a.label.localeCompare(b.label); + }); +} + +function clampIndex(index: number, length: number): number { + if (length <= 0) return 0; + return Math.max(0, Math.min(index, length - 1)); +} + +function nextIndex(index: number, length: number, delta: number): number { + if (length <= 0) return 0; + return (index + delta + length) % length; +} + +function readTranscript(event: SpeechRecognitionEventLike): string { + return Array.from(event.results) + .map((result) => result[0]?.transcript?.trim() ?? '') + .filter(Boolean) + .join(' ') + .trim(); +} + +interface QueueCardProps { + inboxActionKey: `${string}:${DashboardInboxAction}` | null; + inboxActions: DashboardInboxAction[]; + inboxItems: InboxItem[]; + locale: Locale; + onInboxAction: ( + item: InboxItem, + action: DashboardInboxAction, + ) => Promise; + selectedActionIndex: number; + selectedInbox: InboxItem | undefined; + selectedInboxIndex: number; + setSelectedActionIndex: (index: number) => void; +} + +function QueueCard({ + inboxActionKey, + inboxActions, + inboxItems, + locale, + onInboxAction, + selectedActionIndex, + selectedInbox, + selectedInboxIndex, + setSelectedActionIndex, +}: QueueCardProps) { + if (!selectedInbox) { + return ( +
+
+ Queue clear + 새 요청 없음 +
+
+ ); + } + + return ( +
+
+ + {selectedInbox.kind} + + + {selectedInboxIndex + 1}/{inboxItems.length} + +
+

{selectedInbox.title}

+

{selectedInbox.summary}

+
+
+
Target
+
+ {selectedInbox.roomName ?? + selectedInbox.groupFolder ?? + selectedInbox.roomJid ?? + selectedInbox.taskId ?? + '-'} +
+
+
+
Time
+
{formatDate(selectedInbox.lastOccurredAt, locale)}
+
+
+
+ {inboxActions.map((action, index) => { + const actionKey = `${selectedInbox.id}:${action}`; + const busy = inboxActionKey === actionKey; + return ( + + ); + })} +
+
+ ); +} + +interface VoiceCardProps { + canListen: boolean; + listening: boolean; + onSendVoiceText: () => void; + onStartListening: () => void; + selectedRoom: RoomChoice | undefined; + sendingVoice: boolean; + setSelectedRoomIndex: (index: number) => void; + setVoiceText: (value: string) => void; + rooms: RoomChoice[]; + voiceText: string; +} + +function VoiceCard({ + canListen, + listening, + onSendVoiceText, + onStartListening, + selectedRoom, + sendingVoice, + setSelectedRoomIndex, + setVoiceText, + rooms, + voiceText, +}: VoiceCardProps) { + return ( +
+
+ voice + {selectedRoom?.label ?? 'No room'} +
+