Keep in mind it is a toy answer, from my tests it appears it is not general enough.
MMA is well designed to fix problems it creates :)
What I've found is that Dynamic
aren't stable but Initialization
triggers as it should. Let's use it to overwrite it's content when new session occurs:
restartProtect[Dynamic[DateString[], UpdateInterval -> 1]]
restartProtect[Dynamic[DateString[], UpdateInterval -> 1]]
Dynamic[DateString[], UpdateInterval -> 1]
Dynamic[DateString[], UpdateInterval -> 1]
After restart only first two lines will still work.
Here's the code:
restartProtect[expr_] := DynamicModule[{session = $SessionID},
expr
,
SynchronousInitialization -> False,
Initialization :> (
If[
session =!= $SessionID
,
SetOptions[
EvaluationNotebook[],
DefaultDuplicateCellStyle -> "Output"
];
NotebookWrite[
EvaluationBox[],
BoxData @ ReplacePart[
NotebookRead[EvaluationBox[]], {1, 1, 2} -> $SessionID
]
];
SetOptions[
EvaluationNotebook[],
DefaultDuplicateCellStyle -> "Input"
]
]
)
]