Responsive background work
==========================

Give a Morphic application one owned worker process, live progress, cooperative cancellation, safe repeat Start, and reliable window-close cleanup. Verify the actual scheduler and interrupted paths.

Squeak 6.1 build 23976, 64-bit, clean official Linux image

Install the complete support application once, then run nine small independent experiments. The focused methods beside each stage explain the implementation; full file-in sources include all UI and helper methods. Workspace blocks are expressions; chunk-format .st class files are for File List → fileIn.

INSTALLATION
1. File in LQBackgroundLab.st. It installs the model and a small stepping SystemWindow subclass.
2. File in LQBackgroundLabTests.st before stage 9. No additional package, file access, or network connection is needed.
3. To open the final app at any time, Do it: LQBackgroundLab open.
4. Each checkpoint opens an independent model. Close earlier tutorial windows before proceeding.
5. Use the small bounded waits only to reproduce checkpoint results. Normal button actions return immediately to Morphic.

FILE TYPES
LQBackgroundLab.st: chunk-format class source; File List -> fileIn.
LQBackgroundLabTests.st: SUnit test class source; file in after the application.
background-stage-NN.st: Workspace expression; open as text, select all, Do it. Each returns an app or Inspector window.
BackgroundExercises-Solutions.st: solution methods/classes; file in after attempting the exercises.
background-exercises-check.st: Workspace assertions; select all and Do it after solutions.

FINAL APP
LQBackgroundLab open

TEST SUITE
LQBackgroundLabTests suite run

Verified: 16 tests passed.
Real process completion, cooperative cancel, discard partial result, immediate/idle Cancel, repeat Start, restart, reset old result, UI deferred message during work, native stepping, window close, separate ownership, error cleanup, semaphore-coordinated close/cancel during a failing slice.

MEDIA
Screenshots are native Morphic imageForm captures produced by the real Squeak VM. GIFs assemble those native frames from scripted message sequences. They are not mouse recordings, browser re-creations, or performance benchmarks.

All media are delivered on the companion lesson page. This ZIP contains this lesson’s sources and guide only.

STAGE 1: Separate the job from its Morphic view
-----------------------------------------------------------------
Long work in a button action blocks the UI process. Instead, this model owns one worker Process and a small set of plain values: state, completedSteps, result, and cancellation flags. The Morphic window reads those values during its normal step method.
The example sums the integers from 1 to N. A short Delay in each slice makes progress visible and gives other processes a turn. It stands in for a naturally bounded piece of work; there is no file, network, or shell operation in this example. Start, Cancel, and Ping UI are ordinary button messages.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| lab |
lab := LQBackgroundLab open.
lab stage: 1.
lab worker isNil ifFalse: [self error: 'The worker should not exist yet'].
lab

EXPECTED
The window is idle: 0/100 steps, Result: none, and UI Ping count: 0.

WATCH FOR
Forking work does not automatically make it responsive. A CPU-bound loop that never yields can still monopolize its priority level.

TRY IT
Locate the model’s plain state variables in an Inspector. Which variables are Morphs, and which are safe for the worker to update?

Browser · LQBackgroundLab · instance side · Accept this method
initialize
    super initialize.
    worker := nil. cancelRequested := false. closed := false.
    completedSteps := 0. workSize := 100. delayMS := 20.
    result := nil. state := #idle. pulse := 0. stage := 1. errorText := ''.

STAGE 2: Start one background process
-----------------------------------------------------------------
Create the process, store its reference, set its priority, and only then resume it. This order matters because a process may finish quickly: the reference must already belong to the model when cleanup runs.
Processor userBackgroundPriority keeps the job below normal UI work. Each slice ends with Delay>>wait, so this sample yields predictably. A lower priority alone is not a substitute for breaking expensive work into bounded slices.
The worker updates only data fields. It never sends contents:, changed, openInWorld, or a dialog message. That rule keeps Morphic activity on the UI side.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| lab |
lab := LQBackgroundLab open.
lab stage: 2; workSize: 100; delayMilliseconds: 20; start.
(Delay forMilliseconds: 100) wait.
lab step.
lab worker isNil ifTrue: [self error: 'Expected a running worker'].
lab

EXPECTED
The count advances while state is running. The exact captured count varies with timing; the job normally finishes after about two seconds.

WATCH FOR
Do not raise this job to a higher priority than the UI to make it feel faster. Fix the work slicing and scheduling first.

TRY IT
Change workSize to 200. Keep each slice bounded and observe that UI controls still respond.

