Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/apk.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ jobs:
# 测试失败后整个运行要挂几十分钟才收尾(PR #204:20:23 就失败了,21:00 运行才结束)。
environment: ${{ (github.ref == 'refs/heads/main' && github.event_name != 'pull_request') && 'apk-release' || 'apk-ci' }}
env:
BUILD_TOOLS: "35.0.0"
PLATFORM: "android-35"
BUILD_TOOLS: "36.0.0"
PLATFORM: "android-36.1"
NDK: "27.2.12479018"
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
Expand Down
2 changes: 2 additions & 0 deletions android/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />
<!-- 锁屏验证(Consent.java):安卓 11+ 用 BiometricPrompt 验过锁屏才把安全开关存到下次启动。
平台从 28 起要求调用方声明 USE_BIOMETRIC(普通权限,装时自动授予,不弹框;更老的系统不认这条,无影响)。
本应用不调 FingerprintManager,废弃的 USE_FINGERPRINT 不需要;缺这条时 authenticate() 会直接抛
Expand Down Expand Up @@ -43,6 +44,7 @@

<!-- 软件包可见性(30 起):查 Shizuku 装没装、设备工具列应用 / 打开别的应用 -->
<queries>
<provider android:authorities="miui.statusbar.notification.public" />
<package android:name="moe.shizuku.privileged.api" />
<!-- 可选集成「工作岛」:设置里开启后,网关用 pm list packages 检测它装没装 -->
<package android:name="com.dafeiyu.workisland" />
Expand Down
2 changes: 1 addition & 1 deletion android/assets/i18n/java-en.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions android/java/cc/codroid/GatewayService.java
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ public void bytes(long d, long t) {
pb.environment().put("CCAPP_SPAWN_KEY", "stdin");
// 界面地址探测的结果(见 Env.checkHost):回退设备上让网关把界面地址并进主地址(gateway/gw/access.mjs 的 UI_HOST)
pb.environment().put("CCAPP_UI_HOST", Env.HOST);
if (WorkIslandNotifications.supported()) pb.environment().put("CCAPP_NATIVE_WORK_ISLAND", "1");
pb.redirectInput(ProcessBuilder.Redirect.PIPE);
pb.directory(env.app);
pb.redirectErrorStream(true);
Expand Down
3 changes: 3 additions & 0 deletions android/java/cc/codroid/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -1952,6 +1952,9 @@ private void showWeb() {
}
/** 界面里的外观设置(auto / light / dark),下次启动时安装页照着上色 */
/** 界面最终用的语言(i18n.js 解析过的 code,不是 auto):外壳的通知、安装页、更新文案跟着换 */
@android.webkit.JavascriptInterface public void islandAvatar(String k, String data) {
if (Env.bridgeOk(k) && WorkIslandNotifications.supported()) WorkIslandNotifications.saveAvatar(MainActivity.this, data);
}
@android.webkit.JavascriptInterface public void langPref(String k, String code) { if (!Env.bridgeOk(k)) return; Tr.set(code); }
@android.webkit.JavascriptInterface public void themePref(String k, String p) { if (!Env.bridgeOk(k)) return;
if ("auto".equals(p) || "light".equals(p) || "dark".equals(p))
Expand Down
159 changes: 154 additions & 5 deletions android/java/cc/codroid/Notify.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package cc.codroid;

import android.app.KeyguardManager;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.PowerManager;
import android.service.notification.StatusBarNotification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
Expand All @@ -25,7 +30,7 @@
* 等权限确认 / 计划批准 / 选择题 → 单独一个渠道的通知,带命令摘要(不弹横幅)。
* 通知里只放「拒绝」和「打开查看」:通知只能显示截断的摘要,看不全的命令不该在这里放行。
*
* 数据来源:订阅网关的事件流(/api/events),网关协议不动。每条 state 事件都带当前全部待确认项,
* 数据来源:订阅网关的事件流(/api/events)。每条 state 事件都带当前全部待确认项,
* 和已发出的通知比对 —— 新的发、答掉的撤,断线重连或重放都不会重复。
* 跑在 GatewayService 里:界面被关了、只剩前台服务时也能发。
*/
Expand All @@ -47,6 +52,22 @@ static Notify get(Context c) {
private final Context ctx;
private final NotificationManager nm;
private final SharedPreferences sp;
private final WorkIslandNotifications workIsland;
private boolean islandSynced;
private boolean islandMode;
private JSONObject liveReply;
private volatile boolean screenObserver;
private static final String REPLY_MARKER = "cccodroid.workIslandReply";
private final BroadcastReceiver onScreenState = new BroadcastReceiver() {
@Override public void onReceive(Context c, Intent intent) {
synchronized (Notify.this) {
if (!screenObserver) return;
boolean screenOff = Intent.ACTION_SCREEN_OFF.equals(intent.getAction());
if (screenOff) redactReplies();
workIsland.refreshIcons(!screenOff && unlocked());
}
}
};
private Thread loop;
private volatile boolean stopping;

Expand All @@ -66,6 +87,7 @@ static Notify get(Context c) {
private Notify(Context c) {
ctx = c;
nm = c.getSystemService(NotificationManager.class);
workIsland = WorkIslandNotifications.supported() ? new WorkIslandNotifications(ctx, nm, this::unlocked) : null;
sp = c.getSharedPreferences("notify", Context.MODE_PRIVATE);
NotificationChannel done = new NotificationChannel(CH_DONE, Tr.t("任务完成"), NotificationManager.IMPORTANCE_DEFAULT);
done.setDescription(Tr.t("应用在后台时,一轮任务跑完提醒一下"));
Expand All @@ -87,18 +109,31 @@ JSONObject status() throws Exception {
.put("chAsk", a == null || a.getImportance() != NotificationManager.IMPORTANCE_NONE);
}

void set(JSONObject req) {
synchronized void set(JSONObject req) {
SharedPreferences.Editor e = sp.edit();
if (req.has("done")) e.putBoolean("done", req.optBoolean("done", true));
if (req.has("ask")) e.putBoolean("ask", req.optBoolean("ask", true));
e.apply();
if (!askOn()) clearAsks();
if (!doneOn()) redactReplies();
}

// 服务快速停了又起(审查 #105 06-006):以前先看旧线程还活着就返回、stopping 却没复位,旧线程随后退出,就再没人订阅了。
// 现在先复位让旧线程接着干;它恰好已经走出循环的,退出时自己看到没在停,再起一条
synchronized void start() {
stopping = false;
if (workIsland != null && !screenObserver) {
// Remove stale private notifications left by a previous process.
redactReplies();
workIsland.cancel();
try {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_USER_PRESENT);
ctx.registerReceiver(onScreenState, filter, Context.RECEIVER_NOT_EXPORTED);
screenObserver = true;
} catch (RuntimeException ignored) { /* no observer: no snippets or avatars */ }
}
if (loop != null && loop.isAlive()) return;
spawn();
}
Expand All @@ -108,7 +143,23 @@ private void spawn() {
loop.start();
}

synchronized void stop() { stopping = true; }
synchronized void stop() {
stopping = true;
resetIsland();
if (screenObserver) {
ctx.unregisterReceiver(onScreenState);
screenObserver = false;
}
}

private void resetIsland() {
islandSynced = false;
if (workIsland != null) {
liveReply = null;
redactReplies();
workIsland.cancel();
}
}

/** 界面回到前台:确认通知都撤掉(卡片就在眼前) */
void onForeground() { clearAsks(); }
Expand All @@ -132,7 +183,7 @@ private void run() {
while (!stopping) {
HttpURLConnection c = null;
try {
c = Env.gateway("/api/events");
c = Env.gateway(workIsland == null ? "/api/events" : "/api/events?notify=1");
c.setConnectTimeout(3000);
c.setReadTimeout(45_000); // 网关每 15 秒一个心跳,45 秒没动静就当断了
if (lastId != null) c.setRequestProperty("Last-Event-ID", lastId);
Expand All @@ -153,6 +204,7 @@ private void run() {
// 网关还没起来 / 正在重启:安静地等,别刷日志
} finally {
if (c != null) c.disconnect();
synchronized (this) { resetIsland(); }
}
sleep(2000);
}
Expand All @@ -164,6 +216,23 @@ private void onEvent(String json) {
JSONObject ev = new JSONObject(json);
String type = ev.optString("type");
synchronized (this) {
if (workIsland != null && !stopping) {
if ("sync".equals(type)) {
islandSynced = true;
setIslandMode(ev.optBoolean("workIslandMode"));
renderIsland(ev.optJSONObject("workIsland"));
} else if (islandSynced && "work_island".equals(type)) {
renderIsland(ev.optJSONObject("frame"));
} else if (islandSynced && "work_island_mode".equals(type)) {
setIslandMode(ev.optBoolean("enabled"));
} else if (islandSynced && islandMode && "work_island_reply".equals(type)) {
liveReply = ev;
} else if ("work_island_reply_clear".equals(type)) {
redactReplies();
} else if (islandSynced && "work_island_preview".equals(type)) {
workIsland.preview(openIntent("", 82));
}
}
if ("hello".equals(type) || "state".equals(type)) {
if ("hello".equals(type)) {
// 订阅期间网关重启过(启动号变了):旧轮次等不到终止事件,文本回收(BUG-A05)
Expand All @@ -184,6 +253,53 @@ private void onEvent(String json) {
}
}

private void renderIsland(JSONObject frame) {
workIsland.render(frame, openIntent(frame == null ? "" : validatedSid(frame), 81));
}

private void setIslandMode(boolean on) {
if (islandMode != on) clearAsks();
islandMode = on;
if (!on) redactReplies();
syncAsks();
}

private boolean unlocked() {
KeyguardManager keyguard = ctx.getSystemService(KeyguardManager.class);
PowerManager power = ctx.getSystemService(PowerManager.class);
return screenObserver && power != null && power.isInteractive() && keyguard != null
&& !keyguard.isKeyguardLocked() && !keyguard.isDeviceLocked();
}

private void redactReplies() {
liveReply = null;
// Do not recreate dismissed notifications. Only replace currently posted snippets in place.
for (StatusBarNotification entry : nm.getActiveNotifications()) {
if (!TAG_DONE.equals(entry.getTag())) continue;
Notification current = entry.getNotification();
if (current.extras.getBoolean(REPLY_MARKER)) {
nm.notify(TAG_DONE, entry.getId(), islandDone(false, current.contentIntent, ""));
}
}
}

private Notification islandDone(boolean failed, PendingIntent open, String reply) {
String title = failed ? Tr.t("出错了") : Tr.t("已完成");
String status = failed ? title : Tr.t("这一轮跑完了");
Notification.Builder b = new Notification.Builder(ctx, CH_DONE)
.setSmallIcon(WorkIslandNotifications.icon(ctx)).setContentTitle(title)
.setContentText(reply.isEmpty() ? status : reply)
.setContentIntent(open).setAutoCancel(true).setOnlyAlertOnce(true);
if (!reply.isEmpty()) {
android.os.Bundle marker = new android.os.Bundle();
marker.putBoolean(REPLY_MARKER, true);
b.addExtras(marker).setStyle(new Notification.BigTextStyle().bigText(reply))
.setVisibility(Notification.VISIBILITY_PRIVATE)
.setPublicVersion(islandDone(false, open, ""));
}
return b.build();
}

/** 并行多会话:state 里的 runs 是所有正在跑的轮次(旧网关只有 run) */
private void onState(JSONObject st) {
pending.clear();
Expand Down Expand Up @@ -218,6 +334,8 @@ private void syncAsks() {
private void onRunEnd(JSONObject ev) {
String runId = ev.optString("runId");
String text = runText.remove(runId);
JSONObject reply = liveReply;
liveReply = null;
// 只撤这一轮的确认项:别的会话可能还在等(紧跟着的 state 事件会再对齐一次)
for (java.util.Iterator<JSONObject> it = pending.values().iterator(); it.hasNext(); )
if (runId.equals(it.next().optString("runId"))) it.remove();
Expand All @@ -229,7 +347,20 @@ private void onRunEnd(JSONObject ev) {
if (ev.optBoolean("aborted") || !ev.optString("auto").isEmpty() || MainActivity.visible || !doneOn()) return;
// 网关的 run_end 用 failed / isError 表示没成(审查 #105 06-004:以前只看 error 字段,网关从来不带,一律报「已完成」)
boolean failed = ev.optBoolean("failed") || ev.optBoolean("isError") || ev.has("error") && !ev.isNull("error");
String sid = sidOf(ev);
String sid = validatedSid(ev);
if (workIsland != null && (islandMode || !islandSynced)) {
String snippet = "";
long age = reply == null ? Long.MAX_VALUE : System.currentTimeMillis() - reply.optLong("at");
if (!failed && islandSynced && !sid.isEmpty() && reply != null && age >= 0 && age < 10_000
&& runId.equals(reply.optString("runId")) && sid.equals(validatedSid(reply)) && unlocked()) {
snippet = clip(reply.optString("text"), 160);
}
int id = sid.isEmpty() ? ID_DONE : sid.hashCode();
PendingIntent open = openIntent(sid, 0);
nm.notify(TAG_DONE, id, islandDone(failed, open, snippet));
if (!snippet.isEmpty() && !unlocked()) redactReplies();
return;
}
// 每个会话各留最新一条:并行时几个会话先后跑完,不互相顶掉
nm.notify(TAG_DONE, sid.isEmpty() ? ID_DONE : sid.hashCode(), new Notification.Builder(ctx, CH_DONE)
.setSmallIcon(android.R.drawable.stat_notify_chat)
Expand All @@ -256,6 +387,19 @@ private void onSchedNote(JSONObject ev) {
}

private Notification askNote(JSONObject p) {
if (workIsland != null && (islandMode || !islandSynced)) {
String title;
switch (p.optString("tool")) {
case "Bash": case "PowerShell": title = Tr.t("命令待确认 · 点此打开会话"); break;
case "ExitPlanMode": title = Tr.t("计划待批准 · 点此打开会话"); break;
case "AskUserQuestion": title = Tr.t("提问待回答 · 点此打开会话"); break;
default: title = Tr.t("操作待确认 · 点此打开会话");
}
return new Notification.Builder(ctx, CH_ASK)
.setSmallIcon(WorkIslandNotifications.icon(ctx)).setContentTitle(Tr.t("待确认"))
.setContentText(title).setContentIntent(openIntent(validatedSid(p), 1))
.setAutoCancel(true).build();
}
String tool = p.optString("tool");
JSONObject in = p.optJSONObject("input");
if (in == null) in = new JSONObject();
Expand Down Expand Up @@ -323,6 +467,11 @@ static boolean gatewayChanged(String boot, String lastBoot) {
/** 会话号:JSON 里是 null 时 optString 会给出字符串 "null",要单独判 */
private static String sidOf(JSONObject o) { return o.isNull("sessionId") ? "" : o.optString("sessionId", ""); }

private static String validatedSid(JSONObject o) {
String sid = sidOf(o);
return sid.matches("[A-Za-z0-9_-]{1,80}") ? sid : "";
}

private PendingIntent openIntent(String sessionId, int req) {
Intent i = MainActivity.internal(ctx, ACTION_OPEN)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
Expand Down
Loading
Loading