2. Read the report and save a separate note
A large report should not become a large value in application state. The read operation supplies a stream identifier; a registered asynchronous job consumes its chunks and returns only the byte and line counts. Reducers remain synchronous throughout.
The note is different: it is already a small text draft owned by the screen. The write request takes an owned snapshot of that text and sets overwrite: false. An existing document therefore produces an error instead of being replaced.
Replace the screen, state and shell setup below, and add src/jobs.rs. The translations from step one remain unchanged.
{"id":"fission-tabs-1","tabs":[{"index":0,"label":"src/app.rs","value":"src-app-rs"},{"index":1,"label":"src/state.rs","value":"src-state-rs"},{"index":2,"label":"src/jobs.rs","value":"src-jobs-rs"},{"index":3,"label":"src/lib.rs","value":"src-lib-rs"},{"index":4,"label":"preview/lib.rs","value":"preview-lib-rs"}]}
{"id":"fission-tabs-1","index":0,"label":"src/app.rs","value":"src-app-rs"}
use crate::state::{choose_directory, export_note, read_report, FilesState};
use fission::prelude::*;
fission_component! {
pub InspectionFiles<FilesState> {
state {
read_name: String = "inspection.md".into(),
export_name: String = "inspection-note.txt".into(),
note: String = String::new(),
}
}
view(files, state, cx) {
let tokens = &cx.view.env().theme.tokens;
} =>
Container(SafeArea(
child: Scroll(
child: Container(Column(gap: tokens.spacing.m, children: [
Text(cx.tr("files.title")).size(tokens.typography.heading2_size),
Text(cx.tr("files.context")).color(tokens.colors.text_secondary),
Text(cx.tr("files.explanation")),
if let Some(directory) = &state.directory {
Text(directory.name.clone()).weight(tokens.typography.font_weight_semibold)
} else {
Text(cx.tr("files.no_folder")).color(tokens.colors.text_secondary)
},
Button(
child: Text(cx.tr("files.choose")),
key: "choose-folder",
disabled: state.busy,
on_press: reduce { choose_directory(state, cx); },
).semantics_identifier("inspection.files.choose"),
Divider(),
TextInput(
label: Some(cx.tr("files.read_name").into()),
bind: files.read_name,
read_only: state.busy,
semantics_identifier: "inspection.files.read-name".to_string(),
),
Button(
child: Text(cx.tr("files.read")),
key: "read-report",
disabled: state.busy || state.directory.is_none(),
on_press: reduce { read_report(state, files.read_name.clone(), cx); },
).semantics_identifier("inspection.files.read"),
if let Some(summary) = &state.summary {
Row(gap: tokens.spacing.m, wrap: ir_op::FlexWrap::Wrap, children: [
Stat(label: cx.tr("files.bytes"), value: summary.bytes.to_string()),
Stat(label: cx.tr("files.lines"), value: summary.lines.to_string()),
])
},
Divider(),
TextInput(
label: Some(cx.tr("files.export_name").into()),
bind: files.export_name,
read_only: state.busy,
semantics_identifier: "inspection.files.export-name".to_string(),
),
TextInput(
label: Some(cx.tr("files.note").into()),
multiline: true,
bind: files.note,
read_only: state.busy,
semantics_identifier: "inspection.files.note".to_string(),
),
Text(cx.tr("files.no_overwrite")).color(tokens.colors.text_secondary),
Button(
child: Text(cx.tr("files.export")),
key: "export-note",
disabled: state.busy || state.directory.is_none(),
on_press: reduce {
export_note(state, files.export_name.clone(), files.note.clone(), cx);
},
).semantics_identifier("inspection.files.export"),
if let Some(bytes) = state.written_bytes {
Text(format!("{}: {}", cx.tr("files.written_bytes"), bytes))
},
if state.busy { Spinner(motion: Some(SpinnerMotion::Default), label: Some(cx.tr(&state.status_key))) },
Text(cx.tr(&state.status_key)),
if let Some(error) = &state.error { Code(text: error.clone()) },
]))
.padding_all(tokens.spacing.l)
.width_length(Length::percent(100.0))
.max_width(720.0),
),
))
.height_length(Length::vh(100.0))
}
{"id":"fission-tabs-1","index":1,"label":"src/state.rs","value":"src-state-rs"}
use crate::jobs::{ReportRequest, ReportSummary, INSPECT_REPORT};
use fission::prelude::*;
#[derive(Clone, Debug, PartialEq)]
pub struct FilesState {
pub directory: Option<DirectoryHandle>,
pub busy: bool,
pub status_key: String,
pub error: Option<String>,
pub summary: Option<ReportSummary>,
pub written_bytes: Option<u64>,
}
impl Default for FilesState {
fn default() -> Self {
Self {
directory: None,
busy: false,
status_key: "files.status.choose".into(),
error: None,
summary: None,
written_bytes: None,
}
}
}
impl GlobalState for FilesState {}
pub fn choose_directory(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
if state.busy {
return;
}
state.busy = true;
state.error = None;
state.status_key = "files.status.choosing".into();
let ok = cx.effects.bind(DirectoryChosen, reduce_with!(directory_chosen));
let err = cx.effects.bind(DirectoryFailed, reduce_with!(directory_failed));
cx.effects.file_system()
.pick_directory(PickDirectoryRequest {
access: FileSystemAccessMode::ReadWrite,
persistence_key: None,
})
.on_ok(ok)
.on_err(err);
}
#[fission_reducer(DirectoryChosen)]
pub fn directory_chosen(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
state.busy = false;
state.status_key = "files.status.unexpected".into();
if let Some(result) = cx.input.capability_ok(PICK_DIRECTORY) {
if let Some(directory) = result.directory {
state.directory = Some(directory);
state.summary = None;
state.written_bytes = None;
state.status_key = "files.status.selected".into();
} else {
state.status_key = "files.status.cancelled".into();
}
}
}
#[fission_reducer(DirectoryFailed)]
pub fn directory_failed(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
state.busy = false;
state.status_key = "files.status.failed".into();
state.error = cx.input.capability_error(PICK_DIRECTORY)
.map(|error| format!("{}: {}", error.code, error.message))
.or_else(|| cx.input.capability_error_message(PICK_DIRECTORY).map(str::to_owned));
}
pub fn is_file_name(name: &str) -> bool {
!name.is_empty()
&& name == name.trim()
&& name != "."
&& name != ".."
&& !name.chars().any(|ch| matches!(ch, '/' | '\\' | ':' | '\0'))
}
pub fn read_report(state: &mut FilesState, name: String, cx: &mut ReducerContext<FilesState>) {
if state.busy {
return;
}
let Some(directory) = state.directory.as_ref() else {
state.status_key = "files.status.choose".into();
return;
};
if !is_file_name(&name) {
state.status_key = "files.status.invalid_name".into();
return;
}
let location = FileSystemLocation::directory(directory.id, name);
state.busy = true;
state.error = None;
state.summary = None;
state.status_key = "files.status.reading".into();
let ok = cx.effects.bind(ReportOpened, reduce_with!(report_opened));
let err = cx.effects.bind(ReadFailed, reduce_with!(read_failed));
cx.effects.file_system().read(ReadFileRequest { location }).on_ok(ok).on_err(err);
}
#[fission_reducer(ReportOpened)]
pub fn report_opened(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
let Some(result) = cx.input.capability_ok(READ_FILE) else {
state.busy = false;
state.status_key = "files.status.unexpected".into();
return;
};
let ok = cx.effects.bind(ReportInspected, reduce_with!(report_inspected));
let err = cx.effects.bind(InspectionFailed, reduce_with!(inspection_failed));
cx.effects.app(INSPECT_REPORT, ReportRequest { stream: result.stream }).on_ok(ok).on_err(err);
}
#[fission_reducer(ReadFailed)]
pub fn read_failed(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
state.busy = false;
state.status_key = "files.status.failed".into();
state.error = cx.input.capability_error(READ_FILE)
.map(|error| format!("{}: {}", error.code, error.message))
.or_else(|| cx.input.capability_error_message(READ_FILE).map(str::to_owned));
}
#[fission_reducer(ReportInspected)]
pub fn report_inspected(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
state.busy = false;
state.summary = cx.input.job_ok(INSPECT_REPORT);
state.status_key = if state.summary.is_some() {
"files.status.read"
} else {
"files.status.unexpected"
}.into();
}
#[fission_reducer(InspectionFailed)]
pub fn inspection_failed(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
state.busy = false;
state.status_key = "files.status.failed".into();
state.error = cx.input.job_err(INSPECT_REPORT)
.or_else(|| cx.input.job_error_message(INSPECT_REPORT).map(str::to_owned));
}
pub fn export_note(
state: &mut FilesState,
name: String,
note: String,
cx: &mut ReducerContext<FilesState>,
) {
if state.busy {
return;
}
let Some(directory) = state.directory.as_ref() else {
state.status_key = "files.status.choose".into();
return;
};
if !is_file_name(&name) {
state.status_key = "files.status.invalid_name".into();
return;
}
if note.trim().is_empty() {
state.status_key = "files.status.empty_note".into();
return;
}
let location = FileSystemLocation::directory(directory.id, name);
state.busy = true;
state.error = None;
state.written_bytes = None;
state.status_key = "files.status.writing".into();
let ok = cx.effects.bind(NoteWritten, reduce_with!(note_written));
let err = cx.effects.bind(WriteFailed, reduce_with!(write_failed));
cx.effects.file_system().write(WriteFileRequest {
location,
source: FileWriteSource::Bytes(note.into_bytes()),
create_parents: false,
overwrite: false,
}).on_ok(ok).on_err(err);
}
#[fission_reducer(NoteWritten)]
pub fn note_written(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
state.busy = false;
state.written_bytes = cx.input.capability_ok(WRITE_FILE).map(|result| result.byte_len);
state.status_key = if state.written_bytes.is_some() {
"files.status.written"
} else {
"files.status.unexpected"
}.into();
}
#[fission_reducer(WriteFailed)]
pub fn write_failed(state: &mut FilesState, cx: &mut ReducerContext<FilesState>) {
state.busy = false;
state.status_key = "files.status.failed".into();
state.error = cx.input.capability_error(WRITE_FILE)
.map(|error| format!("{}: {}", error.code, error.message))
.or_else(|| cx.input.capability_error_message(WRITE_FILE).map(str::to_owned));
}
{"id":"fission-tabs-1","index":2,"label":"src/jobs.rs","value":"src-jobs-rs"}
use fission::core::{DataStreamId, JobCtx, JobRef, JobSpec};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReportRequest {
pub stream: DataStreamId,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ReportSummary {
pub bytes: u64,
pub lines: u64,
}
pub struct InspectReport;
impl JobSpec for InspectReport {
type Request = ReportRequest;
type Ok = ReportSummary;
type Err = String;
const NAME: &'static str = "inspection.files.inspect-report";
}
pub const INSPECT_REPORT: JobRef<InspectReport> = JobRef::new(InspectReport::NAME);
pub async fn inspect_report(request: ReportRequest, cx: JobCtx) -> Result<ReportSummary, String> {
let mut stream = cx.open_data_stream(request.stream).map_err(|error| error.to_string())?;
let mut bytes = 0_u64;
let mut lines = 0_u64;
let mut ends_with_newline = true;
while let Some(chunk) = std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await {
let chunk = chunk.map_err(|error| error.to_string())?;
bytes = bytes.checked_add(chunk.len() as u64).ok_or("Report is too large")?;
lines = lines.checked_add(chunk.iter().filter(|byte| **byte == b'\n').count() as u64)
.ok_or("Report has too many lines")?;
if !chunk.is_empty() {
ends_with_newline = chunk.ends_with(b"\n");
}
}
if bytes > 0 && !ends_with_newline {
lines = lines.checked_add(1).ok_or("Report has too many lines")?;
}
Ok(ReportSummary { bytes, lines })
}
{"id":"fission-tabs-1","index":3,"label":"src/lib.rs","value":"src-lib-rs"}
mod app;
mod state;
mod translations;
mod jobs;
use fission::prelude::*;
#[cfg(not(any(target_arch = "wasm32", target_os = "android", target_os = "ios")))]
pub fn run_desktop() -> anyhow::Result<()> {
DesktopApp::<state::FilesState, _>::new(app::InspectionFiles)
.with_env(translations::create_env())
.with_async(|asyncs| {
asyncs.register_job(jobs::INSPECT_REPORT, |request, cx| async move {
jobs::inspect_report(request, cx).await
});
})
.run()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
fn mobile_app() -> MobileApp<state::FilesState, app::InspectionFiles> {
let app = MobileApp::<state::FilesState, _>::new(app::InspectionFiles)
.with_env(translations::create_env())
.with_async(|asyncs| {
asyncs.register_job(jobs::INSPECT_REPORT, |request, cx| async move {
jobs::inspect_report(request, cx).await
});
})
.with_title("Inspection documents");
#[cfg(target_os = "android")]
let app = app.with_test_control_port(48761);
app
}
#[cfg(any(target_os = "android", target_os = "ios"))]
pub fn run_mobile() -> anyhow::Result<()> {
mobile_app().run()
}
#[cfg(target_os = "android")]
#[no_mangle]
fn android_main(app_handle: AndroidApp) {
let _ = mobile_app().run_with_android_app(app_handle);
}
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn run_web() -> Result<(), wasm_bindgen::JsValue> {
console_error_panic_hook::set_once();
WebApp::<state::FilesState, _>::new(app::InspectionFiles)
.with_env(translations::create_env())
.with_async(|asyncs| {
asyncs.register_job(jobs::INSPECT_REPORT, |request, cx| async move {
jobs::inspect_report(request, cx).await
});
})
.run()
.map_err(|error| wasm_bindgen::JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1","index":4,"label":"preview/lib.rs","value":"preview-lib-rs"}
mod app;
mod state;
mod translations;
mod jobs;
use fission::prelude::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
console_error_panic_hook::set_once();
WebApp::<state::FilesState, _>::new(app::InspectionFiles)
.with_env(translations::create_env())
.with_async(|asyncs| {
asyncs.register_job(jobs::INSPECT_REPORT, |request, cx| async move {
jobs::inspect_report(request, cx).await
});
})
.with_title("Inspection documents")
.mount("#fission-web-mount")
.run()
.map_err(|error| JsValue::from_str(&error.to_string()))
}
{"id":"fission-tabs-1"}
There are three useful boundaries here. Text drafts belong to the component; the selected directory and completed operation results belong to shared state; stream processing belongs to the asynchronous job. The job receives a stream identifier, not a live component or reducer context.
Only one operation is admitted at a time. The screen disables its controls whilst it is busy, and the reducers check that condition too. As a result, a late report result cannot replace a result for a newly selected folder. A screen that permits concurrent reads would instead need an operation identity and stale-result checks.
File-name validation deliberately accepts one name, not an arbitrary relative path. This is an application input rule, not a replacement for the provider's access enforcement. The line counter counts newline-delimited records, including a final non-empty line without a newline; it does not parse Markdown or assume the report is valid UTF-8.
Read an existing report and compare its byte and line counts with the file. Enter a missing file name and check the failure state. Save a note, then save to the same name again: the second write must fail and leave the original file intact.
Show the app previewHide the app preview
Show the app preview
Hide the app preview