Browser · LQBackgroundLab · instance side · Accept this method
start
    "Install the process reference BEFORE resuming it. Ignore repeated Start."
    (closed or: [worker notNil]) ifTrue: [^ false].
    cancelRequested := false. completedSteps := 0. result := nil. errorText := ''. state := #running.
    worker := [self performWork] newProcess.
    worker priority: Processor userBackgroundPriority.
    worker resume.
    self refresh.
    ^ true

Browser · LQBackgroundLab · instance side · Accept this method
performWork
    "Worker publishes plain values. It never touches Morphs or opens dialogs."
    | total |
    [[
        total := 0.
        1 to: workSize do: [:index |
            (cancelRequested or: [closed]) ifTrue: [^ self].
            total := total + (self valueForStep: index).
            completedSteps := index.
            (Delay forMilliseconds: delayMS) wait].
        (cancelRequested or: [closed]) ifFalse: [
            result := total. state := #completed]
    ] on: Error do: [:error |
        errorText := error messageText. result := nil.
        (closed or: [cancelRequested]) ifFalse: [state := #failed]]]
      ensure: [
        closed ifTrue: [state := #closed. result := nil].
        state = #running ifTrue: [state := #cancelled].
        worker := nil]

STAGE 3: Publish a result only on completion
-----------------------------------------------------------------
The partial sum is a temporary variable inside performWork. It becomes the public result only after the final slice and a final cancellation/closed check. That keeps the word result unambiguous: it always means a complete successful answer.
The ensure: block releases the model’s process reference after completion, cancellation, or an error. Error handling stores a message in plain model state; the UI shows it during a refresh. A later Start clears the old result before any work begins.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| lab deadline |
lab := LQBackgroundLab open.
lab stage: 3; workSize: 10; delayMilliseconds: 1; start.
deadline := Time millisecondClockValue + 3000.
[lab worker notNil and: [Time millisecondClockValue < deadline]]
    whileTrue: [(Delay forMilliseconds: 2) wait].
lab step.
(lab state = #completed and: [lab result = 55])
    ifFalse: [self error: 'Expected the complete sum 55'].
lab

EXPECTED
The worker has stopped, progress is 10/10, state is completed, and Result: 55 is shown.

WATCH FOR
The small polling loop here is a bounded verification block. Do not put a wait-for-completion loop in a production button callback; return to Morphic immediately.

TRY IT
Set N to 20 and predict the result before running: 210.

Browser · LQBackgroundLab · instance side · Accept this method
valueForStep: index
    ^ index

STAGE 4: Refresh progress on the UI process
-----------------------------------------------------------------
LQBackgroundWindow>>step forwards to the model’s step, which calls refresh. The native Morphic scheduler runs the step method at a requested 50 ms interval. The worker can publish progress more often than the UI needs to redraw.
This checkpoint queues a normal deferred UI message and runs a Morphic cycle while the worker is still active. The queued message increments Ping. That is a real UI scheduling test; merely calling a model setter from the worker would not establish that the UI remains available.
The sample uses simple state publication with a single owned writer. For larger compound snapshots or several workers, use a lock, queue, or immutable snapshot with an explicit ownership rule. Do not assume arbitrary multi-field reads are a transaction.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| lab ran |
lab := LQBackgroundLab open.
lab stage: 4; workSize: 100; delayMilliseconds: 20; start.
(Delay forMilliseconds: 60) wait.
ran := false.
WorldState addDeferredUIMessage: [lab ping. ran := true].
World doOneCycleNow.
(ran and: [lab pulse = 1 and: [lab worker notNil]])
    ifFalse: [self error: 'The UI message did not run during work'].
lab

EXPECTED
UI Ping count becomes 1 while the worker is still running. Progress continues to update during ordinary Morphic stepping.

WATCH FOR
World doOneCycleNow is used in this controlled demonstration. Normal application code should return to the UI loop and let it run itself.

TRY IT
Click Ping UI several times during a longer job. The count should change before the result appears.

Browser · LQBackgroundWindow · instance side · Accept this method
step
    self model ifNotNil: [self model step]

Browser · LQBackgroundLab · instance side · Accept this method
step
    self refresh

Browser · LQBackgroundLab · instance side · Accept this method
refresh
    window ifNil: [^ self].
    closed ifTrue: [^ self].
    progressMorph contents: self progressText.
    statusMorph contents: self statusText.
    resultMorph contents: (result ifNil: ['Result: none'] ifNotNil: ['Result: ', result printString]).
    pulseMorph contents: 'UI Ping count: ', pulse printString.
    window changed

STAGE 5: Make repeated Start safe
-----------------------------------------------------------------
Users double-click. A worker reference is also an ownership guard: if it is not nil, Start returns false and leaves that exact Process running. The model never loses the old reference by overwriting it with a second process.
Configuration changes are rejected while a worker exists. A fixed N and slice delay make the job’s promise stable from start to finish. Once the worker has naturally stopped, configuration can change again.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| lab original |
lab := LQBackgroundLab open.
lab stage: 5; workSize: 100; delayMilliseconds: 20; start.
(Delay forMilliseconds: 60) wait.
original := lab worker.
lab start ifTrue: [self error: 'A duplicate job was started'].
lab worker == original ifFalse: [self error: 'The worker reference changed'].
lab ping.
lab

EXPECTED
The second Start returns false. There is one owned worker, and the existing progress is preserved.

WATCH FOR
A boolean running flag without a process reference makes cleanup harder. Keep the owned Process so repeated starts and lifecycle checks refer to the actual job.

TRY IT
Try changing workSize during the run. Handle the expected Error; after completion the same change should succeed.

Browser · LQBackgroundLab · instance side · Accept this method
workSize: anInteger
    worker ifNotNil: [self error: 'Wait for the active worker to stop'].
    (anInteger isInteger and: [anInteger between: 1 and: 100000])
        ifFalse: [self error: 'Work size must be an integer from 1 to 100000'].
    workSize := anInteger

Browser · LQBackgroundLab · instance side · Accept this method
delayMilliseconds: anInteger
    worker ifNotNil: [self error: 'Wait for the active worker to stop'].
    (anInteger isInteger and: [anInteger between: 1 and: 1000])
        ifFalse: [self error: 'Delay must be an integer from 1 to 1000 milliseconds'].
    delayMS := anInteger

STAGE 6: Request cooperative cancellation
-----------------------------------------------------------------
Cancel sets cancelRequested and returns immediately. The worker checks that flag before each slice and once more before publishing the result. Partial sums are discarded. The UI can briefly display Cancel requested while the current slice finishes.
Cancellation latency is bounded by the work between checkpoints plus scheduling delay. This sample has tiny computation and a short Delay. Real file reads, socket calls, or foreign code need their own timeouts or interruption policy; a flag cannot interrupt a permanently blocked primitive.
We never use Process>>terminate to kill arbitrary processes. The job cleans up through its own ensure: block and clears only its own worker reference.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| lab deadline |
lab := LQBackgroundLab open.
lab stage: 6; workSize: 100; delayMilliseconds: 10; start.
(Delay forMilliseconds: 60) wait.
lab requestCancel.
deadline := Time millisecondClockValue + 3000.
[lab worker notNil and: [Time millisecondClockValue < deadline]]
    whileTrue: [(Delay forMilliseconds: 2) wait].
lab step.
(lab state = #cancelled and: [lab result isNil])
    ifFalse: [self error: 'Cancellation published an invalid result'].
lab

EXPECTED
The state becomes cancelled, the worker reference becomes nil, and Result remains none. The progress count can be nonzero because some slices completed.

WATCH FOR
Cancel means “stop at a checkpoint”. Do not show “cancelled” before the owned worker has actually left its work method.

TRY IT
Press Cancel before Start and after completion. Both should be harmless and preserve the existing state.

Browser · LQBackgroundLab · instance side · Accept this method
requestCancel
    "A request, not Process>>terminate. The worker leaves at a checkpoint."
    worker ifNil: [^ false].
    cancelRequested := true.
    self refresh.
    ^ true

STAGE 7: Restart after cancellation
-----------------------------------------------------------------
A new run is allowed after the old worker has finished cleanup. Start resets progress, result, cancellation, and error text before resuming a fresh process. This avoids a stale cancel flag immediately cancelling the next run.
Waiting until the old reference is nil also prevents an old cleanup block from clearing a newer worker’s reference. More complex applications that replace jobs while older ones are still finishing need generation tokens or another explicit ownership scheme.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| lab wait |
lab := LQBackgroundLab open.
lab stage: 7.
wait := [| deadline |
    deadline := Time millisecondClockValue + 3000.
    [lab worker notNil and: [Time millisecondClockValue < deadline]]
        whileTrue: [(Delay forMilliseconds: 2) wait].
    lab worker notNil ifTrue: [self error: 'Worker timeout']].
lab workSize: 100; delayMilliseconds: 10; start; requestCancel.
wait value.
lab workSize: 10; delayMilliseconds: 1; start.
wait value.
lab step.
(lab state = #completed and: [lab result = 55])
    ifFalse: [self error: 'Restart did not complete'].
lab

EXPECTED
The first run cancels. A new run finishes with 10/10 steps and Result: 55; it does not inherit the old cancellation flag.

WATCH FOR
A restart button that immediately assigns a new worker while the old one is still stopping creates an ownership race. This lesson deliberately rejects Start during that interval.

TRY IT
Complete a run, start a longer one, and check that the previous result disappears immediately.

STAGE 8: Treat window close as part of the job lifecycle
-----------------------------------------------------------------
SystemWindow sends windowIsClosing to its model when the native close operation succeeds. The model sets closed and cancelRequested, clears the result, and stops UI stepping. The worker then leaves at its next checkpoint.
Close is idempotent. A closed model refuses a new Start; open a fresh model for a new window. The worker’s failure handler and ensure: block give closed state precedence, so an error in a slice that ends after close cannot revive the UI or publish a result.
The checkpoint closes the actual native window and opens an Inspector on four final values. The order is closed, worker, result, state. The closed application window is gone; the Inspector is a separate debugging tool.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| lab deadline inspector |
lab := LQBackgroundLab open.
lab stage: 8; workSize: 100; delayMilliseconds: 10; start.
lab window delete.
deadline := Time millisecondClockValue + 3000.
[lab worker notNil and: [Time millisecondClockValue < deadline]]
    whileTrue: [(Delay forMilliseconds: 2) wait].
(lab closed and: [lab worker isNil and: [lab result isNil]])
    ifFalse: [self error: 'Close cleanup failed'].
inspector := Inspector openOn: {lab closed. lab worker. lab result. lab state}.
inspector setLabel: 'After close: closed / worker / result / state'.
inspector model selectionIndex: 1.
inspector

EXPECTED
The job window disappears. The Inspector displays #(true nil nil #closed): closed is true, no worker remains, no result remains, and state is closed.

WATCH FOR
Deleting a Morph does not automatically cancel processes you forked. Tie owned resources to an explicit lifecycle hook.

TRY IT
Close the window during a longer run. Then inspect the model you retained in the Workspace and confirm its worker becomes nil.

Browser · LQBackgroundLab · instance side · Accept this method
windowIsClosing
    self close.
    ^ super windowIsClosing

Browser · LQBackgroundLab · instance side · Accept this method
close
    "Idempotent. No wait in the UI; the next checkpoint releases the process."
    closed := true. cancelRequested := true. result := nil. state := #closed.
    window ifNotNil: [window stopStepping].
    ^ self

Browser · LQBackgroundLab · instance side · Accept this method
closeWindow
    window ifNotNil: [window delete. window := nil] ifNil: [self close]

STAGE 9: Verify timing, failure, and repeated actions
-----------------------------------------------------------------
File in LQBackgroundLabTests.st. The suite runs real Squeak Processes and bounded waits. It checks completion, partial-result discard, immediate cancellation, restart, double Start, separate model ownership, native stepping, a deferred UI message, and native window close.
Two semaphore-coordinated tests deliberately pause inside a work slice, apply Close or Cancel from the other process, and then make the slice fail. This establishes that cleanup wins over a late failure rather than depending on a lucky sleep interval.
These tests establish the behavior of this bounded example. They do not benchmark throughput or prove responsiveness for arbitrary blocking foreign calls. The exercises add a progress helper, an idle-only reset, and a sum-of-squares worker without changing the cancellation protocol.

Where: Workspace · select the complete block · Do it (Ctrl/Cmd+D). Each stage creates its own model. Close earlier tutorial windows before opening the next stage.

RUNNABLE CHECKPOINT
| result inspector |
result := LQBackgroundLabTests suite run.
(result failures isEmpty and: [result errors isEmpty])
    ifFalse: [self error: 'Open the Test Runner to inspect failures'].
inspector := Inspector openOn: {result runCount. result passedCount. result failures size. result errors size}.
inspector setLabel: 'Background SUnit: run / passed / failed / errors'.
inspector model selectionIndex: 1.
inspector

EXPECTED
The native Inspector displays #(16 16 0 0). Every worker created by the tests is stopped through its own cancellation/completion path.

WATCH FOR
Tests should wait for a condition with a deadline, not assume a single fixed sleep guarantees completion on every machine.

TRY IT
Run the suite again. Repeated execution should remain green and leave no active tutorial worker.

EXERCISES
1. Expose percentage complete
Add percentageComplete using integer arithmetic and clamp it to 100. The model already rejects N = 0.
Expected: A fresh model returns 0; a completed model returns 100.

Solution (attempt the exercise first):
Browser · LQBackgroundLab · instance side · exercise solutions protocol · Accept the one method. Alternatively, file in BackgroundExercises-Solutions.st.
percentageComplete
    ^ ((100 * completedSteps) // workSize) min: 100

Check:
Workspace · select the entire check block · Print it (Ctrl/Cmd+P), after installing the solution.
LQBackgroundLab new percentageComplete = 0
Expected check result: true

2. Add an idle-only reset
Add resetWhenIdle. Return false while a worker exists or after close; otherwise reset progress, result, error and cancellation to idle.
Expected: Reset succeeds after completion. Reset during a job returns false and does not replace the worker.

Solution (attempt the exercise first):
Browser · LQBackgroundLab · instance side · exercise solutions protocol · Accept the one method. Alternatively, file in BackgroundExercises-Solutions.st.
resetWhenIdle
    (worker notNil or: [closed]) ifTrue: [^ false].
    completedSteps := 0. result := nil. errorText := ''.
    cancelRequested := false. state := #idle.
    self refresh.
    ^ true

Check:
Workspace · select the entire check block · Print it (Ctrl/Cmd+P), after installing the solution.
| lab wait reset cleared rejected same original |
lab := LQBackgroundLab new.
wait := [| deadline |
    deadline := Time millisecondClockValue + 3000.
    [lab worker notNil and: [Time millisecondClockValue < deadline]]
        whileTrue: [(Delay forMilliseconds: 2) wait].
    lab worker notNil ifTrue: [self error: 'Worker did not stop']].
[
    lab workSize: 10; delayMilliseconds: 1; start.
    wait value.
    reset := lab resetWhenIdle.
    cleared := lab state = #idle and: [lab completedSteps = 0 and: [lab result isNil]].
    lab workSize: 100; delayMilliseconds: 5; start.
    original := lab worker.
    rejected := lab resetWhenIdle not.
    same := lab worker == original.
    lab requestCancel. wait value.
    {reset. cleared. rejected. same}
] ensure: [lab closeWindow]
Expected check result: #(true true true true)

3. Compute squares with the same lifecycle
Subclass LQBackgroundLab as LQSquaresLab. Override valueForStep: to return index squared and jobTitle to describe the calculation. Inherit Start, Cancel, and Close unchanged.
Expected: For N = 10, result is 385. Cancellation still yields state cancelled and result nil.

Solution (attempt the exercise first):
File List → fileIn this complete chunk source. It defines LQSquaresLab, then installs valueForStep: and jobTitle on LQSquaresLab’s instance side in the exercise solutions protocol. Alternatively, file in BackgroundExercises-Solutions.st.
LQBackgroundLab subclass: #LQSquaresLab
    instanceVariableNames: '' classVariableNames: '' poolDictionaries: ''
    category: 'LearnSqueak-Background-Exercises'!

!LQSquaresLab methodsFor: 'exercise solutions'!
valueForStep: index
    ^ index squared
! !

!LQSquaresLab methodsFor: 'exercise solutions'!
jobTitle
    ^ 'A cooperative worker: sum of squares from 1 to N'
! !

Check:
Workspace · select the entire check block · Print it (Ctrl/Cmd+P), after installing the solution.
| lab wait complete cancelled |
lab := LQSquaresLab new.
wait := [| deadline |
    deadline := Time millisecondClockValue + 3000.
    [lab worker notNil and: [Time millisecondClockValue < deadline]]
        whileTrue: [(Delay forMilliseconds: 2) wait].
    lab worker notNil ifTrue: [self error: 'Worker did not stop']].
[
    lab workSize: 10; delayMilliseconds: 1; start.
    wait value.
    complete := lab result = 385.
    lab workSize: 100; delayMilliseconds: 5; start; requestCancel.
    wait value.
    cancelled := lab state = #cancelled and: [lab result isNil].
    {complete. cancelled}
] ensure: [lab closeWindow]
Expected check result: #(true true)

CLEANUP
Close the application window to request cancellation and stop stepping. Its owned worker finishes its current slice and exits. Open a new model to begin after close. No global process scan or arbitrary terminate is used.

LIMITS
Cooperative cancellation stops only at a checkpoint; it cannot interrupt a permanently blocked foreign call.
The worker publishes simple values. Multiple workers or compound snapshots need an explicit coordination design.
GIFs use real Processes and native frames but are scripted demonstrations, not performance measurements.

REFERENCES
Squeak official downloads — https://squeak.org/downloads/
The native image source is the API reference: inspect Process, ProcessorScheduler, Delay, WorldState, and SystemWindow in the Browser.
