diff --git a/.env.example b/.env.example index c409bed..def6673 100644 --- a/.env.example +++ b/.env.example @@ -31,7 +31,7 @@ CLAUDE_THINKING=adaptive # Claude thinking mode # --- 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: +# Codex fast mode / goals: ~/.codex/config.toml: # [features] # fast_mode = true # goals = true # /goal — opt-in, default OFF on Codex 0.133+ @@ -40,10 +40,6 @@ CODEX_EFFORT=xhigh # Codex reasoning effort 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: diff --git a/.gitignore b/.gitignore index deda64c..0f4b21e 100644 --- a/.gitignore +++ b/.gitignore @@ -4,10 +4,6 @@ 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/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 3211006..e68c851 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ - 기본 Claude 모델을 Claude Opus 5.5(`claude-opus-5-5`)로 상향. Opus 5.5는 Claude Code CLI 2.1.280 이상이 필요해 `@anthropic-ai/claude-agent-sdk`를 0.3.153 → 0.3.286(번들 CLI 2.1.286)으로 올림 (8b68885) - `@openai/codex`를 0.133.0 → 0.159.3으로 상향. 구버전이 매 실행마다 내던 `failed to decode models response: unknown variant max` 오류와 로그 폭주가 사라지고, 단순 리뷰 턴이 49초 → 5초로 단축됨 (a7f2e02) +### Removed + +- 웹 대시보드(`src/web-dashboard-*`, `apps/dashboard`), Android 앱(`apps/android`), Glasses UI와 이를 위해서만 있던 설정 저장소(`settings-store`, `settings-store-moa`, `room-skill-settings`, `runtime-inventory`, `codex-live-status`, `settings-effort`), `WEB_DASHBOARD_*` 설정, `dashboard:*`/`android:*` 스크립트, react·vite·playwright 의존성. 잘못된 계정(`~/.codex`)을 갱신하던 Codex 계정 새로고침 루프도 함께 제거. 호스트 증거 도구의 `dashboard_dist`/`android_debug_apk` 항목 제거. Discord 상태 대시보드는 그대로 유지 + ### Fixed - Codex 계정이 1개일 때 두 방이 동시에 Codex를 쓰면 두 번째 실행이 "Codex rotation pool unavailable"로 즉시 실패하고 리뷰가 조용히 생략되던 문제 수정. 잠금이 다른 실행에 잡혀 있으면 최대 15분 기다림 (30ba510) diff --git a/apps/android/.gitignore b/apps/android/.gitignore deleted file mode 100644 index bf9b3aa..0000000 --- a/apps/android/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -.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 deleted file mode 100644 index 8277b94..0000000 --- a/apps/android/README.md +++ /dev/null @@ -1,54 +0,0 @@ -# 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 deleted file mode 100644 index 4fd992b..0000000 --- a/apps/android/app/build.gradle.kts +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index a8e9362..0000000 --- a/apps/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - 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 deleted file mode 100644 index 35c53c2..0000000 --- a/apps/android/app/src/main/java/com/ejclaw/android/MainActivity.kt +++ /dev/null @@ -1,166 +0,0 @@ -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 deleted file mode 100644 index ff4f241..0000000 --- a/apps/android/app/src/main/java/com/ejclaw/android/api/EJClawApi.kt +++ /dev/null @@ -1,104 +0,0 @@ -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 deleted file mode 100644 index ad23939..0000000 --- a/apps/android/app/src/main/java/com/ejclaw/android/display/DisplayBridge.kt +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index d6f3f33..0000000 --- a/apps/android/app/src/main/java/com/ejclaw/android/display/DisplaySurface.kt +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 45fba5e..0000000 --- a/apps/android/app/src/main/java/com/ejclaw/android/display/MetaDatDisplaySurface.kt +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 9dc4271..0000000 --- a/apps/android/app/src/main/java/com/ejclaw/android/display/NoopDisplaySurface.kt +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index cc27f99..0000000 --- a/apps/android/app/src/main/java/com/ejclaw/android/model/Models.kt +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 13c77c7..0000000 --- a/apps/android/app/src/main/java/com/ejclaw/android/ui/EJClawView.kt +++ /dev/null @@ -1,80 +0,0 @@ -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 deleted file mode 100644 index f74f311..0000000 --- a/apps/android/app/src/main/res/values/strings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - EJClaw - diff --git a/apps/android/app/src/main/res/values/styles.xml b/apps/android/app/src/main/res/values/styles.xml deleted file mode 100644 index 77f9795..0000000 --- a/apps/android/app/src/main/res/values/styles.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - 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 deleted file mode 100644 index fef849a..0000000 --- a/apps/android/app/src/main/res/xml/network_security_config.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - 100.101.210.95 - - diff --git a/apps/android/build.gradle.kts b/apps/android/build.gradle.kts deleted file mode 100644 index e2572a7..0000000 --- a/apps/android/build.gradle.kts +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index bae9034..0000000 --- a/apps/android/gradle.properties +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index 1b33c55..0000000 Binary files a/apps/android/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/apps/android/gradle/wrapper/gradle-wrapper.properties b/apps/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index d4081da..0000000 --- a/apps/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100755 index 23d15a9..0000000 --- a/apps/android/gradlew +++ /dev/null @@ -1,251 +0,0 @@ -#!/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 deleted file mode 100644 index db3a6ac..0000000 --- a/apps/android/gradlew.bat +++ /dev/null @@ -1,94 +0,0 @@ -@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 deleted file mode 100644 index e45563e..0000000 --- a/apps/android/local.properties.example +++ /dev/null @@ -1,7 +0,0 @@ -## 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 deleted file mode 100644 index 4ac0ad0..0000000 --- a/apps/android/settings.gradle.kts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 3fdc00b..0000000 --- a/apps/dashboard/index.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - EJClaw Ops - - -
- - - diff --git a/apps/dashboard/public/icons/icon-192.png b/apps/dashboard/public/icons/icon-192.png deleted file mode 100644 index 90ed779..0000000 Binary files a/apps/dashboard/public/icons/icon-192.png and /dev/null differ diff --git a/apps/dashboard/public/icons/icon-192.svg b/apps/dashboard/public/icons/icon-192.svg deleted file mode 100644 index 7ac3f43..0000000 --- a/apps/dashboard/public/icons/icon-192.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/apps/dashboard/public/icons/icon-512.png b/apps/dashboard/public/icons/icon-512.png deleted file mode 100644 index 9c4c78a..0000000 Binary files a/apps/dashboard/public/icons/icon-512.png and /dev/null differ diff --git a/apps/dashboard/public/icons/icon-512.svg b/apps/dashboard/public/icons/icon-512.svg deleted file mode 100644 index 7594125..0000000 --- a/apps/dashboard/public/icons/icon-512.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/apps/dashboard/public/manifest.webmanifest b/apps/dashboard/public/manifest.webmanifest deleted file mode 100644 index 3c78ff5..0000000 --- a/apps/dashboard/public/manifest.webmanifest +++ /dev/null @@ -1,27 +0,0 @@ -{ - "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 deleted file mode 100644 index f71f86a..0000000 --- a/apps/dashboard/public/offline.html +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - - EJClaw Offline - - - -
- EJClaw -

Offline

-

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

- -
- - diff --git a/apps/dashboard/public/sw.js b/apps/dashboard/public/sw.js deleted file mode 100644 index ec1b737..0000000 --- a/apps/dashboard/public/sw.js +++ /dev/null @@ -1,78 +0,0 @@ -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 deleted file mode 100644 index 824178c..0000000 --- a/apps/dashboard/src/App.tsx +++ /dev/null @@ -1,683 +0,0 @@ -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 { - isLocale, - 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 { - overview: DashboardOverview; - snapshots: StatusSnapshot[]; - tasks: DashboardTask[]; -} - -type FreshnessLevel = DashboardFreshness; - -const REFRESH_INTERVAL_MS = 15_000; -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 = - 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 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 null; - return Math.max(0, Date.now() - date.getTime()); -} - -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 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 canUsePwaCore(): boolean { - return ( - typeof window !== 'undefined' && - window.isSecureContext && - 'serviceWorker' in navigator - ); -} - -function formatDuration(value: number | null, t: Messages): string { - if (value === null) return '-'; - const seconds = Math.floor(value / 1000); - if (seconds < 60) return `${seconds}${t.units.second}`; - const minutes = Math.floor(seconds / 60); - if (minutes < 60) return `${minutes}${t.units.minute}`; - const hours = Math.floor(minutes / 60); - return `${hours}${t.units.hour} ${minutes % 60}${t.units.minute}`; -} - -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}`; -} - -const ROOM_BOARD_FORMATTERS = { - formatDate, - formatDuration, - formatLiveElapsed, - senderRoleClass, - statusLabel, -}; - -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}`), - ); -} - -function LoadingSkeleton({ t }: { t: Messages }) { - return ( -
-
- - - -
-
- {Array.from({ length: 4 }, (_, index) => ( -
- - - -
- ))} -
-
- ); -} - -function DashboardErrorCard({ - error, - onRetry, - refreshing, - t, -}: { - error: string; - onRetry: () => void; - refreshing: boolean; - t: Messages; -}) { - return ( -
- - {t.error.api} - {humanizeError(error, t)} - - -
- ); -} - -function App() { - const [data, setData] = useState(null); - const [error, setError] = useState(null); - const [loading, setLoading] = useState(true); - const [refreshing, setRefreshing] = useState(false); - 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) { - setLocale(nextLocale); - 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); - setError(null); - } catch (err) { - setError(err instanceof Error ? err.message : String(err)); - } finally { - setLoading(false); - setRefreshing(false); - } - } - - 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(() => { - void refresh(); - }, REFRESH_INTERVAL_MS); - 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; - - function handleKeyDown(event: KeyboardEvent) { - if (event.key === 'Escape') setDrawerOpen(false); - } - - window.addEventListener('keydown', handleKeyDown); - return () => window.removeEventListener('keydown', handleKeyDown); - }, [drawerOpen]); - - if (loading && !data) { - return ; - } - - const roomOptions = data ? buildRoomOptions(data.snapshots) : []; - const freshness = dashboardFreshness(online, data?.overview.generatedAt); - - return ( -
- -
- setDrawerOpen(false)} - onNavigate={navigateToView} - onOpenDrawer={() => setDrawerOpen(true)} - onRefresh={() => void refresh(true)} - refreshing={refreshing} - t={t} - /> - - {error ? ( - void refresh(true)} - refreshing={refreshing} - t={t} - /> - ) : null} - - {data ? ( -
- {activeView === 'usage' ? ( -
-
-

{t.panels.usage}

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

{t.panels.rooms}

- {t.panels.queue} -
- - -
- ) : null} - - {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} - - {activeView === 'settings' ? ( -
-
-

{t.settings.title}

-
- { - if (!serviceRestarting) void handleServiceRestart(); - }} - t={t} - /> -
- ) : null} -
- ) : null} -
-
- ); -} - -export default App; diff --git a/apps/dashboard/src/DashboardNav.tsx b/apps/dashboard/src/DashboardNav.tsx deleted file mode 100644 index fab4d2c..0000000 --- a/apps/dashboard/src/DashboardNav.tsx +++ /dev/null @@ -1,245 +0,0 @@ -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 deleted file mode 100644 index 0410bca..0000000 --- a/apps/dashboard/src/EmptyState.tsx +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index f6b83f6..0000000 --- a/apps/dashboard/src/GlassesApp.tsx +++ /dev/null @@ -1,207 +0,0 @@ -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 deleted file mode 100644 index 9ebf0cd..0000000 --- a/apps/dashboard/src/GlassesPanel.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -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 deleted file mode 100644 index 817a98a..0000000 --- a/apps/dashboard/src/GlassesPanel.tsx +++ /dev/null @@ -1,607 +0,0 @@ -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'} -
-