Skip to content
Merged
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
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ construct a full bookmark index on a panel paint. Native actions stay behind Lib

Cover lookups use a one-row, 16 KiB local-only budget with zero round-trips; post-paint
cover batches are limited to four and only the companion fetches or writes images.
Copy replacement and finish outboxes are companion-owned, account scoped and checkpointed before legacy sources retire. Grouped lists and end-of-book cards are bounded projections; local recommendation review has eight rows. No catalog transport or whole-list aggregation runs in Lua. Keep queue checkpoints available while reading; pause background transfer work, never persistence of reader intent.

Catalog progress is one companion-published row (16 KiB) with zero polling round-trips.
Catalog/root windows decode at most 24 display rows; native Home batches count every nested
book/name plus their stats row. Plans, query interpretation, refresh policy and search stay
Expand Down
1 change: 1 addition & 0 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ CrossInk 2.x only; 1.6 is retired).
## Next release (0.12): BookSync Home

| Outcome | Platforms | Status |
| Finish the server-free catalog cutover: companion-owned copies, grouping, settings recommendations and end-of-book snapshots/outboxes. | Android (Xteink deferred under Android-first ruling) | building on feature/0.12 (F12-Q2 step 4) |
|---|---|---|
| Word of the day, local Reading buddy and hardware Light picker widgets; Highlight and A year ago await authorized server snapshots. | Android; X4 Pro/X4/X3 deferred to firmware | building (device acceptance pending) |
| Server-free Android catalog operations: companion-owned covers, refresh, copies, recommendations and end-of-book snapshots and commands. | Android; X4 Pro, X4, X3 later under Android-first ruling | building: covers, mirror planning and query/store reads migrated; copies, grouping, recommendations and finish pending |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class CommandProvider : ContentProvider() {
val COMMANDS = setOf(
Contract.NET_UP, Contract.NET_DONE, Contract.WIFI_OFF, Contract.SLEEP_NOW, Contract.SETTINGS, Contract.STATS,
Contract.RELAUNCH, Contract.SETUP_LATER, Contract.REPORT, SleepScreen.ACTION_POOL,
Worker.ACTION_STORAGE, Worker.ACTION_COPIES, Worker.ACTION_SLEEP_REFRESH,
Worker.ACTION_STORAGE, Worker.ACTION_SLEEP_REFRESH,
Worker.ACTION_SQLITE_STRESS, Worker.ACTION_PATCH, Updater.ACTION_UPDATE,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,36 @@ object LibraryAccount {
var result: Map<String,Any?>? = null
command(ctx, { result = it.catalog(page,limit) }, { done(result,it) }, invalidate = false)
}
fun recommendedSettings(ctx:Context,args:Map<*,*>,done:(Map<String,Any?>?,String?)->Unit) {
val app=ctx.applicationContext
queue.execute {
val start=System.nanoTime()
val result=runCatching {
val definitions=adapter(app).recommendedSettings()
if(args["definitions"]==true) mapOf("items" to definitions) else {
val result=RecommendationPlan.evaluate(definitions,args)
val destination=java.io.File(android.os.Environment.getExternalStorageDirectory(),"koreader/settings/orbit-recommended.json")
destination.parentFile?.mkdirs()
val tmp=java.io.File(destination.path+".new")
val rows=(result["items"] as? List<*>).orEmpty().map { raw ->
val row=raw as Map<*,*>;row.filterKeys { it in setOf("id","label","state","yours","orbit","was","reason") }
}
tmp.writeText(org.json.JSONObject(mapOf("v" to 1,"at" to System.currentTimeMillis(),"items" to rows)).toString())
check(tmp.renameTo(destination));result
}
}
OLog.i("library.recommendations ms=${(System.nanoTime()-start)/1_000_000}")
main.post { result.fold({done(it,null)},{done(null,"unavailable")}) }
}
}
fun catalogAction(ctx: Context, owner: String, action: String, args: Map<*,*>, done: (Map<String,Any?>?,String?) -> Unit) {
val app=ctx.applicationContext
queue.execute {
try { adapter(app).catalogAction(owner,action,args) { value,error -> main.post { done(value,error) } } }
catch(e: ServerFailure) { main.post { done(null,e.kind) } }
catch(_: Exception) { main.post { done(null,"unavailable") } }
}
}
fun catalogControl(ctx: Context, owner: String, action: String, manual: Boolean, done: (Map<String,Any?>?,String?) -> Unit) {
val app=ctx.applicationContext
queue.execute {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ object Commands {
return SleepScreen.onPool(ctx, intent.getStringExtra("reason") ?: "plugin")
}
// The cache worker's jobs (docs/design/companion-worker.md): every mode, no service needed.
if (intent.action == Worker.ACTION_STORAGE || intent.action == Worker.ACTION_COPIES || intent.action == Worker.ACTION_SLEEP_REFRESH || intent.action == Worker.ACTION_SQLITE_STRESS || intent.action == Worker.ACTION_PATCH) return Worker.onIntent(ctx, intent)
if (intent.action == Worker.ACTION_STORAGE || intent.action == Worker.ACTION_SLEEP_REFRESH || intent.action == Worker.ACTION_SQLITE_STRESS || intent.action == Worker.ACTION_PATCH) return Worker.onIntent(ctx, intent)
// The plugin's "Check for updates": every mode (the plugin downloads nothing itself).
if (intent.action == Updater.ACTION_UPDATE) return Updater.onPluginAsked(ctx.applicationContext, intent.getStringExtra("reason") ?: "plugin")
val action = intent.action ?: return
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: MIT
package net.fledgewing.orbitcompanion

/** Eight local settings, never a catalog. The connector supplies its native binding descriptors;
* observations and compare-before-write acknowledgements stay behind Library on the reader. */
object RecommendationPlan {
fun evaluate(definitions:List<Map<String,Any?>>,args:Map<*,*>):Map<String,Any?> {
require(definitions.size<=8)
val record=(args["record"] as? Map<*,*>).orEmpty()
val prior=(record["items"] as? Map<*,*>).orEmpty().toMutableMap()
val backup=(args["backup"] as? Map<*,*>).orEmpty().toMutableMap()
val observed=(args["observations"] as? Map<*,*>).orEmpty()
val choices=(args["choices"] as? Map<*,*>).orEmpty()
val failed=(args["failed"] as? List<*>).orEmpty()
val writes=mutableListOf<Map<String,Any?>>()
val rows=definitions.map { item ->
val id=item["id"] as String
val obs=(observed[id] as? Map<*,*>).orEmpty()
val current=obs["current"];val ours=item["ours"]
val status=prior[id]
var next=status
val choice=choices[id] ?: choices["all"].takeUnless { it=="ours" && status=="kept" || it=="undo" && item["required_by"]=="wifi" && args["wifi"]==true }
val available=obs["available"]==true
fun apply() {
backup[id]=mapOf("had" to obs.containsKey("current"),"prior" to current,"ours" to ours)
writes.add(mapOf("id" to id,"expected" to current,"value" to ours));next="applied"
}
if(choice=="mine" && status=="conflict") next="kept"
else if(choice=="undo" && status=="applied" || args["lost"]==true && !available && status=="applied") {
val saved=backup[id] as? Map<*,*>
if(saved!=null && current==saved["ours"]) writes.add(mapOf("id" to id,"expected" to current,"value" to saved["prior"]))
backup.remove(id);next=if(args["lost"]==true) "unavailable" else "kept"
} else if(available && choice=="ours" && status in setOf("kept","conflict")) apply()
else if(args["ack"]!=true && (status==null || status=="unavailable")) {
next=when {
!available -> "unavailable"
current==ours -> if(backup[id]!=null) "applied" else "already"
current==obs["default"] || item["stock"]!=null && current==item["stock"] -> "applied"
else -> "conflict"
}
if(next=="applied" && current!=ours) apply()
}
if(id in failed) next="unavailable"
prior[id]=next
item+mapOf("state" to next,"section" to when(next) { "conflict" -> "To review";"applied","already" -> "Applied";"kept" -> "Kept yours";else -> "Unavailable" },
"needs_wifi" to (item["required_by"]=="wifi" && args["wifi"]==true),"yours" to label(item,current),"orbit" to label(item,ours),
"was" to label(item,(backup[id] as? Map<*,*>)?.get("prior")),"reason" to obs["reason"])
}
val conflicts=prior.values.count { it=="conflict" }
val applied=writes.count { w -> prior[w["id"]]=="applied" }
val unseen=((record["unseen"] as? Number)?.toInt().orZero()+applied-(if(args["ack"]==true) failed.toSet().size else 0)).coerceAtLeast(0)
val line=when { unseen>0 && conflicts>0 -> "Applied $unseen · $conflicts to review"; unseen>0 -> "Applied $unseen recommended settings · Review"; conflicts>0 -> "Review $conflicts recommended settings";else -> null }
val ordered=rows.sortedBy { when(it["state"]) { "conflict" -> 0;"applied" -> 1;"already" -> 2;"kept" -> 3;else -> 4 } }
val result=mapOf("items" to ordered,"use_all" to (conflicts>0),"undo_all" to prior.values.any { it=="applied" },"writes" to writes,"record" to mapOf("rev" to 1,"items" to prior,"unseen" to unseen),"backup" to backup,
"conflicts" to conflicts,"seen_line" to (if(conflicts>0) LuaValue.str("Review $conflicts recommended settings") else null),"line" to line?.let(LuaValue::str),"report" to if(conflicts>0) "partial" else if("kept" in prior.values) "reviewed" else "applied")
require(LuaValue.encode(result).size<=16384);return result
}
private fun Int?.orZero()=this ?: 0
private fun label(item:Map<String,Any?>,v:Any?):String {
val labels=(item["value_labels"] as? Map<*,*>).orEmpty()
return when(v) {
null -> "Unset"
true -> "On"
false -> "Off"
is Map<*,*> -> if(v.isEmpty()) "Nothing" else v.keys.map { labels[it] as? String ?: "Custom action" }.sorted().joinToString(" + ")
else -> labels[v.toString()] as? String ?: v.toString()
}.take(200)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import java.io.File
* normalize protocol data before returning it; unsupported operations are explicit. Renderers
* use LibraryReadModel, never this transport-facing interface. */
interface ServerAdapter {
fun recommendedSettings(): List<Map<String,Any?>> = emptyList()
val id: String
fun project(owner: String, request: Map<*, *>): Map<String, Any?> = unsupported()
fun capabilities(owner: String) = project(owner, mapOf("op" to "capabilities"))
Expand All @@ -17,6 +18,7 @@ interface ServerAdapter {
fun lists(owner: String, limit: Int, offset: Int = 0) = project(owner, mapOf("op" to "lists", "limit" to limit, "offset" to offset))
fun sources(owner: String, category: String, limit: Int = 6, offset: Int = 0) =
project(owner, mapOf("op" to "sources", "category" to category, "limit" to limit, "offset" to offset))
fun catalogAction(owner: String, action: String, args: Map<*,*>, done: (Map<String,Any?>?,String?) -> Unit) = done(null,"unsupported")
fun catalogControl(owner: String, action: String, manual: Boolean, done: (Map<String,Any?>?,String?) -> Unit) = done(null,"unsupported")
fun manifest(owner: String): Map<String, Any?> = unsupported()
fun cover(owner: String, key: String): Map<String, Any?> = unsupported()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ object ServerAdapters {
return BookOrbitServerAdapter(credentials, account, ConnectorHttp,
legacyAccount = { net.fledgewing.orbitcompanion.server.bookorbit.LegacyCoverSource.read(
java.io.File(android.os.Environment.getExternalStorageDirectory(),"koreader/settings.reader.lua")) },
actionJob = { creds,owner,action,args,done -> AdapterWorker.catalogAction(ctx,creds,owner,action,args,done) },
catalogJob = { creds,owner,action,manual,done -> AdapterWorker.catalogControl(ctx,creds,owner,action,manual,done) },
coverReferenceJob = { creds, owner, reference, refresh, done ->
AdapterWorker.acquireCoverReference(ctx,creds,owner,reference,refresh,done)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ object ServerCommands {
private class Pending(val at: Long, var body: Map<String,Any?>? = null)
private val jobs = linkedMapOf<String,Pending>()
@Synchronized fun start(ctx: Context, op: String, args: Map<*, *>): String {
require(op in setOf("device.sleep","storage.free","storage.folder","sync.verify.next","sync.verify.result","sync.activate","sync.capture","sync.pull","sync.decide","sync.answer","sync.override","sync.drain","sync.read","sync.write","catalog.window","catalog.control","covers.acquire","downloads.start","account.signIn","account.signOut","login.save","login.remove","login.replace"))
require(op in setOf("device.sleep","storage.free","storage.folder","sync.verify.next","sync.verify.result","sync.activate","sync.capture","sync.pull","sync.decide","sync.answer","sync.override","sync.drain","sync.read","sync.write","catalog.window","catalog.control","catalog.action","settings.recommendations","covers.acquire","downloads.start","account.signIn","account.signOut","login.save","login.remove","login.replace"))
val now = System.currentTimeMillis()
jobs.entries.removeAll { now - it.value.at > 120000 }
require(jobs.size < 32)
Expand Down Expand Up @@ -38,6 +38,8 @@ object ServerCommands {
LibraryAccount.position(ctx,document,update,::finish)
}
"catalog.window" -> LibraryAccount.catalog(ctx,(args["page"] as? Number)?.toInt() ?: 1,(args["limit"] as? Number)?.toInt()?.coerceIn(1,24) ?: 24,::finish)
"settings.recommendations" -> LibraryAccount.recommendedSettings(ctx,args,::finish)
"catalog.action" -> LibraryAccount.catalogAction(ctx,args["owner"] as? String ?: throw IllegalArgumentException("owner"),text("action"),args,::finish)
"catalog.control" -> LibraryAccount.catalogControl(ctx,args["owner"] as? String ?: throw IllegalArgumentException("owner"),text("action"),args["manual"]==true,::finish)
"covers.acquire" -> if (args["reference"] != null)
LibraryAccount.acquireCoverReference(ctx,text("reference"),args["refresh"]==true,args["owner"] as? String ?: throw IllegalArgumentException("owner"),::finish)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ interface ServerRuntime {
/** Command routing only. The selected adapter owns transport and all legacy protocol state. */
object Worker {
const val ACTION_STORAGE = "${Contract.PACKAGE}.action.STORAGE"
const val ACTION_COPIES = "${Contract.PACKAGE}.action.COPIES"
const val ACTION_SLEEP_REFRESH = "${Contract.PACKAGE}.action.SLEEP_REFRESH"
const val ACTION_SQLITE_STRESS = "${Contract.PACKAGE}.action.SQLITE_STRESS"
const val ACTION_PATCH = "${Contract.PACKAGE}.action.PATCH"
Expand Down
Loading
Loading